diff --git a/.autoskillit/.gitignore b/.autoskillit/.gitignore index a6d7ecd9ea..3081171d70 100644 --- a/.autoskillit/.gitignore +++ b/.autoskillit/.gitignore @@ -1 +1,4 @@ temp/ +.secrets.yaml +.onboarded +sync_manifest.json diff --git a/.autoskillit/config.yaml b/.autoskillit/config.yaml index cd97ac9738..ada27986d9 100644 --- a/.autoskillit/config.yaml +++ b/.autoskillit/config.yaml @@ -28,3 +28,7 @@ ci: github: default_repo: "TalonT-Org/AutoSkillit" + +quota_guard: + enabled: false + short_window_threshold: 95.0 diff --git a/.autoskillit/recipes/contracts/smoke-test.yaml b/.autoskillit/recipes/contracts/smoke-test.yaml new file mode 100644 index 0000000000..04ce59fac7 --- /dev/null +++ b/.autoskillit/recipes/contracts/smoke-test.yaml @@ -0,0 +1,130 @@ +generated_at: '2026-04-10T04:34:50.670647+00:00' +bundled_manifest_version: 0.1.0 +skill_hashes: {} +skills: {} +dataflow: +- step: clone + available: + - base_branch + - source_dir + required: [] + produced: + - work_dir + - remote_url +- step: create_branch + available: + - base_branch + - remote_url + - source_dir + - work_dir + required: [] + produced: + - branch_name +- step: setup + available: + - base_branch + - branch_name + - remote_url + - source_dir + - work_dir + required: [] + produced: [] +- step: implement_task + available: + - base_branch + - branch_name + - remote_url + - source_dir + - work_dir + required: [] + produced: [] +- step: run_tests + available: + - base_branch + - branch_name + - remote_url + - source_dir + - work_dir + required: [] + produced: [] +- step: push_branch + available: + - base_branch + - branch_name + - remote_url + - source_dir + - work_dir + required: [] + produced: [] +- step: create_pr + available: + - base_branch + - branch_name + - remote_url + - source_dir + - work_dir + required: [] + produced: [] +- step: close_pr + available: + - base_branch + - branch_name + - remote_url + - source_dir + - work_dir + required: [] + produced: [] +- step: delete_remote_branch + available: + - base_branch + - branch_name + - remote_url + - source_dir + - work_dir + required: [] + produced: [] +- step: register_clone_success + available: + - base_branch + - branch_name + - remote_url + - source_dir + - work_dir + required: [] + produced: [] +- step: fail_delete_remote_branch + available: + - base_branch + - branch_name + - remote_url + - source_dir + - work_dir + required: [] + produced: [] +- step: register_clone_failure + available: + - base_branch + - branch_name + - remote_url + - source_dir + - work_dir + required: [] + produced: [] +- step: done + available: + - base_branch + - branch_name + - remote_url + - source_dir + - work_dir + required: [] + produced: [] +- step: escalate + available: + - base_branch + - branch_name + - remote_url + - source_dir + - work_dir + required: [] + produced: [] diff --git a/.autoskillit/recipes/diagrams/smoke-test.md b/.autoskillit/recipes/diagrams/smoke-test.md new file mode 100644 index 0000000000..46c3dd3fe5 --- /dev/null +++ b/.autoskillit/recipes/diagrams/smoke-test.md @@ -0,0 +1,25 @@ +## smoke-test + +``` + clone + | + create_branch ----+ + | | + setup | + | | + implement_task | + | | + run_tests ---------+---> fail_delete_remote_branch + | | | + push_branch -------+ register_clone_failure + | | + create_pr ---------+ escalate [stop] + | | + close_pr | + | | | + +--+---> delete_remote_branch + | + register_clone_success + | + done [stop] +``` diff --git a/.autoskillit/recipes/full-audit.yaml b/.autoskillit/recipes/full-audit.yaml new file mode 100644 index 0000000000..1200d95c90 --- /dev/null +++ b/.autoskillit/recipes/full-audit.yaml @@ -0,0 +1,149 @@ +name: full-audit +description: >- + Run audit-tests, audit-cohesion, and audit-arch in parallel, validate each + report individually, and create a GitHub issue from each validated report. +summary: "branch → audit×3 ∥ → validate×3 ∥ → issue×3 ∥ → done" + +ingredients: + workspace: + description: "Path to the git repository workspace" + required: true + branch: + description: "The branch to audit against" + required: true + +kitchen_rules: + - >- + Each audit chain (tests, cohesion, arch) is independent. A failure in one + chain MUST NOT block or affect the other two chains. Continue with + successful chains and note failures for escalation. + - >- + Within each wave, fire all run_skill calls in a single message to achieve + parallelism. Do not serialize audit/validate/issue calls. + - >- + Report paths are discovered from session output — look for file paths + in .autoskillit/temp/ directories. Pass discovered paths as positional + arguments to downstream skills. + +steps: + checkout: + tool: run_cmd + description: "Check out the target branch" + with: + cmd: "git checkout ${{ inputs.branch }}" + cwd: "${{ inputs.workspace }}" + step_name: "checkout" + note: > + Ensure the working directory is on the target branch before audits run. + If the checkout fails (e.g., dirty working tree, unknown branch), route + to escalate — audits cannot proceed on the wrong branch. + on_success: run_audits + on_failure: escalate_stop + retries: 0 + on_exhausted: escalate_stop + + run_audits: + tool: run_skill + description: "Run three audit skills in parallel" + with: + skill_command: "/autoskillit:audit-tests" + cwd: "${{ inputs.workspace }}" + step_name: "run_audits" + note: > + PARALLEL AUDIT WAVE — Fire three run_skill calls in a single message: + + 1. run_skill(skill_command="/autoskillit:audit-tests", cwd="${{ inputs.workspace }}", step_name="audit_tests") + 2. run_skill(skill_command="/autoskillit:audit-cohesion", cwd="${{ inputs.workspace }}", step_name="audit_cohesion") + 3. run_skill(skill_command="/autoskillit:audit-arch", cwd="${{ inputs.workspace }}", step_name="audit_arch") + + Each audit writes its report to a well-known temp directory: + - .autoskillit/temp/audit-tests/{name}_{timestamp}.md + - .autoskillit/temp/audit-cohesion/cohesion_audit_{timestamp}.md + - .autoskillit/temp/audit-arch/arch_audit_{timestamp}.md + + After all three complete, discover the most-recently-modified .md file in + each temp directory from the session output. Record which audits succeeded + and their report paths for the validation wave. + + If any audit fails, note the failure but continue with the other two. + Proceed to validate_audits even if only one or two audits succeeded. + Route to escalate_stop ONLY if all three audits fail. + on_success: validate_audits + on_failure: escalate_stop + retries: 1 + on_exhausted: escalate_stop + + validate_audits: + tool: run_skill + description: "Validate each audit report in parallel" + with: + skill_command: "/autoskillit:validate-audit" + cwd: "${{ inputs.workspace }}" + step_name: "validate_audits" + note: > + PARALLEL VALIDATION WAVE — For each audit that succeeded in the previous + wave, fire a run_skill call in a single message. Pass the audit report + path as a positional argument: + + 1. run_skill(skill_command="/autoskillit:validate-audit {tests_report_path}", cwd="${{ inputs.workspace }}", step_name="validate_tests") + 2. run_skill(skill_command="/autoskillit:validate-audit {cohesion_report_path}", cwd="${{ inputs.workspace }}", step_name="validate_cohesion") + 3. run_skill(skill_command="/autoskillit:validate-audit {arch_report_path}", cwd="${{ inputs.workspace }}", step_name="validate_arch") + + Skip validation for any audit that failed in wave 1. + Each validation writes to .autoskillit/temp/validate-audit/: + - validated_report_{source}_{timestamp}.md (first line: "validated: true") + - contested_findings_{source}_{timestamp}.md (only if contested > 0) + + After all complete, discover the validated_report_*.md files from session + output. Record paths for the issue creation wave. + + If any validation fails, note it but continue with the others. + Route to escalate_stop ONLY if all validations fail. + on_success: create_issues + on_failure: escalate_stop + retries: 1 + on_exhausted: escalate_stop + + create_issues: + tool: run_skill + description: "Create GitHub issues from validated reports" + with: + skill_command: "/autoskillit:prepare-issue" + cwd: "${{ inputs.workspace }}" + step_name: "create_issues" + note: > + PARALLEL ISSUE CREATION WAVE — For each validated audit report, fire a + run_skill call in a single message. Pass the validated report path as + the description argument: + + 1. run_skill(skill_command="/autoskillit:prepare-issue {validated_tests_path}", cwd="${{ inputs.workspace }}", step_name="issue_tests") + 2. run_skill(skill_command="/autoskillit:prepare-issue {validated_cohesion_path}", cwd="${{ inputs.workspace }}", step_name="issue_cohesion") + 3. run_skill(skill_command="/autoskillit:prepare-issue {validated_arch_path}", cwd="${{ inputs.workspace }}", step_name="issue_arch") + + Skip issue creation for any validation that failed in wave 2. + The prepare-issue skill auto-detects the "validated: true" sentinel in + the report's first line and uses the audit-report input path (derives + title from H1 heading, strips artifact paths from body). + + Collect the issue URLs from each successful result. + If any issue creation fails, note it but continue with the others. + capture_list: + issue_urls: "${{ result.issue_url }}" + on_success: done + on_failure: escalate_stop + retries: 1 + on_exhausted: escalate_stop + + done: + action: stop + message: >- + Full audit complete. GitHub issues created from validated audit reports. + Check context.issue_urls for the created issue links and + .autoskillit/temp/ for all audit artifacts. + + escalate_stop: + action: stop + message: >- + Full audit pipeline failed — one or more audit chains could not complete. + Check session logs and .autoskillit/temp/ directories for partial results. + Individual chain failures are noted in the session output above. diff --git a/.autoskillit/recipes/smoke-test.yaml b/.autoskillit/recipes/smoke-test.yaml new file mode 100644 index 0000000000..7ab88d4ead --- /dev/null +++ b/.autoskillit/recipes/smoke-test.yaml @@ -0,0 +1,185 @@ +name: smoke-test +autoskillit_version: "0.7.50" +description: >- + Lightweight end-to-end sanity check — clones the repository, creates an + isolated branch, implements a trivial micro-task (smoke_canary), runs the + full project test suite, pushes to remote, opens a GitHub PR, and + immediately closes it without merging. +summary: >- + clone > create_branch > setup > implement_task > run_tests > + push_branch > create_pr > close_pr > delete_remote_branch > + register_clone_success > done + +ingredients: + source_dir: + description: >- + Path to the git repository workspace. Must have a GitHub remote configured + and an authenticated gh CLI available. + required: false + default: "" + base_branch: + description: Base branch for the PR target + default: "" + +kitchen_rules: + - >- + NEVER use native Claude Code tools (Read, Grep, Glob, Edit, Write, + Bash, Agent, WebFetch, WebSearch, NotebookEdit) from the orchestrator. All file + operations are delegated through run_skill or run_cmd. + - >- + Route to escalate or fail_delete_remote_branch on any failure — never investigate + or fix directly from the orchestrator. This is a sanity check, not a stress test: + no retries, no fix loops. + - >- + SOURCE ISOLATION: After clone_repo returns, the source_dir is strictly + off-limits. Never run any command in source_dir — no git checkout, git + fetch, git reset, git pull, run_cmd, run_skill, or any other operation. + All work — skill invocations, git operations, file reads — happens + exclusively in the clone (work_dir). + +steps: + clone: + tool: clone_repo + with: + source_dir: "${{ inputs.source_dir }}" + run_name: "smoke" + branch: "${{ inputs.base_branch }}" + capture: + work_dir: "${{ result.clone_path }}" + remote_url: "${{ result.remote_url }}" + on_success: create_branch + on_failure: escalate + + create_branch: + tool: create_unique_branch + with: + base_branch_name: "smoke/canary" + cwd: "${{ context.work_dir }}" + step_name: "create_branch" + capture: + branch_name: "${{ result.branch_name }}" + on_success: setup + on_failure: register_clone_failure + note: >- + Creates a unique smoke/canary[-N] branch (collision-safe via ls-remote). + + setup: + tool: run_cmd + with: + cmd: "task install-worktree" + cwd: "${{ context.work_dir }}" + step_name: "setup" + on_success: implement_task + on_failure: register_clone_failure + + implement_task: + tool: run_skill + with: + skill_command: >- + /autoskillit:smoke-task In ${{ context.work_dir }}: (1) open + src/autoskillit/smoke_utils.py and append a blank line followed by the + function 'def smoke_canary() -> bool:' with body + ' """Smoke-test sentinel — always returns True."""' and ' return True'; + (2) create tests/test_smoke_canary.py containing exactly: + 'from autoskillit.smoke_utils import smoke_canary' blank line blank line + 'def test_smoke_canary() -> None:' ' assert smoke_canary() is True'; + (3) run git add src/autoskillit/smoke_utils.py tests/test_smoke_canary.py; + (4) run git commit -m 'smoke: add smoke_canary()'. + cwd: "${{ context.work_dir }}" + on_success: run_tests + on_failure: register_clone_failure + + run_tests: + tool: run_cmd + with: + cmd: "task test-check" + cwd: "${{ context.work_dir }}" + step_name: "run_tests" + on_success: push_branch + on_failure: fail_delete_remote_branch + note: >- + Uses run_cmd instead of test_check because the smoke-test runs in the + clone root (not a sub-worktree). The clone-root-as-worktree semantic + rule correctly forbids passing clone_path as worktree_path. + + push_branch: + tool: push_to_remote + with: + clone_path: "${{ context.work_dir }}" + branch: "${{ context.branch_name }}" + remote_url: "${{ context.remote_url }}" + on_success: create_pr + on_failure: fail_delete_remote_branch + + create_pr: + tool: run_cmd + with: + cmd: >- + gh pr create + --title "smoke: add smoke_canary() [DO NOT MERGE]" + --body "Automated smoke-test PR — closed without merging. Safe to ignore." + --base "${{ inputs.base_branch }}" + cwd: "${{ context.work_dir }}" + step_name: "create_pr" + on_success: close_pr + on_failure: fail_delete_remote_branch + + close_pr: + tool: run_cmd + with: + cmd: >- + PR_NUM=$(gh pr view --json number --jq .number) && + [ -n "$PR_NUM" ] && + gh pr close "$PR_NUM" --comment "Smoke test complete. Closing without merge." + cwd: "${{ context.work_dir }}" + step_name: "close_pr" + on_success: delete_remote_branch + on_failure: delete_remote_branch + + delete_remote_branch: + tool: run_cmd + with: + cmd: >- + git push origin --delete "${{ context.branch_name }}" 2>/dev/null || true && + git branch -D "${{ context.branch_name }}" 2>/dev/null || true + cwd: "${{ context.work_dir }}" + step_name: "delete_remote_branch" + on_success: register_clone_success + on_failure: register_clone_success + + register_clone_success: + tool: register_clone_status + with: + clone_path: "${{ context.work_dir }}" + status: "success" + step_name: "register_clone_success" + on_success: done + on_failure: done + + fail_delete_remote_branch: + tool: run_cmd + with: + cmd: >- + git push origin --delete "${{ context.branch_name }}" 2>/dev/null || true && + git branch -D "${{ context.branch_name }}" 2>/dev/null || true + cwd: "${{ context.work_dir }}" + step_name: "fail_delete_remote_branch" + on_success: register_clone_failure + on_failure: register_clone_failure + + register_clone_failure: + tool: register_clone_status + with: + clone_path: "${{ context.work_dir }}" + status: "error" + step_name: "register_clone_failure" + on_success: escalate + on_failure: escalate + + done: + action: stop + message: "Smoke test completed successfully — PR created and closed without merging." + + escalate: + action: stop + message: "Smoke test failed — check step output for details." diff --git a/.claude/skills/audit-arch/SKILL.md b/.claude/skills/audit-arch/SKILL.md index 050220bf7f..47564c4bfc 100644 --- a/.claude/skills/audit-arch/SKILL.md +++ b/.claude/skills/audit-arch/SKILL.md @@ -1,5 +1,6 @@ --- name: audit-arch +categories: [audit] description: Audit codebase for adherence to architectural standards, practices, and rules. Use when user says "audit arch", "audit architecture", "check architecture", or "architectural review". Spawns parallel subagents to examine multiple architectural aspects and generates a structured report. hooks: PreToolUse: @@ -26,7 +27,7 @@ Audit the codebase for adherence to architectural standards and rules. **ALWAYS:** - Use subagents for parallel exploration -- Write report to `temp/audit-arch/arch_audit_{YYYY-MM-DD_HHMMSS}.md` +- Write report to `{{AUTOSKILLIT_TEMP}}/audit-arch/arch_audit_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) - Provide file paths and line numbers - Categorize by severity (CRITICAL, HIGH, MEDIUM, LOW) @@ -219,6 +220,16 @@ infrastructure -> depends on nothing project-specific - Confirm `ToolContext` is only instantiated in `server/_factory.py` and test files - Flag any `Default*` adapter instantiated outside the Composition Root in production code +**Composition-Boundary Tiers — NOT Violations:** + +The Composition Root rule applies only to full DI wiring sessions. The following three tiers are legitimate composition boundaries and MUST NOT be flagged as P12 violations: + +- **Intra-package Default* instantiation** — sibling modules within the same sub-package wiring `Default*` adapters as dataclass field defaults. This pattern is intentional: the sub-package is a cohesive unit and the sibling wiring is not "escaping" the Composition Root. Example: `pipeline/context.py` instantiating `DefaultBackgroundSupervisor`, `DefaultMcpResponseLog` as field defaults. +- **L3 CLI / interactive launcher composition boundaries** — modules in `cli/` with their own lifecycle that do not receive a `ToolContext` at all. These modules compose their own lightweight dependencies because they operate outside the server pipeline. Examples: `cli/_workspace.py`, `cli/_cook.py`. +- **DI convenience default** — an optional parameter typed `SomeProtocol | None = None` with a deferred-import fallback inside `if param is None:`. This is a dependency-injection convenience pattern, not a Composition Root bypass. Example: `recording.py`. + +Only `Default*` instantiation that bypasses the Composition Root AND falls outside all three tiers is a P12 violation. + **Severity:** HIGH — concrete class leakage in field annotations defeats substitutability; Protocol naming gaps make the DI contract non-discoverable --- @@ -278,9 +289,23 @@ These apply across all principles when evaluating architectural decisions: --- +## Pre-Flight Verification Checklist + +Before reporting any finding, complete the mandatory verification for its category. A finding MUST NOT be reported unless the required verification has been performed. + +| Finding category | Required verification before reporting | +|---|---| +| **Missing export** (symbol absent from public API) | Use the Read tool to open the relevant `__init__.py`. Verify both `__all__` contents and direct re-export statements. Discard the finding if the symbol is present. | +| **Missing decorator** (e.g., `runtime_checkable`) | Use the Read tool to open the file containing the class definition. Inspect the 3–5 lines directly preceding the `class` keyword. Discard the finding if the decorator is present. | +| **Enforcement gap** (no test for a rule or constant) | Use the Grep tool to search `tests/` for the exact symbol or constant name. Discard the finding if a matching test file is found. | +| **Code duplication** | Use the Read tool to retrieve the full body of each function. Compare the full signature (parameters, return type) and logic step-by-step. Same-named functions at different abstraction levels are NOT duplicates. Discard if logically distinct. | +| **Misplaced file or incorrect import path** | Use the Bash tool to run `git log --oneline -- {file_path}` (substituting the actual path). Inspect commit messages for intentional placement decisions. Discard the finding if a commit explains the placement. | + +--- + ## Audit Workflow -1. **Launch parallel subagents** for each principle +1. **Launch parallel subagents** for each principle. Each subagent MUST NOT invent or enforce principles beyond its assigned principle. 2. **Apply P1 3-question gate** before finalizing any P1 findings — confirm all three questions are YES and the pattern is not listed under "Non-SSOT Patterns — Do NOT flag these" 3. **Apply cross-cutting exemptions** — verify CC-flagged patterns are not listed under "Standard patterns that are NOT cross-cutting violations" (error accumulation, validator collections, or facade re-exports) 4. **Apply severity gate** — CRITICAL requires data loss, security bypass, or correctness bug; downgrade findings that do not meet this bar @@ -288,16 +313,46 @@ These apply across all principles when evaluating architectural decisions: 6. **Consolidate findings** by principle and severity 7. **Cross-reference:** Ensure findings are categorized by the principle they violate, not just where discovered 8. **Suggest new principle** (optional) — see below -9. **Write report** to `temp/audit-arch/arch_audit_{YYYY-MM-DD_HHMMSS}.md` -10. **Output summary** to terminal +9. **Pre-Flight Verification Pass** — for every finding, perform the verification from the Pre-Flight Verification Checklist; drop the finding if verification fails. +10. **Self-Validation Pass** — before finalizing findings, spot-check a sample of factual claims against the actual codebase. Perform all four checks: + + a. **HIGH/CRITICAL re-read**: For every HIGH or CRITICAL finding, use the Read + tool to re-open the exact file and line range cited. Confirm the code exhibits + the claimed behavior. Downgrade or remove the finding if the evidence does not + hold. + + b. **Concrete-class check** (resource-leak and data-loss findings): For any + finding about a missing `aclose`, unclosed resource, or silent data loss, read + the concrete class body — not only the Protocol or interface declaration. If the + concrete implementation provides the method or handles the data correctly, + remove or revise the finding to reflect the accurate scope. + + c. **Enforcement-search confirmation** (enforcement-gap findings): For any finding + claiming no test enforces a rule or constant, confirm that a Grep search of + `tests/` for the exact symbol was performed during this audit. If it was not, + run it now; discard the finding if a matching test exists. + + d. **Internal validation note**: After completing (a)–(c), record a one-sentence + note for each reviewed finding: either `CONFIRMED – ` or + `REVISED – `. These notes are for + internal quality control and do not appear in the final report. + +11. **Write report** to `{{AUTOSKILLIT_TEMP}}/audit-arch/arch_audit_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +12. **Output summary** to terminal --- ## Principle Suggestion (Optional) -After consolidating findings, consider whether a **new** architectural principle would significantly benefit the codebase. +Launch ONE dedicated subagent AFTER all per-principle findings are consolidated. This subagent's only job is to propose a single new principle. + +**Constraints — ALL are mandatory:** +- At most ONE suggestion per audit, labeled "PROPOSED PRINCIPLE". +- A proposed principle MUST NOT generate findings, errors, warnings, or severity ratings. +- A proposed principle MUST NOT be enforced in this or any subsequent audit. +- Subagents running P1–P14 audits MUST NOT invent or enforce principles beyond their assigned principle. -**Criteria - ALL must be true:** +**Criteria — ALL must be true** (for the dedicated suggestion subagent): - Not a one-off issue - No existing principle covers it - Would prevent recurring architectural debt or bugs @@ -321,6 +376,49 @@ Do NOT flag: --- +## Exception Whitelist + +### General Exceptions (GE) + +These exceptions apply across all principles. Before reporting a finding, verify it does not match any entry below. + +**GE-1** — Deferred function-body imports with `# noqa: PLC0415` are not P3/P4 layer violations. Only module-level unsuppressed cross-layer imports are flagged. +*Source: audit-arch round 1 contest batch.* + +**GE-2** — `TYPE_CHECKING`-only imports create zero runtime coupling and must not be flagged as cross-layer or cross-domain violations. +*Source: audit-arch round 1 contest batch.* + +**GE-7** — Stdlib-only forced duplication with an output-equivalence test is accepted; not a P6 violation when the module has a documented zero-external-imports constraint. +*Source: audit-arch round 2 contest batch.* + +**GE-9** — Decorator-based registration imports in `__init__.py` (e.g., importing `rules_*.py` to trigger `@semantic_rule` registration) are intentional and not impure side effects. +*Source: audit-arch round 2 contest batch.* + +**GE-13** — "No dedicated test file" ≠ "no test coverage." Before claiming a module lacks coverage, grep `tests/` for `from . import`. Absence of `test_.py` is not evidence. +*Source: audit-arch round 1 and cohesion round 1 contest batches.* + +**GE-16** — Same-shape functions with different return types serving different layers or precision purposes are not duplicates. +*Source: audit-arch round 2 contest batch.* + +**GE-17** — Approximately 6 lines of shared boilerplate between functions with fundamentally different feature sets is not duplication. Threshold: fewer than 8 lines of overlap between functions whose core logic is distinct does not constitute a P6 violation. +*Source: audit-arch round 2 contest batch.* + +### Project-Specific Exceptions (PS) + +These exceptions apply to known autoskillit codebase patterns that are legitimately non-standard. + +**PS-1** — `smoke_utils.py` at package root: stable callable-path API; `autoskillit.smoke_utils.*` is baked into recipe YAMLs and must remain at the top-level path. + +**PS-2** — `hook_registry.py` at package root: the `hooks/` sub-package has a stdlib-only constraint; `hook_registry` cannot be placed inside `hooks/`. See commit `ee83681d`. + +**PS-4** — `_llm_triage.py` at package root: circular import constraint with its sole caller `server/helpers.py` prevents placing it inside `server/`. + +**PS-7** — `SkillResolver` naming: no `SkillResolver` Protocol exists; the `Default*` naming convention applies only to Protocol implementors. `SkillResolver` is the only implementation and needs no `Default` prefix. + +**PS-8** — L3 `server/` and `cli/` are excluded from REQ-IMP-001 intentionally; `IL-005` and `IL-006` provide compensating controls at the gateway boundary. + +--- + ## Severity Guidelines **CRITICAL** (requires at least one of): diff --git a/.claude/skills/audit-cohesion/SKILL.md b/.claude/skills/audit-cohesion/SKILL.md index bc6ecb3101..47df601f55 100644 --- a/.claude/skills/audit-cohesion/SKILL.md +++ b/.claude/skills/audit-cohesion/SKILL.md @@ -1,5 +1,6 @@ --- name: audit-cohesion +categories: [audit] description: Audit codebase for internal cohesion - how well components fit together and maintain consistent patterns. Distinct from audit-arch (which checks rule violations); this checks integration fitness and convergence. Use when user says "audit cohesion", "check cohesion", "cohesion audit", or "alignment check". hooks: PreToolUse: @@ -31,8 +32,8 @@ Audit the codebase for internal cohesion: how well components integrate and main **ALWAYS:** - Use subagents for parallel exploration (one per cohesion dimension) -- All output goes under `temp/audit-cohesion/` (create if needed) -- Final report: `temp/audit-cohesion/cohesion_audit_{YYYY-MM-DD_HHMMSS}.md` — always one file, never split +- All output goes under `{{AUTOSKILLIT_TEMP}}/audit-cohesion/` (create if needed) +- Final report: `{{AUTOSKILLIT_TEMP}}/audit-cohesion/cohesion_audit_{YYYY-MM-DD_HHMMSS}.md` — always one file, never split - Subagents must NOT create their own files — they return findings in their response text only - Score each dimension (STRONG, ADEQUATE, WEAK, FRACTURED) @@ -451,9 +452,9 @@ After all subagents return: ### Step 3: Write Report -Ensure `temp/audit-cohesion/` exists (`mkdir -p`). +Ensure `{{AUTOSKILLIT_TEMP}}/audit-cohesion/` exists (`mkdir -p`). -Write to `temp/audit-cohesion/cohesion_audit_{YYYY-MM-DD_HHMMSS}.md` — **always one file, never split**. +Write to `{{AUTOSKILLIT_TEMP}}/audit-cohesion/cohesion_audit_{YYYY-MM-DD_HHMMSS}.md` — **always one file, never split**. The report WILL be long. This is expected and correct — thoroughness over brevity. Do not reduce content to stay under any line count. @@ -513,6 +514,42 @@ Do NOT flag: --- +## Exception Whitelist + +### General Exceptions (GE) + +These exceptions apply to cohesion audit findings. Before reporting, verify the finding does not match any entry below. + +**GE-10** — Naming convention enforcement applies to exported/public symbols only. Module-private classes not in `__all__` are not naming violations. +*Source: [C4-C-1], [C4-C-2] April cohesion round.* + +**GE-11** — `public_name = _private_name` in `__init__.py` is a standard re-export idiom — not "logic in `__init__`." +*Source: [C1-E] April cohesion round.* + +**GE-12** — Modules with documented stdlib-only or early-boot constraints using bare `logging` are exempt from structured-logging conventions. +*Source: April cohesion round.* + +**GE-13** — Grep `tests/` for imports before claiming no test coverage. Absence of `test_.py` is not evidence of missing coverage. +*Source: cohesion round 1 contest batches.* + +**GE-15** — Documented optional/empty-when-skipped recipe context variables are not phantom. +*Source: [C7-3] April cohesion round.* + +### C10 File-Verification Rule + +Before claiming a documentation error, read the actual file at the cited path — don't rely on the CLAUDE.md ASCII tree representation. +*Source: [C10-D] April cohesion round.* + +### Project-Specific Exceptions (PS) + +**PS-3** — `test_check` in `server/tools_workspace.py` omits the `_require_enabled()` guard by design: it uses the dual-tag headless detection path and must be callable from both interactive and headless sessions. + +**PS-5** — CLAUDE.md findings tracked in #713. Suppress cohesion findings related to CLAUDE.md accuracy until #713 closes. + +**PS-6** — `remove_clone` string booleans (`"true"`/`"false"`) are a domain contract baked into recipe YAMLs; converting to Python `bool` would break recipe compatibility. + +--- + ## Score Guidelines **STRONG:** Components fit together cleanly. Patterns are consistent, interfaces are complete. No action needed. diff --git a/.claude/skills/audit-tests/SKILL.md b/.claude/skills/audit-tests/SKILL.md index e1a61ad3b3..0cf960c0d8 100644 --- a/.claude/skills/audit-tests/SKILL.md +++ b/.claude/skills/audit-tests/SKILL.md @@ -1,5 +1,6 @@ --- name: audit-tests +categories: [audit] description: Audit the test suite for useless tests, consolidation opportunities, over-mocking, weak assertions, placement/organization issues, xdist safety violations, and other test quality issues. Use when user says "audit tests", "audit test suite", "review tests", or "test quality check". Generates an improvement plan in temp/ with explanations for each proposed change. hooks: PreToolUse: @@ -64,7 +65,7 @@ Tests that span two modules should be placed in the directory of their primary c - Use subagents for parallel exploration - Read both the test AND the code it tests before judging - Provide file paths, line numbers, and an explanation for each finding -- Write the improvement plan to `temp/audit-tests/test_audit_{YYYY-MM-DD_HHMMSS}.md` +- Write the improvement plan to `{{AUTOSKILLIT_TEMP}}/audit-tests/test_audit_{YYYY-MM-DD_HHMMSS}.md` - Categorize findings by issue type and severity --- @@ -214,7 +215,7 @@ After subagents complete: ### Step 3: Generate Improvement Plan -Write a structured plan to: `temp/audit-tests/test_audit_{YYYY-MM-DD_HHMMSS}.md` +Write a structured plan to: `{{AUTOSKILLIT_TEMP}}/audit-tests/test_audit_{YYYY-MM-DD_HHMMSS}.md` Organize the plan into phases grouped by issue type. Each finding must include: - **File path and line range** diff --git a/.claude/skills/chart-course/SKILL.md b/.claude/skills/chart-course/SKILL.md new file mode 100644 index 0000000000..f05c928292 --- /dev/null +++ b/.claude/skills/chart-course/SKILL.md @@ -0,0 +1,520 @@ +--- +name: chart-course +description: Interactive strategic compass builder. Guides the user through mapping all possible project directions with progressive codebase analysis, web research, and architectural diagrams at every step. Produces a machine-readable compass document for downstream alignment tracking. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: chart-course] Charting strategic course...'" + once: true +--- + +# Chart Course — Interactive Strategic Compass Builder + +## When to Use + +- Starting a new project phase and mapping all possible directions +- Project has grown enough that strategic coherence needs explicit tracking +- Understanding how near-term work relates to long-term options +- Updating an existing compass after significant project changes +- Preparing for a planning session and need a current landscape assessment + +This is an **interactive** skill. The user provides vision and priorities; +the skill provides codebase analysis, external research, and visualization. +The compass is built collaboratively through conversation, not generated +autonomously. + +## Arguments + +``` +/chart-course {focus_or_question} [compass_path=] +``` + +- `{focus_or_question}` — Required. A broad strategic question or focus area. + Examples: "Map all possible directions for the research platform", + "What are our options for distributed compute?", + "Where should we invest for compliance readiness?" +- `compass_path=` — Optional. Path to an existing compass document. + When provided, the skill loads the existing compass as the starting point + and the conversation focuses on updating, adding, or retiring directions. + +### GitHub Issue Detection + +Scan ARGUMENTS for GitHub issue references (full URL, `owner/repo#N`, bare `#N`). +If detected, call `fetch_github_issue(issue_url, include_comments: true)` and +incorporate the issue content as additional strategic context. + +## Critical Constraints + +**NEVER:** +- Modify any source code files — this is a read-only analysis skill +- Create files outside `{{AUTOSKILLIT_TEMP}}/chart-course/` +- Dismiss directions the user raises — every direction gets honest assessment +- Use implementation difficulty as a reason to exclude a direction +- Include cost estimates or timelines — map what IS, not what it costs +- Skip diagrams — progressive visualization is the core value of this skill +- Generate the compass document without user review and approval +- Write the final compass to disk until the user confirms (plan-apply pattern) +- Proceed past a checkpoint without user response + +**ALWAYS:** +- Use `model: "sonnet"` for all Task tool subagent calls +- Initialize code-index via `set_project_path` before exploration (Phase 1) +- Ask the user before moving to the next phase +- Generate at least one diagram per direction explored +- Ground readiness assessments in actual file paths, protocols, and code patterns +- Include source URLs for all external research claims +- Invoke arch-lens and mermaid skills via the Skill tool (see Skill Loading Checklist) +- Emit output tokens as literal plain text at the end (no markdown formatting on token names) + +## Skill Loading Checklist + +When generating architectural diagrams at any point during the conversation: +- [ ] Determine which arch-lens best fits the aspect being visualized +- [ ] LOAD the corresponding `/autoskillit:arch-lens-*` via the Skill tool +- [ ] The arch-lens skill will LOAD `/autoskillit:mermaid` for styling +- [ ] Diagram uses ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Color legend table included +- [ ] Every new or proposed component is wired into the call chain + +If the Skill tool cannot invoke a sub-skill (disable-model-invocation or +unavailable), produce the diagram directly using mermaid syntax with the +standard classDef palette and note the fallback. + +For custom diagrams not covered by an arch-lens (timelines, dependency +graphs, comparison matrices), LOAD `/autoskillit:mermaid` directly via +the Skill tool and produce the diagram using its styling conventions. + +## Workflow + +The workflow is organized into phases. Each phase ends with a user +checkpoint. Do not proceed to the next phase until the user responds. + +--- + +### Phase 1: Codebase Survey (automated) + +#### Step 1.1: Code-Index Initialization + +``` +mcp__code-index__set_project_path(path="{PROJECT_ROOT}") +``` + +Fall back to native Glob/Grep if unavailable. + +#### Step 1.2: Load Existing Compass (if compass_path provided) + +If `compass_path` was provided: +1. Verify file exists with Glob +2. Read the document +3. Extract the `---compass-data---` YAML block +4. Parse existing directions — these become the baseline +5. Present to user: "Found existing compass with N directions. I'll + re-evaluate each against the current codebase." + +#### Step 1.3: Launch Parallel Exploration Subagents + +Launch ALL concurrently in a single message. Every subagent uses `model: "sonnet"`. + +**Subagent A: Architecture & Extension Points** +Explore protocol definitions, plugin points, layering (L0/L1/L2/L3), +TODO/PLANNED/FIXME comments, stub implementations, and configuration +points. Return: extension points with file paths and what capability +each is designed to support. + +**Subagent B: Current Capability Inventory** +Catalog all MCP tools, skills (by tier and category), recipes, hooks, +CLI commands, and run_python callables. Note dependencies between them. +Return: structured capability list. + +**Subagent C: Growth Limitations & Technical Debt** +Find hardcoded values, platform assumptions, scaling bottlenecks, tight +coupling, missing abstractions, and test gaps. Return: categorized +limitations with which areas of growth they would affect. + +**Subagent D: External Landscape Research (Web Search)** +Research the domain indicated by `focus_or_question`: competitors, +adjacent tools, industry trends, emerging standards, regulations. +Return: landscape summary with source URLs. + +**Subagent E: Dependency & Coupling Map** +Map import graph between top-level packages, co-change coupling from +git history, cross-layer violations, circular dependencies. +Return: dependency map with coupling scores. + +**Subagent F: Existing Strategic Context** +Search `{{AUTOSKILLIT_TEMP}}/` and `docs/` for existing strategy docs, +research reports, roadmaps. Read last 50 git commits for thematic +patterns. Check GitHub issues for strategic labels. +Return: summary of existing context and themes. + +**Additional subagents** may be launched for any other dimensions the +focus question or codebase warrants. The above are the mandatory minimum. + +#### Step 1.4: Present Initial Landscape + +After all subagents complete, synthesize findings into a concise briefing: + +1. **Architecture snapshot** — key layers, extension points, what's flexible + vs. rigid. Generate a **C4 Container diagram** using: + ``` + LOAD /autoskillit:arch-lens-c4-container via Skill tool + ``` + +2. **Capability map** — what the project can do today + +3. **Growth edges** — where the architecture is designed for extension + vs. where it would resist change. Generate a **Module Dependency diagram**: + ``` + LOAD /autoskillit:arch-lens-module-dependency via Skill tool + ``` + +4. **External landscape highlights** — what others are doing, key trends + +5. **Existing strategic context** — what prior work tells us about direction + +#### Checkpoint 1 + +Present the landscape briefing with both diagrams and ask: + +> "Here's where the project stands architecturally. What directions are +> you thinking about? What's your vision for where this could go? +> I'll analyze each direction you describe against the codebase." + +Wait for user response before proceeding. + +--- + +### Phase 2: Direction Exploration (interactive loop) + +This phase repeats for each direction the user describes. The user may +describe one direction at a time or several at once. + +#### Step 2.1: Capture the Direction + +From the user's description, extract: +- A short name for the direction +- What it would entail (capability, architecture change, domain expansion, etc.) +- Any stated dependencies or prerequisites + +#### Step 2.2: Analyze Fit + +For each direction, launch targeted analysis: + +**Subagent: Codebase Fit Analysis** (`model: "sonnet"`) +- Where in the architecture would this connect? +- What existing protocols, abstractions, or extension points support it? +- What would need to change to accommodate it? +- What existing capabilities does it build on? +- What would it conflict with or make harder? + +**Subagent: External Research** (`model: "sonnet"`, web search) +- How do other projects in this space handle this? +- Are there standards, libraries, or patterns to adopt? +- What pitfalls have others encountered? + +Launch additional subagents as needed for any other aspects the direction +requires — regulatory implications, performance profiling, integration +patterns, etc. + +#### Step 2.3: Generate Direction Diagram + +Select the most appropriate arch-lens for this direction and LOAD it: + +| Direction type | Arch-lens to use | +|----------------|------------------| +| New execution path or workflow | `arch-lens-process-flow` | +| Data pipeline or storage | `arch-lens-data-lineage` | +| New module or component | `arch-lens-c4-container` | +| API or integration boundary | `arch-lens-security` | +| Parallel execution / scaling | `arch-lens-concurrency` | +| Infrastructure / deployment | `arch-lens-deployment` | +| State management / lifecycle | `arch-lens-state-lifecycle` | +| Error handling / resilience | `arch-lens-error-resilience` | +| Developer tooling / CI | `arch-lens-development` | +| Operational / monitoring | `arch-lens-operational` | +| Data access patterns | `arch-lens-repository-access` | +| Cross-component scenarios | `arch-lens-scenarios` | +| Coupling / dependency | `arch-lens-module-dependency` | + +Mark proposed/new components distinctly in the diagram (use the `newComponent` +classDef from the mermaid skill palette and the `★` symbol). + +If the direction involves experimental or research aspects, also consider +loading an appropriate exp-lens for dimensional analysis. + +#### Step 2.4: Present Direction Analysis + +Present to the user: +1. **Fit assessment** — how this direction connects to existing architecture +2. **Readiness score** — ready / partial / planned / concept, with evidence +3. **Architecture diagram** — showing where this plugs in (new components highlighted) +4. **External landscape** — what others do, relevant standards +5. **Dependencies** — what must exist first +6. **Tensions** — what this would make harder or conflict with + +#### Step 2.5: Refine with User + +Ask: + +> "Here's how [direction name] would fit. Does this match your thinking? +> Any aspects I should dig deeper into? Or shall we explore the next direction?" + +The user may: +- Refine the direction (re-analyze with updated description) +- Ask to dig deeper into a specific aspect (launch focused subagents) +- Ask for additional diagrams from different perspectives +- Move to the next direction +- Go back and revise a previous direction + +Adapt to whatever the user needs. Repeat Steps 2.1–2.5 for each new direction. + +#### Checkpoint 2 + +After the user has described all directions they want to explore (or says +they're ready to proceed), ask: + +> "We've explored N directions so far. Ready for me to map the +> relationships between them — what enables what, what conflicts, +> and where the strategic fork points are?" + +Wait for user response. + +--- + +### Phase 3: Relationship Mapping (automated with user review) + +#### Step 3.1: Build Direction Catalog + +From all explored directions, compile the full catalog. For each direction: + +| Field | Source | +|-------|--------| +| `id` | Assign `D{NNN}` IDs (preserve existing IDs in update mode) | +| `name` | From user description (confirmed in Phase 2) | +| `category` | One of: `architecture`, `capability`, `domain-expansion`, `compliance`, `performance`, `developer-experience`, `integration`, `infrastructure` | +| `description` | 2-3 sentences from Phase 2 analysis | +| `readiness` | `ready` / `partial` / `planned` / `concept` — from Phase 2 fit assessment | +| `readiness_evidence` | Specific file paths and code patterns from Phase 2 | +| `dependencies` | Direction IDs that must come first | +| `enables` | Direction IDs that become easier after this | +| `conflicts` | Direction IDs that become harder after this | +| `signals` | Files, grep patterns, modules relevant to this direction | +| `priority` | `high` / `medium` / `low` / `exploratory` — ask user if not clear | + +#### Step 3.2: Map Dependencies and Conflicts + +For each pair of directions, assess: +- Does pursuing A make B easier? (enables) +- Does pursuing A require B first? (depends-on) +- Does pursuing A make B harder? (conflicts) + +Use codebase evidence — shared protocols, module boundaries, test +infrastructure, configuration coupling. + +#### Step 3.3: Generate Path Dependency Graph + +LOAD `/autoskillit:mermaid` via the Skill tool and produce a custom +flowchart showing all directions and their relationships: + +- **Nodes** = directions, colored by readiness (ready=green, partial=yellow, + planned=blue, concept=gray) +- **Green solid edges** = enables +- **Blue dashed edges** = depends-on +- **Red dotted edges** = conflicts +- Label each node with ID + short name + +Annotate the diagram with: +- **Bottleneck directions** — high fan-out of enables edges (mark with `★`) +- **Fork points** — conflicting direction pairs (mark with `⚡`) +- **Clusters** — mutually-reinforcing groups (visual grouping via subgraph) + +#### Step 3.4: Generate Timeline / Sequencing Diagram + +LOAD `/autoskillit:mermaid` via the Skill tool and produce a Gantt-style +or swim-lane diagram showing a natural sequencing of directions based on +dependency order: + +- Foundations first (directions others depend on) +- Independent directions shown in parallel +- Late-stage directions that depend on many prerequisites shown last +- Fork points shown as decision nodes + +This is NOT a timeline with dates — it is a dependency-ordered sequence +showing what COULD come before what. + +#### Step 3.5: Present Relationship Map + +Present to the user: +1. **Direction catalog table** — all directions with readiness and priority +2. **Path dependency graph** — mermaid diagram +3. **Sequencing diagram** — dependency-ordered view +4. **Bottleneck analysis** — which directions unlock the most others +5. **Fork points** — where strategic choices must be made +6. **Cluster analysis** — groups of mutually-reinforcing directions + +#### Checkpoint 3 + +Ask: + +> "Here's how all the directions relate to each other. Do these +> relationships look right? Any dependencies or conflicts I missed? +> Any priorities you want to adjust before I assemble the compass?" + +Wait for user to review and confirm or request adjustments. +If adjustments needed, revise and re-present. + +--- + +### Phase 4: Current Trajectory Assessment + +#### Step 4.1: Analyze Recent Work + +Using git log and any available PR/issue data: +1. Read last 30-50 commits +2. Map commits to directions (which directions does recent work advance?) +3. Identify drift — work that moves away from stated priorities +4. Identify any inadvertent path narrowing + +#### Step 4.2: Generate Trajectory Overlay + +LOAD `/autoskillit:mermaid` via the Skill tool and produce a variant of +the path dependency graph with trajectory annotations: + +- Directions being actively advanced: bold border +- Directions with no recent movement: dashed border +- Directions being drifted from: red highlight + +#### Step 4.3: Present Trajectory + +Present the trajectory assessment with the annotated diagram and a brief +narrative about where the project is currently headed vs. where the +compass says it could go. + +#### Checkpoint 4 + +Ask: + +> "This is where recent work has been heading. Ready for me to +> assemble the full compass document?" + +--- + +### Phase 5: Compass Assembly (plan-apply pattern) + +#### Step 5.1: Draft the Compass + +Assemble the full compass document in memory with these sections: + +1. **Strategic Focus** — the question that drove this compass +2. **Executive Summary** — 3-5 bullets on current state + trajectory +3. **Direction Catalog** — full table + detailed per-direction subsections +4. **Path Dependency Graph** — mermaid diagram from Phase 3 +5. **Sequencing Diagram** — from Phase 3 +6. **Trajectory Overlay** — from Phase 4 +7. **Cluster Analysis** — mutually-reinforcing direction groups +8. **Fork Points** — strategic choices requiring decisions +9. **Bottleneck Directions** — high-leverage unlock points +10. **Current Trajectory** — where recent work is heading +11. **Cannot Assess** — minimum 2 directions where evidence was insufficient +12. **Methodology** — tools used, limitations, caveats + +Plus the machine-readable compass block at the very end: + +``` +---compass-data--- +version: 1 +generated: "{ISO-8601 timestamp}" +focus: "{focus_or_question}" +project_root: "{absolute project root path}" +directions: + - id: D001 + name: "Direction Name" + category: architecture + readiness: partial + readiness_evidence: + - "src/path/file.py — ProtocolName exists but lacks implementations" + dependencies: [] + enables: [D003, D007] + conflicts: [D012] + signals: + files: + - "src/relevant/module/" + - "src/specific_file.py" + patterns: + - "GhostKitchenProvider" + - "run_on_eks" + modules: + - "execution" + - "server" + priority: high + ... +---end-compass-data--- +``` + +#### Step 5.2: Present for Approval + +Show the user a summary of what will be written: +- File path: `{{AUTOSKILLIT_TEMP}}/chart-course/compass_{topic}_{YYYY-MM-DD_HHMMSS}.md` +- Direction count with readiness distribution +- Section outline +- The compass-data block (so user can verify direction metadata) + +Ask: + +> "Here's what the compass document will contain. Write it?" + +#### Step 5.3: Write on Confirmation + +Only on user confirmation, write the compass document to disk. + +If the user requests changes, revise and re-present Step 5.2. + +If the user declines, do not write. Inform the user that all diagrams +produced during the conversation are still available in their context. + +--- + +### Phase 6: Finalization + +#### Step 6.1: Terminal Summary + +Print: +- Compass path (absolute) +- Direction count and readiness distribution +- Top 3 bottleneck directions +- Any fork points identified +- Reminder: "Use `/check-bearing compass_path=` + to check branch alignment against this compass." + +#### Step 6.2: Output Tokens + +Emit as the absolute last lines: + +``` +compass_path = {absolute_path_to_compass_document} +direction_count = {integer} +ready_count = {integer} +%%ORDER_UP%% +``` + +**Token rules:** Plain text only. No markdown bold, italic, or backtick +formatting on token names. The pipeline adjudicator uses regex matching +and decoration breaks it. + +## Output + +| Token | Value | Used By | +|-------|-------|---------| +| `compass_path` | Absolute path to the compass document | `check-bearing`, recipe capture | +| `direction_count` | Total directions identified | Informational | +| `ready_count` | Directions with readiness = ready | Informational | + +## Related Skills + +- `/check-bearing` — Assess branch alignment against this compass +- `/autoskillit:investigate` — Deep investigation of specific technical questions +- `/autoskillit:scope` — Scope a specific research question from the compass +- `/autoskillit:review-approach` — Research approaches for specific directions +- `/autoskillit:make-plan` — Plan implementation of a chosen direction diff --git a/.claude/skills/check-bearing/SKILL.md b/.claude/skills/check-bearing/SKILL.md new file mode 100644 index 0000000000..7ccfa947c8 --- /dev/null +++ b/.claude/skills/check-bearing/SKILL.md @@ -0,0 +1,502 @@ +--- +name: check-bearing +description: Assess a branch or PR's alignment with the strategic compass. Evaluates whether changes advance, drift from, or close off strategic directions. Produces an alignment dashboard with per-direction impact analysis and a verdict. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: check-bearing] Checking strategic alignment...'" + once: true +--- + +# Check Bearing — Strategic Alignment Review + +## When to Use + +- Before merging a branch — verify it does not close off strategic paths +- During PR review — understand how changes affect long-term options +- After a sprint — assess cumulative alignment of recent work +- When evaluating whether to pursue a particular implementation approach +- As a gate in the implementation or merge-prs recipe + +## Arguments + +``` +/check-bearing {target} compass_path= +``` + +- `{target}` — Required. One of: + - A branch name (e.g., `feature/add-provenance`) + - A PR number (e.g., `#142`) + - A PR URL (e.g., `https://github.com/owner/repo/pull/142`) + - `HEAD` — assess uncommitted + staged changes on the current branch + - `--since ` — assess all changes since divergence from that branch + +- `compass_path=` — Required. Absolute or relative path to a compass + document produced by `/chart-course`. The file must contain a + `---compass-data---` ... `---end-compass-data---` block. + +### Target Resolution + +**Branch name:** +- Detect base branch via `git merge-base` against `main` and `integration` +- Use the closer base (fewer commits ahead) +- Diff: `git diff {merge_base}...{branch}` + +**PR number or URL:** +- Extract PR metadata via `gh pr view {number} --json baseRefName,title,body,files` +- Diff: `gh pr diff {number}` + +**HEAD:** +- Diff: `git diff` (unstaged) + `git diff --cached` (staged) + +**--since :** +- Diff: `git diff {branch}...HEAD` +- Log: `git log --oneline {branch}...HEAD` + +## Critical Constraints + +**NEVER:** +- Modify any source code files — this is a read-only analysis skill +- Create files outside `{{AUTOSKILLIT_TEMP}}/check-bearing/` +- Assess implementation quality — that is audit-impl's domain +- Recommend specific code changes — report alignment facts, not fixes +- Skip directions because they seem irrelevant — assess ALL directions in the compass +- Mark a direction as CLOSES without specific architectural evidence showing + why the change creates a barrier that would require significant rework to undo +- Use the compass priority field to suppress findings — all closures matter + regardless of priority +- Conflate "this change doesn't advance direction X" with "this change harms + direction X" — most changes are genuinely NEUTRAL to most directions + +**ALWAYS:** +- Use `model: "sonnet"` for all Task tool subagent calls +- Initialize code-index via `set_project_path` before exploration (Step 0.5) +- Parse the `---compass-data---` block before launching any analysis subagents +- Provide specific file-level evidence for every non-NEUTRAL assessment +- Flag stale compass data (>30 days old) with a prominent warning +- Distinguish between intentional advancement and incidental impact +- Emit output tokens as literal plain text (no markdown bold/italic formatting on token names) +- Include a confidence qualifier (HIGH / MEDIUM / LOW) on each direction assessment +- Default to NEUTRAL — the burden of proof is on non-neutral classification + +## Workflow + +### Step 0: Parse Arguments + +Extract `target` and `compass_path` from ARGUMENTS. + +For `compass_path`: scan tokens for `compass_path=`. +For `target`: everything in ARGUMENTS that is not the `compass_path=` parameter. + +Verify `compass_path` exists using Glob. If not found: +``` +verdict = ERROR +%%ORDER_UP%% +``` +Exit immediately. + +Determine target type: +- Starts with `#` or contains `/pull/` → PR mode +- Equals `HEAD` → working tree mode +- Starts with `--since` → since mode +- Otherwise → branch mode + +### Step 0.5: Code-Index Initialization + +``` +mcp__code-index__set_project_path(path="{PROJECT_ROOT}") +``` + +If the code-index MCP server is unavailable, fall back to native Glob/Grep. + +### Step 1: Load and Parse Compass + +1. Read the compass document at `compass_path` +2. Locate the `---compass-data---` block +3. Parse the YAML content between `---compass-data---` and `---end-compass-data---` +4. Extract all directions into a structured catalog +5. Check the `generated` timestamp: + - If >30 days old, set `stale_warning = true` + - If >90 days old, set `stale_warning = critical` +6. Count total directions, group by category and priority + +If the compass-data block is missing or unparseable: +``` +verdict = ERROR +%%ORDER_UP%% +``` +Exit immediately. + +### Step 2: Analyze Branch Changes + +Execute the appropriate commands based on target type determined in Step 0. + +Capture these artifacts for subagent distribution: +- `changed_files` — list of all modified, added, and deleted file paths +- `full_diff` — complete unified diff output +- `diff_stats` — `git diff --stat` summary (files changed, insertions, deletions) +- `commit_messages` — `git log --oneline` output (empty for HEAD mode) +- `pr_metadata` — title, body, labels (PR mode only) + +If the diff is empty (no changes), emit: +``` +verdict = ALIGNED +alignment_score = 0.0 +path_openness = 1.0 +dashboard_path = (none — no changes to assess) +%%ORDER_UP%% +``` +Exit immediately. + +### Step 3: Pre-Filter Directions by Signal Overlap + +Before launching expensive per-direction subagents, perform a quick signal match +to avoid spawning 30+ subagents for a 10-line change. + +For each direction in the compass catalog: + +1. **File signal match:** Do any `signals.files` entries appear as prefixes of + paths in `changed_files`? (Use path prefix matching, not exact match — + `src/autoskillit/execution/` matches `src/autoskillit/execution/headless.py`) + +2. **Pattern signal match:** Do any `signals.patterns` appear anywhere in `full_diff`? + (Plain substring search, case-sensitive) + +3. **Module signal match:** Do any `signals.modules` appear as path components in + `changed_files`? (e.g., module `execution` matches path `src/autoskillit/execution/foo.py`) + +Classify each direction: +- **SIGNAL_HIT** — at least one signal matched. Requires full subagent analysis. +- **NO_SIGNAL** — zero signals matched. Gets lightweight bulk assessment only. + +### Step 4: Launch Parallel Direction Assessment Subagents + +#### 4a: Full Assessment (SIGNAL_HIT directions) + +Launch one subagent per SIGNAL_HIT direction. Cap at 8 concurrent subagents; +if more than 8 SIGNAL_HIT directions, batch into waves of 8. + +Each subagent receives: +- The direction's full metadata (id, name, category, description, readiness, + readiness_evidence, dependencies, enables, conflicts, signals) +- The portions of `full_diff` for files matching the direction's signals +- The full `diff_stats` for overall context +- The `commit_messages` for intent signals + +Each subagent evaluates this rubric and returns structured JSON: + +```json +{ + "direction_id": "D001", + "impact": "ADVANCES | SUPPORTS | NEUTRAL | DRIFT | CLOSES", + "confidence": "HIGH | MEDIUM | LOW", + "score": 0, + "evidence": [ + "src/path/file.py:42 — adds FooProtocol that direction D001 requires", + "src/path/other.py:deleted — removes BarAdapter that D001 depends on" + ], + "explanation": "One sentence explaining why this impact was chosen", + "reversibility": "easy | moderate | hard", + "intentional": true +} +``` + +**Impact definitions (subagents must follow these strictly):** + +| Impact | Score | Meaning | Evidence Required | +|--------|-------|---------|-------------------| +| ADVANCES | +2 | Changes directly implement or build toward this direction | Specific new code, protocols, or infrastructure that the direction needs | +| SUPPORTS | +1 | Changes create favorable conditions without targeting this direction | Refactoring, abstractions, or cleanup that happens to help | +| NEUTRAL | 0 | No meaningful positive or negative impact | Default — absence of evidence for other categories | +| DRIFT | -1 | Changes make this direction slightly harder or less natural | New coupling, hardcoded assumptions, or patterns that work against the direction | +| CLOSES | -2 | Changes create barriers requiring significant rework to pursue this direction | Concrete architectural decisions that conflict (not just "didn't advance it") | + +**Confidence definitions:** +- HIGH — clear, direct evidence in the diff for the classification +- MEDIUM — indirect evidence or reasonable inference from the changes +- LOW — assessment based on broader implications, not specific diff lines + +#### 4b: Bulk Assessment (NO_SIGNAL directions) + +Group NO_SIGNAL directions into batches of 5. Launch one subagent per batch. + +Each bulk subagent receives: +- The 5 directions' metadata (id, name, description, signals) +- The `diff_stats` summary (NOT the full diff — these directions had no signal overlap) +- The `commit_messages` + +Most NO_SIGNAL directions should classify as NEUTRAL. The subagent's job is to +catch cases where the signal list was incomplete — if the diff clearly impacts +a direction despite no signal match, flag it with confidence: LOW. + +Returns the same JSON structure for each direction in the batch. + +Launch additional subagents as needed for any other aspects the diff +warrants — security implications, API surface changes, configuration +coupling, etc. The above are the mandatory minimum. + +### Step 5: Cross-Cutting Path Closure Analysis + +After all Step 4 subagents complete, launch one additional subagent that +reviews ALL non-NEUTRAL findings holistically. This subagent looks for: + +**Cascade effects:** +Does DRIFT on direction A combined with DRIFT on direction B effectively +CLOSE direction C (which depends on both A and B)? + +For each potential cascade: +```json +{ + "direction_id": "D007", + "caused_by": ["D001", "D003"], + "explanation": "D007 depends on both D001 and D003; drift on both compounds" +} +``` + +**Irreversibility assessment:** +Are any changes in the diff particularly hard to undo? +- Public API surface changes (consumers may depend on them) +- Database schema or data format changes +- Removed abstractions that were protecting flexibility +- New concrete dependencies that replace protocol-based injection + +```json +{ + "file": "src/path/file.py", + "line": 42, + "concern": "Replaces SubprocessRunner protocol with direct subprocess call", + "affects_directions": ["D005", "D011"] +} +``` + +**New coupling introduced:** +Does the diff create new import relationships or dependencies between +modules that were previously independent? + +```json +{ + "from_module": "recipe", + "to_module": "execution", + "concern": "Direct import bypasses pipeline layer", + "affects_directions": ["D008"] +} +``` + +### Step 6: Compute Alignment Scores + +Aggregate all subagent results into project-level metrics. + +**Per-direction impact scores** — from Step 4 subagent assessments: +- ADVANCES = +2, SUPPORTS = +1, NEUTRAL = 0, DRIFT = -1, CLOSES = -2 + +**Priority weights:** +- high = 3, medium = 2, low = 1, exploratory = 0.5 + +**Weighted alignment score:** +``` +alignment_score = sum(score_i * weight_i) / sum(2 * weight_i) +``` +Range: -1.0 (every direction at max negative impact) to +1.0 (every direction +maximally advanced). Most real changes will be near 0.0. + +**Path openness:** +``` +path_openness = count(directions NOT scored CLOSES) / total_directions +``` +Range: 0.0 to 1.0. Measures what fraction of strategic paths remain unblocked. + +**Critical closures:** +- Any direction with priority = high AND impact = CLOSES +- Any cascade closure from Step 5 affecting a high-priority direction + +### Step 7: Determine Verdict + +Apply this logic strictly: + +``` +IF any critical_closures exist: + verdict = CONFLICT + +ELSE IF alignment_score < -0.3 + OR path_openness < 0.70: + verdict = DRIFT + +ELSE IF alignment_score >= 0.0 + AND path_openness >= 0.90: + verdict = ALIGNED + +ELSE: + verdict = DRIFT +``` + +**Verdict definitions:** +- **ALIGNED** — Changes advance or are neutral to strategic directions. No paths + closed. The project maintains or improves its strategic optionality. +- **DRIFT** — Changes push away from some directions without closing them off + entirely. Not blocking, but worth awareness. May indicate a need for + compensating work in a future branch. +- **CONFLICT** — Changes close off high-priority strategic paths. Merging would + reduce strategic optionality in ways that are hard to reverse. Review and + discuss before proceeding. + +**CONFLICT does not mean "do not merge."** It means "merge with eyes open." +Some path closures are intentional strategic decisions. The skill reports facts; +humans decide. + +### Step 8: Write Alignment Dashboard + +Write to: +`{{AUTOSKILLIT_TEMP}}/check-bearing/alignment_{target_slug}_{YYYY-MM-DD_HHMMSS}.md` + +where `{target_slug}` is a snake_case slug derived from the target +(branch name, PR number, or "head"). Max 40 chars. + +**Required sections in order:** + +#### 1. Target Summary +Branch/PR name, base branch, commit count, files changed, lines added/removed. +If PR mode, include PR title and labels. + +#### 2. Compass Reference +Path to compass document, generated date, total directions in compass. +If `stale_warning` is set, include a prominent warning: +- `>30 days`: "Compass is N days old. Consider running chart-course to refresh." +- `>90 days`: "STALE COMPASS: N days old. Results may not reflect current architecture." + +#### 3. Verdict +One of `ALIGNED` / `DRIFT` / `CONFLICT` with a one-sentence rationale +grounded in the specific findings. + +#### 4. Alignment Scorecard + +| Metric | Value | +|--------|-------| +| Alignment Score | {-1.0 to 1.0} | +| Path Openness | {0.0 to 1.0} ({X}/{Y} directions open) | +| Directions Advanced | {count} | +| Directions Drifted | {count} | +| Directions Closed | {count} | +| Critical Closures | {count} | + +#### 5. Direction Impact Table +All directions sorted by absolute impact score (highest impact first): + +| ID | Name | Priority | Impact | Score | Confidence | Evidence Summary | +|----|------|----------|--------|-------|------------|------------------| + +NEUTRAL directions may be collapsed into a summary count rather than +listed individually if there are more than 15. + +#### 6. Path Closure Warnings +Detailed analysis of any CLOSES findings or cascade closures. +For each closure: +- Direction name and priority +- Specific evidence from the diff +- Reversibility assessment +- Which other directions are affected + +If no closures, state "No path closures detected." + +#### 7. Advancement Highlights +Directions being actively advanced by these changes. +For each advancement: +- What specifically in the diff advances this direction +- Whether the advancement appears intentional or incidental + +#### 8. Drift Concerns +Directions being drifted from. For each: +- What in the diff causes drift +- Reversibility (easy/moderate/hard) +- Whether compensating work in a future branch could restore alignment + +#### 9. Cross-Cutting Analysis +From Step 5: cascade effects, irreversibility concerns, new coupling. +If none, state "No cross-cutting concerns identified." + +#### 10. Recommendations +Strategic awareness items — NOT code change suggestions. Examples: +- "Direction D005 (distributed compute) is drifting. If still a priority, + consider a follow-up branch that restores the SubprocessRunner protocol." +- "This branch intentionally advances D001 at the cost of D012. Ensure + this trade-off is an explicit decision." + +#### 11. Machine-Readable Alignment Block + +This block MUST appear at the very end of the document: + +``` +---alignment-data--- +version: 1 +target: "{target}" +compass_path: "{compass_path}" +compass_generated: "{ISO-8601 from compass}" +generated: "{ISO-8601 now}" +verdict: ALIGNED +alignment_score: 0.42 +path_openness: 0.95 +direction_count: 28 +impacts: + - id: D001 + impact: ADVANCES + score: 2 + confidence: HIGH + - id: D002 + impact: NEUTRAL + score: 0 + confidence: HIGH + - id: D003 + impact: DRIFT + score: -1 + confidence: MEDIUM +critical_closures: [] +cascade_closures: [] +---end-alignment-data--- +``` + +### Step 9: Terminal Summary and Output Tokens + +Print a brief terminal summary: + +``` +=== Strategic Alignment: {target} === +Verdict: {ALIGNED|DRIFT|CONFLICT} +Alignment Score: {score} | Path Openness: {openness} + +Advances: D001 (Provenance Layer), D003 (Metrics Contract) +Drift: D007 (Ghost Kitchens) — reversibility: easy +Closures: (none) + +Dashboard: {path} +``` + +Then emit the output tokens as the absolute last lines: + +``` +verdict = {ALIGNED|DRIFT|CONFLICT} +alignment_score = {float} +path_openness = {float} +dashboard_path = {absolute_path} +%%ORDER_UP%% +``` + +**Token rules:** Plain text only. No markdown bold, italic, or backtick +formatting on token names. The pipeline adjudicator uses regex matching +and decoration breaks it. + +## Output + +| Token | Value | Recipe Routing | +|-------|-------|----------------| +| `verdict` | `ALIGNED`, `DRIFT`, or `CONFLICT` | `on_result: field: verdict` matches exact string | +| `alignment_score` | Float from -1.0 to 1.0 | Available via `${{ context.alignment_score }}` | +| `path_openness` | Float from 0.0 to 1.0 | Available via `${{ context.path_openness }}` | +| `dashboard_path` | Absolute path to alignment dashboard | Available via `${{ context.dashboard_path }}` | + +## Related Skills + +- `/chart-course` — Build or update the strategic compass this skill reads +- `/autoskillit:review-pr` — Code quality review (complementary — quality vs. alignment) +- `/autoskillit:audit-impl` — Plan compliance audit (complementary — plan vs. strategy) +- `/autoskillit:review-design` — Experiment design review (complementary — design validity vs. strategic fit) diff --git a/.claude/skills/promote-to-main/SKILL.md b/.claude/skills/promote-to-main/SKILL.md index 4948d8890d..09109af767 100644 --- a/.claude/skills/promote-to-main/SKILL.md +++ b/.claude/skills/promote-to-main/SKILL.md @@ -114,7 +114,7 @@ from autoskillit.pipeline.tokens import DefaultTokenLog from autoskillit.pipeline.telemetry_fmt import TelemetryFormatter from autoskillit.execution.session_log import resolve_log_dir -cfg_path = pathlib.Path(".autoskillit") / "temp" / ".autoskillit_hook_config.json" +cfg_path = pathlib.Path(".autoskillit") / "temp" / ".hook_config.json" kitchen_id = "" if cfg_path.exists(): _cfg = json.loads(cfg_path.read_text()) diff --git a/.claude/skills/validate-audit/SKILL.md b/.claude/skills/validate-audit/SKILL.md new file mode 100644 index 0000000000..10f1c6b35a --- /dev/null +++ b/.claude/skills/validate-audit/SKILL.md @@ -0,0 +1,297 @@ +--- +name: validate-audit +categories: [audit] +description: Validate audit findings from audit-arch, audit-tests, or audit-cohesion against actual code, git history, and design intent using 9–10 parallel subagents. Removes contested findings, documents exceptions, adjusts severities. Use when user says "validate audit", "validate findings", "validate report", or "check audit results". +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: validate-audit] Validating audit findings against code...'" + once: true +--- + +# Validate Audit Findings Skill + +Validate audit findings from `audit-arch`, `audit-tests`, or `audit-cohesion` against actual +code, git history, and design intent using 9–10 parallel subagents. Contested findings are +separated into their own file. The validated report carries a `validated: true` marker to +signal downstream processing. + +## When to Use + +- User says "validate audit", "validate findings", "validate report", "check audit results" +- After running `audit-arch`, `audit-tests`, or `audit-cohesion` to filter noise before acting + +## Arguments + +``` +{audit_report_path} +``` + +- `audit_report_path` — absolute path to an audit report produced by `audit-arch`, + `audit-tests`, or `audit-cohesion`. If omitted, use the most recent file under + `{{AUTOSKILLIT_TEMP}}/audit-arch/`, `{{AUTOSKILLIT_TEMP}}/audit-tests/`, or + `{{AUTOSKILLIT_TEMP}}/audit-cohesion/` (most recent mtime wins across all three). + If no files exist under any of these directories, print an error message and exit + with a non-zero status. + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Create files outside `{{AUTOSKILLIT_TEMP}}/validate-audit/` +- Issue subagent Task calls sequentially — ALL must be in a single parallel message +- Write output files before synthesizing ALL subagent results +- Subagents must NOT create their own files — they return findings in response text only + +**ALWAYS:** +- Use `model: "sonnet"` when spawning all subagents via the Task tool +- Issue all Task calls in a single message to maximize parallelism +- Write `validated: true` as the **first line** of the validated report file +- Respect interactive vs headless mode for the approval step (Step 6) + +## Finding Verdicts + +| Verdict | Meaning | Action | +|---------|---------|--------| +| **VALID** | Finding confirmed by code evidence | Include as-is in validated report | +| **VALID BUT EXCEPTION WARRANTED** | Real issue; documented constraint applies | Include with exception note | +| **CONTESTED** | Factually wrong or counterproductive | Exclude from report; write to contested file | + +--- + +## Known Project Exceptions + +Before assigning a final verdict, code validation agents MUST consult this table. A finding that matches a Known Project Exception receives verdict **VALID BUT EXCEPTION WARRANTED** with the matching PS ID as the exception note. + +| ID | Exception | Rationale | +|----|-----------|-----------| +| PS-1 | `smoke_utils.py` at package root | Stable callable-path API for recipe YAMLs | +| PS-2 | `hook_registry.py` at package root | stdlib-only constraint on `hooks/`; commit `ee83681d` | +| PS-3 | `test_check` omits `_require_enabled()` | Dual-tag headless design | +| PS-4 | `_llm_triage.py` at package root | Circular import constraint | +| PS-5 | CLAUDE.md findings tracked in #713 | Suppress until #713 closes | +| PS-6 | `remove_clone` string booleans | Domain contract | +| PS-7 | `SkillResolver` naming | No Protocol to be "Default" of | +| PS-8 | L3 `server/`/`cli/` exclusion from REQ-IMP-001 | IL-005/IL-006 compensate | + +--- + +## Workflow + +### Step 0 — Code-Index Initialization + +Call `set_project_path` with the repo root: + +``` +mcp__code-index__set_project_path(path="{PROJECT_ROOT}") +``` + +Use project-relative paths in all code-index queries (e.g., `src/autoskillit/pipeline/`). +Fall back to native Grep/Glob if the code-index server is unavailable. + +### Step 1 — Detect Audit Format and Parse Findings + +Read the audit report file. Detect its source by examining the document title or preamble: + +- **audit-arch**: Title contains "Architectural Audit" or findings reference "Principle P{N}" +- **audit-tests**: Title contains "Test Suite Audit" or findings reference issue categories +- **audit-cohesion**: Title contains "Cohesion Audit" or findings reference "Dimension C{N}" + +If none of the three patterns match, print: +`"Error: unrecognized audit report format — expected title 'Architectural Audit', 'Test Suite Audit', or 'Cohesion Audit'. Aborting."` +and exit with a non-zero status. + +For each finding, extract: +- **ID** — principle/category/dimension label (e.g., P3, Category 1, C5) or a short slug +- **Text** — the full finding description +- **Severity** — CRITICAL / HIGH / MEDIUM / LOW (arch, tests) or + STRONG/ADEQUATE/WEAK/FRACTURED (cohesion) +- **Location** — `file:line` references, if present +- **Category** — the principle, issue category, or dimension label + +Collect all findings into a flat list. Record the source audit skill (`arch`, `tests`, or +`cohesion`) for use in output filenames. + +### Step 2 — Group into Thematic Batches + +Cluster findings by **code area**: inspect `file:line` references in each finding and group +by the top-level package touched (e.g., `pipeline/`, `execution/`, `server/`, `core/`, +`recipe/`, `cli/`, `workspace/`). + +- Target **8–9 code-area batches** for code validation agents. +- Findings without file references: place in a "cross-cutting" batch. +- Fewer than 8 distinct areas: assign each area its own batch; use however many batches are available. +- More than 9 distinct areas: merge smallest clusters until ≤ 9 groups remain. +- The 10th slot is reserved for the history research agent (runs against ALL findings). + +### Step 3 — Launch Parallel Subagents (SINGLE MESSAGE) + +**Issue ALL Task calls in a single message.** Do not output any prose between tool calls. + +Spawn the following agents simultaneously using `model: "sonnet"`: + +**Code Validation Agents (8–9 agents)** + +Each agent receives its assigned finding batch and these instructions: + +> You are validating audit findings against the actual codebase. For each finding in your +> batch: +> 1. Read the source code at the referenced `file:line` location using Glob/Grep/Read. +> 2. Check recent git history: `git log -10 --oneline -- {file}`. +> 3. Evaluate whether the finding accurately describes the code as it currently exists. +> 4. Assign a verdict: VALID, VALID BUT EXCEPTION WARRANTED, or CONTESTED. +> 5. If CONTESTED: provide specific code evidence that refutes the finding. +> 6. If VALID BUT EXCEPTION WARRANTED: describe the constraint that warrants an exception. +> 7. Before finalizing the verdict, check Known Project Exceptions table — if the finding matches a row, set verdict to VALID BUT EXCEPTION WARRANTED with the PS ID. +> 8. If severity should be adjusted, state the new severity and rationale. +> Do NOT modify any files. Return structured text only — no files created. + +**History Research Agent (1 agent)** + +Receives ALL findings. Instructions: + +> You are researching historical context for audit findings. For each finding: +> 1. Search git log for commits touching the referenced files in the last 90 days. +> 2. Check for open or recently-closed GitHub issues or PRs related to the code area: +> `gh issue list --state all --search "{keyword from finding}"`. +> 3. If a finding references a known in-progress fix or tracked issue, note it. +> Do NOT create any files. Return structured text only. + +**Subagent output format — code validation agents:** + +``` +## Batch {N} Verdicts + +### [{ID}] {short finding description} +- **Verdict**: VALID | VALID BUT EXCEPTION WARRANTED | CONTESTED +- **Code evidence**: {file:line + what the code actually shows} +- **Rationale**: {why this verdict} +- **Severity adjustment**: {new severity and reason} (omit if unchanged) +- **Exception note**: {constraint that warrants the exception} (EXCEPTION only) +``` + +**Subagent output format — history research agent:** + +``` +## Historical Context + +### [{ID}] {short finding description} +- **Recent commits**: {commit hashes + summaries, or "none in last 90 days"} +- **Related issues/PRs**: {numbers and titles, or "none found"} +- **Context note**: {how history affects the verdict, or "no impact"} +``` + +### Step 4 — Synthesize Results + +After all agents return: + +1. For each finding, merge the code agent verdict with historical context. +2. If history reveals an in-progress fix (open PR or tracked issue) for a VALID finding, + upgrade to VALID BUT EXCEPTION WARRANTED; use the PR/issue number as the exception note. +3. Tally: `N_valid`, `N_exception`, `N_contested`. +4. Collect all severity adjustments. + +### Step 5 — Generate Output Files + +Ensure `{{AUTOSKILLIT_TEMP}}/validate-audit/` exists (`mkdir -p`). + +**File 1 — Validated report** +Path: `{{AUTOSKILLIT_TEMP}}/validate-audit/validated_report_{source}_{YYYY-MM-DD_HHMMSS}.md` + +Structure: + +```markdown +validated: true + +# Validated Audit Report — {source} ({YYYY-MM-DD}) + +**Original report:** {audit_report_path} +**Findings processed:** {total} | **Valid:** {N_valid} | **Exception warranted:** {N_exception} | **Contested:** {N_contested} + +--- + +## Validation Status + +| Finding | Original Severity | Verdict | Adjusted Severity | +|---------|------------------|---------|------------------| +| ... | ... | ... | ... | + +--- + +## Validated Findings + +{Each VALID finding: original text, verdict badge, severity adjustment if any.} + +## Findings with Exceptions + +{Each VALID BUT EXCEPTION WARRANTED finding: original text + exception note.} + +--- + +*{N_contested} finding(s) contested and excluded — see contested_findings_{source}_{ts}.md* +``` + +**File 2 — Contested findings** (write only when `N_contested > 0`) +Path: `{{AUTOSKILLIT_TEMP}}/validate-audit/contested_findings_{source}_{YYYY-MM-DD_HHMMSS}.md` + +Structure: + +```markdown +# Contested Findings — {source} ({YYYY-MM-DD}) + +{For each CONTESTED finding:} + +## [{ID}] {short description} + +**Original severity:** {severity} +**Contest rationale:** {why it is factually wrong or counterproductive} +**Code evidence:** {specific file:line + what the code actually shows} +**Historical context:** {from history agent, if relevant; else omit} +``` + +### Step 6 — Interactive vs Headless Approval + +Detect headless mode: run `echo "${AUTOSKILLIT_HEADLESS:-0}"` via Bash. Output `1` means +headless. + +**Headless mode:** Write both output files immediately without prompting. Print to terminal: + +``` +[validate-audit] Done. + Valid: {N_valid} | Exceptions: {N_exception} | Contested: {N_contested} + Report: {{AUTOSKILLIT_TEMP}}/validate-audit/validated_report_{source}_{ts}.md + Contested: {{AUTOSKILLIT_TEMP}}/validate-audit/contested_findings_{source}_{ts}.md +``` + +(Omit the "Contested:" line if `N_contested == 0`.) + +**Interactive mode:** Display the validation status table (verdict counts), then ask: + +> Write validated report and contested findings files? [Y/n] + +On Y or empty input, write both files. After writing, if `N_contested > 0`, offer: + +> Run `/autoskillit:prepare-issue` for contested findings? [y/N] + +If the user confirms, pass the contested findings file path to `prepare-issue`. + +--- + +## Output Location + +``` +{{AUTOSKILLIT_TEMP}}/validate-audit/ +├── validated_report_{source}_{YYYY-MM-DD_HHMMSS}.md (always written) +└── contested_findings_{source}_{YYYY-MM-DD_HHMMSS}.md (when N_contested > 0) +``` + +`{source}` is `arch`, `tests`, or `cohesion` based on the input report. + +## Related Skills + +- `/autoskillit:audit-arch` — produces reports this skill validates +- `/autoskillit:audit-tests` — produces reports this skill validates +- `/autoskillit:audit-cohesion` — produces reports this skill validates +- `/autoskillit:prepare-issue` — offered interactively for contested findings diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..fc74f35c96 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,3 @@ +# Vendored binary assets — suppress diff spam on updates +src/autoskillit/assets/**/*.js binary +src/autoskillit/assets/**/*.css binary diff --git a/.github/workflows/patch-bump-integration.yml b/.github/workflows/patch-bump-integration.yml index b0c5877aa8..a4dc0a6171 100644 --- a/.github/workflows/patch-bump-integration.yml +++ b/.github/workflows/patch-bump-integration.yml @@ -28,6 +28,9 @@ jobs: with: uv-version: "0.9.21" + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + - name: Compute new patch version id: version run: | @@ -75,6 +78,9 @@ jobs: env: NEW_VERSION: ${{ steps.version.outputs.new }} + - name: Configure git auth for private deps + run: git config --global url."https://${{ secrets.GH_USER }}:${{ secrets.GH_PAT }}@github.com/TalonT-Org/".insteadOf "https://github.com/TalonT-Org/" + - name: Regenerate uv.lock run: uv lock diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 92b9e815c1..c561c4188d 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -34,6 +34,9 @@ jobs: with: uv-version: "0.9.21" + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + - name: Verify lockfile is up to date run: uv lock --check @@ -72,21 +75,15 @@ jobs: echo "task: $(task --version)" uv run python --version + - name: Configure git auth for private deps + run: git config --global url."https://${{ secrets.GH_USER }}:${{ secrets.GH_PAT }}@github.com/TalonT-Org/".insteadOf "https://github.com/TalonT-Org/" + + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + - name: Install dependencies run: uv sync --locked --extra dev - - name: Generate hooks.json - run: | - uv run python -c " - from autoskillit.hooks import generate_hooks_json - from autoskillit.core.io import atomic_write - from autoskillit.core.paths import pkg_root - import json - path = pkg_root() / 'hooks' / 'hooks.json' - atomic_write(path, json.dumps(generate_hooks_json(), indent=2) + '\n') - print(f'Generated: {path}') - " - - name: Generate recipe diagrams run: uv run autoskillit recipes render diff --git a/.github/workflows/version-bump.yml b/.github/workflows/version-bump.yml index 54bde29989..9ef0c58b8b 100644 --- a/.github/workflows/version-bump.yml +++ b/.github/workflows/version-bump.yml @@ -26,6 +26,9 @@ jobs: with: uv-version: "0.9.21" + - name: Install Rust toolchain + uses: dtolnay/rust-toolchain@stable + - name: Compute new minor version id: version run: | @@ -68,6 +71,9 @@ jobs: env: NEW_VERSION: ${{ steps.version.outputs.new_main }} + - name: Configure git auth for private deps + run: git config --global url."https://${{ secrets.GH_USER }}:${{ secrets.GH_PAT }}@github.com/TalonT-Org/".insteadOf "https://github.com/TalonT-Org/" + - name: Regenerate uv.lock (main) run: uv lock diff --git a/CLAUDE.md b/CLAUDE.md index 48be437f0e..4f2413ee91 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ Mandatory instructions for AI-assisted development in this repository. ## **1. Core Project Goal** -A Claude Code plugin that orchestrates automated skill-driven workflows using headless sessions. It provides 42 MCP tools (run_cmd, run_python, run_skill, test_check, merge_worktree, reset_test_dir, classify_fix, reset_workspace, read_db, migrate_recipe, clone_repo, remove_clone, push_to_remote, register_clone_status, batch_cleanup_clones, report_bug, prepare_issue, enrich_issues, claim_issue, release_issue, wait_for_ci, wait_for_merge_queue, toggle_auto_merge, create_unique_branch, check_pr_mergeable, write_telemetry_files, get_pr_reviews, bulk_close_issues, set_commit_status, get_quota_events, kitchen_status, list_recipes, load_recipe, validate_recipe, get_pipeline_report, get_token_summary, get_timing_summary, fetch_github_issue, get_issue_title, get_ci_status, open_kitchen, close_kitchen) with 40 tools tagged `kitchen` and hidden at startup via FastMCP v3 `mcp.disable(tags={'kitchen'})`, 1 tool additionally tagged `headless` (test_check) and revealed in headless sessions via `mcp.enable(tags={'headless'})`, and 2 Free Range tools (open_kitchen, close_kitchen) always visible. Revealed per-session via `open_kitchen` tool, and 61 bundled skills (60 slash commands + 1 internal) registered as `/autoskillit:*` slash commands. +A Claude Code plugin that orchestrates automated skill-driven workflows using headless sessions. It provides MCP tools (gated behind `open_kitchen`/`close_kitchen` via FastMCP v3 tag-based visibility) and bundled skills registered as `/autoskillit:*` slash commands. ## **2. General Principles** @@ -29,9 +29,8 @@ A Claude Code plugin that orchestrates automated skill-driven workflows using he * **Avoid Redundancy**: Do not duplicate logic or utilities. * **Use Current Package Versions**: Web search for current stable versions when adding dependencies. * **Version Bumps**: When bumping the package version, update `pyproject.toml` and run `task sync-plugin-version && uv lock`; then search tests for hardcoded version strings (e.g. `AUTOSKILLIT_INSTALLED_VERSION` monkeypatches) and update them. - * **Run pre-commit before committing**: Always run `pre-commit run --all-files` before - committing. Do not skip this step even when code appears clean — hooks auto-fix - formatting and abort the commit, requiring re-stage and retry. + * **Run pre-commit before committing**: Always run `pre-commit run --all-files` before committing. Do not skip this step even when code appears clean — hooks auto-fix formatting and abort the commit, requiring re-stage and retry. + * **Hook Renames**: Renaming a hook script under `src/autoskillit/hooks/` must update `HOOK_REGISTRY` in `hook_registry.py` AND add the old basename to `RETIRED_SCRIPT_BASENAMES` in the same commit. `test_no_retired_name_has_a_live_file` will fail otherwise. ### **3.2. File System** @@ -39,27 +38,12 @@ A Claude Code plugin that orchestrates automated skill-driven workflows using he * **Do Not Add Root Files**: Never create new root files unless explicitly required. * **Never commit unless told to do so** -### **3.3. Pipeline Execution** +### **3.3. Code Index MCP Usage** - * **Orchestrator Discipline**: When executing a pipeline script (loaded via `load_recipe`), NEVER use native Claude Code tools directly. The following tools are prohibited for the orchestrator: Read, Grep, Glob, Edit, Write, Bash, Task, Explore, WebFetch, WebSearch, NotebookEdit. - * **Delegate Through Headless Sessions**: All code reading, searching, editing, and investigation MUST go through `run_skill`, which launches headless sessions with full tool access. - * **Route Failures, Do Not Investigate**: When a pipeline step fails, follow the step's `on_failure` route. Do NOT use native tools to diagnose failures — the downstream skill has diagnostic access that the orchestrator does not. - * **Use `run_cmd` for Shell Access**: If shell commands are needed during a pipeline, use the `run_cmd` MCP tool, not the native Bash tool. - -### **3.5. Code Index MCP Usage** - - * **Initialize before use**: Always call `set_project_path` with the project root - as the first action in any session that will use code-index tools. Without this - call, all code-index tools (`find_files`, `search_code_advanced`, `get_file_summary`, - `get_symbol_body`) fail with "Project path not set" and cascade-cancel sibling - parallel calls. + * **Initialize before use**: Always call `set_project_path` with the project root as the first action in any session that will use code-index tools. Without this call, all code-index tools fail with "Project path not set" and cascade-cancel sibling parallel calls. * **Index is locked to the main project root**: The `code-index` MCP server is indexed against the source repo and must never be redirected to a worktree or branch. Its value is for exploration before code changes — at that point any worktree is identical to main, so the index is accurate regardless of where you are working. - * **Prefer code-index tools over native search tools when exploring the codebase**: - * `find_files` instead of Glob for in-project file discovery - * `search_code_advanced` instead of Grep for in-project content search (auto-selects best backend, paginates results, supports fuzzy matching) - * `get_file_summary` to understand a file's structure before reading it - * `get_symbol_body` to retrieve a specific function or class by name, including a `called_by` call graph, without loading the whole file - * **Do not rely on code-index tools for code added or modified during a branch** — use Read/Grep directly for that. + * **Prefer code-index tools over native search** when exploring the codebase: `find_files`, `search_code_advanced`, `get_file_summary`, `get_symbol_body` (includes `called_by` call graph). + * **Do not rely on code-index for code added or modified during a branch** — use Read/Grep directly for that. * **Fall back to native Grep/Glob** for multiline patterns or paths outside the project root. ### **3.4. CLAUDE.md Modifications** @@ -69,7 +53,7 @@ A Claude Code plugin that orchestrates automated skill-driven workflows using he ## **4. Testing Guidelines** -The project uses pytest with pytest-asyncio for async test support. Tests run in parallel via pytest-xdist (`-n 4`). All tests must be safe for parallel execution. +The project uses pytest with pytest-asyncio. Tests run in parallel via pytest-xdist (`-n 4`). All tests must be safe for parallel execution. * **Run tests**: `task test-all` from the project root (human-facing, runs lint + tests). For automation and MCP tools, `task test-check` is used (unambiguous PASS/FAIL, correct PIPESTATUS capture). Never use `pytest`, `python -m pytest`, or any other test runner directly. * **Always run tests at end of task** @@ -79,226 +63,232 @@ The project uses pytest with pytest-asyncio for async test support. Tests run in ## **5. Pre-commit Hooks** -Install hooks after cloning: `pre-commit install` - -Hooks run automatically on commit. To run manually: `pre-commit run --all-files` +Install hooks after cloning: `pre-commit install`. Run manually with `pre-commit run --all-files`. Configured hooks: ruff format (auto-fix), ruff check (auto-fix), mypy type checking, uv lock check, gitleaks secret scanning. ## **6. Architecture** +Top-level layout: + ``` -src/autoskillit/ -├── __init__.py # Package version + NullHandler for stdlib compat -├── __main__.py # python -m autoskillit entry point (delegates to cli) -├── _llm_triage.py # LLM-assisted contract staleness triage (Haiku subprocess) -├── smoke_utils.py # Utility callables for smoke-test pipeline run_python steps -├── hook_registry.py # Canonical hook definitions (HookDef, HOOK_REGISTRY, generate_hooks_json) -├── version.py # Version health utilities (Layer 0) -├── .claude-plugin/ # Plugin metadata (plugin.json) -├── .mcp.json # MCP server config for plugin loading -├── core/ # L0 foundation sub-package (zero autoskillit imports) -│ ├── __init__.py # Re-exports full public surface -│ ├── io.py # atomic_write, ensure_project_temp, load_yaml, dump_yaml_str, YAMLError -│ ├── logging.py # get_logger, configure_logging, PACKAGE_LOGGER_NAME -│ ├── paths.py # pkg_root(), is_git_worktree() — canonical package root resolver -│ ├── types.py # Thin re-export hub — imports * from all _type_*.py sub-modules -│ ├── _type_enums.py # 14 StrEnums: RetryReason, MergeState, ClaudeFlags, Severity, etc. -│ ├── _type_subprocess.py # SubprocessResult, SubprocessRunner Protocol, _TERMINATION_CONTRACT -│ ├── _type_constants.py # GATED_TOOLS, FREE_RANGE_TOOLS, SKILL_TOOLS, SKILL_COMMAND_PREFIX, etc. -│ ├── _type_results.py # LoadResult, LoadReport, SkillResult, FailureRecord, CleanupResult, CIRunScope, etc. -│ ├── _type_protocols.py # 20 Protocols: GatePolicy, HeadlessExecutor, GitHubFetcher, CIWatcher, etc. -│ ├── _type_helpers.py # extract_skill_name, resolve_target_skill, truncate_text -│ ├── _terminal_table.py # TerminalColumn, _render_terminal_table — L0 color-agnostic terminal table primitive (pipeline/ and cli/ safe) -│ ├── branch_guard.py # is_protected_branch — pure-function protected-branch validation -│ ├── claude_conventions.py # ClaudeDirectoryConventions — canonical skill discovery directory layout constants; LayoutError, validate_add_dir() -│ └── github_url.py # parse_github_repo — canonical GitHub URL parser (str → owner/repo | None) -├── config/ # L1 configuration sub-package -│ ├── __init__.py # Re-exports AutomationConfig + GitHubConfig + resolve_ingredient_defaults -│ ├── defaults.yaml # Bundled package defaults (always loaded as first layer) -│ ├── ingredient_defaults.py # resolve_ingredient_defaults — auto-detect source_dir + base_branch -│ └── settings.py # Dataclass config + dynaconf-backed layered resolution -├── pipeline/ # L1 pipeline state sub-package -│ ├── __init__.py # Re-exports ToolContext, DefaultGateState, DefaultAuditLog, DefaultTokenLog, -│ │ # TelemetryFormatter, DefaultBackgroundSupervisor, DefaultTimingLog -│ ├── audit.py # FailureRecord, DefaultAuditLog -│ ├── background.py # DefaultBackgroundSupervisor — supervised background task execution; BackgroundSupervisor Protocol in core/ -│ ├── context.py # ToolContext DI container (config, audit, token_log, gate, plugin_dir, runner) -│ ├── gate.py # DefaultGateState, GATED_TOOLS, UNGATED_TOOLS, gate_error_result -│ │ # (UNGATED_TOOLS is an alias for FREE_RANGE_TOOLS in core/types.py) -│ ├── mcp_response.py # McpResponseEntry, DefaultMcpResponseLog — per-tool response size tracking -│ ├── telemetry_fmt.py # TelemetryFormatter — canonical token/timing display (single source of truth) -│ ├── timings.py # TimingEntry, DefaultTimingLog — per-step wall-clock accumulation -│ ├── tokens.py # TokenEntry, DefaultTokenLog -│ └── pr_gates.py # PR eligibility gates: is_ci_passing, is_review_passing, partition_prs -├── execution/ # L1 execution sub-package +generic_automation_mcp/ +├── assets/ +├── docs/ +├── scripts/ +├── src/autoskillit/ # see below +├── tests/ # mirrors src/ layout; see tests/CLAUDE.md +├── Taskfile.yml +├── install.sh +└── pyproject.toml +``` + +`src/autoskillit/`: + +``` +├── __init__.py +├── __main__.py +├── _llm_triage.py # Contract staleness triage (Haiku subprocess) +├── smoke_utils.py # Callables for smoke-test pipeline run_python steps +├── hook_registry.py # HookDef, HOOK_REGISTRY, generate_hooks_json +├── version.py # Version health utilities (L0) +├── .claude-plugin/ # plugin.json +├── .mcp.json +│ +├── core/ # L0 foundation (zero autoskillit imports) │ ├── __init__.py # Re-exports public surface -│ ├── commands.py # ClaudeInteractiveCmd/ClaudeHeadlessCmd builders -│ ├── db.py # Read-only SQLite execution with defence-in-depth -│ ├── diff_annotator.py # Deterministic diff annotation and findings filter for review-pr -│ ├── headless.py # Headless Claude session orchestration (L1 service) -│ ├── linux_tracing.py # Linux-only /proc + psutil process tracing (accumulate snapshots) -│ ├── anomaly_detection.py # Post-hoc anomaly detection over ProcSnapshot series -│ ├── session_log.py # File-based session diagnostics log writer (XDG-aware) -│ ├── process.py # Subprocess management facade (re-exports from _process_*.py) -│ ├── _process_io.py # create_temp_io, read_temp_output -│ ├── _process_jsonl.py # _jsonl_contains_marker, _jsonl_has_record_type, _marker_is_standalone -│ ├── _process_kill.py # kill_process_tree, async_kill_process_tree -│ ├── _process_monitor.py # _heartbeat, _session_log_monitor, _has_active_api_connection -│ ├── _process_pty.py # pty_wrap_command -│ ├── _process_race.py # RaceAccumulator, RaceSignals, resolve_termination, _watch_* -│ ├── quota.py # Quota-aware check: QuotaStatus, cache, fetch, check_and_sleep_if_needed -│ ├── ci.py # GitHub Actions CI watcher service (L1, httpx-based, never raises) -│ ├── merge_queue.py # GitHub merge queue watcher service (L1, httpx-based, never raises) -│ ├── github.py # GitHub issue fetcher (L1, httpx-based, never raises) -│ ├── session.py # ClaudeSessionResult, SkillResult, extract_token_usage -│ ├── remote_resolver.py # resolve_remote_repo — canonical async resolver (upstream > origin, clone-aware) -│ ├── testing.py # Pytest output parsing and pass/fail adjudication -│ └── pr_analysis.py # PR analysis helpers: extract_linked_issues, is_valid_fidelity_finding, DOMAIN_PATHS, partition_files_by_domain -├── workspace/ # L1 workspace sub-package -│ ├── __init__.py # Re-exports CleanupResult, SkillResolver, DefaultSessionSkillManager, clone_repo, remove_clone, push_to_remote -│ ├── cleanup.py # Directory teardown utilities (CleanupResult, preserve list) -│ ├── clone.py # Clone-based run isolation: clone_repo, remove_clone, push_to_remote -│ ├── session_skills.py # Per-session ephemeral skill dirs (SkillsDirectoryProvider, -│ │ # DefaultSessionSkillManager, resolve_ephemeral_root) -│ │ # Subset filtering + project-local override detection -│ ├── clone_registry.py # Clone cleanup registry — shared file-based coordination for deferred batch cleanup (register_clone, read_registry, cleanup_candidates, batch_delete) -│ └── skills.py # Bundled skill listing (SkillResolver) -├── recipe/ # L2 recipe sub-package -│ ├── __init__.py # Re-exports Recipe, RecipeStep, validate_recipe, load_recipe, etc. -│ ├── contracts.py # Contract card generation and staleness triage utilities -│ ├── io.py # load_recipe, list_recipes, iter_steps_with_context, find_recipe_by_name -│ ├── loader.py # Path-based recipe metadata utilities (parse_recipe_metadata); RecipeInfo defined in schema.py -│ ├── _api.py # Recipe orchestration API: load/validate pipelines, format responses -│ ├── diagrams.py # Recipe flow diagram generation, loading, and staleness detection -│ ├── registry.py # RuleFinding, RuleSpec, _RULE_REGISTRY, semantic_rule, run_semantic_rules -│ ├── repository.py # Concrete RecipeRepository implementation -│ ├── _analysis.py # Step graph building and dataflow analysis -│ ├── rules_bypass.py # Semantic rules for skip_when_false bypass routing contracts -│ ├── rules_ci.py # Semantic rules for CI polling patterns (ci-polling-inline-shell) -│ ├── rules_clone.py # Semantic rules for clone/push workflow validation -│ ├── rules_contracts.py # Semantic rules for skill contract completeness (missing-output-patterns) -│ ├── rules_dataflow.py # Semantic rules for capture/output dataflow analysis -│ ├── rules_graph.py # Semantic rules for step graph reachability and cycles -│ ├── rules_inputs.py # Semantic rules for ingredient/version validation -│ ├── rules_merge.py # Semantic rules for merge_worktree routing completeness -│ ├── rules_recipe.py # Semantic rules for unknown sub-recipe references (unknown-sub-recipe rule) -│ ├── rules_skill_content.py # Semantic rules for SKILL.md bash-block placeholder validation (undefined-bash-placeholder) -│ ├── rules_skills.py # Semantic rules for skill_command resolvability (unknown-skill-command) -│ ├── rules_tools.py # Semantic rules for MCP tool name/param validity (unknown-tool, dead-with-param) -│ ├── rules_verdict.py # Semantic rules for skill verdict routing completeness (unrouted-verdict-value) -│ ├── rules_worktree.py # Semantic rules for worktree retry lifecycle -│ ├── _skill_placeholder_parser.py # Shared parser helpers for SKILL.md bash-block placeholder analysis -│ ├── schema.py # Recipe, RecipeStep, DataFlowWarning, AUTOSKILLIT_VERSION_KEY -│ ├── staleness_cache.py # Disk-backed staleness check cache (StalenessEntry, read_staleness_cache, write_staleness_cache) -│ └── validator.py # validate_recipe, run_semantic_rules (re-exported), analyze_dataflow -├── migration/ # L2 migration sub-package -│ ├── __init__.py # Re-exports MigrationEngine, applicable_migrations, FailureStore, check_and_migrate -│ ├── engine.py # MigrationEngine, adapter ABC hierarchy, default_migration_engine() -│ ├── _api.py # Top-level check_and_migrate convenience function -│ ├── loader.py # Migration note discovery and version chaining -│ └── store.py # FailureStore: migration failure persistence (JSON, atomic writes) -├── server/ # L3 FastMCP server sub-package -│ ├── __init__.py # FastMCP app, kitchen gating (mcp.disable tags={'kitchen'}), -│ │ # headless tool reveal (AUTOSKILLIT_HEADLESS) -│ ├── git.py # Git merge workflow for merge_worktree (perform_merge) -│ ├── _editable_guard.py # Pre-deletion editable install guard — scan_editable_installs_for_worktree (stdlib-only) -│ ├── helpers.py # Shared server-layer helpers (worktree setup, path utilities) -│ ├── tools_kitchen.py # open_kitchen, close_kitchen tool handlers + recipe:// resource -│ ├── tools_ci.py # wait_for_ci, get_ci_status, set_commit_status, toggle_auto_merge, wait_for_merge_queue tool handlers -│ ├── tools_clone.py # clone_repo, remove_clone, push_to_remote, register_clone_status, batch_cleanup_clones tool handlers -│ ├── tools_execution.py # run_cmd, run_python, run_skill tool handlers -│ ├── tools_git.py # merge_worktree, classify_fix, create_unique_branch, check_pr_mergeable tool handlers -│ ├── tools_recipe.py # migrate_recipe, load_recipe, list_recipes, validate_recipe tool handlers -│ ├── tools_status.py # kitchen_status, get_pipeline_report, get_token_summary, get_timing_summary, get_quota_events, write_telemetry_files, read_db tool handlers -│ ├── tools_github.py # fetch_github_issue, get_issue_title, report_bug tool handlers -│ ├── tools_issue_lifecycle.py # prepare_issue, enrich_issues, claim_issue, release_issue tool handlers -│ ├── tools_pr_ops.py # get_pr_reviews, bulk_close_issues tool handlers -│ ├── tools_workspace.py # test_check, reset_test_dir, reset_workspace tool handlers -│ ├── _factory.py # Composition Root: make_context() wires ToolContext -│ └── _state.py # Server state extraction (lazy init, plugin dir resolution) -├── cli/ # L3 CLI sub-package -│ ├── __init__.py # Re-exports main entry point -│ ├── _ansi.py # Terminal color utilities (supports_color, NO_COLOR/TERM=dumb) -│ ├── _terminal.py # terminal_guard() context manager — saves/restores TTY attrs around interactive subprocess -│ ├── _terminal_table.py # Re-export shim: TerminalColumn, _render_terminal_table from core/_terminal_table (L0) -│ ├── _cook.py # cook command: ephemeral skill session launcher (claude --add-dir) -│ ├── _doctor.py # Doctor command -- 12 project setup checks -│ ├── _hooks.py # Unified PreToolUse hook registration helpers -│ ├── _init_helpers.py # Init command helpers: interactive prompts and workspace marker -│ ├── _marketplace.py # Plugin install/upgrade marketplace operations -│ ├── _mcp_names.py # MCP prefix detection for prompt builders (detect_autoskillit_mcp_prefix, DIRECT_PREFIX, MARKETPLACE_PREFIX, resolve_tool_name) -│ ├── _onboarding.py # First-run detection and guided onboarding menu (is_first_run, run_onboarding_menu) -│ ├── _prompts.py # Orchestrator prompt builder for recipe execution -│ ├── _stale_check.py # Stale-install check: version comparison, hook-drift prompt, dismissal state -│ ├── _workspace.py # Workspace clean helpers: age partitioning, display, and confirmation -│ └── app.py # CLI: serve, init, config show, skills, recipes, workspace, doctor, migrate, quota_status -├── hooks/ # Claude Code PreToolUse, PostToolUse, and SessionStart hook scripts +│ ├── io.py # atomic_write, ensure_project_temp, YAML helpers +│ ├── logging.py +│ ├── paths.py # pkg_root(), is_git_worktree() +│ ├── types.py # Re-export hub for _type_*.py +│ ├── _type_enums.py # StrEnums +│ ├── _type_subprocess.py +│ ├── _type_constants.py # GATED_TOOLS, FREE_RANGE_TOOLS, SKILL_TOOLS, etc. +│ ├── _type_results.py # LoadResult, SkillResult, FailureRecord, CleanupResult, etc. +│ ├── _type_protocols.py # Protocols: GatePolicy, HeadlessExecutor, CIWatcher, etc. +│ ├── _type_helpers.py +│ ├── _claude_env.py # IDE-scrubbing canonical env builder for claude subprocesses +│ ├── _terminal_table.py # L0 color-agnostic terminal table primitive +│ ├── branch_guard.py +│ ├── claude_conventions.py # Skill discovery directory layout constants +│ ├── github_url.py # parse_github_repo +│ ├── kitchen_state.py # Kitchen-open session marker (stdlib-only; readable from hooks) +│ └── readiness.py # Filesystem readiness sentinel primitives for MCP server startup (L0) +│ +├── config/ # L1 +│ ├── __init__.py +│ ├── defaults.yaml +│ ├── ingredient_defaults.py +│ └── settings.py # Dataclass config + dynaconf layered resolution +│ +├── pipeline/ # L1 pipeline state +│ ├── __init__.py +│ ├── audit.py # FailureRecord, DefaultAuditLog +│ ├── background.py # DefaultBackgroundSupervisor +│ ├── context.py # ToolContext DI container +│ ├── gate.py # DefaultGateState, gate_error_result +│ ├── mcp_response.py # Per-tool response size tracking +│ ├── telemetry_fmt.py # Canonical token/timing display +│ ├── timings.py +│ ├── tokens.py +│ └── pr_gates.py # is_ci_passing, is_review_passing, partition_prs +│ +├── execution/ # L1 +│ ├── __init__.py +│ ├── commands.py # Claude{Interactive,Headless}Cmd builders +│ ├── db.py # Read-only SQLite with defence-in-depth +│ ├── diff_annotator.py # Diff annotation + findings filter for review-pr +│ ├── headless.py # Headless Claude session orchestration +│ ├── _headless_scan.py # Write-path JSONL scanning (extracted from headless.py) +│ ├── linux_tracing.py # /proc + psutil process tracing (Linux) +│ ├── anomaly_detection.py # Post-hoc anomaly detection over snapshots +│ ├── session_log.py # XDG-aware session diagnostics log writer +│ ├── recording.py # Record/replay subprocess runners via api-simulator +│ ├── process.py # Facade re-exporting from _process_*.py +│ ├── _process_io.py +│ ├── _process_jsonl.py +│ ├── _process_kill.py +│ ├── _process_monitor.py +│ ├── _process_pty.py +│ ├── _process_race.py # RaceAccumulator, resolve_termination +│ ├── quota.py # QuotaStatus, cache, check_and_sleep_if_needed +│ ├── ci.py # GitHub Actions CI watcher (httpx, never raises) +│ ├── merge_queue.py # GitHub merge queue watcher +│ ├── github.py # GitHub issue fetcher +│ ├── session.py # ClaudeSessionResult, extract_token_usage +│ ├── remote_resolver.py # upstream > origin, clone-aware +│ ├── testing.py # Pytest output parsing + pass/fail adjudication +│ └── pr_analysis.py # extract_linked_issues, DOMAIN_PATHS, partition_files_by_domain +│ +├── workspace/ # L1 +│ ├── __init__.py +│ ├── cleanup.py # CleanupResult, preserve list +│ ├── clone.py # Clone-based run isolation +│ ├── session_skills.py # Per-session ephemeral skill dirs; subset filtering +│ ├── clone_registry.py # Shared file-based coordination for deferred cleanup +│ ├── skills.py # SkillResolver — bundled skill listing +│ └── worktree.py +│ +├── recipe/ # L2 +│ ├── __init__.py +│ ├── contracts.py # Contract card generation + staleness triage +│ ├── io.py # load_recipe, list_recipes, iter_steps_with_context +│ ├── loader.py # Path-based recipe metadata utilities +│ ├── _api.py # Orchestration API +│ ├── diagrams.py # Flow diagram generation + staleness detection +│ ├── experiment_type_registry.py # ExperimentTypeSpec, load_all_experiment_types +│ ├── registry.py # RuleFinding, RuleSpec, semantic_rule decorator +│ ├── repository.py +│ ├── _analysis.py # Step graph building + dataflow analysis +│ ├── rules_blocks.py # Block-level budget rules (block-run-cmd-budget, etc.) +│ ├── rules_bypass.py +│ ├── rules_ci.py +│ ├── rules_clone.py +│ ├── rules_cmd.py +│ ├── rules_contracts.py +│ ├── rules_dataflow.py +│ ├── rules_fixing.py +│ ├── rules_graph.py +│ ├── rules_inputs.py +│ ├── rules_isolation.py +│ ├── rules_merge.py +│ ├── rules_packs.py +│ ├── rules_reachability.py # Symbolic reachability rules (capture-inversion-detection, event-scope-requires-upstream-capture) +│ ├── rules_recipe.py +│ ├── rules_skill_content.py +│ ├── rules_skills.py +│ ├── rules_tools.py +│ ├── rules_verdict.py +│ ├── rules_worktree.py # Semantic validation rule modules +│ ├── _skill_placeholder_parser.py +│ ├── schema.py # Recipe, RecipeStep, DataFlowWarning +│ ├── staleness_cache.py +│ └── validator.py # validate_recipe, analyze_dataflow +│ +├── migration/ # L2 +│ ├── __init__.py +│ ├── engine.py # MigrationEngine, adapter ABC hierarchy +│ ├── _api.py # check_and_migrate +│ ├── loader.py # Migration note discovery + version chaining +│ └── store.py # FailureStore (JSON, atomic writes) +│ +├── server/ # L3 FastMCP server +│ ├── __init__.py # FastMCP app, kitchen gating, headless tool reveal +│ ├── git.py # Merge workflow for merge_worktree +│ ├── _editable_guard.py # Pre-deletion editable install guard (stdlib-only) +│ ├── _lifespan.py # FastMCP lifespan: recorder teardown on shutdown +│ ├── _wire_compat.py # Claude Code wire-format sanitization middleware +│ ├── helpers.py +│ ├── tools_kitchen.py # open_kitchen, close_kitchen + recipe:// resource +│ ├── tools_ci.py # CI/merge-queue tool handlers +│ ├── tools_clone.py +│ ├── tools_execution.py # run_cmd, run_python, run_skill +│ ├── tools_git.py # merge_worktree, classify_fix, etc. +│ ├── tools_recipe.py +│ ├── tools_status.py # kitchen_status, reports, summaries, quota events, read_db +│ ├── tools_github.py # fetch_github_issue, get_issue_title, report_bug +│ ├── tools_issue_lifecycle.py # prepare/enrich/claim/release issue +│ ├── tools_pr_ops.py # get_pr_reviews, bulk_close_issues +│ ├── tools_workspace.py # test_check, reset_test_dir, reset_workspace +│ ├── _factory.py # Composition Root: make_context() +│ └── _state.py # Lazy init, plugin dir resolution +│ +├── cli/ # L3 CLI +│ ├── __init__.py +│ ├── _ansi.py # supports_color, NO_COLOR/TERM=dumb +│ ├── _terminal.py # terminal_guard() TTY restore +│ ├── _terminal_table.py # Re-export shim from core/_terminal_table +│ ├── _cook.py # cook: ephemeral skill session launcher +│ ├── _doctor.py # 16 project setup checks +│ ├── _hooks.py # PreToolUse hook registration helpers +│ ├── _init_helpers.py +│ ├── _installed_plugins.py # InstalledPluginsFile — canonical accessor for installed_plugins.json +│ ├── _install_info.py # InstallInfo, InstallType, detect_install(), comparison_branch(), dismissal_window(), upgrade_command() +│ ├── _marketplace.py # Plugin install/upgrade +│ ├── _mcp_names.py # MCP prefix detection +│ ├── _onboarding.py # First-run detection + guided menu +│ ├── _prompts.py # Orchestrator prompt builder +│ ├── _timed_input.py # timed_prompt() and status_line() CLI primitives +│ ├── _update.py # run_update_command(): first-class upgrade path for `autoskillit update` +│ ├── _update_checks.py # Unified startup update check: version/hook/source-drift signals, branch-aware dismissal +│ ├── _serve_guard.py # Async signal-guarded MCP server bootstrap (extracted from app.py) +│ ├── _workspace.py # Workspace clean helpers +│ └── app.py # CLI entry: serve, init, config, skills, recipes, doctor, update, etc. +│ +├── hooks/ # Claude Code PreToolUse/PostToolUse/SessionStart scripts │ ├── __init__.py -│ ├── hooks.json # Plugin hook registration (auto-discovered by Claude Code) -│ ├── branch_protection_guard.py # PreToolUse hook — denies merge_worktree/push_to_remote targeting protected branches -│ ├── quota_check.py # Quota guard hook — blocks run_skill when threshold exceeded -│ ├── remove_clone_guard.py # Remove-clone guard — denies remove_clone calls with keep != "true" -│ ├── skill_cmd_check.py # PreToolUse hook — validates skill_command path argument format -│ ├── skill_command_guard.py # PreToolUse hook — blocks run_skill with non-slash skill_command -│ ├── open_kitchen_guard.py # PreToolUse hook — blocks open_kitchen from headless sessions -│ ├── unsafe_install_guard.py # PreToolUse hook — blocks run_cmd editable installs without --python .venv -│ ├── headless_orchestration_guard.py # PreToolUse hook — blocks run_skill/run_cmd/run_python from headless sessions -│ ├── pretty_output.py # PostToolUse hook — reformats MCP JSON responses as Markdown-KV -│ ├── token_summary_appender.py # PostToolUse hook — appends ## Token Usage Summary table to PR body after run_skill returns a GitHub PR URL -│ └── session_start_reminder.py # SessionStart hook — injects /autoskillit:open-kitchen reminder when resuming a prior session (transcript_path size > 0) -├── migrations/ # Data: versioned migration YAML notes -│ └── __init__.py -├── recipes/ # Bundled recipe YAML definitions -│ ├── contracts/ # Per-recipe contract cards (generated) -│ ├── diagrams/ # Per-recipe flow diagrams (generated) -│ ├── sub-recipes/ # Reusable sub-recipe YAML fragments -│ ├── implementation-groups.yaml -│ ├── implementation.yaml -│ ├── merge-prs.yaml -│ ├── remediation.yaml -│ └── smoke-test.yaml -├── skills/ # Tier 1 bundled skills (plugin-scanned, entry points) -│ ├── open-kitchen/ # /autoskillit:open-kitchen — reveals MCP tools -│ ├── close-kitchen/ # /autoskillit:close-kitchen — hides MCP tools -│ └── sous-chef/ # Internal: injected by open_kitchen, not a slash cmd -└── skills_extended/ # Tier 2+3 bundled skills (NOT plugin-scanned) - │ - │ ── Tier 2: Interactive skills (cook + headless) ── - ├── investigate/ ├── make-plan/ - ├── implement-worktree/ ├── rectify/ - ├── dry-walkthrough/ ├── make-groups/ - ├── review-approach/ ├── mermaid/ - ├── make-arch-diag/ ├── arch-lens-*/ (13 skills) - ├── audit-arch/ ├── audit-cohesion/ - ├── audit-tests/ ├── audit-defense-standards/ - ├── audit-bugs/ ├── audit-friction/ - ├── validate-audit/ - ├── make-req/ ├── elaborate-phase/ - ├── write-recipe/ ├── migrate-recipes/ - ├── setup-project/ ├── sprint-planner/ - ├── design-guards/ ├── triage-issues/ - ├── collapse-issues/ ├── issue-splitter/ - ├── enrich-issues/ ├── prepare-issue/ - └── process-issues/ - │ - │ ── Tier 3: Pipeline / automation skills ── - ├── open-pr/ ├── open-integration-pr/ - ├── merge-pr/ ├── analyze-prs/ - ├── review-pr/ ├── resolve-review/ - ├── implement-worktree-no-merge/ ├── resolve-failures/ - ├── retry-worktree/ ├── resolve-merge-conflicts/ - ├── audit-impl/ ├── smoke-task/ - ├── report-bug/ ├── pipeline-summary/ - ├── diagnose-ci/ └── verify-diag/ +│ ├── hooks.json # Plugin hook registration +│ ├── branch_protection_guard.py +│ ├── _hook_settings.py # Shared stdlib-only settings resolver for quota guard hooks +│ ├── quota_guard.py # Blocks run_skill when threshold exceeded +│ ├── quota_post_hook.py # Appends quota warning to run_skill output +│ ├── remove_clone_guard.py +│ ├── skill_cmd_guard.py +│ ├── skill_command_guard.py +│ ├── ask_user_question_guard.py # Blocks AskUserQuestion if kitchen is not open +│ ├── open_kitchen_guard.py +│ ├── unsafe_install_guard.py +│ ├── generated_file_write_guard.py +│ ├── headless_orchestration_guard.py +│ ├── pretty_output_hook.py # Dispatch entrypoint for MCP JSON → Markdown-KV reformatter +│ ├── _fmt_primitives.py # Payload dataclasses, token formatter, pipeline-mode + short-name +│ ├── _fmt_execution.py # run_skill, run_cmd, test_check, merge_worktree formatters +│ ├── _fmt_status.py # token/timing summary, kitchen_status, clone_repo formatters +│ ├── _fmt_recipe.py # load_recipe, open_kitchen, list_recipes formatters +│ ├── token_summary_hook.py # Appends Token Usage Summary to PR body +│ └── session_start_hook.py # Injects open-kitchen reminder on resume +│ +├── migrations/ # Versioned migration YAML notes +├── recipes/ # Bundled recipe YAML + contracts/, diagrams/, sub-recipes/ +├── skills/ # Tier 1: open-kitchen, close-kitchen, sous-chef +└── skills_extended/ # Tier 2 (interactive) + Tier 3 (pipeline/automation) skills + # incl. arch-lens-* (13) and exp-lens-* (18) diagram families ``` -**Session diagnostics logs** are stored globally at `~/.local/share/autoskillit/logs/` (Linux) or `~/Library/Application Support/autoskillit/logs/` (macOS). Override with `linux_tracing.log_dir` in config. Session directories are named by Claude Code session UUID when available (preferred: parsed from stdout, fallback: discovered from JSONL filename via Channel B). When no session ID is available from either source, directories use `no_session_{timestamp}` naming. Query the index: `jq 'select(.success == false)' ~/.local/share/autoskillit/logs/sessions.jsonl`. +**Session diagnostics logs** live at `~/.local/share/autoskillit/logs/` (Linux) or `~/Library/Application Support/autoskillit/logs/` (macOS). Override with `linux_tracing.log_dir`. Session directories are named by Claude Code session UUID when available (parsed from stdout, or discovered from JSONL filename via Channel B). Fallback: `no_session_{timestamp}`. Query the index: `jq 'select(.success == false)' ~/.local/share/autoskillit/logs/sessions.jsonl`. -**CRITICAL**: When using subagents, invoke with "CLAUDE_CODE_EXIT_AFTER_STOP_DELAY=120000" to ensure subagents exit when finished. +**CRITICAL**: When using subagents, invoke with `CLAUDE_CODE_EXIT_AFTER_STOP_DELAY=120000` to ensure subagents exit when finished. ## 7. Session Diagnostics -**Path components use hyphens, not underscores.** Log directory names and session folder -names are hyphen-separated. Never assume underscores when constructing or searching for -log paths — hyphen mismatch causes ENOENT (session f9170655 pattern). \ No newline at end of file +**Path components use hyphens, not underscores.** Log directory names and session folder names are hyphen-separated. Never assume underscores when constructing or searching for log paths — hyphen mismatch causes ENOENT (session f9170655 pattern). diff --git a/README.md b/README.md index 5764a0b1bf..384fa9cb7f 100644 --- a/README.md +++ b/README.md @@ -1,17 +1,20 @@

- AutoSkillit — Skill-driven automation for agentic workflows + AutoSkillit

-Automate your processes with skills, automate your skills with Autoskillit. +AutoSkillit is a Claude Code plugin that runs YAML recipes through a two-tier +orchestrator. Bundled recipes turn GitHub issues into merged PRs by chaining +plan, dry-walkthrough, worktree, test, and PR-review skills against 42 MCP +tools and 109 bundled skills. https://github.com/user-attachments/assets/bcd910c8-7269-46d6-a496-53b2cb24d212 -## Prerequisites +## Requirements -- **Python 3.11+** -- **[uv](https://docs.astral.sh/uv/)** — package manager (`pip install uv` or see uv docs) -- **[Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code)** — `npm install -g @anthropic-ai/claude-code` -- **[gh CLI](https://cli.github.com/)** — required for GitHub features (PR creation, issue management, CI status) +- Python 3.11+ +- [uv](https://docs.astral.sh/uv/) — package manager +- [Claude Code CLI](https://docs.anthropic.com/en/docs/claude-code) — `npm install -g @anthropic-ai/claude-code` +- [gh CLI](https://cli.github.com/) — required for PR creation, issue management, CI status ## Install @@ -19,68 +22,39 @@ https://github.com/user-attachments/assets/bcd910c8-7269-46d6-a496-53b2cb24d212 curl -fsSL https://raw.githubusercontent.com/TalonT-Org/AutoSkillit/stable/install.sh | sh ``` -## Quick Start +## Quick try ```bash -# 1. Set up your project cd your-project autoskillit init - -# 2. Run the implementation recipe autoskillit order implementation ``` -### First-Time Project Setup - -After installation, run the setup wizard to configure AutoSkillit for your project: +## What it does -```bash -autoskillit cook -# Then in the Claude session: -/autoskillit:setup-project -``` +Each bundled recipe is a sequenced graph of skill invocations. The orchestrator +holds a kitchen of 40 kitchen-tagged MCP tools plus 2 free range tools (`open_kitchen`, +`close_kitchen`), launches headless Claude sessions for the heavy work, and +routes verdicts through retry, merge, and review gates. The 5 bundled recipes +are `implementation`, `implementation-groups`, `merge-prs`, `remediation`, and +`research`. -This explores your codebase and generates project-tailored recipes and config. - -That's it. Describe what you want to build, and AutoSkillit handles the rest: - -``` -Plan ─── Dry-walkthrough ─── Implement ─── Test ─── Merge ─── Push ─── PR ─── Review - │ │ - ▼ ▼ -Deep codebase Isolated worktree -analysis -``` - -## Bundled Recipes - -| Recipe | What it automates | -|--------|-------------------| -| `implementation` | Plan → dry-walkthrough → implement → test → merge → PR → review | -| `remediation` | Investigate → plan → implement → test → merge → PR | -| `implementation-groups` | Decompose large docs → sequenced group implementation | -| `merge-prs` | Analyze open PRs → merge in order → single integration PR | - -## CLI +## Documentation -| Command | Purpose | -|---------|---------| -| `autoskillit install` | Register plugin with Claude Code | -| `autoskillit init` | Create project config | -| `autoskillit order [recipe]` | Run a recipe (prompts if omitted) | -| `autoskillit cook` | Launch Claude with all bundled skills as slash commands | +Full docs are under [docs/](docs/README.md). Topic entry points: -See the [CLI Reference](docs/cli-reference.md) for all commands. +- [docs/getting-started.md](docs/getting-started.md) +- [docs/installation.md](docs/installation.md) +- [docs/configuration.md](docs/configuration.md) +- [docs/recipes/overview.md](docs/recipes/overview.md) +- [docs/execution/architecture.md](docs/execution/architecture.md) +- [docs/safety/hooks.md](docs/safety/hooks.md) +- [docs/developer/contributing.md](docs/developer/contributing.md) -## Documentation +## Examples -- **[Getting Started](docs/getting-started.md)** — Walk through the implementation workflow step by step -- **[Installation](docs/installation.md)** — Prerequisites, install, troubleshooting -- **[Recipes](docs/recipes.md)** — All recipes with flow diagrams and input reference -- **[CLI Reference](docs/cli-reference.md)** — All commands and options -- **[Configuration](docs/configuration.md)** — Layered config, all settings, examples -- **[Architecture](docs/architecture.md)** — Gating, clone isolation, headless sessions, hooks -- **[Contributing](docs/developer/contributing.md)** — Development setup, testing, architecture layers +Real end-to-end runs against `TalonT-Org/spectral-init` are in +[docs/examples/research-pipeline.md](docs/examples/research-pipeline.md). ## License diff --git a/Taskfile.yml b/Taskfile.yml index d1f79b064b..b499f3c39d 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -109,7 +109,7 @@ tasks: set -o pipefail set +e - $PYTEST_CMD tests/test_smoke_pipeline.py -m smoke -v --tb=short -o "addopts=" --basetemp={{.PYTEST_TMPDIR}} -o "cache_dir={{.PYTEST_CACHEDIR}}" 2>&1 | tee "$TEST_OUTPUT" + $PYTEST_CMD tests/recipe/test_smoke_pipeline.py -m smoke -v --tb=short -o "addopts=" --basetemp={{.PYTEST_TMPDIR}} -o "cache_dir={{.PYTEST_CACHEDIR}}" 2>&1 | tee "$TEST_OUTPUT" PYTEST_EXIT=$? set +o pipefail set -e @@ -118,6 +118,20 @@ tasks: echo "Smoke test output saved to: $TEST_OUTPUT" exit $PYTEST_EXIT + test-smoke-record: + desc: Record smoke test scenario by running autoskillit order with recording enabled + env: + RECORD_SCENARIO: "1" + RECORD_SCENARIO_DIR: '{{.RECORD_SCENARIO_DIR | default "tests/fixtures/scenarios/smoke-happy"}}' + RECORD_SCENARIO_RECIPE: "smoke-test" + cmds: + - | + mkdir -p "$RECORD_SCENARIO_DIR" + echo "Recording smoke-test scenario" + echo " RECORD_SCENARIO_DIR=$RECORD_SCENARIO_DIR" + echo "" + autoskillit order smoke-test + check-docs: desc: Verify documentation counts match source code cmds: @@ -128,6 +142,11 @@ tasks: cmds: - python scripts/sync_plugin_json.py + sync-hooks-hash: + desc: "Regenerate src/autoskillit/hooks/registry.sha256 from the live HOOK_REGISTRY" + cmds: + - uv run python -c "from autoskillit.hook_registry import HOOK_REGISTRY_HASH, HOOKS_DIR; (HOOKS_DIR / 'registry.sha256').write_text(HOOK_REGISTRY_HASH + '\n')" + install-worktree: desc: Set up development environment (isolated venv in worktrees, direct install in main) status: @@ -138,14 +157,14 @@ tasks: # Detect if we're in a git worktree (worktrees have .git as a file, not a directory) if [[ -f ".git" ]]; then echo "Worktree detected — creating isolated venv" - uv venv .venv + uv venv --clear .venv uv pip install -e '.[dev]' --python .venv/bin/python elif [[ -d ".venv" ]]; then echo "Main directory — installing into existing venv" uv pip install -e '.[dev]' --python .venv/bin/python else echo "Main directory — creating venv and installing" - uv venv .venv + uv venv --clear .venv uv pip install -e '.[dev]' --python .venv/bin/python fi echo "Done: $(python --version 2>/dev/null || .venv/bin/python --version)" @@ -153,5 +172,18 @@ tasks: install-dev: desc: Install dev version of autoskillit from the integration branch cmds: - - uv tool install --force "git+https://github.com/TalonT-Org/AutoSkillit.git@integration" + - uv tool install --force "autoskillit[dev] @ git+https://github.com/TalonT-Org/AutoSkillit.git@integration" - "$(uv tool dir)/autoskillit/bin/autoskillit install" + + vendor-mermaid: + desc: Download latest mermaid v11 UMD bundle to src/autoskillit/assets/mermaid/ + cmds: + - mkdir -p src/autoskillit/assets/mermaid + - | + VERSION=$(curl -sfL https://unpkg.com/mermaid@11/package.json \ + | python3 -c "import sys, json; print(json.load(sys.stdin)['version'])") + echo "Fetching mermaid ${VERSION}..." + curl -sfL "https://unpkg.com/mermaid@${VERSION}/dist/mermaid.min.js" \ + -o src/autoskillit/assets/mermaid/mermaid.min.js + echo "${VERSION}" > src/autoskillit/assets/mermaid/VERSION + echo "Vendored mermaid ${VERSION} ($(wc -c < src/autoskillit/assets/mermaid/mermaid.min.js) bytes)" diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000000..842b9ad257 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,28 @@ +# AutoSkillit documentation + +AutoSkillit is a Claude Code plugin that runs YAML recipes through a +two-tier orchestrator. The bundled recipes implement issue → plan → worktree +→ tests → PR → merge pipelines using 44 MCP tools and 109 bundled skills. + +## Start here + +- [getting-started.md](getting-started.md) — install, run your first recipe +- [installation.md](installation.md) — environment, doctor checks, secrets +- [configuration.md](configuration.md) — config layers, ingredient defaults + +## Quick reference + +- [cli.md](cli.md) — every `autoskillit` command +- [update-checks.md](update-checks.md) — update checks, dismissal windows, `autoskillit update` +- [faq.md](faq.md) — common questions +- [glossary.md](glossary.md) — canonical terms + +## Topic-based subdirectories + +- [recipes/](recipes/README.md) — bundled recipes, authoring, composition +- [skills/](skills/README.md) — Tier model, catalog, subsets, overrides +- [execution/](execution/README.md) — architecture, tool access, orchestration +- [safety/](safety/README.md) — hooks, workspace isolation +- [operations/](operations/README.md) — sprint guide, observability +- [developer/](developer/README.md) — contributing, diagnostics, end-turn hazards +- [examples/](examples/README.md) — end-to-end pipeline runs diff --git a/docs/cli-reference.md b/docs/cli.md similarity index 85% rename from docs/cli-reference.md rename to docs/cli.md index 73d8b63a86..ee30505148 100644 --- a/docs/cli-reference.md +++ b/docs/cli.md @@ -77,14 +77,19 @@ Launch an interactive pipeline session. Run health checks on your setup. - autoskillit doctor [--output-json] [--fix] + autoskillit doctor [--output-json] **Flags:** - `--output-json` — Output results as JSON -- `--fix` — Attempt to fix issues automatically -Runs 8 checks: stale MCP servers, MCP registration, PATH, project config, -version consistency, hook health, hook registration, recipe version health. +Runs 14 checks enumerated by `run_doctor` in `cli/_doctor.py` (12 numbered +plus the lettered sub-checks `4b` *Config secrets placement* and `7b` *Hook +registry drift*). The checks cover stale MCP servers, plugin registration, +PATH, project config, secrets placement, version consistency, hook health, +hook registration, hook registry drift, recipe version health, gitignore +completeness, secret-scanning hook, editable install source, and stale entry +points. See [installation.md](installation.md#post-install-verification) for +the full table. --- @@ -171,7 +176,7 @@ List all bundled skills. autoskillit skills list -Shows name, source, and path for all bundled skills (see `autoskillit skills list` for the full list). +Shows name, source, and path for all bundled skills. The complete catalogue is also documented in [skills/catalog.md](skills/catalog.md). --- diff --git a/docs/configuration.md b/docs/configuration.md index 2cee7fd440..7d5ca6ef5c 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -8,8 +8,11 @@ Most projects only need one setting — the test command: autoskillit init This creates `.autoskillit/config.yaml` with the test command you provide. -Everything else has sensible defaults. See [Getting Started](getting-started.md) -for a full tutorial. +Every other field falls back to the layered defaults loaded by +`config/settings.py` (package `defaults.yaml` → user-level +`~/.autoskillit/config.yaml` → project-level `.autoskillit/config.yaml` → +`.autoskillit/.secrets.yaml` → `AUTOSKILLIT_*` environment variables, in that +order). See [Getting Started](getting-started.md) for a full tutorial. ## Common Configurations @@ -73,7 +76,7 @@ AUTOSKILLIT_QUOTA_GUARD__ENABLED=false # disables quota guard This is useful for CI pipelines or per-session overrides without touching config files. -Partial configs are fine. Unset fields keep their defaults. View the resolved config with [`autoskillit config show`](cli-reference.md#autoskillit-config-show). +Partial configs are fine. Unset fields keep their defaults. View the resolved config with [`autoskillit config show`](cli.md#autoskillit-config-show). ## Test Command @@ -136,9 +139,14 @@ Default: `command: null` (disabled), `preserve_dirs: []`. ```yaml quota_guard: enabled: true - threshold: 80.0 # block run_skill when 5-hour utilization exceeds this % - buffer_seconds: 60 # extra buffer after quota reset before resuming - cache_max_age: 60 # seconds before a live quota fetch is triggered + short_window_threshold: 85.0 # block at this % for short windows (e.g. five_hour) + long_window_threshold: 98.0 # block at this % for long windows (weekly, sonnet, opus) + long_window_patterns: # substrings (case-insensitive) that classify a + - weekly # window name as long-window + - sonnet + - opus + buffer_seconds: 60 # extra buffer after quota reset before resuming + cache_max_age: 60 # seconds before a live quota fetch is triggered ``` Check current quota: `autoskillit quota-status`. @@ -182,7 +190,7 @@ linux_tracing: tmpfs_path: "/dev/shm" # RAM-backed path for crash resilience ``` -See [Session Diagnostics](developer/session-diagnostics.md) for details on log output. +See [Session Diagnostics](developer/diagnostics.md) for details on log output. ## Headless Sessions @@ -305,7 +313,7 @@ skills: ``` Any bundled skill can be promoted or demoted by adding it to the desired tier list. A skill -in multiple tiers simultaneously is a validation error. See **[Skill Visibility](skill-visibility.md)** +in multiple tiers simultaneously is a validation error. See **[Skill Visibility](skills/visibility.md)** for the full tier breakdown, session mode table, and override rules. ## Subset Categories @@ -325,7 +333,7 @@ subsets: ``` Disabling a subset hides its members from all session modes — even after `open_kitchen`. -See **[Subset Categories](subset-categories.md)** for the complete category listing and +See **[Subset Categories](skills/subsets.md)** for the complete category listing and FastMCP mechanics. ## Full Example diff --git a/docs/developer/README.md b/docs/developer/README.md new file mode 100644 index 0000000000..aeab79c08e --- /dev/null +++ b/docs/developer/README.md @@ -0,0 +1,7 @@ +# Developer + +For people working on AutoSkillit itself. + +- [contributing.md](contributing.md) — pre-commit, version bumps, code-index setup +- [diagnostics.md](diagnostics.md) — session diagnostic logs and `sessions.jsonl` +- [end-turn-hazards.md](end-turn-hazards.md) — recipe authoring hazards at session end diff --git a/docs/developer/contributing.md b/docs/developer/contributing.md index d45e71f4ef..aa8abf5093 100644 --- a/docs/developer/contributing.md +++ b/docs/developer/contributing.md @@ -47,5 +47,5 @@ When bumping the version, update three locations: ## Further Reading -- **[Session Diagnostics](session-diagnostics.md)** — Process-level diagnostic logging for headless sessions +- **[Session Diagnostics](diagnostics.md)** — Process-level diagnostic logging for headless sessions - **[End-Turn Hazards](end-turn-hazards.md)** — Stochastic failure modes in skill authoring and how to prevent them diff --git a/docs/developer/session-diagnostics.md b/docs/developer/diagnostics.md similarity index 91% rename from docs/developer/session-diagnostics.md rename to docs/developer/diagnostics.md index 7966e73dd2..c35654558e 100644 --- a/docs/developer/session-diagnostics.md +++ b/docs/developer/diagnostics.md @@ -105,3 +105,11 @@ jq 'select(.peak_rss_kb > 1000000)' ~/.local/share/autoskillit/logs/sessions.jso ## Disabling Set `linux_tracing.enabled: false` in your config to disable all session diagnostics file output. Non-Linux platforms produce no output regardless of this setting. + +## Path components use hyphens, not underscores + +Log directory names and session folder names are hyphen-separated. Never assume +underscores when constructing or searching for log paths — a hyphen mismatch +causes ENOENT (the root cause of the session `f9170655` debugging session). +The invariant is documented in `CLAUDE.md` §7 and enforced when +`execution/session_log.py` lays out per-session directories. diff --git a/docs/developer/end-turn-hazards.md b/docs/developer/end-turn-hazards.md index bb96fe012e..1acde7b99c 100644 --- a/docs/developer/end-turn-hazards.md +++ b/docs/developer/end-turn-hazards.md @@ -190,7 +190,7 @@ two detectors on every SKILL.md in the project: | `_check_loop_boundary()` | "For each" loops with tool invocations but no anti-prose guard | These run as part of `test_no_text_then_tool_in_any_step`, a parametrized -test that scans all 61 bundled skills. Any new skill with an unguarded +test that scans all 109 bundled skills. Any new skill with an unguarded loop fails CI automatically. ## If This Gets Fixed Upstream diff --git a/docs/examples/README.md b/docs/examples/README.md new file mode 100644 index 0000000000..be6600389d --- /dev/null +++ b/docs/examples/README.md @@ -0,0 +1,5 @@ +# Examples + +End-to-end runs that exercise AutoSkillit against a real downstream repo. + +- [research-pipeline.md](research-pipeline.md) — four merged research/archive PR pairs from `TalonT-Org/spectral-init` diff --git a/docs/examples/research-pipeline.md b/docs/examples/research-pipeline.md new file mode 100644 index 0000000000..fc64978dde --- /dev/null +++ b/docs/examples/research-pipeline.md @@ -0,0 +1,59 @@ +# Research pipeline example + +Four end-to-end runs of the `research` recipe against +[`TalonT-Org/spectral-init`](https://github.com/TalonT-Org/spectral-init). +Each example pairs the research PR (where the experiment ran) with the +archive PR (where the artifacts were committed) and links the on-disk +artifact tree. + +These four pairs are also encoded in +`tests/docs/test_doc_links.py` as the canonical allowlist; if you add a +fifth example, update the test fixture in the same commit. + +## Example 1 — initial spectral baseline + +- Research PR: +- Archive PR: +- Artifact tree: + + +The first run exercised the `research` recipe end to end against an empty +target repository. The orchestrator collected ingredients, ran +`scope` → `plan-experiment` → `implement-experiment` → `run-experiment` → +`generate-report`, and committed both the experiment results and the auxiliary +artifacts in two separate PRs so reviewers could read the report without +diffing the data. + +## Example 2 — comparator construction follow-up + +- Research PR: +- Archive PR: +- Artifact tree: + + +Followed up on Example 1 by running the `exp-lens-comparator-construction` +lens skill against the prior baseline. The pipeline split the research and +archive concerns the same way: the research PR carries the report and the +archive PR carries the regenerated lens diagram. + +## Example 3 — variance stability rerun + +- Research PR: +- Archive PR: +- Artifact tree: + + +Rerun of the variance-stability experiment after a tooling change. The +orchestrator cleanly resumed from the prior staleness-cache hit so only the +affected experiment artifacts were regenerated. + +## Example 4 — sensitivity sweep + +- Research PR: +- Archive PR: +- Artifact tree: + + +Final example: a sensitivity sweep across three input parameters, fanned +out via wavefront scheduling and stitched together by `pipeline-summary` +into a single GitHub issue. diff --git a/docs/execution/README.md b/docs/execution/README.md new file mode 100644 index 0000000000..8ffe23a6d3 --- /dev/null +++ b/docs/execution/README.md @@ -0,0 +1,8 @@ +# Execution + +How AutoSkillit runs recipes: tool gating, headless sessions, retry routing, +merge gates. + +- [architecture.md](architecture.md) — orchestrator, kitchen, sous-chef +- [tool-access.md](tool-access.md) — kitchen vs free range, the 42 MCP tools +- [orchestration.md](orchestration.md) — tier model, retry reasons, merge decision tree diff --git a/docs/architecture.md b/docs/execution/architecture.md similarity index 81% rename from docs/architecture.md rename to docs/execution/architecture.md index 82d47c7dbd..4eed2963a2 100644 --- a/docs/architecture.md +++ b/docs/execution/architecture.md @@ -1,10 +1,10 @@ # Architecture -How AutoSkillit works under the hood. +How AutoSkillit runs a recipe end to end: orchestrator, kitchen gating, clone and worktree isolation, session model, and diagnostics. ## Overview -AutoSkillit is a Claude Code plugin that orchestrates automated workflows using headless sessions. It provides 42 MCP tools and 61 bundled skills, organized into a gated visibility system. +AutoSkillit is a Claude Code plugin that orchestrates automated workflows using headless sessions. It provides 43 MCP tools and 109 bundled skills, organized into a gated visibility system. ## Core Concepts @@ -23,18 +23,18 @@ AutoSkillit uses a three-tier tool visibility model: - **Free-range (2 tools)**: Always visible — `open_kitchen`, `close_kitchen` - **Headless tools (1 tool)**: Revealed in headless sessions via `mcp.enable({'headless'})` — `test_check` -- **Kitchen tools (37 tools total, 36 kitchen-only)**: Gated behind `open_kitchen` — `run_skill`, - `run_cmd`, `run_python`, `merge_worktree`, `clone_repo`, `push_to_remote`, and 30 more. +- **Kitchen-tagged tools (41 tools total)**: Gated behind `open_kitchen` — `run_skill`, + `run_cmd`, `run_python`, `merge_worktree`, `clone_repo`, `push_to_remote`, and 31 more. One kitchen tool (`test_check`) also carries the `headless` tag and is additionally pre-enabled in headless sessions. -When you call `open_kitchen` (automatically done by `order`), all 37 kitchen-tagged tools become +When you call `open_kitchen` (automatically done by `order`), all 41 kitchen-tagged tools become available for that session. This keeps normal Claude Code sessions clean — no pipeline tools cluttering the tool list. Functional category subsets (`github`, `ci`, `clone`, `telemetry`) can be disabled in config; those tools remain hidden even after `open_kitchen`. -See **[MCP Tool Access Control](mcp-tool-access.md)** for the complete tool map. +See **[MCP Tool Access Control](tool-access.md)** for the complete tool map. ## Clone Isolation @@ -60,7 +60,7 @@ AutoSkillit supports four session modes with different tool and skill visibility - **`$ claude` (plugin, no kitchen)**: Regular Claude Code session with the AutoSkillit plugin loaded. Sees 2 Free Range MCP tools (`open_kitchen`, `close_kitchen`) and Tier 1 skills only - (`open-kitchen`, `close-kitchen`). After calling `/open-kitchen`, all 37 kitchen-tagged MCP + (`open-kitchen`, `close-kitchen`). After calling `/open-kitchen`, all 41 kitchen-tagged MCP tools become available. - **`$ autoskillit cook`**: Interactive development session. Sees all three skill tiers @@ -68,7 +68,7 @@ AutoSkillit supports four session modes with different tool and skill visibility `$ claude`); `/open-kitchen` reveals kitchen tools. - **`$ autoskillit order`**: Pipeline orchestrator session. Kitchen is pre-opened at startup — - all 42 MCP tools are available immediately. All skill tiers are accessible. The orchestrator + all 44 MCP tools are available immediately. All skill tiers are accessible. The orchestrator delegates work through `run_skill` (headless sessions) and `run_cmd` (shell commands). - **`run_skill` (headless)**: Worker sessions launched by the orchestrator. Sees 2 Free Range @@ -77,11 +77,11 @@ AutoSkillit supports four session modes with different tool and skill visibility Bash, etc.) and all skill tiers via `--add-dir skills_extended/`. This prevents recursive session nesting and keeps the orchestrator as a pure routing engine. -See **[Skill Visibility](skill-visibility.md)** for the full tier breakdown and configuration. +See **[Skill Visibility](../skills/visibility.md)** for the full tier breakdown and configuration. ## Safety -See **[Hooks & Safety](hooks-and-safety.md)** for the complete safety system: protected branches, quota management, format validation, and session boundary enforcement. +See **[Hooks](../safety/hooks.md)** for the complete safety system: protected branches, quota management, format validation, and session boundary enforcement. ## Session Diagnostics @@ -89,4 +89,4 @@ Pipeline sessions are logged to `~/.local/share/autoskillit/logs/` (Linux) or `~ Query the index: `jq 'select(.success == false)' ~/.local/share/autoskillit/logs/sessions.jsonl` -See **[Session Diagnostics](developer/session-diagnostics.md)** for details. +See **[Session Diagnostics](../developer/diagnostics.md)** for details. diff --git a/docs/execution/orchestration.md b/docs/execution/orchestration.md new file mode 100644 index 0000000000..83d230049f --- /dev/null +++ b/docs/execution/orchestration.md @@ -0,0 +1,138 @@ +# Orchestration + +How AutoSkillit routes work between the Tier 1 orchestrator and the Tier 2/3 +worker sessions, what the orchestrator does on every retry verdict, and how +the merge pipeline decides whether a worktree is ready to land. + +## Two-tier model + +AutoSkillit splits agent execution into two layers: + +- **Tier 1 — orchestrator.** A Claude Code session running the + `autoskillit order` CLI command, with the kitchen pre-opened. Sees all 42 + MCP tools, spawns headless workers, and routes verdicts. Never reads or + writes code itself. +- **Tier 2/3 — worker.** A headless Claude session launched by `run_skill`. + Sees the 2 free range tools plus `test_check` (the only `headless`-tagged + tool). Cannot call `run_skill`, `run_cmd`, or `run_python`. + +The boundary is enforced three ways: FastMCP visibility, the +`headless_orchestration_guard.py` PreToolUse hook, and the +`_require_not_headless()` runtime guard inside `tools_execution.py`. All +three must independently agree before any orchestration tool can fire. + +## Recipe as a program + +A recipe (`recipe/schema.py:Recipe`) is a sequenced list of `RecipeStep` +entries. Each step names either an MCP tool (`run_skill`, `merge_worktree`, +…) or a sub-recipe. The orchestrator's job is to walk the step graph, +collect each step's inputs from the recipe ingredients and from prior +captures, invoke the tool, and route the verdict. + +## Verdict routing + +The orchestrator's gate (`pipeline/gate.py:DefaultGateState`) inspects each +tool result. The routing rules per tool: + +- `run_skill` — read the structured tokens emitted by the worker; route to + the matching `verdict_routes` entry. Unrouted verdicts are a recipe + validation error caught by `recipe/rules_verdict.py`. +- `merge_worktree` — read `merge_state` from the JSON response; reroute on + the `MergeFailedStep` value (path validation, protected branch, dirty + tree, test gate, …). +- `clone_repo` / `remove_clone` — read `clone_id` and stash for later + cleanup via `register_clone_status` and `batch_cleanup_clones`. + +## The 11 `retry_reason` values + +`RetryReason` is a `StrEnum` in `src/autoskillit/core/_type_enums.py` with +11 distinct values. Each value triggers a different recovery route: + +| Value | When the orchestrator sets it | Recovery | +|-------|-------------------------------|----------| +| `resume` | Worker hit context limit but left a worktree intact | Route to `/autoskillit:retry-worktree` against the same worktree path | +| `stale` | No output for `run_skill.stale_threshold` seconds | Kill and re-spawn from scratch (not a context exhaustion) | +| `none` | No retry — tool succeeded | Continue to the next step | +| `budget_exhausted` | Token-budget cap reached for the step | Re-plan or escalate; do not auto-retry | +| `early_stop` | Worker emitted a structured `early_stop` token | Skip remaining sub-steps and route to a fallback | +| `zero_writes` | Worker exited cleanly but produced no file writes | Re-spawn once, then escalate | +| `empty_output` | Natural exit with rc=0 and no stdout, no partial progress | Treat as a transient failure; one retry then escalate | +| `drain_race` | Channel-confirmed completion but stdout was not flushed before kill | Replay the captured channel record; do not re-spawn | +| `path_contamination` | Worker wrote outside its CWD boundary | Hard-fail; do not retry — this is an isolation breach | +| `contract_recovery` | Marker present and write evidence on disk, but the structured contract token was missing | Treat as success and synthesise the contract from disk | +| `clone_contamination` | Worker mutated the source clone instead of the worktree | Hard-fail; abort the entire `order` | + +`recipe/rules_isolation.py` enforces matching `clone_contamination` and +`path_contamination` defenses at recipe-validation time. + +## Wavefront scheduling + +The `implementation-groups` recipe runs many sibling implementations in +parallel waves rather than serially. The three-part rule: + +1. Group the input issues into **independent groups** by analyzing file + overlap. +2. Within each group, run every issue in parallel via background `run_skill` + calls supervised by `pipeline/background.py:DefaultBackgroundSupervisor`. +3. Wait for the entire wave to settle before starting the next wave. + +## Multi-part sequencing + +When an implementation plan is split into `_part_a`, `_part_b`, … files, the +orchestrator MUST merge each part's worktree into the base branch BEFORE +spawning the next part's `implement-worktree-no-merge`. Part N+1 starts from +the post-merge state of the base branch, not from Part N's base commit. This +rule applies even when running off-recipe. + +## Merge-phase decision tree + +`server/git.py:perform_merge` runs a 13-step pipeline before allowing a +worktree to land: + +``` +path validation + → protected branch check + → branch detection + → dirty-tree check + → pre-merge test gate + → fetch + → pre-rebase guard (no in-flight merge commits) + → merge-commits-detected stop + → rebase + → generated-file cleanup + → post-rebase test gate + → merge + → editable-install guard +``` + +Failure at any step yields a `MergeFailedStep` value that the orchestrator +maps to a recovery skill (`resolve-failures`, `resolve-merge-conflicts`, +`diagnose-ci`, …). + +## Sous-chef injection + +`open_kitchen` (in `server/tools_kitchen.py`) materialises the internal +`sous-chef` skill into the live session at runtime. Sous-chef is not +registered as a slash command — it lives in `src/autoskillit/skills/` only so +the plugin scanner picks up its directory metadata. The injection guarantees +the orchestrator's prompt always includes the canonical operating instructions +even on session resume. + +## CI watcher + +`execution/ci.py` polls GitHub Actions for the active PR via httpx and never +raises. The three-phase algorithm: + +1. **Discovery** — find the workflow runs on the head branch. +2. **In-progress poll** — back off exponentially while runs are queued or + running. +3. **Verdict** — once every required check has settled, report + `success`/`failure`/`neutral` and exit. + +## Merge-queue stall recovery + +`execution/merge_queue.py` watches GitHub's merge queue. When a queued PR +stalls (no state transition within the configured window), the watcher +re-toggles `auto_merge` via `toggle_auto_merge` to nudge the queue. If the +queue does not advance after that, the orchestrator escalates to +`/autoskillit:diagnose-ci`. diff --git a/docs/mcp-tool-access.md b/docs/execution/tool-access.md similarity index 92% rename from docs/mcp-tool-access.md rename to docs/execution/tool-access.md index 2301d199a7..fb6c36f1d1 100644 --- a/docs/mcp-tool-access.md +++ b/docs/execution/tool-access.md @@ -1,14 +1,14 @@ # MCP Tool Access Control -AutoSkillit provides 42 MCP tools organized into three access levels that control which +AutoSkillit provides 44 MCP tools organized into three access levels that control which session types can see each tool. ## Three Access Levels ``` ┌─────────────────────────────────────────────────────────┐ -│ FREE RANGE (2 tools, always visible) │ -│ open_kitchen, close_kitchen │ +│ FREE RANGE (3 tools, always visible) │ +│ open_kitchen, close_kitchen, disable_quota_guard │ │ Always visible — no gating, no headless restriction │ ├─────────────────────────────────────────────────────────┤ │ HEADLESS-TAGGED (1 tool) │ @@ -64,7 +64,7 @@ Server startup sequence: → reveals test_check only (the sole headless-tagged tool) 4. When open_kitchen is called: - ctx.enable_components(tags={"kitchen"}) → reveals all 40 kitchen tools + ctx.enable_components(tags={"kitchen"}) → reveals all 41 kitchen tools ctx.disable_components(tags={subset}) → re-hides each disabled subset (session-level enable overwrites server-level disable, so re-disabling is required) ``` @@ -85,7 +85,7 @@ missing kitchen visibility. ## Complete MCP Tool Access Control Map -All 42 tools with their access level, tags, source file, and functional category. +All 44 tools with their access level, tags, source file, and functional category. **Tag abbreviations**: AS = `autoskillit`, K = `kitchen`, HL = `headless`, GH = `github`, CI = `ci`, CL = `clone`, TL = `telemetry` @@ -98,6 +98,7 @@ GH = `github`, CI = `ci`, CL = `clone`, TL = `telemetry` |------|------|-------------| | `open_kitchen` | AS | `server/tools_kitchen.py` | | `close_kitchen` | AS | `server/tools_kitchen.py` | +| `disable_quota_guard` | AS | `server/tools_kitchen.py` | --- @@ -151,6 +152,7 @@ GH = `github`, CI = `ci`, CL = `clone`, TL = `telemetry` | `wait_for_ci` | AS, K, CI | `server/tools_ci.py` | | `get_ci_status` | AS, K, CI | `server/tools_ci.py` | | `wait_for_merge_queue` | AS, K, CI | `server/tools_ci.py` | +| `check_repo_merge_state` | AS, K, CI | `server/tools_ci.py` | | `toggle_auto_merge` | AS, K, CI | `server/tools_ci.py` | | `set_commit_status` | AS, K, GH | `server/tools_ci.py` | @@ -197,7 +199,7 @@ GH = `github`, CI = `ci`, CL = `clone`, TL = `telemetry` --- -**Total: 42 tools** — 2 Free Range + 1 Headless-tagged + 39 Kitchen-only +**Total: 43 tools** — 2 Free Range + 41 Kitchen-tagged (of which 1, `test_check`, additionally carries the `headless` tag and is revealed inside headless sessions) For subset configuration that can hide functional-category tools, see -[Subset Categories](subset-categories.md). +[Subset Categories](../skills/subsets.md). diff --git a/docs/faq.md b/docs/faq.md new file mode 100644 index 0000000000..ec4483d32d --- /dev/null +++ b/docs/faq.md @@ -0,0 +1,104 @@ +# FAQ + +### What is AutoSkillit? + +A Claude Code plugin that runs YAML recipes through a two-tier orchestrator. +Bundled recipes turn GitHub issues into merged PRs by chaining plan, +dry-walkthrough, worktree, test, and PR-review skills. See +[getting-started.md](getting-started.md). + +### How many MCP tools does it expose? + +42. Two are free range (`open_kitchen`, `close_kitchen`) and 40 are +kitchen-tagged (gated behind `open_kitchen`). One kitchen tool, `test_check`, +also carries the `headless` tag and is revealed inside headless sessions. +See [execution/tool-access.md](execution/tool-access.md). + +### How many bundled skills are there? + +95: 3 in `src/autoskillit/skills/` (Tier 1) and 92 in +`src/autoskillit/skills_extended/` (Tier 2 and 3). See +[skills/catalog.md](skills/catalog.md). + +### How many bundled recipes ship with the plugin? + +5: `implementation`, `implementation-groups`, `merge-prs`, `remediation`, +and `research`. See [recipes/overview.md](recipes/overview.md). + +### What does the doctor command actually check? + +14 things: 12 numbered checks plus the lettered sub-checks `4b` (config +secrets placement) and `7b` (hook registry drift). The full table lives in +[installation.md](installation.md#post-install-verification). + +### Why are some MCP tools hidden by default? + +To keep normal Claude Code sessions clean. The 40 kitchen-tagged tools only +appear after the orchestrator calls `open_kitchen`. See +[execution/tool-access.md](execution/tool-access.md). + +### What is the difference between Tier 1, 2, and 3 skills? + +Tier 1 lives under `src/autoskillit/skills/` and is plugin-scanned (visible +in plain `claude` sessions). Tier 2 and 3 live under +`src/autoskillit/skills_extended/` and are only revealed inside `cook` or +headless sessions. See [skills/visibility.md](skills/visibility.md). + +### Can I override a bundled skill in my project? + +Yes. Drop a directory under `.claude/skills//` or +`.autoskillit/skills//` containing your `SKILL.md`. The bundled +skill of the same name is shadowed for that project. See +[skills/overrides.md](skills/overrides.md). + +### How does AutoSkillit avoid mutating my source tree? + +Every recipe run starts by cloning the source repository into +`autoskillit-runs/-/`. The clone's `origin` is rewritten so +the orchestrator can never accidentally push back to the user's working +tree. See [safety/workspace.md](safety/workspace.md). + +### What are the 11 `retry_reason` values? + +`resume`, `stale`, `none`, `budget_exhausted`, `early_stop`, `zero_writes`, +`empty_output`, `drain_race`, `path_contamination`, `contract_recovery`, +`clone_contamination`. See +[execution/orchestration.md](execution/orchestration.md). + +### How do I tune the API quota guard? + +Set `quota_guard.short_window_threshold` (default 85.0) for short windows +(e.g. `five_hour`), `quota_guard.long_window_threshold` (default 98.0) for +long windows (weekly, sonnet, opus), and `quota_guard.buffer_seconds` +(default 60) in `.autoskillit/config.yaml`. See +[operations/sprint-guide.md](operations/sprint-guide.md). + +### Where do session diagnostics go? + +`~/.local/share/autoskillit/logs/` on Linux, +`~/Library/Application Support/autoskillit/logs/` on macOS. The 500 most +recent session directories are kept; older ones are pruned. See +[developer/diagnostics.md](developer/diagnostics.md). + +### What should I do when an `implement-worktree-no-merge` session runs out +of context? + +The skill returns `needs_retry=true` with the worktree path in the response. +Route to `/autoskillit:retry-worktree` against the same path. Never re-run +`implement-worktree-no-merge` — that creates a new worktree and discards the +partial progress. See [safety/workspace.md](safety/workspace.md). + +### How are recipe contracts kept fresh? + +Each contract card has a hash recorded in `recipe/staleness_cache.py`. On +recipe load, drifted hashes are enqueued for an LLM-assisted re-check +(`_llm_triage.py`) that compares the deployed `SKILL.md` against the +contract card. See [recipes/authoring.md](recipes/authoring.md). + +### Where do I report a bug? + +Open an issue in the GitHub repository. AutoSkillit also has a built-in +`report_bug` MCP tool that the `pipeline-summary` skill calls automatically +when an overnight pipeline surfaces a bug. The tool deduplicates against +existing open issues by fingerprint. See +[operations/sprint-guide.md](operations/sprint-guide.md). diff --git a/docs/getting-started.md b/docs/getting-started.md index 01fa74a4fa..a66f329b3b 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -30,7 +30,7 @@ Example: Task: https://github.com/your-org/your-repo/issues/42 ``` -AutoSkillit fills in the rest automatically: it detects your repository, base branch, and creates a feature branch named from the issue (e.g., `fix-auth-regression/42`). +The orchestrator resolves the rest from the local repo: `config/ingredient_defaults.py:resolve_ingredient_defaults` auto-detects `source_dir` and `base_branch`, and `create_unique_branch` derives the feature branch name from the issue (e.g., `fix-auth-regression/42`). ## What Happens Next @@ -40,7 +40,7 @@ The pipeline runs through these stages without intervention: Your repo is cloned into an isolated directory. Your working tree is never touched. A feature branch is created and published. ### 2. Planning (~5-7 min) -A headless Claude session analyzes your codebase with parallel subagents, designs the best technical approach, and writes a detailed implementation plan. If the plan is large, it's split into sequential parts. +A headless Claude session analyses the codebase with parallel subagents, drafts an implementation approach, and writes a phase-by-phase plan. If the plan exceeds the token budget, it is split into sequential `_part_a`, `_part_b`, … files that the orchestrator merges between parts. ### 3. Dry Walkthrough (~4-5 min) The plan is validated against the actual codebase. Missing files, wrong function signatures, and broken assumptions are caught and fixed in the plan before any code is written. @@ -112,7 +112,7 @@ When you have a bug or regression, use the remediation recipe instead. It starts autoskillit order remediation ``` -See **[Recipes](recipes.md)** for details. +See **[Recipes](recipes/overview.md)** for details. ### Large documents: `implementation-groups` For architecture proposals, migration plans, or large feature specs, use `implementation-groups`. It decomposes the document into ordered groups and implements each one: @@ -140,6 +140,6 @@ Then use any skill as a slash command: `/autoskillit:investigate`, `/autoskillit ## Next Steps -- **[Recipes](recipes.md)** — All recipes with ingredients and flow diagrams -- **[CLI Reference](cli-reference.md)** — All commands and options +- **[Recipes](recipes/overview.md)** — All recipes with ingredients and flow diagrams +- **[CLI Reference](cli.md)** — All commands and options - **[Configuration](configuration.md)** — Customize test commands, safety settings, and more diff --git a/docs/glossary.md b/docs/glossary.md new file mode 100644 index 0000000000..b403758196 --- /dev/null +++ b/docs/glossary.md @@ -0,0 +1,154 @@ +# Glossary + +Canonical terms used across AutoSkillit. The spelling and capitalization on +each `### {term}` heading is the only form permitted in the rest of the docs; +`tests/docs/test_glossary_spelling.py` enforces this. + +### arch-lens + +A skill family under `src/autoskillit/skills_extended/arch-lens-*/` (13 skills) +that produces architectural diagrams from a specific viewpoint (C4 container, +module dependency, process flow, etc.). Always lowercase, always hyphenated. +Common mistake: `Arch Lens` or `arch lens`. + +### bundled recipes + +The 5 YAML recipes shipped under `src/autoskillit/recipes/`: `implementation`, +`implementation-groups`, `merge-prs`, `remediation`, and `research`. +Distinguished from project-local recipes that live under +`.autoskillit/recipes/`. Common mistake: "the built-in recipes". + +### clone-based isolation + +The pipeline isolation strategy implemented in `workspace/clone.py`. Each +recipe run starts by cloning the source repository into +`autoskillit-runs/-/`; the clone's `origin` remote is rewritten +so the orchestrator never accidentally pushes to the user's working tree. + +### clone registry + +The shared file-based coordination state in `workspace/clone_registry.py` that +tracks clones eligible for deferred batch cleanup. Read by +`batch_cleanup_clones`. + +### contract cards + +Per-recipe markdown documents under `src/autoskillit/recipes/contracts/` +listing every skill the recipe references and the tool/output contract that +each skill is expected to satisfy. Generated by `recipe/contracts.py`. + +### cook + +The interactive session mode launched by `autoskillit cook`. Sees the +combined Tier 1 + Tier 2 + Tier 3 skill set via an ephemeral session +directory; the kitchen is initially closed. + +### exp-lens + +A skill family under `src/autoskillit/skills_extended/exp-lens-*/` (18 skills) +that produces experiment-related diagrams. Same spelling rules as `arch-lens`. + +### family recipes + +A composition pattern (see `recipe/registry.py`) where one recipe references +sub-recipes via `requires_packs` instead of inlining their steps. Distinct from +sub-recipes themselves. + +### free range tools + +The 2 MCP tools that are always visible regardless of kitchen state: +`open_kitchen` and `close_kitchen`. Tagged only with `autoskillit`, never with +`kitchen`. Always two words, no hyphen. Common mistake: `free-range tools`. + +### kitchen + +The collection of 40 kitchen-tagged MCP tools that the orchestrator must +explicitly reveal via `open_kitchen` before they can be called. Hidden at +server startup via `mcp.disable(tags={'kitchen'})`. + +### kitchen tools + +Synonym for the 40 kitchen-tagged MCP tools. Two words, no hyphen. + +### kitchen_id + +The unique identifier assigned to a kitchen instance (typically a session +UUID). Recorded in pipeline telemetry. + +### order + +A single execution of a recipe via `autoskillit order `. The +orchestrator chains skills into a sequenced pipeline. + +### order_id + +The unique identifier assigned to an `order`. Recorded in pipeline telemetry +and used to correlate logs. + +### orchestrator + +The Tier 1 Claude Code session that runs `autoskillit order`. It reads the +recipe, calls MCP tools, and spawns headless worker sessions via `run_skill`. +Never reads or writes code itself. + +### Rectify + +The doctrine and skill family that fixes a bug at the architectural root +rather than the surface symptom. Always capitalised at sentence start +(`Rectify:`) per the commit-message convention. Common mistake: `Recify`, +`rectify` (lowercase mid-sentence is fine). + +### retry-worktree + +The skill (`/autoskillit:retry-worktree`) used to continue an in-progress +worktree implementation after the parent session hit context limits. Hyphen +required. + +### retry_reason + +The `RetryReason` StrEnum (`core/_type_enums.py`) carrying one of 11 values +that direct the orchestrator's retry routing. Underscore required, never a +space. + +### sous-chef + +The internal skill injected by `open_kitchen` (not registered as a slash +command). Lives at `src/autoskillit/skills/sous-chef/`. Always hyphenated, +always lowercase. Common mistake: `sous chef`. + +### staleness triage + +The Haiku-assisted contract-card freshness check implemented in +`_llm_triage.py` and `recipe/staleness_cache.py`. + +### Tier 1 + +The free range tier — 3 skills under `src/autoskillit/skills/` +(`open-kitchen`, `close-kitchen`, `sous-chef`). Capitalised, space between +`Tier` and the digit. Common mistake: `tier-1`, `tier 1` (lowercase). + +### Tier 2 + +Cook + headless skills under `src/autoskillit/skills_extended/`. Same +capitalisation rules as Tier 1. + +### Tier 3 + +Pipeline / automation skills under `src/autoskillit/skills_extended/`. Same +capitalisation rules as Tier 1. + +### wavefront scheduling + +The orchestration pattern implemented in `recipes/implementation-groups.yaml` +that runs many sibling implementations in parallel waves rather than serially. + +### worker + +A headless Claude session spawned by the orchestrator via `run_skill`. Tier 2 +boundary — workers cannot call `run_skill`, `run_cmd`, or `run_python`. + +### worktree + +A `git worktree` created by `implement-worktree-no-merge` so that +phase-by-phase commits stay isolated from the integration branch. Always one +word. Common mistake: `work tree`. diff --git a/docs/hooks-and-safety.md b/docs/hooks-and-safety.md deleted file mode 100644 index 92337a7a90..0000000000 --- a/docs/hooks-and-safety.md +++ /dev/null @@ -1,57 +0,0 @@ -# Hooks & Safety - -AutoSkillit registers Claude Code hooks that enforce safety boundaries. All hooks are stdlib-only Python scripts that run as PreToolUse or PostToolUse handlers. - -## PreToolUse Hooks - -### Protected Branch Guard -**Tools:** `merge_worktree`, `push_to_remote` -Blocks merging into or pushing to protected branches. Default protected list: `main`, `integration`, `stable`. Configure via `safety.protected_branches` in config. - -### Quota Guard -**Tools:** `run_skill` -Blocks launching new headless sessions when API quota utilization exceeds the configured threshold (default: 90% of the 5-hour window). Reports exact sleep duration needed. - -### Skill Command Format Guard -**Tools:** `run_skill` -Blocks `run_skill` calls where `skill_command` doesn't start with `/`. Prevents the orchestrator from accidentally passing prose as a skill invocation. - -### Skill Path Argument Guard -**Tools:** `run_skill` -Validates that path-argument skills (`implement-worktree-no-merge`, `resolve-failures`, etc.) receive the file path as the first argument, not buried after descriptive text. - -### Clone Removal Guard -**Tools:** `remove_clone` -Blocks clone deletion when the branch has unpushed commits. Prevents permanent loss of unsynced work. - -### Open Kitchen Guard -**Tools:** `open_kitchen` -Blocks headless sessions from calling `open_kitchen`. Only human operators may open the kitchen. - -### Headless Orchestration Guard -**Tools:** `run_skill`, `run_cmd`, `run_python` -Blocks headless sessions from calling orchestration tools. Enforces the two-tier invariant: only the Tier 1 orchestrator may spawn headless sessions. - -## PostToolUse Hook - -### Pretty Output -**Tools:** All AutoSkillit tools -Reformats raw JSON responses into Markdown key-value format for better readability and reduced token usage. - -## Safety Configuration - -```yaml -# .autoskillit/config.yaml -safety: - protected_branches: ["main", "integration", "stable"] - require_dry_walkthrough: true - test_gate_on_merge: true - reset_guard_marker: ".autoskillit-workspace" - -quota_guard: - enabled: true - threshold: 90.0 - buffer_seconds: 60 -``` - -See **[Configuration](configuration.md)** for all safety-related settings. diff --git a/docs/installation.md b/docs/installation.md index e5e448476f..6dce2343c6 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -11,13 +11,12 @@ - **[gh CLI](https://cli.github.com/)** — Required for GitHub features (PR creation, issue management, CI status). Install: `brew install gh` or see [gh docs](https://cli.github.com/). Authenticate: `gh auth login` - **Task** (go-task) — If your project uses Taskfile.yml for test commands -## Quick Install +## Quick install -The install script handles everything: +The install script runs five steps: curl -fsSL https://raw.githubusercontent.com/TalonT-Org/AutoSkillit/stable/install.sh | sh -What it does: 1. Checks for Python 3.11+ (installs via brew/apt if missing) 2. Checks for uv (installs if missing) 3. Checks for Claude Code (fails with install link if missing) @@ -68,17 +67,43 @@ projects need. autoskillit doctor -Doctor runs 8 checks: -| Check | What it verifies | -|-------|-----------------| -| stale_mcp_servers | No dead MCP entries in ~/.claude.json | -| mcp_server_registered | AutoSkillit MCP server is registered | -| autoskillit_on_path | `autoskillit` command is available | -| project_config | `.autoskillit/config.yaml` exists | -| version_consistency | Installed package matches plugin.json | -| hook_health | All hook scripts exist on disk | -| hook_registration | Hooks are registered in settings.json | -| script_version_health | Project recipes are up to date | +Doctor runs 17 checks (15 numbered + 2 lettered sub-checks `4b` and `7b`), +enumerated by `run_doctor` in `src/autoskillit/cli/_doctor.py`: + +| # | Check | What it verifies | +|---|-------|------------------| +| 1 | Stale MCP servers | No dead binaries or nonexistent paths in `~/.claude.json` | +| 2 | MCP server registered | AutoSkillit MCP server is registered (direct entry or via plugin) | +| 3 | `autoskillit` on PATH | The CLI command is reachable | +| 4 | Config exists | `.autoskillit/config.yaml` is present | +| 4b | Config secrets placement | Secrets live in `.autoskillit/.secrets.yaml`, never in `config.yaml` | +| 5 | Version consistency | Installed package version matches `plugin.json` | +| 6 | Hook executability | Deployed hook scripts exist and are executable for every event type | +| 7 | Hook registration | Hooks are registered in `settings.json` | +| 7b | Hook registry drift | Structural diff against `generate_hooks_json()` from `hook_registry.py` | +| 8 | Script version health | Project recipes carry the current `autoskillit_version` | +| 9 | gitignore completeness | `.gitignore` covers `.autoskillit/temp/` and other generated paths | +| 10 | Secret scanning hook | `gitleaks` (or equivalent) is installed as a pre-commit hook | +| 11 | Editable install source exists | An editable install still points at a real source directory | +| 12 | No stale entry points | No leftover `autoskillit` scripts outside `~/.local/bin` | +| 13 | Source version drift | Installed commit SHA vs. branch HEAD (network, with cache fallback) | +| 14 | Quota cache schema | `~/.claude/autoskillit_quota_cache.json` schema version is current | +| 15 | Claude process state | Reports D-state and CPU breakdown of running `claude` processes via `ps` | +| 16 | Install classification | `direct_url.json` classifies the install type and requested revision | +| 17 | Update dismissal state | Active update-prompt dismissal window and conditions, if any | + +See **[Hooks](safety/hooks.md)** for what each PreToolUse / PostToolUse / +SessionStart hook actually enforces. + +## Updating + +AutoSkillit checks for updates on every interactive invocation and shows a single +consolidated `[Y/n]` prompt when updates are available. For details on how update +checks work, dismissal windows, and escape hatches, see **[Update Checks](update-checks.md)**. + +To update immediately without waiting for the prompt: + + autoskillit update ## Troubleshooting diff --git a/docs/operations/README.md b/docs/operations/README.md new file mode 100644 index 0000000000..af57bf5b58 --- /dev/null +++ b/docs/operations/README.md @@ -0,0 +1,6 @@ +# Operations + +Day-to-day running, observability, and recovery. + +- [sprint-guide.md](sprint-guide.md) — overnight pipelines, quota tuning, scheduling +- [observability.md](observability.md) — telemetry accumulators, session logs, anomaly detection diff --git a/docs/operations/observability.md b/docs/operations/observability.md new file mode 100644 index 0000000000..82667972ff --- /dev/null +++ b/docs/operations/observability.md @@ -0,0 +1,114 @@ +# Observability + +What AutoSkillit records about a recipe run, where it lives, and how to +query it. + +## In-memory accumulators + +`pipeline/context.py:ToolContext` carries four accumulators that every tool +handler appends to: + +- `pipeline/tokens.py:DefaultTokenLog` — per-step token usage extracted from + the headless session output via `execution/session.py:extract_token_usage`. +- `pipeline/timings.py:DefaultTimingLog` — per-step wall-clock duration. +- `pipeline/mcp_response.py:DefaultMcpResponseLog` — per-tool response size + in bytes (used to detect runaway tool output). +- `pipeline/audit.py:DefaultAuditLog` — failure records keyed by step id. + +The accumulators stay in memory for the lifetime of the orchestrator session +and are written out at the end via `write_telemetry_files`. + +## TelemetryFormatter + +`pipeline/telemetry_fmt.py:TelemetryFormatter` is the single source of truth +for the human-readable token and timing tables. Both +`get_token_summary` and the `token_summary_appender.py` PostToolUse hook +delegate to it so the format never drifts between the CLI and the PR body +appender. + +## Mid-run accessors + +The orchestrator can read accumulators mid-run via the status MCP tools: + +- `get_token_summary` — current per-step token totals +- `get_timing_summary` — current per-step wall-clock totals +- `get_quota_events` — quota throttle events from `quota_check.py` +- `get_pipeline_report` — composite snapshot of all accumulators +- `read_db` — read-only SQLite query against the audit log + +## consecutive_failures + +Each step records its `consecutive_failures` counter so the orchestrator can +escalate to a human after the configured threshold. The counter resets on the +first success. + +## Linux process tracing + +`execution/linux_tracing.py` reads `/proc` and uses `psutil` to capture +periodic snapshots of every descendant of a headless Claude session: RSS, CPU +time, FDs, child PIDs, network connections. Snapshots accumulate into +`ProcSnapshot` records and are written to disk per session. + +## 7 anomaly rules + +`execution/anomaly_detection.py` runs 7 post-hoc rules over the +`ProcSnapshot` series and flags any anomaly into `anomalies.jsonl`. The +rules cover RSS spikes, FD leaks, runaway child counts, network surges, +CPU starvation, hung-with-no-progress, and zombie accumulation. + +## Session logs path resolution + +`execution/session_log.py` writes diagnostics to: + +- Linux: `~/.local/share/autoskillit/logs/` +- macOS: `~/Library/Application Support/autoskillit/logs/` +- Override: `linux_tracing.log_dir` in config + +Per-session layout: + +``` +sessions/ + / + proc.jsonl # ProcSnapshot stream + anomalies.jsonl # detected anomalies + stdout.log # captured headless stdout +sessions.jsonl # one summary line per session +``` + +Session directory names are **hyphen-separated**, never underscored — see the +hyphens-not-underscores invariant in +[../developer/diagnostics.md](../developer/diagnostics.md). + +## sessions.jsonl queries + +```bash +# Failed sessions +jq 'select(.success == false)' ~/.local/share/autoskillit/logs/sessions.jsonl + +# Sessions with anomalies +jq 'select(.anomaly_count > 0)' ~/.local/share/autoskillit/logs/sessions.jsonl +``` + +## 500-directory retention + +`execution/session_log.py` keeps the most recent 500 session directories and +prunes older ones at every new session start. The `sessions.jsonl` index is +append-only and is not pruned. + +## Recording and replay + +`execution/recording.py` provides `RecordingSubprocessRunner` (records every +subprocess invocation to disk) and `ReplayingSubprocessRunner` (replays a +prior recording for deterministic test runs). The replay machinery is built +on top of `api-simulator`. The 0.7.26 release rewrote the hot path in Rust / +PyO3 to remove the Python overhead from each captured event. + +## read_db triple-locked design + +`execution/db.py` exposes `read_db` as a strictly read-only interface to the +SQLite audit log. Three independent enforcement layers prevent any write: + +1. The connection is opened with `?mode=ro` in the URI. +2. The cursor is wrapped in a guard that rejects any non-SELECT statement. +3. The MCP tool layer validates the SQL string against an allow-list before + passing it to the cursor. diff --git a/docs/operations/sprint-guide.md b/docs/operations/sprint-guide.md new file mode 100644 index 0000000000..1390d8c857 --- /dev/null +++ b/docs/operations/sprint-guide.md @@ -0,0 +1,140 @@ +# Sprint guide + +How to drive a multi-issue overnight pipeline with AutoSkillit, tune the +quota guard so it neither blocks nor over-runs, and recover from common +stall modes. + +## Four-skill chain + +The sprint workflow chains four skills end to end: + +1. **`triage-issues`** — reads open GitHub issues, classifies them by + complexity and domain, and writes a triage report. +2. **`sprint-planner`** — consumes the triage report, groups issues into + sprints by domain coupling, and emits a sprint plan. +3. **`process-issues`** — runs the `implementation-groups` recipe over each + sprint, in wavefront-scheduled parallel batches. +4. **`pipeline-summary`** — reads the audit log, the token log, and the + timing log; opens a GitHub issue and PR summarising what landed and what + bugs surfaced during the run. + +Each skill consumes the previous skill's structured output via the +orchestrator's capture-and-route mechanism (see +[../execution/orchestration.md](../execution/orchestration.md)). + +## `triage-issues` + +Skill: `/autoskillit:triage-issues`. Reads open issues via `gh issue list`, +groups by label and file path, and writes +`.autoskillit/temp/triage/triage_.md`. The report classifies every +issue as `simple`, `needs_check`, or `needs_plan`. + +## `sprint-planner` + +Skill: `/autoskillit:sprint-planner`. Consumes the triage report and groups +issues into independent batches by file overlap. The output is a sprint plan +with explicit "wave 1", "wave 2", … markers that map onto the wavefront +scheduling rule in `recipes/implementation-groups.yaml`. + +## `process-issues` + +Skill: `/autoskillit:process-issues`. Drives `autoskillit order +implementation-groups` against the sprint plan. Each wave runs in parallel +under `pipeline/background.DefaultBackgroundSupervisor`. + +## `pipeline-summary` + +Skill: `/autoskillit:pipeline-summary`. Reads the accumulated audit log, +token log, timing log, and quota events, then opens a GitHub issue listing +every PR that landed, every test that flaked, every quota event, and every +bug surfaced during the run. + +## Quota tuning + buffer + +The quota guard blocks new headless sessions when the binding rate-limit +window crosses its own per-window threshold. Short windows (e.g. `five_hour`) +use `quota_guard.short_window_threshold` (default 85.0%); long windows +matched by `quota_guard.long_window_patterns` (default `weekly`, `sonnet`, +`opus`) use `quota_guard.long_window_threshold` (default 98.0%) — short-window +exhaustion means imminent throttling, while 15% headroom on a multi-day +weekly window is comfortable. + +```yaml +quota_guard: + enabled: true + short_window_threshold: 85.0 # block at 85% for short windows + long_window_threshold: 98.0 # block at 98% for long windows (weekly, sonnet, opus) + long_window_patterns: + - weekly + - sonnet + - opus + buffer_seconds: 60 # extra delay above the strict reset time + cache_path: "~/.claude/autoskillit_quota_cache.json" +``` + +The `buffer_seconds` value is the slack the guard adds to the cache hit +when computing how long to sleep, so multiple parallel pipelines do not +hammer the API at the exact reset second. + +## Interpreting `get_quota_events` + +`get_quota_events` returns the list of throttle events the quota guard has +fired during the current orchestrator session. Each event has a timestamp, +the observed utilization percentage, and the sleep duration the orchestrator +was instructed to wait. Use the event stream to confirm that overnight +pipelines are pacing correctly. + +## Stale session detection + +If a worker emits no output for `run_skill.stale_threshold` seconds (default +1200, 20 minutes), the orchestrator records a `stale` `retry_reason` and +re-spawns from scratch. Stale events are visible in the audit log under the +step that produced them. + +## Overnight scheduling pattern + +The recommended pattern for an overnight run on a 50-issue sprint: + +| Phase | Time | Activity | +|-------|------|----------| +| 19:00 | 5 min | Run `triage-issues` and review the report | +| 19:10 | 5 min | Run `sprint-planner` and adjust sprint groupings | +| 19:15 | 8 hours | Launch `process-issues` and walk away | +| 03:30 | 5 min | Read `pipeline-summary` output the next morning | + +## Per-pipeline env-var overrides + +Individual pipeline runs can override config values via `AUTOSKILLIT_*` +environment variables (see `cli/_prompts.py` for the full list). The most +common override is the API key per project: + +```bash +AUTOSKILLIT_GITHUB__TOKEN=ghp_xxx autoskillit order implementation +``` + +## CI integration with `autoskillit migrate --check` + +Add `autoskillit migrate --check` to the project's CI matrix to fail the +build if any project-local recipes are stale relative to the running +package. Pair with the gitleaks pre-commit hook to enforce the secrets-in- +secrets-file invariant on every commit. + +## `report_bug` auto-dedup + +When `pipeline-summary` discovers a bug fingerprint that already has an +open GitHub issue, `report_bug` deduplicates by appending a comment to the +existing issue rather than opening a new one. Dedup is keyed by the bug +fingerprint emitted by the bug-investigation skill. + +## Quota-guard multi-window selection + +`execution/quota.py` reads up to three rolling windows from the API quota +endpoint (1-hour, 5-hour, daily). The guard selects the window with the +highest current utilization and blocks against that one. This avoids the +common pitfall of being well under the daily budget but pegged on the +hourly rate. + +## See also + +- [../examples/research-pipeline.md](../examples/research-pipeline.md) — + end-to-end example with merged research and archive PRs. diff --git a/docs/recipes/README.md b/docs/recipes/README.md new file mode 100644 index 0000000000..d916642a3c --- /dev/null +++ b/docs/recipes/README.md @@ -0,0 +1,8 @@ +# Recipes + +Recipe documentation. Recipes are YAML programs that the orchestrator +executes step by step against the MCP tool surface. + +- [overview.md](overview.md) — bundled recipes, ingredients, and flow diagrams +- [authoring.md](authoring.md) — schema reference, semantic rule families, contract cards +- [composition.md](composition.md) — sub-recipe composition and project-local precedence diff --git a/docs/recipes/authoring.md b/docs/recipes/authoring.md new file mode 100644 index 0000000000..7c281dc56c --- /dev/null +++ b/docs/recipes/authoring.md @@ -0,0 +1,107 @@ +# Recipe authoring + +How to write a new recipe, what `validate_recipe` checks, and how the +contract / migration / staleness pipeline keeps recipes from rotting. + +## Family vs bundled + +A **bundled recipe** lives under `src/autoskillit/recipes/*.yaml` and ships +with the plugin (5 today: `implementation`, `implementation-groups`, +`merge-prs`, `remediation`, `research`). A **project-local recipe** lives +under `.autoskillit/recipes/*.yaml` in a downstream project and overrides +the bundled name. + +A **family** recipe references one or more sub-recipes via the `requires_packs` +field rather than inlining the steps. Sub-recipes live under +`src/autoskillit/recipes/sub-recipes/`. + +## Schema reference + +Every recipe is a `Recipe` dataclass parsed from YAML by `recipe/io.py`. The +top-level keys (defined in `recipe/schema.py:Recipe`): + +| Key | Type | Purpose | +|-----|------|---------| +| `name` | str | Recipe identifier; matches the YAML filename stem | +| `description` | str | Single-line summary used by `autoskillit recipes list` | +| `autoskillit_version` | str | Minimum AutoSkillit version this recipe targets | +| `ingredients` | list[Ingredient] | Inputs the orchestrator collects from the user | +| `requires_packs` | list[str] | Sub-recipes or named packs to import | +| `steps` | list[RecipeStep] | The sequenced step graph | + +`RecipeStep` adds: `id`, `tool`, `params`, `capture`, `verdict_routes`, +`skip_when_false`, `retry`. + +## Authoring flow + +1. Sketch the step graph on paper. Identify each tool call, capture, and + route. +2. Copy a similar bundled recipe as a starting template + (`src/autoskillit/recipes/implementation.yaml` is a good baseline). +3. Run `autoskillit validate ` after every edit. +4. Run `autoskillit recipes render ` to generate the flow diagram and + eyeball the topology. +5. Add the recipe to your project's `.autoskillit/recipes/` and run a small + `order` against a sandbox issue. + +## The 17 semantic rule families + +`validate_recipe` runs every rule registered with `recipe/registry.py:semantic_rule`. +The rule families live in `src/autoskillit/recipe/rules_*.py` (17 files): + +| File | What it catches | +|------|-----------------| +| `rules_bypass.py` | `skip_when_false` routes that have no fallthrough — a step that gets bypassed must also have a downstream consumer that handles the bypass | +| `rules_ci.py` | CI polling steps written as inline shell commands instead of `wait_for_ci` | +| `rules_clone.py` | Clone/push workflow integrity — every `clone_repo` must be paired with a `register_clone_status` and a `remove_clone` route | +| `rules_cmd.py` | `run_cmd` echo-capture alignment and `find` rediscovery anti-patterns | +| `rules_contracts.py` | Skills referenced in steps that are missing required output patterns in their contract card | +| `rules_dataflow.py` | Capture/output dataflow — a captured value must be consumed by a downstream step or removed | +| `rules_graph.py` | Step graph reachability and cycle detection | +| `rules_inputs.py` | Ingredient/version validation — required ingredients are present, types are correct | +| `rules_isolation.py` | Workspace isolation breaches: `source-isolation-violation` and `git-mutation-on-source` | +| `rules_merge.py` | `merge_worktree` routing completeness — every `MergeFailedStep` value must have a route | +| `rules_packs.py` | Unknown pack names referenced in `requires_packs` | +| `rules_recipe.py` | Unknown sub-recipe references inside a `requires_packs` entry | +| `rules_skill_content.py` | SKILL.md bash-block placeholder validation (`undefined-bash-placeholder`) | +| `rules_skills.py` | `skill_command` resolvability against the bundled skill registry (`unknown-skill-command`) | +| `rules_tools.py` | MCP tool name and parameter validity (`unknown-tool`, `dead-with-param`) | +| `rules_verdict.py` | Skill verdict routing completeness — every emitted verdict value must be routed | +| `rules_worktree.py` | Worktree retry lifecycle — every step that creates a worktree must have a downstream merge or cleanup | + +The 17-family count is enforced by `tests/docs/test_doc_counts.py`. + +## Contract cards + +Every skill referenced by a recipe carries a **contract card** in +`src/autoskillit/recipes/contracts//.md`. The card lists the +inputs the recipe will pass, the structured output tokens the recipe expects +to read, and the verdicts the recipe routes on. The contract is the source of +truth for `rules_contracts.py`. + +## Staleness detection and Haiku triage + +`recipe/staleness_cache.py` writes a per-contract hash and timestamp to disk. +When a recipe loads, the cache is consulted and any contract hash that has +drifted is enqueued for an LLM-assisted re-check via `_llm_triage.py`, which +spawns a Haiku subprocess to compare the deployed SKILL.md against the +contract card. The Haiku verdict is one of `FRESH`, `STALE`, or `UNCERTAIN`; +`UNCERTAIN` is escalated to a human via `cli/_stale_check.py`. + +## Migration engine + +When a recipe declares an `autoskillit_version` older than the running +package, the migration engine in `migration/engine.py` walks the migration +notes under `src/autoskillit/migrations/` and applies them in order. Each +note is a 7-step sequence: + +1. Read current YAML. +2. Validate it parses. +3. Apply the note's transformer. +4. Validate the transformed YAML. +5. Diff old vs new. +6. Write the new YAML atomically. +7. Record the new `autoskillit_version`. + +Failures are recorded in `migration/store.py:FailureStore` (atomic JSON +writes) so the next `autoskillit migrate` run can resume. diff --git a/docs/sub-recipe-composition.md b/docs/recipes/composition.md similarity index 100% rename from docs/sub-recipe-composition.md rename to docs/recipes/composition.md diff --git a/docs/recipes.md b/docs/recipes/overview.md similarity index 76% rename from docs/recipes.md rename to docs/recipes/overview.md index e707de045b..5c9d6072fd 100644 --- a/docs/recipes.md +++ b/docs/recipes/overview.md @@ -23,7 +23,7 @@ Plan, implement, test, and open a PR for a task or GitHub issue. | `auto_merge` | `true` | Enroll PR in merge queue after CI passes | | `base_branch` | *(auto-detect)* | Branch to merge into | -See **[Getting Started](getting-started.md)** for a complete walkthrough. +See **[Getting Started](../getting-started.md)** for a complete walkthrough. ### remediation @@ -78,11 +78,25 @@ Consolidate multiple open PRs into a single integration branch and PR. | `base_branch` | *(auto-detect)* | Branch that all PRs target | | `audit` | `true` | Run quality audit on conflict resolutions | -### smoke-test +### research -Integration self-test of the orchestration engine. Creates a local bare repo and exercises the full pipeline with stub skills. +Two-phase technical research recipe. Phase 1 scopes a research question and opens an experiment design issue for human review. Phase 2 implements the experiment, runs it, writes a report to `research/`, and opens a PR. -**When to use:** Internal testing only. Verifies that step routing, tool dispatch, capture/context threading, retry logic, and merge mechanics all work correctly. +**Flow:** scope → plan → issue → (resume with issue_number) → [setup?] → implement → run → report → open-pr + +**When to use:** When you want to investigate a technical question, benchmark an approach, or run a reproducible experiment. Produces a structured research report in `research/`. + +**Key ingredients:** + +| Ingredient | Default | Description | +|-----------|---------|-------------| +| `task` | *(required)* | Research question or topic to investigate | +| `issue_number` | *(optional)* | Approved experiment design issue — skips phase 1 when provided | +| `source_dir` | *(required)* | Path to the project root | +| `base_branch` | `main` | Branch to target for the research PR | +| `setup_phases` | `false` | When `true`, decompose experiment into sequenced setup phases | + +**Requires pack:** `research` (pack members: `scope`, `plan-experiment`, `implement-experiment`, `run-experiment`, `generate-report`) ## Project Recipes @@ -118,7 +132,7 @@ steps: message: "Failed." ``` -See **[Sub-Recipe Composition](sub-recipe-composition.md)** for advanced patterns like sprint mode. +See **[Sub-Recipe Composition](composition.md)** for advanced patterns like sprint mode. ## Recipe Management diff --git a/docs/safety/README.md b/docs/safety/README.md new file mode 100644 index 0000000000..5b7bff23ba --- /dev/null +++ b/docs/safety/README.md @@ -0,0 +1,6 @@ +# Safety + +Guardrails that prevent destructive or out-of-scope actions. + +- [hooks.md](hooks.md) — the 13 PreToolUse / PostToolUse / SessionStart hooks +- [workspace.md](workspace.md) — clone-based isolation, merge_worktree pipeline, registry diff --git a/docs/safety/hooks.md b/docs/safety/hooks.md new file mode 100644 index 0000000000..45576e0305 --- /dev/null +++ b/docs/safety/hooks.md @@ -0,0 +1,126 @@ +# Hooks + +AutoSkillit registers 13 Claude Code hook scripts: 9 PreToolUse, 3 PostToolUse, +and 1 SessionStart. Every script is stdlib-only Python so it can run before the +project virtualenv is on the path. Scripts live in `src/autoskillit/hooks/` +and are bound to event types in `src/autoskillit/hook_registry.py` via the +`HOOK_REGISTRY` list of `HookDef` entries; `generate_hooks_json()` then +materializes the canonical `hooks.json` that Claude Code reads. + +## PreToolUse hooks (9) + +### `branch_protection_guard.py` +**Guarded tools:** `merge_worktree`, `push_to_remote` +Denies merges and pushes targeting branches in `safety.protected_branches` +(`main`, `integration`, `stable` by default). Pure-function check via +`core/branch_guard.is_protected_branch`. + +### `quota_check.py` +**Guarded tool:** `run_skill` +Blocks launching new headless sessions when the cached binding window marks +`should_block=True`. The threshold is per-window: short windows (e.g. +`five_hour`) use `quota_guard.short_window_threshold` (default 85.0%); long +windows matched by `quota_guard.long_window_patterns` (default `weekly`, +`sonnet`, `opus`) use `quota_guard.long_window_threshold` (default 98.0%). +Reports the exact sleep duration the orchestrator must wait. + +### `skill_command_guard.py` +**Guarded tool:** `run_skill` +Blocks `run_skill` calls where `skill_command` does not start with `/`. +Catches the case where the orchestrator passed prose instead of a slash +command. + +### `skill_cmd_check.py` +**Guarded tool:** `run_skill` +Validates that path-argument skills (`implement-worktree-no-merge`, +`resolve-failures`, etc.) receive the file path as the first token rather +than buried after descriptive text. + +### `remove_clone_guard.py` +**Guarded tool:** `remove_clone` +Denies `remove_clone` unless `keep="true"` is set explicitly. Prevents +unintended deletion of clones that may still have unpushed work. + +### `open_kitchen_guard.py` +**Guarded tool:** `open_kitchen` +Blocks `open_kitchen` from running inside a headless session. Only human +operators may open the kitchen. + +### `headless_orchestration_guard.py` +**Guarded tools:** `run_skill`, `run_cmd`, `run_python` +Blocks orchestration tools from headless sessions. Enforces the two-tier +invariant: only the Tier 1 orchestrator may spawn headless sessions. + +### `unsafe_install_guard.py` +**Guarded tool:** `run_cmd` +Denies `run_cmd` calls that perform editable installs without `--python +.venv`. Prevents pollution of the global Python environment. + +### `generated_file_write_guard.py` +**Guarded tools:** `Write`, `Edit` +Denies writes to generated files (`hooks.json`, `settings.json`). The hooks +file must be regenerated through `generate_hooks_json()`, never edited by +hand. + +## PostToolUse hooks (3) + +### `pretty_output.py` +**Guarded tools:** all AutoSkillit MCP tools +Reformats raw JSON responses into Markdown key-value pairs for readable +display and reduced token usage. + +### `token_summary_appender.py` +**Guarded tool:** `run_skill` +After `run_skill` returns a GitHub PR URL, appends a `## Token Usage Summary` +table to the PR body so reviewers can see per-step token cost. + +### `quota_post_check.py` +**Guarded tool:** `run_skill` +After `run_skill` returns, appends a quota warning to the tool output when +the cached binding window marks `should_block=True` (per-window threshold — +see `quota_check.py` above). Gives the orchestrator a chance to back off +voluntarily before the PreToolUse hook starts denying. + +## SessionStart hook (1) + +### `session_start_reminder.py` +Injects a reminder to call `/autoskillit:open-kitchen` when resuming a +prior session (transcript_path size > 0). Without this, resumed orchestrator +sessions silently lose access to the kitchen tools. + +## Drift detection + +`cli/_doctor.py:_check_hook_registry_drift` calls `generate_hooks_json()` and +compares against the deployed `hooks.json` field by field, reporting any +missing or orphaned hook scripts. The check is gated by a 12-hour dismissal +cooldown to keep the doctor noise level reasonable; missing hook files are +detected separately by `_check_hook_health` so an ENOENT does not collapse +into a generic drift report. + +## Stdlib-only rationale + +Every hook script imports only the Python standard library. The hooks run +before any project virtualenv is activated, and Claude Code spawns them as +plain `python` subprocesses, so any third-party import would fail in the +common case where the user has not installed AutoSkillit's dependencies into +the global Python. + +## Safety configuration + +```yaml +# .autoskillit/config.yaml +safety: + protected_branches: ["main", "integration", "stable"] + require_dry_walkthrough: true + test_gate_on_merge: true + reset_guard_marker: ".autoskillit-workspace" + +quota_guard: + enabled: true + short_window_threshold: 85.0 + long_window_threshold: 98.0 + long_window_patterns: ["weekly", "sonnet", "opus"] + buffer_seconds: 60 +``` + +See **[Configuration](../configuration.md)** for all safety-related settings. diff --git a/docs/safety/workspace.md b/docs/safety/workspace.md new file mode 100644 index 0000000000..2aacf7a72d --- /dev/null +++ b/docs/safety/workspace.md @@ -0,0 +1,98 @@ +# Workspace safety + +How AutoSkillit isolates pipeline work from your real source tree, what +`merge_worktree` actually does on a green run, and how the editable-install +guard prevents broken CLI installations after cleanup. + +## Clone-based isolation + +`workspace/clone.py:clone_repo` creates a fresh clone of the source repository +into `autoskillit-runs/-/` and rewrites the clone's `origin` +remote so the orchestrator can never accidentally push to the user's working +tree. The orchestrator runs every subsequent step against the clone, never +the source. + +## Origin re-pointing + +After the clone, `clone_repo` rewrites `origin` to the canonical GitHub +remote (resolved by `execution/remote_resolver.resolve_remote_repo`, +preferring `upstream` over `origin` and de-duplicating clone-local remotes). +This guarantees that even if the orchestrator runs `git push origin`, it +hits the upstream repository rather than the user's local clone path. + +## Clone registry + +`workspace/clone_registry.py` maintains a shared file-based registry of +clones eligible for deferred batch cleanup. The registry is read by +`batch_cleanup_clones` to delete stale clones in bulk after a recipe finishes. +The registry uses atomic JSON writes so concurrent recipe runs cannot corrupt +each other. + +## `merge_worktree` 13-step pipeline + +`server/git.py:perform_merge` runs every step in order; failure at any step +returns a `MergeFailedStep` value to the orchestrator and aborts the merge: + +1. **path validation** — the worktree path must exist and be a real git + worktree, not a regular directory. +2. **protected branch check** — `core/branch_guard.is_protected_branch` + denies merges into branches in `safety.protected_branches`. +3. **branch detection** — resolve the worktree's HEAD branch and the merge + target branch. +4. **dirty tree check** — both the worktree and the target must be clean. +5. **pre-merge test gate** — run the project's test command via `test_check`; + abort on failure. +6. **fetch** — `git fetch origin` to refresh remote refs. +7. **pre-rebase check** — abort if the worktree is already in a half-merged + state. +8. **merge-commits-detected stop** — fail loudly if the worktree contains + merge commits; AutoSkillit only supports linear history. +9. **rebase** — rebase the worktree onto the latest target. +10. **generated-file cleanup** — remove autogenerated files (`hooks.json`, + `settings.json`) before the second test gate. +11. **post-rebase test gate** — re-run `test_check` after the rebase to + catch latent conflicts. +12. **merge** — fast-forward merge into the target branch. +13. **editable install guard** — see below. + +## Editable install guard + +`server/_editable_guard.py:scan_editable_installs_for_worktree` runs after +the merge but before any cleanup. It scans the user's Python tools for +editable installs that point inside the worktree directory. If any are +found, the merge result is `MERGE_SUCCEEDED_CLEANUP_BLOCKED` and the +worktree is left intact so the user can re-install from the source path +before deletion. Without this guard, deleting a worktree that hosted an +editable install would silently break the user's `autoskillit` CLI. + +## Workspace markers + +`autoskillit workspace init` creates a `.autoskillit-workspace` marker file +inside a directory, marking it as a sanctioned scratch directory for tests +and reset operations. `reset_workspace` and `reset_test_dir` refuse to act on +any directory without this marker — preventing accidental wipes of the wrong +filesystem path. The marker name is configurable via +`safety.reset_guard_marker`. + +## Retry-worktree for context exhaustion + +When a long `implement-worktree-no-merge` session hits its context limit, the +worker session terminates with `needs_retry=true` and the worktree is left +intact on disk with all commits made up to that point. The orchestrator MUST +route to `/autoskillit:retry-worktree` against the same worktree path +(returned in `result.worktree_path`) — never re-call +`/autoskillit:implement-worktree-no-merge`, which would create a brand-new +timestamped worktree and discard the partial progress. + +## Isolation rules in `recipe/rules_isolation.py` + +Two semantic rules enforce the isolation invariants at recipe-validation +time: + +- `source-isolation-violation` — fires when a recipe step targets the source + directory instead of the clone. +- `git-mutation-on-source` — fires when a recipe runs a git mutation + command (`git commit`, `git push`, `git rebase`) against the source remote. + +Both rules cause `validate_recipe` to fail before the orchestrator can ever +run the recipe. diff --git a/docs/skills/README.md b/docs/skills/README.md new file mode 100644 index 0000000000..4195fcfabf --- /dev/null +++ b/docs/skills/README.md @@ -0,0 +1,9 @@ +# Skills + +Skill documentation. A skill is a slash command (or one internal injection) +that runs in a Claude Code session. + +- [visibility.md](visibility.md) — Tier 1/2/3 model and the 95-skill catalogue +- [catalog.md](catalog.md) — every bundled skill grouped by purpose +- [subsets.md](subsets.md) — `tool_subsets` filtering categories +- [overrides.md](overrides.md) — project-local skill overrides under `.autoskillit/skills/` diff --git a/docs/skills/catalog.md b/docs/skills/catalog.md new file mode 100644 index 0000000000..6cd7240c8f --- /dev/null +++ b/docs/skills/catalog.md @@ -0,0 +1,128 @@ +# Skill catalog + +The complete list of bundled skills (109 total: 3 in `src/autoskillit/skills/`, +106 in `src/autoskillit/skills_extended/`). Filesystem walk this directory if +you need an exhaustive listing; this catalog groups by purpose. + +## Tier 1 — free range (3) + +Plugin-scanned at `src/autoskillit/skills/`: + +- `open-kitchen` — reveals the 40 kitchen MCP tools +- `close-kitchen` — re-hides them +- `sous-chef` — internal injection by `open_kitchen`; never appears as a slash command + +## Tier 2 — interactive cook + headless + +Located under `src/autoskillit/skills_extended/`. Grouped by purpose: + +### Plan and implementation +`investigate`, `make-plan`, `dry-walkthrough`, `review-approach`, +`implement-worktree`, `rectify`, `make-groups`, `mermaid`, `make-arch-diag`, +`make-experiment-diag` + +### Audit suite +`audit-arch`, `audit-cohesion`, `audit-tests`, `audit-defense-standards`, +`audit-bugs`, `audit-friction`, `validate-audit` + +### Requirements and planning +`make-req`, `elaborate-phase`, `write-recipe`, `migrate-recipes`, +`setup-project`, `sprint-planner`, `design-guards`, `triage-issues`, +`collapse-issues`, `issue-splitter`, `enrich-issues`, `prepare-issue`, +`process-issues` + +### Experiment family +`scope`, `plan-experiment`, `implement-experiment`, `run-experiment`, +`generate-report`, `troubleshoot-experiment` + +## Tier 3 — pipeline / automation + +Also under `src/autoskillit/skills_extended/`. Used by recipes for unattended +runs: + +`open-pr`, `open-integration-pr`, `merge-pr`, `analyze-prs`, `review-pr`, +`resolve-review`, `implement-worktree-no-merge`, `resolve-failures`, +`retry-worktree`, `resolve-merge-conflicts`, `audit-impl`, `smoke-task`, +`report-bug`, `pipeline-summary`, `diagnose-ci`, `verify-diag` + +## arch-lens family (13) + +13 architectural-diagram skills under `skills_extended/arch-lens-*/`. Each +answers a specific question about the system: + +| Skill | Lens | Question | +|-------|------|----------| +| `arch-lens-c4-container` | C4 container | How is it built? | +| `arch-lens-module-dependency` | Module dependency | How are modules coupled? | +| `arch-lens-process-flow` | Process flow | How does it behave? | +| `arch-lens-data-lineage` | Data lineage | Where is the data? | +| `arch-lens-repository-access` | Repository access | How is data accessed? | +| `arch-lens-state-lifecycle` | State lifecycle | How is state corruption prevented? | +| `arch-lens-deployment` | Deployment | Where does it run? | +| `arch-lens-development` | Development | How is it built and tested? | +| `arch-lens-operational` | Operational | How is it run and monitored? | +| `arch-lens-concurrency` | Concurrency | How does parallelism work? | +| `arch-lens-error-resilience` | Error / resilience | How are failures handled? | +| `arch-lens-scenarios` | Scenarios | Do the components work together? | +| `arch-lens-security` | Security | Where are the trust boundaries? | + +## exp-lens family (18) + +18 experiment-related diagram skills under `skills_extended/exp-lens-*/`: + +| Skill | Lens | +|-------|------| +| `exp-lens-benchmark-representativeness` | Benchmark representativeness | +| `exp-lens-causal-assumptions` | Causal assumptions | +| `exp-lens-comparator-construction` | Comparator construction | +| `exp-lens-error-budget` | Error budget | +| `exp-lens-estimand-clarity` | Estimand clarity | +| `exp-lens-exploratory-confirmatory` | Exploratory vs. confirmatory | +| `exp-lens-fair-comparison` | Fair comparison | +| `exp-lens-governance-risk` | Governance and risk | +| `exp-lens-iterative-learning` | Iterative learning | +| `exp-lens-measurement-validity` | Measurement validity | +| `exp-lens-pipeline-integrity` | Pipeline integrity | +| `exp-lens-randomization-blocking` | Randomization blocking | +| `exp-lens-reproducibility-artifacts` | Reproducibility artifacts | +| `exp-lens-sensitivity-robustness` | Sensitivity and robustness | +| `exp-lens-severity-testing` | Severity testing | +| `exp-lens-unit-interference` | Unit interference | +| `exp-lens-validity-threats` | Validity threats | +| `exp-lens-variance-stability` | Variance stability | + +## vis-lens family (12) + +12 visualization-planning lenses orchestrated by `plan-visualization`, under +`skills_extended/vis-lens-*/`. Each answers a specific question about a figure or the +figure set: + +| # | Skill | Cognitive Mode | Primary Question | Priority | +|---|-------|---------------|------------------|----------| +| 1 | `vis-lens-always-on` | Composite | Is everything correct by default? | P0 | +| 2 | `vis-lens-antipattern` | Diagnostic | What visualization antipatterns are present? | P0 | +| 3 | `vis-lens-chart-select` | Typological | What chart type fits this data shape? | P0 | +| 4 | `vis-lens-domain-norms` | Normative | Does the figure follow domain conventions? | P0 | +| 5 | `vis-lens-uncertainty` | Probabilistic | Is uncertainty properly communicated? | P0 | +| 6 | `vis-lens-color-access` | Chromatic | Is the color encoding accessible and perceptually uniform? | P1 | +| 7 | `vis-lens-figure-table` | Decisional | Should this result be a figure or a table? | P1 | +| 8 | `vis-lens-multi-compare` | Comparative | Are multi-condition comparisons statistically sound? | P1 | +| 9 | `vis-lens-temporal` | Sequential | Is temporal/sequential data displayed correctly? | P1 | +| 10 | `vis-lens-caption-annot` | Annotative | Are figure captions and axis labels fully self-contained? | P2 | +| 11 | `vis-lens-story-arc` | Narrative | Do the figures tell a coherent story across the report? | P2 | +| 12 | `vis-lens-reproducibility` | Replicative | Can the figures be reproduced from the data and code? | P2 | + +## Rectify doctrine + +Several Tier 2 skills (`rectify`, `audit-bugs`, `design-guards`, +`audit-defense-standards`) form the **Rectify doctrine** — when a bug is +investigated, the fix lands at the architectural root rather than the surface +symptom, and the audit suite is updated so the same class of bug cannot +recur. Commit messages prefix with `Rectify:` for traceability; the count of +`Rectify:` commits is reported in `docs/developer/contributing.md`. + +## Total: 109 + +3 (Tier 1) + 106 (`skills_extended/`) = 109 bundled skills. The total is +verified by `tests/docs/test_doc_counts.py` against a filesystem walk so any +addition or removal is caught immediately. diff --git a/docs/project-local-overrides.md b/docs/skills/overrides.md similarity index 99% rename from docs/project-local-overrides.md rename to docs/skills/overrides.md index 475fb20b8e..57982ae13e 100644 --- a/docs/project-local-overrides.md +++ b/docs/skills/overrides.md @@ -66,7 +66,7 @@ Compare your project-local skills against the bundled skill list: ls .claude/skills/ # List bundled skills (Tier 2+3) -autoskillit skills +autoskillit skills list ``` Any name appearing in both lists is overriding its bundled counterpart. diff --git a/docs/subset-categories.md b/docs/skills/subsets.md similarity index 93% rename from docs/subset-categories.md rename to docs/skills/subsets.md index a3a03c0591..1bacc4a613 100644 --- a/docs/subset-categories.md +++ b/docs/skills/subsets.md @@ -15,8 +15,8 @@ manually reclassifying each of its tools and skills one by one. A project withou | Category | MCP Tools | Skills | |----------|-----------|--------| | `github` | `fetch_github_issue`, `get_issue_title`, `prepare_issue`, `enrich_issues`, `claim_issue`, `release_issue`, `report_bug`, `get_pr_reviews`, `bulk_close_issues`, `check_pr_mergeable`, `push_to_remote`, `create_unique_branch`, `set_commit_status` | `open-pr`, `open-integration-pr`, `merge-pr`, `review-pr`, `resolve-review`, `analyze-prs`, `prepare-issue`, `enrich-issues`, `process-issues`, `triage-issues`, `collapse-issues`, `issue-splitter`, `report-bug`, `pipeline-summary` | -| `ci` | `wait_for_ci`, `get_ci_status`, `wait_for_merge_queue` | `diagnose-ci` | -| `clone` | `clone_repo`, `remove_clone` | — | +| `ci` | `wait_for_ci`, `get_ci_status`, `wait_for_merge_queue`, `toggle_auto_merge` | `diagnose-ci` | +| `clone` | `clone_repo`, `remove_clone`, `register_clone_status`, `batch_cleanup_clones` | — | | `telemetry` | `get_token_summary`, `get_timing_summary`, `write_telemetry_files`, `get_quota_events` | — | | `arch-lens` | — | All 13 `arch-lens-*` skills, `make-arch-diag`, `verify-diag` | | `audit` | — | `audit-arch`, `audit-cohesion`, `audit-tests`, `audit-defense-standards`, `audit-bugs`, `audit-friction`, `audit-impl` | @@ -80,7 +80,7 @@ Custom tags behave like built-in categories for filtering purposes: disabling ## FastMCP Mechanics: Why `open_kitchen` Re-Disables Subsets FastMCP session rules override server rules. When `open_kitchen` calls -`ctx.enable_components(tags={"kitchen"})` to reveal the 37 kitchen-tagged tools, this +`ctx.enable_components(tags={"kitchen"})` to reveal the 40 kitchen-tagged tools, this operation overwrites the server-level `mcp.disable(tags={"github"})` mark applied at startup. As a result, `open_kitchen` must immediately re-call `ctx.disable_components(tags={subset})` for each configured disabled subset to restore diff --git a/docs/skill-visibility.md b/docs/skills/visibility.md similarity index 95% rename from docs/skill-visibility.md rename to docs/skills/visibility.md index 622eeafe65..85bc9aed83 100644 --- a/docs/skill-visibility.md +++ b/docs/skills/visibility.md @@ -2,10 +2,10 @@ ## Overview -AutoSkillit's 61 bundled skills are organized into three tiers that control when and where +AutoSkillit's 109 bundled skills are organized into three tiers that control when and where they appear as slash commands. The tier system is orthogonal to subset categories — you can disable a subset across all tiers simultaneously, or reclassify individual skills between -tiers. See [Subset Categories](subset-categories.md) for subset configuration. +tiers. See [Subset Categories](subsets.md) for subset configuration. ## The Three Tiers @@ -84,7 +84,7 @@ and `/autoskillit:close-kitchen`. Skills in `skills_extended/` are never seen. Order is similar to cook: AutoSkillit launches Claude Code with access to all tiers. The key difference is the orchestrator (`sous-chef` skill) is injected and the kitchen -is pre-opened so all 42 MCP tools are available from the start. +is pre-opened so all 44 MCP tools are available from the start. ### Headless session (launched by `run_skill`) @@ -130,7 +130,7 @@ of tier. The two axes compose independently: | **Tier 2** | Skill visible in cook + headless | Skill hidden from all sessions | | **Tier 3** | Skill visible in cook + headless | Skill hidden from all sessions | -See [Subset Categories](subset-categories.md) for how to configure subset disablement. +See [Subset Categories](subsets.md) for how to configure subset disablement. ## Why Two Directories, Not `disable-model-invocation` diff --git a/docs/update-checks.md b/docs/update-checks.md new file mode 100644 index 0000000000..e444791563 --- /dev/null +++ b/docs/update-checks.md @@ -0,0 +1,65 @@ +# Updating AutoSkillit + +## How update checks work + +On every interactive CLI invocation (excluding headless/MCP sessions and CI), +AutoSkillit checks for available updates and shows a single `[Y/n]` prompt if +any of the following conditions fire: + +- **binary** — a newer release is available on your install's branch +- **hooks** — new or changed hook entries have been added since last install +- **branch drift** — the installed commit SHA lags the HEAD of your tracked branch + +All three conditions are consolidated into a single prompt listing each reason. +Answering `Y` runs the appropriate upgrade command followed by `autoskillit install`. + +## Branch-aware dismissal windows + +Dismissal windows vary by install type to balance convenience and safety: + +| Install | Window | +|---------|--------| +| stable / main / release-tag | 7 days | +| integration / local-editable | 12 hours | + +The window is determined at check time from the current `direct_url.json` — +not from what was stored when you dismissed. + +Dismissal expires on two axes: + +1. **Time** — the window elapses. +2. **Version delta** — the running version advances past the dismissed version. + +## The `autoskillit update` command + +To upgrade immediately without waiting for a prompt: + + autoskillit update + +This runs the install-type-aware upgrade command, then `autoskillit install`, +then verifies that the version advanced. On success it clears any active +dismissal state so the next check starts fresh. + +For unknown install types (e.g. installed from PyPI without a VCS reference), +`autoskillit update` exits with code 2 and prints a reinstallation hint. + +## Escape hatches + +Set either env var to silence all update checks for a single invocation: + + AUTOSKILLIT_SKIP_STALE_CHECK=1 autoskillit + AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK=1 autoskillit + +Both are automatically injected by the update logic itself so that subprocesses +launched during an update do not re-enter the check. + +## Install detection + +Update checks read `direct_url.json` from the installed package metadata +(populated by `uv` or `pip` at install time). The `~/.autoskillit/dev` marker +file is no longer consulted — install classification is derived entirely from +`direct_url.json`. + +Use `autoskillit doctor` to inspect the current classification: + + install_classification: install_type=git-vcs, requested_revision=stable, commit_id=abc12345 diff --git a/pyproject.toml b/pyproject.toml index 910fe74754..938bec2394 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "autoskillit" -version = "0.7.0" +version = "0.8.38" description = "MCP server for orchestrating automated skill-driven workflows with Claude Code" readme = "README.md" license = {text = "MIT"} @@ -25,12 +25,15 @@ classifiers = [ requires-python = ">=3.11" dependencies = [ "anyio>=4.6.0", - "dynaconf>=3.2.12,<4.0", - "fastmcp>=3.1.1,<4.0", + "dynaconf>=3.2.13,<4.0", + "fastmcp>=3.2.0,<4.0", "httpx>=0.28,<0.29", - "igraph>=1.0", + "igraph>=1.0,<2.0", + "markdown-it-py>=3.0", "packaging>=23.0", "psutil>=7.2.0", + "pygments>=2.20.0", + "pyjwt>=2.12.0", "pyyaml>=6.0", "cyclopts>=4.0", "structlog>=25.0,<26.0", @@ -46,6 +49,7 @@ dev = [ "ruff>=0.15.0", "import-linter>=2.1", "packaging>=25.0", + "api-simulator", ] [project.urls] @@ -85,6 +89,7 @@ timeout = 60 timeout_method = "signal" markers = [ "smoke: end-to-end smoke tests requiring Claude API access (deselect with: -m 'not smoke')", + "integration: integration tests that spawn real subprocesses (deselect with: -m 'not integration')", ] [tool.ruff] @@ -94,8 +99,12 @@ line-length = 99 [tool.ruff.lint] select = ["E", "F", "I", "UP", "TID251"] +[tool.ruff.lint.per-file-ignores] +"tests/execution/test_session_classification_e2e.py" = ["E402"] + [tool.ruff.lint.flake8-tidy-imports.banned-api] "logging.getLogger" = {msg = "Use get_logger() from autoskillit._logging instead."} +"signal.signal" = {msg = "Use anyio.open_signal_receiver instead of signal.signal — see _serve_with_signal_guard in cli/app.py."} [tool.importlinter] root_packages = ["autoskillit"] @@ -148,6 +157,14 @@ forbidden_modules = [ name = "L1 pipeline does not import L2 or L3" type = "forbidden" source_modules = ["autoskillit.pipeline"] +# EXCEPTION: autoskillit.config is intentionally omitted from the +# forbidden_modules list. pipeline.context.ToolContext owns +# AutomationConfig as the DI wiring point — see the docstrings on +# pipeline/context.py and pipeline/__init__.py. The coupling is safe +# because config/ depends only on L0 (enforced by IL-002), so no +# cycle is possible. This exception is asserted by +# tests/arch/test_import_linter_contracts.py +# ::test_il003_pipeline_config_exception_documented. forbidden_modules = [ "autoskillit.execution", "autoskillit.workspace", @@ -223,3 +240,6 @@ forbidden_modules = [ "autoskillit.server", "autoskillit.cli", ] + +[tool.uv.sources] +api-simulator = { git = "https://github.com/TalonT-Org/api-simulator", rev = "8f711f958d4d93a8e53a3c3b51279fb420870f3a", subdirectory = "crates/api-simulator-py" } diff --git a/scripts/check_doc_counts.py b/scripts/check_doc_counts.py index ed178739fb..f3a1a15ef8 100755 --- a/scripts/check_doc_counts.py +++ b/scripts/check_doc_counts.py @@ -22,13 +22,21 @@ def count_skills() -> int: - """Count directories in skills/ and skills_extended/ that contain a SKILL.md.""" + """Count public skills in skills/ and skills_extended/. + + Only counts skills whose SKILL.md begins with YAML frontmatter (``---``), + matching the behaviour of DefaultSkillResolver().list_all() which excludes + internal bootstrap documents such as sous-chef. + """ count = 0 for skills_dir in (SKILLS_DIR, SKILLS_EXTENDED_DIR): if skills_dir.is_dir(): - count += sum( - 1 for d in skills_dir.iterdir() if d.is_dir() and (d / "SKILL.md").exists() - ) + for d in skills_dir.iterdir(): + skill_md = d / "SKILL.md" + if d.is_dir() and skill_md.exists(): + text = skill_md.read_text(encoding="utf-8") + if text.startswith("---\n"): + count += 1 return count @@ -84,6 +92,16 @@ def count_tools() -> tuple[int, int]: re.IGNORECASE, ) +# Patterns that indicate a sub-family count rather than a global skill total. +# When any of these appear on the same line as an "X skills" claim, the +# claim describes a sub-family (arch-lens, exp-lens, Tier 1/2/3, audit suite, +# rectify doctrine, …) and is exempt from the global-total check. +SUBFAMILY_CONTEXT = re.compile( + r"arch-lens|exp-lens|Tier\s+[123]|skills_extended" + r"|src/autoskillit/skills/|audit\s+suite|rectify\s+doctrine|sub-family", + re.IGNORECASE, +) + # Patterns to find numeric claims in docs SKILL_COUNT_PAT = re.compile(r"(\d+)\s+(?:bundled\s+)?skills") RECIPE_COUNT_PAT = re.compile(r"(\d+)\s+recipes") @@ -122,13 +140,15 @@ def scan_docs() -> list[str]: if SELF_CORRECTING.search(line): continue - # Check skill counts - for m in SKILL_COUNT_PAT.finditer(line): - claimed = int(m.group(1)) - if claimed != actual_skills and claimed > 1: - errors.append( - f"{rel}:{lineno}: claims {claimed} skills, actual is {actual_skills}" - ) + # Check skill counts (skip sub-family contexts like Tier 1/2/3, + # arch-lens, exp-lens, audit suite — those are not global totals) + if not SUBFAMILY_CONTEXT.search(line): + for m in SKILL_COUNT_PAT.finditer(line): + claimed = int(m.group(1)) + if claimed != actual_skills and claimed > 1: + errors.append( + f"{rel}:{lineno}: claims {claimed} skills, actual is {actual_skills}" + ) # Check recipe counts for m in RECIPE_COUNT_PAT.finditer(line): diff --git a/src/autoskillit/.claude-plugin/plugin.json b/src/autoskillit/.claude-plugin/plugin.json index 3a6583e33f..b57e84aad2 100644 --- a/src/autoskillit/.claude-plugin/plugin.json +++ b/src/autoskillit/.claude-plugin/plugin.json @@ -1,5 +1,5 @@ { "name": "autoskillit", - "version": "0.7.0", + "version": "0.8.38", "description": "Orchestrated skill-driven workflows using Claude Code headless sessions" } diff --git a/src/autoskillit/_llm_triage.py b/src/autoskillit/_llm_triage.py index d32bda98dc..8da813550b 100644 --- a/src/autoskillit/_llm_triage.py +++ b/src/autoskillit/_llm_triage.py @@ -16,6 +16,7 @@ OutputFormat, SubprocessResult, TerminationReason, + build_claude_env, get_logger, ) from autoskillit.execution import parse_session_result, run_managed_async @@ -122,6 +123,7 @@ async def _triage_batch( cmd=triage_cmd, cwd=Path.cwd(), timeout=30.0, + env=build_claude_env(), pty_mode=True, ) if result.termination == TerminationReason.TIMED_OUT: diff --git a/src/autoskillit/assets/mermaid/LICENSE.mermaid b/src/autoskillit/assets/mermaid/LICENSE.mermaid new file mode 100644 index 0000000000..fb61087c6b --- /dev/null +++ b/src/autoskillit/assets/mermaid/LICENSE.mermaid @@ -0,0 +1,21 @@ +mermaid.js — https://mermaid.js.org +Copyright (c) 2014-2025 Knut Sveidqvist and contributors +License: MIT (https://opensource.org/licenses/MIT) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src/autoskillit/assets/mermaid/VERSION b/src/autoskillit/assets/mermaid/VERSION new file mode 100644 index 0000000000..2d1951b4aa --- /dev/null +++ b/src/autoskillit/assets/mermaid/VERSION @@ -0,0 +1 @@ +11.14.0 diff --git a/src/autoskillit/assets/mermaid/mermaid.min.js b/src/autoskillit/assets/mermaid/mermaid.min.js new file mode 100644 index 0000000000..2e90922b11 --- /dev/null +++ b/src/autoskillit/assets/mermaid/mermaid.min.js @@ -0,0 +1,3298 @@ +"use strict";var __esbuild_esm_mermaid_nm;(__esbuild_esm_mermaid_nm||={}).mermaid=(()=>{var s8e=Object.create;var Ax=Object.defineProperty;var o8e=Object.getOwnPropertyDescriptor;var l8e=Object.getOwnPropertyNames;var c8e=Object.getPrototypeOf,u8e=Object.prototype.hasOwnProperty;var o=(t,e)=>Ax(t,"name",{value:e,configurable:!0});var P=(t,e)=>()=>(t&&(e=t(t=0)),e);var ar=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ur=(t,e)=>{for(var r in e)Ax(t,r,{get:e[r],enumerable:!0})},a4=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of l8e(e))!u8e.call(t,n)&&n!==r&&Ax(t,n,{get:()=>e[n],enumerable:!(i=o8e(e,n))||i.enumerable});return t},Kr=(t,e,r)=>(a4(t,e,"default"),r&&a4(r,e,"default")),Wa=(t,e,r)=>(r=t!=null?s8e(c8e(t)):{},a4(e||!t||!t.__esModule?Ax(r,"default",{value:t,enumerable:!0}):r,t)),s4=t=>a4(Ax({},"__esModule",{value:!0}),t);var h8e,Tg,_8,TY,o4=P(()=>{"use strict";h8e=Object.freeze({left:0,top:0,width:16,height:16}),Tg=Object.freeze({rotate:0,vFlip:!1,hFlip:!1}),_8=Object.freeze({...h8e,...Tg}),TY=Object.freeze({..._8,body:"",hidden:!1})});var f8e,kY,CY=P(()=>{"use strict";o4();f8e=Object.freeze({width:null,height:null}),kY=Object.freeze({...f8e,...Tg})});var D8,l4,wY=P(()=>{"use strict";D8=o((t,e,r,i="")=>{let n=t.split(":");if(t.slice(0,1)==="@"){if(n.length<2||n.length>3)return null;i=n.shift().slice(1)}if(n.length>3||!n.length)return null;if(n.length>1){let l=n.pop(),u=n.pop(),h={provider:n.length>0?n[0]:i,prefix:u,name:l};return e&&!l4(h)?null:h}let a=n[0],s=a.split("-");if(s.length>1){let l={provider:i,prefix:s.shift(),name:s.join("-")};return e&&!l4(l)?null:l}if(r&&i===""){let l={provider:i,prefix:"",name:a};return e&&!l4(l,r)?null:l}return null},"stringToIcon"),l4=o((t,e)=>t?!!((e&&t.prefix===""||t.prefix)&&t.name):!1,"validateIconName")});function EY(t,e){let r={};!t.hFlip!=!e.hFlip&&(r.hFlip=!0),!t.vFlip!=!e.vFlip&&(r.vFlip=!0);let i=((t.rotate||0)+(e.rotate||0))%4;return i&&(r.rotate=i),r}var SY=P(()=>{"use strict";o(EY,"mergeIconTransformations")});function L8(t,e){let r=EY(t,e);for(let i in TY)i in Tg?i in t&&!(i in r)&&(r[i]=Tg[i]):i in e?r[i]=e[i]:i in t&&(r[i]=t[i]);return r}var AY=P(()=>{"use strict";o4();SY();o(L8,"mergeIconData")});function _Y(t,e){let r=t.icons,i=t.aliases||Object.create(null),n=Object.create(null);function a(s){if(r[s])return n[s]=[];if(!(s in n)){n[s]=null;let l=i[s]&&i[s].parent,u=l&&a(l);u&&(n[s]=[l].concat(u))}return n[s]}return o(a,"resolve"),(e||Object.keys(r).concat(Object.keys(i))).forEach(a),n}var DY=P(()=>{"use strict";o(_Y,"getIconsTree")});function LY(t,e,r){let i=t.icons,n=t.aliases||Object.create(null),a={};function s(l){a=L8(i[l]||n[l],a)}return o(s,"parse"),s(e),r.forEach(s),L8(t,a)}function R8(t,e){if(t.icons[e])return LY(t,e,[]);let r=_Y(t,[e])[e];return r?LY(t,e,r):null}var RY=P(()=>{"use strict";AY();DY();o(LY,"internalGetIconData");o(R8,"getIconData")});function N8(t,e,r){if(e===1)return t;if(r=r||100,typeof t=="number")return Math.ceil(t*e*r)/r;if(typeof t!="string")return t;let i=t.split(d8e);if(i===null||!i.length)return t;let n=[],a=i.shift(),s=p8e.test(a);for(;;){if(s){let l=parseFloat(a);isNaN(l)?n.push(a):n.push(Math.ceil(l*e*r)/r)}else n.push(a);if(a=i.shift(),a===void 0)return n.join("");s=!s}}var d8e,p8e,NY=P(()=>{"use strict";d8e=/(-?[0-9.]*[0-9]+[0-9.]*)/g,p8e=/^-?[0-9.]*[0-9]+[0-9.]*$/g;o(N8,"calculateSize")});function m8e(t,e="defs"){let r="",i=t.indexOf("<"+e);for(;i>=0;){let n=t.indexOf(">",i),a=t.indexOf("",a);if(s===-1)break;r+=t.slice(n+1,a).trim(),t=t.slice(0,i).trim()+t.slice(s+1)}return{defs:r,content:t}}function g8e(t,e){return t?""+t+""+e:e}function IY(t,e,r){let i=m8e(t);return g8e(i.defs,e+i.content+r)}var MY=P(()=>{"use strict";o(m8e,"splitSVGDefs");o(g8e,"mergeDefsAndContent");o(IY,"wrapSVGContent")});function I8(t,e){let r={..._8,...t},i={...kY,...e},n={left:r.left,top:r.top,width:r.width,height:r.height},a=r.body;[r,i].forEach(y=>{let v=[],x=y.hFlip,b=y.vFlip,T=y.rotate;x?b?T+=2:(v.push("translate("+(n.width+n.left).toString()+" "+(0-n.top).toString()+")"),v.push("scale(-1 1)"),n.top=n.left=0):b&&(v.push("translate("+(0-n.left).toString()+" "+(n.height+n.top).toString()+")"),v.push("scale(1 -1)"),n.top=n.left=0);let w;switch(T<0&&(T-=Math.floor(T/4)*4),T=T%4,T){case 1:w=n.height/2+n.top,v.unshift("rotate(90 "+w.toString()+" "+w.toString()+")");break;case 2:v.unshift("rotate(180 "+(n.width/2+n.left).toString()+" "+(n.height/2+n.top).toString()+")");break;case 3:w=n.width/2+n.left,v.unshift("rotate(-90 "+w.toString()+" "+w.toString()+")");break}T%2===1&&(n.left!==n.top&&(w=n.left,n.left=n.top,n.top=w),n.width!==n.height&&(w=n.width,n.width=n.height,n.height=w)),v.length&&(a=IY(a,'',""))});let s=i.width,l=i.height,u=n.width,h=n.height,f,d;s===null?(d=l===null?"1em":l==="auto"?h:l,f=N8(d,u/h)):(f=s==="auto"?u:s,d=l===null?N8(f,h/u):l==="auto"?h:l);let p={},m=o((y,v)=>{y8e(v)||(p[y]=v.toString())},"setAttr");m("width",f),m("height",d);let g=[n.left,n.top,u,h];return p.viewBox=g.join(" "),{attributes:p,viewBox:g,body:a}}var y8e,OY=P(()=>{"use strict";o4();CY();NY();MY();y8e=o(t=>t==="unset"||t==="undefined"||t==="none","isUnsetKeyword");o(I8,"iconToSVG")});function M8(t,e=x8e){let r=[],i;for(;i=v8e.exec(t);)r.push(i[1]);if(!r.length)return t;let n="suffix"+(Math.random()*16777216|Date.now()).toString(16);return r.forEach(a=>{let s=typeof e=="function"?e(a):e+(b8e++).toString(),l=a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");t=t.replace(new RegExp('([#;"])('+l+')([")]|\\.[a-z])',"g"),"$1"+s+n+"$3")}),t=t.replace(new RegExp(n,"g"),""),t}var v8e,x8e,b8e,PY=P(()=>{"use strict";v8e=/\sid="(\S+)"/g,x8e="IconifyId"+Date.now().toString(16)+(Math.random()*16777216|0).toString(16),b8e=0;o(M8,"replaceIDs")});function O8(t,e){let r=t.indexOf("xlink:")===-1?"":' xmlns:xlink="http://www.w3.org/1999/xlink"';for(let i in e)r+=" "+i+'="'+e[i]+'"';return'"+t+""}var BY=P(()=>{"use strict";o(O8,"iconToHTML")});var FY=P(()=>{"use strict";wY();RY();OY();PY();BY()});var P8,Yi,kg=P(()=>{"use strict";P8=o((t,e,{depth:r=2,clobber:i=!1}={})=>{let n={depth:r,clobber:i};return Array.isArray(e)&&!Array.isArray(t)?(e.forEach(a=>P8(t,a,n)),t):Array.isArray(e)&&Array.isArray(t)?(e.forEach(a=>{t.includes(a)||t.push(a)}),t):t===void 0||r<=0?t!=null&&typeof t=="object"&&typeof e=="object"?Object.assign(t,e):e:(e!==void 0&&typeof t=="object"&&typeof e=="object"&&Object.keys(e).forEach(a=>{typeof e[a]=="object"&&e[a]!==null&&(t[a]===void 0||typeof t[a]=="object")?(t[a]===void 0&&(t[a]=Array.isArray(e[a])?[]:{}),t[a]=P8(t[a],e[a],{depth:r-1,clobber:i})):(i||typeof t[a]!="object"&&typeof e[a]!="object")&&(t[a]=e[a])}),t)},"assignWithDepth"),Yi=P8});var c4=ar((B8,F8)=>{"use strict";(function(t,e){typeof B8=="object"&&typeof F8<"u"?F8.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs=e()})(B8,(function(){"use strict";var t=1e3,e=6e4,r=36e5,i="millisecond",n="second",a="minute",s="hour",l="day",u="week",h="month",f="quarter",d="year",p="date",m="Invalid Date",g=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,y=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,v={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:o(function(A){var _=["th","st","nd","rd"],D=A%100;return"["+A+(_[(D-20)%10]||_[D]||_[0])+"]"},"ordinal")},x=o(function(A,_,D){var N=String(A);return!N||N.length>=_?A:""+Array(_+1-N.length).join(D)+A},"m"),b={s:x,z:o(function(A){var _=-A.utcOffset(),D=Math.abs(_),N=Math.floor(D/60),R=D%60;return(_<=0?"+":"-")+x(N,2,"0")+":"+x(R,2,"0")},"z"),m:o(function A(_,D){if(_.date()1)return A(O[0])}else{var $=_.name;w[$]=_,R=$}return!N&&R&&(T=R),R||!N&&T},"t"),S=o(function(A,_){if(C(A))return A.clone();var D=typeof _=="object"?_:{};return D.date=A,D.args=arguments,new M(D)},"O"),L=b;L.l=E,L.i=C,L.w=function(A,_){return S(A,{locale:_.$L,utc:_.$u,x:_.$x,$offset:_.$offset})};var M=(function(){function A(D){this.$L=E(D.locale,null,!0),this.parse(D),this.$x=this.$x||D.x||{},this[k]=!0}o(A,"M");var _=A.prototype;return _.parse=function(D){this.$d=(function(N){var R=N.date,B=N.utc;if(R===null)return new Date(NaN);if(L.u(R))return new Date;if(R instanceof Date)return new Date(R);if(typeof R=="string"&&!/Z$/i.test(R)){var O=R.match(g);if(O){var $=O[2]-1||0,z=(O[7]||"0").substring(0,3);return B?new Date(Date.UTC(O[1],$,O[3]||1,O[4]||0,O[5]||0,O[6]||0,z)):new Date(O[1],$,O[3]||1,O[4]||0,O[5]||0,O[6]||0,z)}}return new Date(R)})(D),this.init()},_.init=function(){var D=this.$d;this.$y=D.getFullYear(),this.$M=D.getMonth(),this.$D=D.getDate(),this.$W=D.getDay(),this.$H=D.getHours(),this.$m=D.getMinutes(),this.$s=D.getSeconds(),this.$ms=D.getMilliseconds()},_.$utils=function(){return L},_.isValid=function(){return this.$d.toString()!==m},_.isSame=function(D,N){var R=S(D);return this.startOf(N)<=R&&R<=this.endOf(N)},_.isAfter=function(D,N){return S(D){"use strict";$Y=Wa(c4(),1),dh={trace:0,debug:1,info:2,warn:3,error:4,fatal:5},Q={trace:o((...t)=>{},"trace"),debug:o((...t)=>{},"debug"),info:o((...t)=>{},"info"),warn:o((...t)=>{},"warn"),error:o((...t)=>{},"error"),fatal:o((...t)=>{},"fatal")},_x=o(function(t="fatal"){let e=dh.fatal;typeof t=="string"?t.toLowerCase()in dh&&(e=dh[t]):typeof t=="number"&&(e=t),Q.trace=()=>{},Q.debug=()=>{},Q.info=()=>{},Q.warn=()=>{},Q.error=()=>{},Q.fatal=()=>{},e<=dh.fatal&&(Q.fatal=console.error?console.error.bind(console,yl("FATAL"),"color: orange"):console.log.bind(console,"\x1B[35m",yl("FATAL"))),e<=dh.error&&(Q.error=console.error?console.error.bind(console,yl("ERROR"),"color: orange"):console.log.bind(console,"\x1B[31m",yl("ERROR"))),e<=dh.warn&&(Q.warn=console.warn?console.warn.bind(console,yl("WARN"),"color: orange"):console.log.bind(console,"\x1B[33m",yl("WARN"))),e<=dh.info&&(Q.info=console.info?console.info.bind(console,yl("INFO"),"color: lightblue"):console.log.bind(console,"\x1B[34m",yl("INFO"))),e<=dh.debug&&(Q.debug=console.debug?console.debug.bind(console,yl("DEBUG"),"color: lightgreen"):console.log.bind(console,"\x1B[32m",yl("DEBUG"))),e<=dh.trace&&(Q.trace=console.debug?console.debug.bind(console,yl("TRACE"),"color: lightgreen"):console.log.bind(console,"\x1B[32m",yl("TRACE")))},"setLogLevel"),yl=o(t=>`%c${(0,$Y.default)().format("ss.SSS")} : ${t} : `,"format")});var u4,zY,GY=P(()=>{"use strict";u4={min:{r:0,g:0,b:0,s:0,l:0,a:0},max:{r:255,g:255,b:255,h:360,s:100,l:100,a:1},clamp:{r:o(t=>t>=255?255:t<0?0:t,"r"),g:o(t=>t>=255?255:t<0?0:t,"g"),b:o(t=>t>=255?255:t<0?0:t,"b"),h:o(t=>t%360,"h"),s:o(t=>t>=100?100:t<0?0:t,"s"),l:o(t=>t>=100?100:t<0?0:t,"l"),a:o(t=>t>=1?1:t<0?0:t,"a")},toLinear:o(t=>{let e=t/255;return t>.03928?Math.pow((e+.055)/1.055,2.4):e/12.92},"toLinear"),hue2rgb:o((t,e,r)=>(r<0&&(r+=1),r>1&&(r-=1),r<.16666666666666666?t+(e-t)*6*r:r<.5?e:r<.6666666666666666?t+(e-t)*(.6666666666666666-r)*6:t),"hue2rgb"),hsl2rgb:o(({h:t,s:e,l:r},i)=>{if(!e)return r*2.55;t/=360,e/=100,r/=100;let n=r<.5?r*(1+e):r+e-r*e,a=2*r-n;switch(i){case"r":return u4.hue2rgb(a,n,t+.3333333333333333)*255;case"g":return u4.hue2rgb(a,n,t)*255;case"b":return u4.hue2rgb(a,n,t-.3333333333333333)*255}},"hsl2rgb"),rgb2hsl:o(({r:t,g:e,b:r},i)=>{t/=255,e/=255,r/=255;let n=Math.max(t,e,r),a=Math.min(t,e,r),s=(n+a)/2;if(i==="l")return s*100;if(n===a)return 0;let l=n-a,u=s>.5?l/(2-n-a):l/(n+a);if(i==="s")return u*100;switch(n){case t:return((e-r)/l+(e{"use strict";T8e={clamp:o((t,e,r)=>e>r?Math.min(e,Math.max(r,t)):Math.min(r,Math.max(e,t)),"clamp"),round:o(t=>Math.round(t*1e10)/1e10,"round")},VY=T8e});var k8e,WY,UY=P(()=>{"use strict";k8e={dec2hex:o(t=>{let e=Math.round(t).toString(16);return e.length>1?e:`0${e}`},"dec2hex")},WY=k8e});var C8e,sr,Qc=P(()=>{"use strict";GY();qY();UY();C8e={channel:zY,lang:VY,unit:WY},sr=C8e});var ph,oa,Dx=P(()=>{"use strict";Qc();ph={};for(let t=0;t<=255;t++)ph[t]=sr.unit.dec2hex(t);oa={ALL:0,RGB:1,HSL:2}});var $8,HY,YY=P(()=>{"use strict";Dx();$8=class{static{o(this,"Type")}constructor(){this.type=oa.ALL}get(){return this.type}set(e){if(this.type&&this.type!==e)throw new Error("Cannot change both RGB and HSL channels at the same time");this.type=e}reset(){this.type=oa.ALL}is(e){return this.type===e}},HY=$8});var z8,jY,XY=P(()=>{"use strict";Qc();YY();Dx();z8=class{static{o(this,"Channels")}constructor(e,r){this.color=r,this.changed=!1,this.data=e,this.type=new HY}set(e,r){return this.color=r,this.changed=!1,this.data=e,this.type.type=oa.ALL,this}_ensureHSL(){let e=this.data,{h:r,s:i,l:n}=e;r===void 0&&(e.h=sr.channel.rgb2hsl(e,"h")),i===void 0&&(e.s=sr.channel.rgb2hsl(e,"s")),n===void 0&&(e.l=sr.channel.rgb2hsl(e,"l"))}_ensureRGB(){let e=this.data,{r,g:i,b:n}=e;r===void 0&&(e.r=sr.channel.hsl2rgb(e,"r")),i===void 0&&(e.g=sr.channel.hsl2rgb(e,"g")),n===void 0&&(e.b=sr.channel.hsl2rgb(e,"b"))}get r(){let e=this.data,r=e.r;return!this.type.is(oa.HSL)&&r!==void 0?r:(this._ensureHSL(),sr.channel.hsl2rgb(e,"r"))}get g(){let e=this.data,r=e.g;return!this.type.is(oa.HSL)&&r!==void 0?r:(this._ensureHSL(),sr.channel.hsl2rgb(e,"g"))}get b(){let e=this.data,r=e.b;return!this.type.is(oa.HSL)&&r!==void 0?r:(this._ensureHSL(),sr.channel.hsl2rgb(e,"b"))}get h(){let e=this.data,r=e.h;return!this.type.is(oa.RGB)&&r!==void 0?r:(this._ensureRGB(),sr.channel.rgb2hsl(e,"h"))}get s(){let e=this.data,r=e.s;return!this.type.is(oa.RGB)&&r!==void 0?r:(this._ensureRGB(),sr.channel.rgb2hsl(e,"s"))}get l(){let e=this.data,r=e.l;return!this.type.is(oa.RGB)&&r!==void 0?r:(this._ensureRGB(),sr.channel.rgb2hsl(e,"l"))}get a(){return this.data.a}set r(e){this.type.set(oa.RGB),this.changed=!0,this.data.r=e}set g(e){this.type.set(oa.RGB),this.changed=!0,this.data.g=e}set b(e){this.type.set(oa.RGB),this.changed=!0,this.data.b=e}set h(e){this.type.set(oa.HSL),this.changed=!0,this.data.h=e}set s(e){this.type.set(oa.HSL),this.changed=!0,this.data.s=e}set l(e){this.type.set(oa.HSL),this.changed=!0,this.data.l=e}set a(e){this.changed=!0,this.data.a=e}},jY=z8});var w8e,Rf,Lx=P(()=>{"use strict";XY();w8e=new jY({r:0,g:0,b:0,a:0},"transparent"),Rf=w8e});var KY,$p,G8=P(()=>{"use strict";Lx();Dx();KY={re:/^#((?:[a-f0-9]{2}){2,4}|[a-f0-9]{3})$/i,parse:o(t=>{if(t.charCodeAt(0)!==35)return;let e=t.match(KY.re);if(!e)return;let r=e[1],i=parseInt(r,16),n=r.length,a=n%4===0,s=n>4,l=s?1:17,u=s?8:4,h=a?0:-1,f=s?255:15;return Rf.set({r:(i>>u*(h+3)&f)*l,g:(i>>u*(h+2)&f)*l,b:(i>>u*(h+1)&f)*l,a:a?(i&f)*l/255:1},t)},"parse"),stringify:o(t=>{let{r:e,g:r,b:i,a:n}=t;return n<1?`#${ph[Math.round(e)]}${ph[Math.round(r)]}${ph[Math.round(i)]}${ph[Math.round(n*255)]}`:`#${ph[Math.round(e)]}${ph[Math.round(r)]}${ph[Math.round(i)]}`},"stringify")},$p=KY});var h4,Rx,QY=P(()=>{"use strict";Qc();Lx();h4={re:/^hsla?\(\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?(?:deg|grad|rad|turn)?)\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?%)\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?%)(?:\s*?(?:,|\/)\s*?\+?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e-?\d+)?(%)?))?\s*?\)$/i,hueRe:/^(.+?)(deg|grad|rad|turn)$/i,_hue2deg:o(t=>{let e=t.match(h4.hueRe);if(e){let[,r,i]=e;switch(i){case"grad":return sr.channel.clamp.h(parseFloat(r)*.9);case"rad":return sr.channel.clamp.h(parseFloat(r)*180/Math.PI);case"turn":return sr.channel.clamp.h(parseFloat(r)*360)}}return sr.channel.clamp.h(parseFloat(t))},"_hue2deg"),parse:o(t=>{let e=t.charCodeAt(0);if(e!==104&&e!==72)return;let r=t.match(h4.re);if(!r)return;let[,i,n,a,s,l]=r;return Rf.set({h:h4._hue2deg(i),s:sr.channel.clamp.s(parseFloat(n)),l:sr.channel.clamp.l(parseFloat(a)),a:s?sr.channel.clamp.a(l?parseFloat(s)/100:parseFloat(s)):1},t)},"parse"),stringify:o(t=>{let{h:e,s:r,l:i,a:n}=t;return n<1?`hsla(${sr.lang.round(e)}, ${sr.lang.round(r)}%, ${sr.lang.round(i)}%, ${n})`:`hsl(${sr.lang.round(e)}, ${sr.lang.round(r)}%, ${sr.lang.round(i)}%)`},"stringify")},Rx=h4});var f4,V8,ZY=P(()=>{"use strict";G8();f4={colors:{aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyanaqua:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",transparent:"#00000000",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},parse:o(t=>{t=t.toLowerCase();let e=f4.colors[t];if(e)return $p.parse(e)},"parse"),stringify:o(t=>{let e=$p.stringify(t);for(let r in f4.colors)if(f4.colors[r]===e)return r},"stringify")},V8=f4});var JY,Nx,ej=P(()=>{"use strict";Qc();Lx();JY={re:/^rgba?\(\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))\s*?(?:,|\s)\s*?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?))(?:\s*?(?:,|\/)\s*?\+?(-?(?:\d+(?:\.\d+)?|(?:\.\d+))(?:e\d+)?(%?)))?\s*?\)$/i,parse:o(t=>{let e=t.charCodeAt(0);if(e!==114&&e!==82)return;let r=t.match(JY.re);if(!r)return;let[,i,n,a,s,l,u,h,f]=r;return Rf.set({r:sr.channel.clamp.r(n?parseFloat(i)*2.55:parseFloat(i)),g:sr.channel.clamp.g(s?parseFloat(a)*2.55:parseFloat(a)),b:sr.channel.clamp.b(u?parseFloat(l)*2.55:parseFloat(l)),a:h?sr.channel.clamp.a(f?parseFloat(h)/100:parseFloat(h)):1},t)},"parse"),stringify:o(t=>{let{r:e,g:r,b:i,a:n}=t;return n<1?`rgba(${sr.lang.round(e)}, ${sr.lang.round(r)}, ${sr.lang.round(i)}, ${sr.lang.round(n)})`:`rgb(${sr.lang.round(e)}, ${sr.lang.round(r)}, ${sr.lang.round(i)})`},"stringify")},Nx=JY});var E8e,la,mh=P(()=>{"use strict";G8();QY();ZY();ej();Dx();E8e={format:{keyword:V8,hex:$p,rgb:Nx,rgba:Nx,hsl:Rx,hsla:Rx},parse:o(t=>{if(typeof t!="string")return t;let e=$p.parse(t)||Nx.parse(t)||Rx.parse(t)||V8.parse(t);if(e)return e;throw new Error(`Unsupported color format: "${t}"`)},"parse"),stringify:o(t=>!t.changed&&t.color?t.color:t.type.is(oa.HSL)||t.data.r===void 0?Rx.stringify(t):t.a<1||!Number.isInteger(t.r)||!Number.isInteger(t.g)||!Number.isInteger(t.b)?Nx.stringify(t):$p.stringify(t),"stringify")},la=E8e});var S8e,d4,q8=P(()=>{"use strict";Qc();mh();S8e=o((t,e)=>{let r=la.parse(t);for(let i in e)r[i]=sr.channel.clamp[i](e[i]);return la.stringify(r)},"change"),d4=S8e});var A8e,Fn,W8=P(()=>{"use strict";Qc();Lx();mh();q8();A8e=o((t,e,r=0,i=1)=>{if(typeof t!="number")return d4(t,{a:e});let n=Rf.set({r:sr.channel.clamp.r(t),g:sr.channel.clamp.g(e),b:sr.channel.clamp.b(r),a:sr.channel.clamp.a(i)});return la.stringify(n)},"rgba"),Fn=A8e});var _8e,zp,tj=P(()=>{"use strict";Qc();mh();_8e=o((t,e)=>sr.lang.round(la.parse(t)[e]),"channel"),zp=_8e});var D8e,rj,ij=P(()=>{"use strict";Qc();mh();D8e=o(t=>{let{r:e,g:r,b:i}=la.parse(t),n=.2126*sr.channel.toLinear(e)+.7152*sr.channel.toLinear(r)+.0722*sr.channel.toLinear(i);return sr.lang.round(n)},"luminance"),rj=D8e});var L8e,nj,aj=P(()=>{"use strict";ij();L8e=o(t=>rj(t)>=.5,"isLight"),nj=L8e});var R8e,yi,sj=P(()=>{"use strict";aj();R8e=o(t=>!nj(t),"isDark"),yi=R8e});var N8e,Cg,p4=P(()=>{"use strict";Qc();mh();N8e=o((t,e,r)=>{let i=la.parse(t),n=i[e],a=sr.channel.clamp[e](n+r);return n!==a&&(i[e]=a),la.stringify(i)},"adjustChannel"),Cg=N8e});var I8e,Ke,oj=P(()=>{"use strict";p4();I8e=o((t,e)=>Cg(t,"l",e),"lighten"),Ke=I8e});var M8e,Ye,lj=P(()=>{"use strict";p4();M8e=o((t,e)=>Cg(t,"l",-e),"darken"),Ye=M8e});var O8e,m4,cj=P(()=>{"use strict";p4();O8e=o((t,e)=>Cg(t,"a",-e),"transparentize"),m4=O8e});var P8e,ie,uj=P(()=>{"use strict";mh();q8();P8e=o((t,e)=>{let r=la.parse(t),i={};for(let n in e)e[n]&&(i[n]=r[n]+e[n]);return d4(t,i)},"adjust"),ie=P8e});var B8e,hj,fj=P(()=>{"use strict";mh();W8();B8e=o((t,e,r=50)=>{let{r:i,g:n,b:a,a:s}=la.parse(t),{r:l,g:u,b:h,a:f}=la.parse(e),d=r/100,p=d*2-1,m=s-f,y=((p*m===-1?p:(p+m)/(1+p*m))+1)/2,v=1-y,x=i*y+l*v,b=n*y+u*v,T=a*y+h*v,w=s*d+f*(1-d);return Fn(x,b,T,w)},"mix"),hj=B8e});var F8e,Ge,dj=P(()=>{"use strict";mh();fj();F8e=o((t,e=100)=>{let r=la.parse(t);return r.r=255-r.r,r.g=255-r.g,r.b=255-r.b,hj(r,t,e)},"invert"),Ge=F8e});var pj=P(()=>{"use strict";W8();tj();sj();oj();lj();cj();uj();dj()});var Yn=P(()=>{"use strict";pj()});var jn,Xn,oc=P(()=>{"use strict";jn="#ffffff",Xn="#f2f2f2"});var Jt,vl=P(()=>{"use strict";Yn();Jt=o((t,e)=>e?ie(t,{s:-40,l:10}):ie(t,{s:-40,l:-10}),"mkBorder")});var H8,mj,gj=P(()=>{"use strict";Yn();oc();vl();H8=class{static{o(this,"Theme")}constructor(){this.background="#f4f4f4",this.primaryColor="#fff4dd",this.noteBkgColor="#fff5ad",this.noteTextColor="#333",this.THEME_COLOR_LIMIT=12,this.radius=5,this.strokeWidth=1,this.fontFamily='"trebuchet ms", verdana, arial, sans-serif',this.fontSize="16px",this.useGradient=!0,this.dropShadow="drop-shadow( 1px 2px 2px rgba(185,185,185,1))"}updateColors(){if(this.primaryTextColor=this.primaryTextColor||(this.darkMode?"#eee":"#333"),this.secondaryColor=this.secondaryColor||ie(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||ie(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||Jt(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||Jt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||Jt(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||Jt(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||"#fff5ad",this.noteTextColor=this.noteTextColor||"#333",this.secondaryTextColor=this.secondaryTextColor||Ge(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||Ge(this.tertiaryColor),this.lineColor=this.lineColor||Ge(this.background),this.arrowheadColor=this.arrowheadColor||Ge(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.primaryBorderColor,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?Ye(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||Ye(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||Ge(this.lineColor),this.sectionBkgColor=this.sectionBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.altSectionBkgColor||"white",this.sectionBkgColor=this.sectionBkgColor||this.secondaryColor,this.sectionBkgColor2=this.sectionBkgColor2||this.primaryColor,this.excludeBkgColor=this.excludeBkgColor||"#eeeeee",this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||this.primaryColor,this.activeTaskBorderColor=this.activeTaskBorderColor||this.primaryColor,this.activeTaskBkgColor=this.activeTaskBkgColor||Ke(this.primaryColor,23),this.gridColor=this.gridColor||"lightgrey",this.doneTaskBkgColor=this.doneTaskBkgColor||"lightgrey",this.doneTaskBorderColor=this.doneTaskBorderColor||"grey",this.critBorderColor=this.critBorderColor||"#ff8888",this.critBkgColor=this.critBkgColor||"red",this.todayLineColor=this.todayLineColor||"red",this.vertLineColor=this.vertLineColor||"navy",this.taskTextColor=this.taskTextColor||this.textColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||"#003163",this.noteFontWeight=this.noteFontWeight||"normal",this.fontWeight=this.fontWeight||"normal",this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.darkMode?(this.rowOdd=this.rowOdd||Ye(this.mainBkg,5)||"#ffffff",this.rowEven=this.rowEven||Ye(this.mainBkg,10)):(this.rowOdd=this.rowOdd||Ke(this.mainBkg,75)||"#ffffff",this.rowEven=this.rowEven||Ke(this.mainBkg,5)),this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||this.tertiaryColor,this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||ie(this.primaryColor,{h:30}),this.cScale4=this.cScale4||ie(this.primaryColor,{h:60}),this.cScale5=this.cScale5||ie(this.primaryColor,{h:90}),this.cScale6=this.cScale6||ie(this.primaryColor,{h:120}),this.cScale7=this.cScale7||ie(this.primaryColor,{h:150}),this.cScale8=this.cScale8||ie(this.primaryColor,{h:210,l:150}),this.cScale9=this.cScale9||ie(this.primaryColor,{h:270}),this.cScale10=this.cScale10||ie(this.primaryColor,{h:300}),this.cScale11=this.cScale11||ie(this.primaryColor,{h:330}),this.darkMode)for(let r=0;r{this[i]=e[i]}),this.updateColors(),r.forEach(i=>{this[i]=e[i]})}},mj=o(t=>{let e=new H8;return e.calculate(t),e},"getThemeVariables")});var Y8,yj,vj=P(()=>{"use strict";Yn();vl();Y8=class{static{o(this,"Theme")}constructor(){this.background="#333",this.primaryColor="#1f2020",this.secondaryColor=Ke(this.primaryColor,16),this.tertiaryColor=ie(this.primaryColor,{h:-160}),this.primaryBorderColor=Ge(this.background),this.secondaryBorderColor=Jt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=Jt(this.tertiaryColor,this.darkMode),this.primaryTextColor=Ge(this.primaryColor),this.secondaryTextColor=Ge(this.secondaryColor),this.tertiaryTextColor=Ge(this.tertiaryColor),this.lineColor=Ge(this.background),this.textColor=Ge(this.background),this.mainBkg="#1f2020",this.secondBkg="calculated",this.mainContrastColor="lightgrey",this.darkTextColor=Ke(Ge("#323D47"),10),this.lineColor="calculated",this.border1="#ccc",this.border2=Fn(255,255,255,.25),this.arrowheadColor="calculated",this.fontFamily='"trebuchet ms", verdana, arial, sans-serif',this.fontSize="16px",this.labelBackground="#181818",this.textColor="#ccc",this.THEME_COLOR_LIMIT=12,this.radius=5,this.strokeWidth=1,this.nodeBkg="calculated",this.nodeBorder="calculated",this.clusterBkg="calculated",this.clusterBorder="calculated",this.defaultLinkColor="calculated",this.titleColor="#F9FFFE",this.edgeLabelBackground="calculated",this.actorBorder="calculated",this.actorBkg="calculated",this.actorTextColor="calculated",this.actorLineColor="calculated",this.signalColor="calculated",this.signalTextColor="calculated",this.labelBoxBkgColor="calculated",this.labelBoxBorderColor="calculated",this.labelTextColor="calculated",this.loopTextColor="calculated",this.noteBorderColor="calculated",this.noteBkgColor="#fff5ad",this.noteTextColor="calculated",this.activationBorderColor="calculated",this.activationBkgColor="calculated",this.sequenceNumberColor="black",this.clusterBkg="#302F3D",this.sectionBkgColor=Ye("#EAE8D9",30),this.altSectionBkgColor="calculated",this.sectionBkgColor2="#EAE8D9",this.excludeBkgColor=Ye(this.sectionBkgColor,10),this.taskBorderColor=Fn(255,255,255,70),this.taskBkgColor="calculated",this.taskTextColor="calculated",this.taskTextLightColor="calculated",this.taskTextOutsideColor="calculated",this.taskTextClickableColor="#003163",this.activeTaskBorderColor=Fn(255,255,255,50),this.activeTaskBkgColor="#81B1DB",this.gridColor="calculated",this.doneTaskBkgColor="calculated",this.doneTaskBorderColor="grey",this.critBorderColor="#E83737",this.critBkgColor="#E83737",this.taskTextDarkColor="calculated",this.todayLineColor="#DB5757",this.vertLineColor="#00BFFF",this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor="calculated",this.archEdgeArrowColor="calculated",this.archEdgeWidth="3",this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth="2px",this.rowOdd=this.rowOdd||Ke(this.mainBkg,5)||"#ffffff",this.rowEven=this.rowEven||Ye(this.mainBkg,10),this.labelColor="calculated",this.errorBkgColor="#a44141",this.errorTextColor="#ddd",this.useGradient=!0,this.gradientStart=this.primaryBorderColor,this.gradientStop=this.secondaryBorderColor,this.dropShadow="drop-shadow( 1px 2px 2px rgba(185,185,185,1))",this.noteFontWeight=this.noteFontWeight||"normal",this.fontWeight=this.fontWeight||"normal"}updateColors(){this.secondBkg=Ke(this.mainBkg,16),this.lineColor=this.mainContrastColor,this.arrowheadColor=this.mainContrastColor,this.nodeBkg=this.mainBkg,this.nodeBorder=this.border1,this.clusterBkg=this.secondBkg,this.clusterBorder=this.border2,this.defaultLinkColor=this.lineColor,this.edgeLabelBackground=Ke(this.labelBackground,25),this.actorBorder=this.border1,this.actorBkg=this.mainBkg,this.actorTextColor=this.mainContrastColor,this.actorLineColor=this.actorBorder,this.signalColor=this.mainContrastColor,this.signalTextColor=this.mainContrastColor,this.labelBoxBkgColor=this.actorBkg,this.labelBoxBorderColor=this.actorBorder,this.labelTextColor=this.mainContrastColor,this.loopTextColor=this.mainContrastColor,this.noteBorderColor=this.secondaryBorderColor,this.noteBkgColor=this.secondBkg,this.noteTextColor=this.secondaryTextColor,this.activationBorderColor=this.border1,this.activationBkgColor=this.secondBkg,this.altSectionBkgColor=this.background,this.taskBkgColor=Ke(this.mainBkg,23),this.taskTextColor=this.darkTextColor,this.taskTextLightColor=this.mainContrastColor,this.taskTextOutsideColor=this.taskTextLightColor,this.gridColor=this.mainContrastColor,this.doneTaskBkgColor=this.mainContrastColor,this.taskTextDarkColor=Ge(this.doneTaskBkgColor),this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||"#555",this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.primaryBorderColor,this.specialStateColor="#f4f4f4",this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.fillType0=this.primaryColor,this.fillType1=this.secondaryColor,this.fillType2=ie(this.primaryColor,{h:64}),this.fillType3=ie(this.secondaryColor,{h:64}),this.fillType4=ie(this.primaryColor,{h:-64}),this.fillType5=ie(this.secondaryColor,{h:-64}),this.fillType6=ie(this.primaryColor,{h:128}),this.fillType7=ie(this.secondaryColor,{h:128}),this.cScale1=this.cScale1||"#0b0000",this.cScale2=this.cScale2||"#4d1037",this.cScale3=this.cScale3||"#3f5258",this.cScale4=this.cScale4||"#4f2f1b",this.cScale5=this.cScale5||"#6e0a0a",this.cScale6=this.cScale6||"#3b0048",this.cScale7=this.cScale7||"#995a01",this.cScale8=this.cScale8||"#154706",this.cScale9=this.cScale9||"#161722",this.cScale10=this.cScale10||"#00296f",this.cScale11=this.cScale11||"#01629c",this.cScale12=this.cScale12||"#010029",this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||ie(this.primaryColor,{h:30}),this.cScale4=this.cScale4||ie(this.primaryColor,{h:60}),this.cScale5=this.cScale5||ie(this.primaryColor,{h:90}),this.cScale6=this.cScale6||ie(this.primaryColor,{h:120}),this.cScale7=this.cScale7||ie(this.primaryColor,{h:150}),this.cScale8=this.cScale8||ie(this.primaryColor,{h:210}),this.cScale9=this.cScale9||ie(this.primaryColor,{h:270}),this.cScale10=this.cScale10||ie(this.primaryColor,{h:300}),this.cScale11=this.cScale11||ie(this.primaryColor,{h:330});for(let e=0;e{this[i]=e[i]}),this.updateColors(),r.forEach(i=>{this[i]=e[i]})}},yj=o(t=>{let e=new Y8;return e.calculate(t),e},"getThemeVariables")});var j8,Zc,wg=P(()=>{"use strict";Yn();vl();oc();j8=class{static{o(this,"Theme")}constructor(){this.background="#f4f4f4",this.primaryColor="#ECECFF",this.secondaryColor=ie(this.primaryColor,{h:120}),this.secondaryColor="#ffffde",this.tertiaryColor=ie(this.primaryColor,{h:-160}),this.primaryBorderColor=Jt(this.primaryColor,this.darkMode),this.secondaryBorderColor=Jt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=Jt(this.tertiaryColor,this.darkMode),this.primaryTextColor=Ge(this.primaryColor),this.secondaryTextColor=Ge(this.secondaryColor),this.tertiaryTextColor=Ge(this.tertiaryColor),this.lineColor=Ge(this.background),this.textColor=Ge(this.background),this.background="white",this.mainBkg="#ECECFF",this.secondBkg="#ffffde",this.lineColor="#333333",this.border1="#9370DB",this.primaryBorderColor=Jt(this.primaryColor,this.darkMode),this.border2="#aaaa33",this.arrowheadColor="#333333",this.fontFamily='"trebuchet ms", verdana, arial, sans-serif',this.fontSize="16px",this.labelBackground="rgba(232,232,232, 0.8)",this.textColor="#333",this.THEME_COLOR_LIMIT=12,this.radius=5,this.strokeWidth=1,this.nodeBkg="calculated",this.nodeBorder="calculated",this.clusterBkg="calculated",this.clusterBorder="calculated",this.defaultLinkColor="calculated",this.titleColor="calculated",this.edgeLabelBackground="calculated",this.actorBorder="calculated",this.actorBkg="calculated",this.actorTextColor="black",this.actorLineColor="calculated",this.signalColor="calculated",this.signalTextColor="calculated",this.labelBoxBkgColor="calculated",this.labelBoxBorderColor="calculated",this.labelTextColor="calculated",this.loopTextColor="calculated",this.noteBorderColor="calculated",this.noteBkgColor="#fff5ad",this.noteTextColor="calculated",this.activationBorderColor="#666",this.activationBkgColor="#f4f4f4",this.sequenceNumberColor="white",this.clusterBkg="#FBFBFF",this.sectionBkgColor="calculated",this.altSectionBkgColor="calculated",this.sectionBkgColor2="calculated",this.excludeBkgColor="#eeeeee",this.taskBorderColor="calculated",this.taskBkgColor="calculated",this.taskTextLightColor="calculated",this.taskTextColor=this.taskTextLightColor,this.taskTextDarkColor="calculated",this.taskTextOutsideColor=this.taskTextDarkColor,this.taskTextClickableColor="calculated",this.activeTaskBorderColor="calculated",this.activeTaskBkgColor="calculated",this.gridColor="calculated",this.doneTaskBkgColor="calculated",this.doneTaskBorderColor="calculated",this.critBorderColor="calculated",this.critBkgColor="calculated",this.todayLineColor="calculated",this.vertLineColor="calculated",this.sectionBkgColor=Fn(102,102,255,.49),this.altSectionBkgColor="white",this.sectionBkgColor2="#fff400",this.taskBorderColor="#534fbc",this.taskBkgColor="#8a90dd",this.taskTextLightColor="white",this.taskTextColor="calculated",this.taskTextDarkColor="black",this.taskTextOutsideColor="calculated",this.taskTextClickableColor="#003163",this.activeTaskBorderColor="#534fbc",this.activeTaskBkgColor="#bfc7ff",this.gridColor="lightgrey",this.doneTaskBkgColor="lightgrey",this.doneTaskBorderColor="grey",this.critBorderColor="#ff8888",this.critBkgColor="red",this.todayLineColor="red",this.vertLineColor="navy",this.noteFontWeight=this.noteFontWeight||"normal",this.fontWeight=this.fontWeight||"normal",this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor="calculated",this.archEdgeArrowColor="calculated",this.archEdgeWidth="3",this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth="2px",this.rowOdd="calculated",this.rowEven="calculated",this.labelColor="black",this.errorBkgColor="#552222",this.errorTextColor="#552222",this.useGradient=!1,this.gradientStart=this.primaryBorderColor,this.gradientStop=this.secondaryBorderColor,this.dropShadow="drop-shadow(1px 2px 2px rgba(185, 185, 185, 1))",this.updateColors()}updateColors(){this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||ie(this.primaryColor,{h:30}),this.cScale4=this.cScale4||ie(this.primaryColor,{h:60}),this.cScale5=this.cScale5||ie(this.primaryColor,{h:90}),this.cScale6=this.cScale6||ie(this.primaryColor,{h:120}),this.cScale7=this.cScale7||ie(this.primaryColor,{h:150}),this.cScale8=this.cScale8||ie(this.primaryColor,{h:210}),this.cScale9=this.cScale9||ie(this.primaryColor,{h:270}),this.cScale10=this.cScale10||ie(this.primaryColor,{h:300}),this.cScale11=this.cScale11||ie(this.primaryColor,{h:330}),this.cScalePeer1=this.cScalePeer1||Ye(this.secondaryColor,45),this.cScalePeer2=this.cScalePeer2||Ye(this.tertiaryColor,40);for(let e=0;e{this[i]==="calculated"&&(this[i]=void 0)}),typeof e!="object"){this.updateColors();return}let r=Object.keys(e);r.forEach(i=>{this[i]=e[i]}),this.updateColors(),r.forEach(i=>{this[i]=e[i]})}},Zc=o(t=>{let e=new j8;return e.calculate(t),e},"getThemeVariables")});var X8,xj,bj=P(()=>{"use strict";Yn();oc();vl();X8=class{static{o(this,"Theme")}constructor(){this.background="#f4f4f4",this.primaryColor="#cde498",this.secondaryColor="#cdffb2",this.background="white",this.mainBkg="#cde498",this.secondBkg="#cdffb2",this.lineColor="green",this.border1="#13540c",this.border2="#6eaa49",this.arrowheadColor="green",this.fontFamily='"trebuchet ms", verdana, arial, sans-serif',this.fontSize="16px",this.tertiaryColor=Ke("#cde498",10),this.primaryBorderColor=Jt(this.primaryColor,this.darkMode),this.secondaryBorderColor=Jt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=Jt(this.tertiaryColor,this.darkMode),this.primaryTextColor=Ge(this.primaryColor),this.secondaryTextColor=Ge(this.secondaryColor),this.tertiaryTextColor=Ge(this.primaryColor),this.lineColor=Ge(this.background),this.textColor=Ge(this.background),this.THEME_COLOR_LIMIT=12,this.radius=5,this.strokeWidth=1,this.nodeBkg="calculated",this.nodeBorder="calculated",this.clusterBkg="calculated",this.clusterBorder="calculated",this.defaultLinkColor="calculated",this.titleColor="#333",this.edgeLabelBackground="#e8e8e8",this.actorBorder="calculated",this.actorBkg="calculated",this.actorTextColor="black",this.actorLineColor="calculated",this.signalColor="#333",this.signalTextColor="#333",this.labelBoxBkgColor="calculated",this.labelBoxBorderColor="#326932",this.labelTextColor="calculated",this.loopTextColor="calculated",this.noteBorderColor="calculated",this.noteBkgColor="#fff5ad",this.noteTextColor="calculated",this.activationBorderColor="#666",this.activationBkgColor="#f4f4f4",this.sequenceNumberColor="white",this.sectionBkgColor="#6eaa49",this.altSectionBkgColor="white",this.sectionBkgColor2="#6eaa49",this.excludeBkgColor="#eeeeee",this.taskBorderColor="calculated",this.taskBkgColor="#487e3a",this.taskTextLightColor="white",this.taskTextColor="calculated",this.taskTextDarkColor="black",this.taskTextOutsideColor="calculated",this.taskTextClickableColor="#003163",this.activeTaskBorderColor="calculated",this.activeTaskBkgColor="calculated",this.gridColor="lightgrey",this.doneTaskBkgColor="lightgrey",this.doneTaskBorderColor="grey",this.critBorderColor="#ff8888",this.critBkgColor="red",this.todayLineColor="red",this.vertLineColor="#00BFFF",this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor="calculated",this.archEdgeArrowColor="calculated",this.archEdgeWidth="3",this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth="2px",this.noteFontWeight="normal",this.fontWeight="normal",this.labelColor="black",this.errorBkgColor="#552222",this.errorTextColor="#552222",this.useGradient=!0,this.gradientStart=this.primaryBorderColor,this.gradientStop=this.secondaryBorderColor,this.dropShadow="drop-shadow( 1px 2px 2px rgba(185,185,185,0.5))"}updateColors(){this.actorBorder=Ye(this.mainBkg,20),this.actorBkg=this.mainBkg,this.labelBoxBkgColor=this.actorBkg,this.labelTextColor=this.actorTextColor,this.loopTextColor=this.actorTextColor,this.noteBorderColor=this.border2,this.noteTextColor=this.actorTextColor,this.actorLineColor=this.actorBorder,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||ie(this.primaryColor,{h:30}),this.cScale4=this.cScale4||ie(this.primaryColor,{h:60}),this.cScale5=this.cScale5||ie(this.primaryColor,{h:90}),this.cScale6=this.cScale6||ie(this.primaryColor,{h:120}),this.cScale7=this.cScale7||ie(this.primaryColor,{h:150}),this.cScale8=this.cScale8||ie(this.primaryColor,{h:210}),this.cScale9=this.cScale9||ie(this.primaryColor,{h:270}),this.cScale10=this.cScale10||ie(this.primaryColor,{h:300}),this.cScale11=this.cScale11||ie(this.primaryColor,{h:330}),this.cScalePeer1=this.cScalePeer1||Ye(this.secondaryColor,45),this.cScalePeer2=this.cScalePeer2||Ye(this.tertiaryColor,40);for(let e=0;e{this[i]=e[i]}),this.updateColors(),r.forEach(i=>{this[i]=e[i]})}},xj=o(t=>{let e=new X8;return e.calculate(t),e},"getThemeVariables")});var K8,Tj,kj=P(()=>{"use strict";Yn();vl();oc();K8=class{static{o(this,"Theme")}constructor(){this.primaryColor="#eee",this.contrast="#707070",this.secondaryColor=Ke(this.contrast,55),this.background="#ffffff",this.tertiaryColor=ie(this.primaryColor,{h:-160}),this.primaryBorderColor=Jt(this.primaryColor,this.darkMode),this.secondaryBorderColor=Jt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=Jt(this.tertiaryColor,this.darkMode),this.primaryTextColor=Ge(this.primaryColor),this.secondaryTextColor=Ge(this.secondaryColor),this.tertiaryTextColor=Ge(this.tertiaryColor),this.lineColor=Ge(this.background),this.textColor=Ge(this.background),this.mainBkg="#eee",this.secondBkg="calculated",this.lineColor="#666",this.border1="#999",this.border2="calculated",this.note="#ffa",this.text="#333",this.critical="#d42",this.done="#bbb",this.arrowheadColor="#333333",this.fontFamily='"trebuchet ms", verdana, arial, sans-serif',this.fontSize="16px",this.THEME_COLOR_LIMIT=12,this.radius=5,this.strokeWidth=1,this.nodeBkg="calculated",this.nodeBorder="calculated",this.clusterBkg="calculated",this.clusterBorder="calculated",this.defaultLinkColor="calculated",this.titleColor="calculated",this.edgeLabelBackground="white",this.actorBorder="calculated",this.actorBkg="calculated",this.actorTextColor="calculated",this.actorLineColor=this.actorBorder,this.signalColor="calculated",this.signalTextColor="calculated",this.labelBoxBkgColor="calculated",this.labelBoxBorderColor="calculated",this.labelTextColor="calculated",this.loopTextColor="calculated",this.noteBorderColor="calculated",this.noteBkgColor="calculated",this.noteTextColor="calculated",this.activationBorderColor="#666",this.activationBkgColor="#f4f4f4",this.sequenceNumberColor="white",this.sectionBkgColor="calculated",this.altSectionBkgColor="white",this.sectionBkgColor2="calculated",this.excludeBkgColor="#eeeeee",this.taskBorderColor="calculated",this.taskBkgColor="calculated",this.taskTextLightColor="white",this.taskTextColor="calculated",this.taskTextDarkColor="calculated",this.taskTextOutsideColor="calculated",this.taskTextClickableColor="#003163",this.activeTaskBorderColor="calculated",this.activeTaskBkgColor="calculated",this.gridColor="calculated",this.doneTaskBkgColor="calculated",this.doneTaskBorderColor="calculated",this.critBkgColor="calculated",this.critBorderColor="calculated",this.todayLineColor="calculated",this.vertLineColor="calculated",this.personBorder=this.primaryBorderColor,this.personBkg=this.mainBkg,this.archEdgeColor="calculated",this.archEdgeArrowColor="calculated",this.archEdgeWidth="3",this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth="2px",this.noteFontWeight="normal",this.fontWeight="normal",this.rowOdd=this.rowOdd||Ke(this.mainBkg,75)||"#ffffff",this.rowEven=this.rowEven||"#f4f4f4",this.labelColor="black",this.errorBkgColor="#552222",this.errorTextColor="#552222",this.useGradient=!0,this.gradientStart=this.primaryBorderColor,this.gradientStop=this.secondaryBorderColor,this.dropShadow="drop-shadow( 1px 2px 2px rgba(185,185,185,1))"}updateColors(){this.secondBkg=Ke(this.contrast,55),this.border2=this.contrast,this.actorBorder=Ke(this.border1,23),this.actorBkg=this.mainBkg,this.actorTextColor=this.text,this.actorLineColor=this.actorBorder,this.signalColor=this.text,this.signalTextColor=this.text,this.labelBoxBkgColor=this.actorBkg,this.labelBoxBorderColor=this.actorBorder,this.labelTextColor=this.text,this.loopTextColor=this.text,this.noteBorderColor="#999",this.noteBkgColor="#666",this.noteTextColor="#fff",this.cScale0=this.cScale0||"#555",this.cScale1=this.cScale1||"#F4F4F4",this.cScale2=this.cScale2||"#555",this.cScale3=this.cScale3||"#BBB",this.cScale4=this.cScale4||"#777",this.cScale5=this.cScale5||"#999",this.cScale6=this.cScale6||"#DDD",this.cScale7=this.cScale7||"#FFF",this.cScale8=this.cScale8||"#DDD",this.cScale9=this.cScale9||"#BBB",this.cScale10=this.cScale10||"#999",this.cScale11=this.cScale11||"#777";for(let e=0;e{this[i]=e[i]}),this.updateColors(),r.forEach(i=>{this[i]=e[i]})}},Tj=o(t=>{let e=new K8;return e.calculate(t),e},"getThemeVariables")});var Q8,Cj,wj=P(()=>{"use strict";Yn();vl();oc();Q8=class{static{o(this,"Theme")}constructor(){this.background="#ffffff",this.primaryColor="#cccccc",this.mainBkg="#ffffff",this.noteBkgColor="#fff5ad",this.noteTextColor="#333",this.THEME_COLOR_LIMIT=12,this.radius=3,this.strokeWidth=2,this.primaryBorderColor=Jt(this.primaryColor,this.darkMode),this.fontFamily="arial, sans-serif",this.fontSize="14px",this.nodeBorder="#000000",this.stateBorder="#000000",this.useGradient=!0,this.gradientStart="#0042eb",this.gradientStop="#eb0042",this.dropShadow="drop-shadow( 0px 1px 2px rgba(0, 0, 0, 0.25));",this.tertiaryColor="#ffffff",this.archEdgeColor="calculated",this.archEdgeArrowColor="calculated",this.archEdgeWidth="3",this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth="2px",this.noteFontWeight="normal",this.fontWeight="normal"}updateColors(){this.primaryTextColor=this.primaryTextColor||(this.darkMode?"#eee":"#333"),this.secondaryColor=this.secondaryColor||ie(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||ie(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||Jt(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||Jt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||Jt(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||Jt(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||"#fff5ad",this.noteTextColor=this.noteTextColor||"#333",this.secondaryTextColor=this.secondaryTextColor||Ge(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||Ge(this.tertiaryColor),this.lineColor=this.lineColor||Ge(this.background),this.arrowheadColor=this.arrowheadColor||Ge(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.primaryBorderColor,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?Ye(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||Ye(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||Ge(this.lineColor);let e="#ECECFE",r="#E9E9F1",i=ie(e,{h:180,l:5});if(this.sectionBkgColor=this.sectionBkgColor||i,this.altSectionBkgColor=this.altSectionBkgColor||"white",this.sectionBkgColor=this.sectionBkgColor||r,this.sectionBkgColor2=this.sectionBkgColor2||e,this.excludeBkgColor=this.excludeBkgColor||"#eeeeee",this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||e,this.activeTaskBorderColor=this.activeTaskBorderColor||e,this.activeTaskBkgColor=this.activeTaskBkgColor||Ke(e,23),this.gridColor=this.gridColor||"lightgrey",this.doneTaskBkgColor=this.doneTaskBkgColor||"lightgrey",this.doneTaskBorderColor=this.doneTaskBorderColor||"grey",this.critBorderColor=this.critBorderColor||"#ff8888",this.critBkgColor=this.critBkgColor||"red",this.todayLineColor=this.todayLineColor||"red",this.taskTextColor=this.taskTextColor||this.textColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||"#003163",this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||"#f0f0f0",this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||e,this.cScale1=this.cScale1||r,this.cScale2=this.cScale2||i,this.cScale3=this.cScale3||ie(e,{h:30}),this.cScale4=this.cScale4||ie(e,{h:60}),this.cScale5=this.cScale5||ie(e,{h:90}),this.cScale6=this.cScale6||ie(e,{h:120}),this.cScale7=this.cScale7||ie(e,{h:150}),this.cScale8=this.cScale8||ie(e,{h:210,l:150}),this.cScale9=this.cScale9||ie(e,{h:270}),this.cScale10=this.cScale10||ie(e,{h:300}),this.cScale11=this.cScale11||ie(e,{h:330}),this.darkMode)for(let a=0;a{this[i]=e[i]}),this.updateColors(),r.forEach(i=>{this[i]=e[i]})}},Cj=o(t=>{let e=new Q8;return e.calculate(t),e},"getThemeVariables")});var Z8,Ej,Sj=P(()=>{"use strict";Yn();vl();oc();Z8=class{static{o(this,"Theme")}constructor(){this.background="#333",this.primaryColor="#1f2020",this.secondaryColor=Ke(this.primaryColor,16),this.tertiaryColor=ie(this.primaryColor,{h:-160}),this.primaryBorderColor=Ge(this.background),this.secondaryBorderColor=Jt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=Jt(this.tertiaryColor,this.darkMode),this.primaryTextColor=Ge(this.primaryColor),this.secondaryTextColor=Ge(this.secondaryColor),this.tertiaryTextColor=Ge(this.tertiaryColor),this.mainBkg="#2a2020",this.secondBkg="calculated",this.mainContrastColor="lightgrey",this.darkTextColor=Ke(Ge("#323D47"),10),this.border1="#ccc",this.border2=Fn(255,255,255,.25),this.arrowheadColor=Ge(this.background),this.fontFamily="arial, sans-serif",this.fontSize="14px",this.labelBackground="#181818",this.textColor="#ccc",this.THEME_COLOR_LIMIT=12,this.radius=3,this.strokeWidth=1,this.noteBkgColor="#fff5ad",this.noteTextColor="#333",this.THEME_COLOR_LIMIT=12,this.fontFamily="arial, sans-serif",this.fontSize="14px",this.useGradient=!0,this.gradientStart="#0042eb",this.gradientStop="#eb0042",this.dropShadow="drop-shadow( 1px 2px 2px rgba(185,185,185,0.2))",this.archEdgeColor="calculated",this.archEdgeArrowColor="calculated",this.archEdgeWidth="3",this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth="2px",this.noteFontWeight="normal",this.fontWeight="normal"}updateColors(){if(this.primaryTextColor=this.primaryTextColor||(this.darkMode?"#eee":"#333"),this.secondaryColor=this.secondaryColor||ie(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||ie(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||Jt(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||Jt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||Jt(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||Jt(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||"#fff5ad",this.noteTextColor=this.noteTextColor||"#333",this.secondaryTextColor=this.secondaryTextColor||Ge(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||Ge(this.tertiaryColor),this.lineColor=this.lineColor||Ge(this.background),this.arrowheadColor=this.arrowheadColor||Ge(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.border1,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?Ye(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||Ye(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||Ge(this.lineColor),this.sectionBkgColor=this.sectionBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.altSectionBkgColor||"white",this.sectionBkgColor=this.sectionBkgColor||this.secondaryColor,this.sectionBkgColor2=this.sectionBkgColor2||this.primaryColor,this.excludeBkgColor=this.excludeBkgColor||"#eeeeee",this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||this.primaryColor,this.activeTaskBorderColor=this.activeTaskBorderColor||this.primaryColor,this.activeTaskBkgColor=this.activeTaskBkgColor||Ke(this.primaryColor,23),this.gridColor=this.gridColor||"lightgrey",this.doneTaskBkgColor=this.doneTaskBkgColor||"lightgrey",this.doneTaskBorderColor=this.doneTaskBorderColor||"grey",this.critBorderColor=this.critBorderColor||"#ff8888",this.critBkgColor=this.critBkgColor||"red",this.todayLineColor=this.todayLineColor||"red",this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.taskTextColor=this.taskTextColor||this.textColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||"#003163",this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||"#f0f0f0",this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||ie(this.primaryColor,{h:30}),this.cScale4=this.cScale4||ie(this.primaryColor,{h:60}),this.cScale5=this.cScale5||ie(this.primaryColor,{h:90}),this.cScale6=this.cScale6||ie(this.primaryColor,{h:120}),this.cScale7=this.cScale7||ie(this.primaryColor,{h:150}),this.cScale8=this.cScale8||ie(this.primaryColor,{h:210,l:150}),this.cScale9=this.cScale9||ie(this.primaryColor,{h:270}),this.cScale10=this.cScale10||ie(this.primaryColor,{h:300}),this.cScale11=this.cScale11||ie(this.primaryColor,{h:330}),this.darkMode)for(let r=0;r{this[i]=e[i]}),this.updateColors(),r.forEach(i=>{this[i]=e[i]})}},Ej=o(t=>{let e=new Z8;return e.calculate(t),e},"getThemeVariables")});var J8,Aj,_j=P(()=>{"use strict";Yn();vl();oc();J8=class{static{o(this,"Theme")}constructor(){this.background="#ffffff",this.primaryColor="#cccccc",this.mainBkg="#ffffff",this.noteBkgColor="#fff5ad",this.noteTextColor="#28253D",this.THEME_COLOR_LIMIT=12,this.radius=12,this.strokeWidth=2,this.primaryBorderColor=Jt("#28253D",this.darkMode),this.fontFamily='"Recursive Variable", arial, sans-serif',this.fontSize="14px",this.nodeBorder="#28253D",this.stateBorder="#28253D",this.useGradient=!1,this.gradientStart="#0042eb",this.gradientStop="#eb0042",this.dropShadow="url(#drop-shadow)",this.nodeShadow=!0,this.tertiaryColor="#ffffff",this.clusterBkg="#F9F9FB",this.clusterBorder="#BDBCCC",this.noteBorderColor="#FACC15",this.archEdgeColor="calculated",this.archEdgeArrowColor="calculated",this.archEdgeWidth="3",this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth="2px",this.actorBorder="#28253D",this.filterColor="#000000"}updateColors(){this.primaryTextColor=this.primaryTextColor||(this.darkMode?"#eee":"#28253D"),this.secondaryColor=this.secondaryColor||ie(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||ie(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||Jt(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||Jt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||Jt(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||Jt(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||"#FEF9C3",this.noteTextColor=this.noteTextColor||"#28253D",this.secondaryTextColor=this.secondaryTextColor||Ge(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||Ge(this.tertiaryColor),this.lineColor=this.lineColor||Ge(this.background),this.arrowheadColor=this.arrowheadColor||Ge(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.primaryBorderColor,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?Ye(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.noteFontWeight=600,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||Ye(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||Ge(this.lineColor);let e="#ECECFE",r="#E9E9F1",i=ie(e,{h:180,l:5});this.sectionBkgColor=this.sectionBkgColor||i,this.altSectionBkgColor=this.altSectionBkgColor||"white",this.sectionBkgColor=this.sectionBkgColor||r,this.sectionBkgColor2=this.sectionBkgColor2||e,this.excludeBkgColor=this.excludeBkgColor||"#eeeeee",this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||e,this.activeTaskBorderColor=this.activeTaskBorderColor||e,this.activeTaskBkgColor=this.activeTaskBkgColor||Ke(e,23),this.gridColor=this.gridColor||"lightgrey",this.doneTaskBkgColor=this.doneTaskBkgColor||"lightgrey",this.doneTaskBorderColor=this.doneTaskBorderColor||"grey",this.critBorderColor=this.critBorderColor||"#ff8888",this.critBkgColor=this.critBkgColor||"red",this.todayLineColor=this.todayLineColor||"red",this.taskTextColor=this.taskTextColor||this.textColor,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||"#003163",this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.compositeTitleBackground="#F9F9FB",this.altBackground="#F9F9FB",this.stateEdgeLabelBackground="#FFFFFF",this.fontWeight=600,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||"#f0f0f0",this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor;for(let a=0;a{this[i]=e[i]}),this.updateColors(),r.forEach(i=>{this[i]=e[i]})}},Aj=o(t=>{let e=new J8;return e.calculate(t),e},"getThemeVariables")});var eD,Dj,Lj=P(()=>{"use strict";Yn();vl();oc();eD=class{static{o(this,"Theme")}constructor(){this.background="#333",this.primaryColor="#1f2020",this.secondaryColor=Ke(this.primaryColor,16),this.tertiaryColor=ie(this.primaryColor,{h:-160}),this.primaryBorderColor=Ge(this.background),this.secondaryBorderColor=Jt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=Jt(this.tertiaryColor,this.darkMode),this.primaryTextColor=Ge(this.primaryColor),this.secondaryTextColor=Ge(this.secondaryColor),this.tertiaryTextColor=Ge(this.tertiaryColor),this.mainBkg="#111113",this.secondBkg="calculated",this.mainContrastColor="lightgrey",this.darkTextColor=Ke(Ge("#323D47"),10),this.border1="#ccc",this.border2=Fn(255,255,255,.25),this.arrowheadColor=Ge(this.background),this.fontFamily='"Recursive Variable", arial, sans-serif',this.fontSize="14px",this.labelBackground="#111113",this.textColor="#ccc",this.THEME_COLOR_LIMIT=12,this.radius=12,this.strokeWidth=2,this.noteBkgColor=this.noteBkgColor??"#FEF9C3",this.noteTextColor=this.noteTextColor??"#28253D",this.THEME_COLOR_LIMIT=12,this.fontFamily='"Recursive Variable", arial, sans-serif',this.fontSize="14px",this.nodeBorder="#FFFFFF",this.stateBorder="#FFFFFF",this.useGradient=!1,this.gradientStart="#0042eb",this.gradientStop="#eb0042",this.dropShadow="url(#drop-shadow)",this.nodeShadow=!0,this.archEdgeColor="calculated",this.archEdgeArrowColor="calculated",this.archEdgeWidth="3",this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth="2px",this.clusterBkg="#1E1A2E",this.clusterBorder="#BDBCCC",this.noteBorderColor="#FACC15",this.noteFontWeight=600,this.filterColor="#FFFFFF"}updateColors(){if(this.primaryTextColor=this.primaryTextColor||(this.darkMode?"#eee":"#FFFFFF"),this.secondaryColor=this.secondaryColor||ie(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||ie(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||Jt(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||Jt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||Jt(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||Jt(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||"#fff5ad",this.noteTextColor=this.noteTextColor||"#FFFFFF",this.secondaryTextColor=this.secondaryTextColor||Ge(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||Ge(this.tertiaryColor),this.lineColor=this.lineColor||Ge(this.background),this.arrowheadColor=this.arrowheadColor||Ge(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.border1,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?Ye(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder="#FFFFFF",this.signalColor="#FFFFFF",this.labelBoxBorderColor="#BDBCCC",this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||Ye(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||Ge(this.lineColor),this.sectionBkgColor=this.sectionBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.altSectionBkgColor||"white",this.sectionBkgColor=this.sectionBkgColor||this.secondaryColor,this.sectionBkgColor2=this.sectionBkgColor2||this.primaryColor,this.excludeBkgColor=this.excludeBkgColor||"#eeeeee",this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||this.primaryColor,this.activeTaskBorderColor=this.activeTaskBorderColor||this.primaryColor,this.activeTaskBkgColor=this.activeTaskBkgColor||Ke(this.primaryColor,23),this.gridColor=this.gridColor||"lightgrey",this.doneTaskBkgColor=this.doneTaskBkgColor||"lightgrey",this.doneTaskBorderColor=this.doneTaskBorderColor||"grey",this.critBorderColor=this.critBorderColor||"#ff8888",this.critBkgColor=this.critBkgColor||"red",this.todayLineColor=this.todayLineColor||"red",this.taskTextColor=this.taskTextColor||this.textColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||"#003163",this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.compositeBackground="#16141F",this.altBackground="#16141F",this.compositeTitleBackground="#16141F",this.stateEdgeLabelBackground="#16141F",this.fontWeight=600,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||"#f0f0f0",this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||this.primaryColor,this.cScale1=this.cScale1||this.secondaryColor,this.cScale2=this.cScale2||this.tertiaryColor,this.cScale3=this.cScale3||ie(this.primaryColor,{h:30}),this.cScale4=this.cScale4||ie(this.primaryColor,{h:60}),this.cScale5=this.cScale5||ie(this.primaryColor,{h:90}),this.cScale6=this.cScale6||ie(this.primaryColor,{h:120}),this.cScale7=this.cScale7||ie(this.primaryColor,{h:150}),this.cScale8=this.cScale8||ie(this.primaryColor,{h:210,l:150}),this.cScale9=this.cScale9||ie(this.primaryColor,{h:270}),this.cScale10=this.cScale10||ie(this.primaryColor,{h:300}),this.cScale11=this.cScale11||ie(this.primaryColor,{h:330}),this.darkMode)for(let r=0;r{this[i]=e[i]}),this.updateColors(),r.forEach(i=>{this[i]=e[i]})}},Dj=o(t=>{let e=new eD;return e.calculate(t),e},"getThemeVariables")});var tD,Rj,Nj=P(()=>{"use strict";Yn();vl();oc();tD=class{static{o(this,"Theme")}constructor(){this.background="#ffffff",this.primaryColor="#cccccc",this.mainBkg="#ffffff",this.noteBkgColor="#fff5ad",this.noteTextColor="#28253D",this.THEME_COLOR_LIMIT=12,this.radius=12,this.strokeWidth=2,this.primaryBorderColor=Jt(this.primaryColor,this.darkMode),this.fontFamily='"Recursive Variable", arial, sans-serif',this.fontSize="14px",this.nodeBorder="#28253D",this.stateBorder="#28253D",this.useGradient=!1,this.gradientStart="#0042eb",this.gradientStop="#eb0042",this.dropShadow="url(#drop-shadow)",this.nodeShadow=!0,this.tertiaryColor="#ffffff",this.archEdgeColor="calculated",this.archEdgeArrowColor="calculated",this.archEdgeWidth="3",this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth="2px",this.actorBorder="#28253D",this.noteBorderColor="#FACC15",this.noteFontWeight=600,this.borderColorArray=["#E879F9","#2DD4BF","#FB923C","#22D3EE","#4ADE80","#A78BFA","#F87171","#FACC15","#818CF8","#A3E635 ","#38BDF8","#FB7185"],this.bkgColorArray=["#FDF4FF","#F0FDFA","#FFF7ED","#ECFEFF","#F0FDF4","#F5F3FF","#FEF2F2","#FEFCE8","#EEF2FF","#F7FEE7","#F0F9FF","#FFF1F2"],this.filterColor="#000000"}updateColors(){this.primaryTextColor=this.primaryTextColor||(this.darkMode?"#eee":"#28253D"),this.secondaryColor=this.secondaryColor||ie(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||ie(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||Jt(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||Jt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||Jt(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||Jt(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||"#fff5ad",this.noteTextColor=this.noteTextColor||"#28253D",this.secondaryTextColor=this.secondaryTextColor||Ge(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||Ge(this.tertiaryColor),this.lineColor=this.lineColor||Ge(this.background),this.arrowheadColor=this.arrowheadColor||Ge(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.primaryBorderColor,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?Ye(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||Ye(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||Ge(this.lineColor);let e="#ECECFE",r="#E9E9F1",i=ie(e,{h:180,l:5});this.sectionBkgColor=this.sectionBkgColor||i,this.altSectionBkgColor=this.altSectionBkgColor||"white",this.sectionBkgColor=this.sectionBkgColor||r,this.sectionBkgColor2=this.sectionBkgColor2||e,this.excludeBkgColor=this.excludeBkgColor||"#eeeeee",this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||e,this.activeTaskBorderColor=this.activeTaskBorderColor||e,this.activeTaskBkgColor=this.activeTaskBkgColor||Ke(e,23),this.gridColor=this.gridColor||"lightgrey",this.doneTaskBkgColor=this.doneTaskBkgColor||"lightgrey",this.doneTaskBorderColor=this.doneTaskBorderColor||"grey",this.critBorderColor=this.critBorderColor||"#ff8888",this.critBkgColor=this.critBkgColor||"red",this.todayLineColor=this.todayLineColor||"red",this.taskTextColor=this.taskTextColor||this.textColor,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||"#003163",this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||"#f0f0f0",this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||"#f4a8ff",this.cScale1=this.cScale1||"#46ecd5",this.cScale2=this.cScale2||"#ffb86a",this.cScale3=this.cScale3||"#dab2ff",this.cScale4=this.cScale4||"#7bf1a8",this.cScale5=this.cScale5||"#c4b4ff",this.cScale6=this.cScale6||"#ffa2a2",this.cScale7=this.cScale7||"#ffdf20",this.cScale8=this.cScale8||"#a3b3ff",this.cScale9=this.cScale9||"#bbf451",this.cScale10=this.cScale10||"#74d4ff",this.cScale11=this.cScale11||"#ffa1ad";for(let a=0;a{this[i]=e[i]}),this.updateColors(),r.forEach(i=>{this[i]=e[i]})}},Rj=o(t=>{let e=new tD;return e.calculate(t),e},"getThemeVariables")});var rD,Ij,Mj=P(()=>{"use strict";Yn();vl();oc();rD=class{static{o(this,"Theme")}constructor(){this.background="#333",this.primaryColor="#1f2020",this.secondaryColor=Ke(this.primaryColor,16),this.tertiaryColor=ie(this.primaryColor,{h:-160}),this.primaryBorderColor=Ge(this.background),this.secondaryBorderColor=Jt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=Jt(this.tertiaryColor,this.darkMode),this.primaryTextColor=Ge(this.primaryColor),this.secondaryTextColor=Ge(this.secondaryColor),this.tertiaryTextColor=Ge(this.tertiaryColor),this.mainBkg="#111113",this.secondBkg="calculated",this.mainContrastColor="lightgrey",this.darkTextColor=Ke(Ge("#323D47"),10),this.border1="#ccc",this.border2=Fn(255,255,255,.25),this.arrowheadColor=Ge(this.background),this.fontFamily='"Recursive Variable", arial, sans-serif',this.fontSize="14px",this.labelBackground="#111113",this.textColor="#ccc",this.THEME_COLOR_LIMIT=12,this.radius=12,this.strokeWidth=2,this.noteBkgColor=this.noteBkgColor??"#FEF9C3",this.noteTextColor=this.noteTextColor??"#28253D",this.THEME_COLOR_LIMIT=12,this.fontFamily='"Recursive Variable", arial, sans-serif',this.fontSize="14px",this.nodeBorder="#FFFFFF",this.stateBorder="#FFFFFF",this.useGradient=!1,this.gradientStart="#0042eb",this.gradientStop="#eb0042",this.dropShadow="url(#drop-shadow)",this.nodeShadow=!0,this.archEdgeColor="calculated",this.archEdgeArrowColor="calculated",this.archEdgeWidth="3",this.archGroupBorderColor=this.primaryBorderColor,this.archGroupBorderWidth="2px",this.clusterBkg="#1E1A2E",this.clusterBorder="#BDBCCC",this.noteBorderColor="#FACC15",this.noteFontWeight=600,this.borderColorArray=["#E879F9","#2DD4BF","#FB923C","#22D3EE","#4ADE80","#A78BFA","#F87171","#FACC15","#818CF8","#A3E635 ","#38BDF8","#FB7185"],this.bkgColorArray=[],this.filterColor="#FFFFFF"}updateColors(){this.primaryTextColor=this.primaryTextColor||(this.darkMode?"#eee":"#FFFFFF"),this.secondaryColor=this.secondaryColor||ie(this.primaryColor,{h:-120}),this.tertiaryColor=this.tertiaryColor||ie(this.primaryColor,{h:180,l:5}),this.primaryBorderColor=this.primaryBorderColor||Jt(this.primaryColor,this.darkMode),this.secondaryBorderColor=this.secondaryBorderColor||Jt(this.secondaryColor,this.darkMode),this.tertiaryBorderColor=this.tertiaryBorderColor||Jt(this.tertiaryColor,this.darkMode),this.noteBorderColor=this.noteBorderColor||Jt(this.noteBkgColor,this.darkMode),this.noteBkgColor=this.noteBkgColor||"#fff5ad",this.noteTextColor=this.noteTextColor||"#FFFFFF",this.secondaryTextColor=this.secondaryTextColor||Ge(this.secondaryColor),this.tertiaryTextColor=this.tertiaryTextColor||Ge(this.tertiaryColor),this.lineColor=this.lineColor||Ge(this.background),this.arrowheadColor=this.arrowheadColor||Ge(this.background),this.textColor=this.textColor||this.primaryTextColor,this.border2=this.border2||this.tertiaryBorderColor,this.nodeBkg=this.nodeBkg||this.primaryColor,this.mainBkg=this.mainBkg||this.primaryColor,this.nodeBorder=this.nodeBorder||this.border1,this.clusterBkg=this.clusterBkg||this.tertiaryColor,this.clusterBorder=this.clusterBorder||this.tertiaryBorderColor,this.defaultLinkColor=this.defaultLinkColor||this.lineColor,this.titleColor=this.titleColor||this.tertiaryTextColor,this.edgeLabelBackground=this.edgeLabelBackground||(this.darkMode?Ye(this.secondaryColor,30):this.secondaryColor),this.nodeTextColor=this.nodeTextColor||this.primaryTextColor,this.actorBorder="#FFFFFF",this.signalColor="#FFFFFF",this.labelBoxBorderColor="#BDBCCC",this.actorBorder=this.actorBorder||this.primaryBorderColor,this.actorBkg=this.actorBkg||this.mainBkg,this.actorTextColor=this.actorTextColor||this.primaryTextColor,this.actorLineColor=this.actorLineColor||this.actorBorder,this.labelBoxBkgColor=this.labelBoxBkgColor||this.actorBkg,this.signalColor=this.signalColor||this.textColor,this.signalTextColor=this.signalTextColor||this.textColor,this.labelBoxBorderColor=this.labelBoxBorderColor||this.actorBorder,this.labelTextColor=this.labelTextColor||this.actorTextColor,this.loopTextColor=this.loopTextColor||this.actorTextColor,this.activationBorderColor=this.activationBorderColor||Ye(this.secondaryColor,10),this.activationBkgColor=this.activationBkgColor||this.secondaryColor,this.sequenceNumberColor=this.sequenceNumberColor||Ge(this.lineColor),this.rootLabelColor="#FFFFFF",this.sectionBkgColor=this.sectionBkgColor||this.tertiaryColor,this.altSectionBkgColor=this.altSectionBkgColor||"white",this.sectionBkgColor=this.sectionBkgColor||this.secondaryColor,this.sectionBkgColor2=this.sectionBkgColor2||this.primaryColor,this.excludeBkgColor=this.excludeBkgColor||"#eeeeee",this.taskBorderColor=this.taskBorderColor||this.primaryBorderColor,this.taskBkgColor=this.taskBkgColor||this.primaryColor,this.activeTaskBorderColor=this.activeTaskBorderColor||this.primaryColor,this.activeTaskBkgColor=this.activeTaskBkgColor||Ke(this.primaryColor,23),this.gridColor=this.gridColor||"lightgrey",this.doneTaskBkgColor=this.doneTaskBkgColor||"lightgrey",this.doneTaskBorderColor=this.doneTaskBorderColor||"grey",this.critBorderColor=this.critBorderColor||"#ff8888",this.critBkgColor=this.critBkgColor||"red",this.todayLineColor=this.todayLineColor||"red",this.taskTextColor=this.taskTextColor||this.textColor,this.vertLineColor=this.vertLineColor||this.primaryBorderColor,this.taskTextOutsideColor=this.taskTextOutsideColor||this.textColor,this.taskTextLightColor=this.taskTextLightColor||this.textColor,this.taskTextColor=this.taskTextColor||this.primaryTextColor,this.taskTextDarkColor=this.taskTextDarkColor||this.textColor,this.taskTextClickableColor=this.taskTextClickableColor||"#003163",this.archEdgeColor=this.lineColor,this.archEdgeArrowColor=this.lineColor,this.personBorder=this.personBorder||this.primaryBorderColor,this.personBkg=this.personBkg||this.mainBkg,this.transitionColor=this.transitionColor||this.lineColor,this.transitionLabelColor=this.transitionLabelColor||this.textColor,this.stateLabelColor=this.stateLabelColor||this.stateBkg||this.primaryTextColor,this.stateBkg=this.stateBkg||this.mainBkg,this.labelBackgroundColor=this.labelBackgroundColor||this.stateBkg,this.compositeBackground=this.compositeBackground||this.background||this.tertiaryColor,this.altBackground=this.altBackground||"#f0f0f0",this.compositeTitleBackground=this.compositeTitleBackground||this.mainBkg,this.compositeBorder=this.compositeBorder||this.nodeBorder,this.innerEndBackground=this.nodeBorder,this.errorBkgColor=this.errorBkgColor||this.tertiaryColor,this.errorTextColor=this.errorTextColor||this.tertiaryTextColor,this.transitionColor=this.transitionColor||this.lineColor,this.specialStateColor=this.lineColor,this.cScale0=this.cScale0||"#f4a8ff",this.cScale1=this.cScale1||"#46ecd5",this.cScale2=this.cScale2||"#ffb86a",this.cScale3=this.cScale3||"#dab2ff",this.cScale4=this.cScale4||"#7bf1a8",this.cScale5=this.cScale5||"#c4b4ff",this.cScale6=this.cScale6||"#ffa2a2",this.cScale7=this.cScale7||"#ffdf20",this.cScale8=this.cScale8||"#a3b3ff",this.cScale9=this.cScale9||"#bbf451",this.cScale10=this.cScale10||"#74d4ff",this.cScale11=this.cScale11||"#ffa1ad";for(let r=0;r{this[i]=e[i]}),this.updateColors(),r.forEach(i=>{this[i]=e[i]})}},Ij=o(t=>{let e=new rD;return e.calculate(t),e},"getThemeVariables")});var xl,g4=P(()=>{"use strict";gj();vj();wg();bj();kj();wj();Sj();_j();Lj();Nj();Mj();xl={base:{getThemeVariables:mj},dark:{getThemeVariables:yj},default:{getThemeVariables:Zc},forest:{getThemeVariables:xj},neutral:{getThemeVariables:Tj},neo:{getThemeVariables:Cj},"neo-dark":{getThemeVariables:Ej},redux:{getThemeVariables:Aj},"redux-dark":{getThemeVariables:Dj},"redux-color":{getThemeVariables:Rj},"redux-dark-color":{getThemeVariables:Ij}}});var so,Oj=P(()=>{"use strict";so={flowchart:{useMaxWidth:!0,titleTopMargin:25,subGraphTitleMargin:{top:0,bottom:0},diagramPadding:8,htmlLabels:null,nodeSpacing:50,rankSpacing:50,curve:"basis",padding:15,defaultRenderer:"dagre-wrapper",wrappingWidth:200,inheritDir:!1},sequence:{useMaxWidth:!0,hideUnusedParticipants:!1,activationWidth:10,diagramMarginX:50,diagramMarginY:10,actorMargin:50,width:150,height:65,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center",mirrorActors:!0,forceMenus:!1,bottomMarginAdj:1,rightAngles:!1,showSequenceNumbers:!1,actorFontSize:14,actorFontFamily:'"Open Sans", sans-serif',actorFontWeight:400,noteFontSize:14,noteFontFamily:'"trebuchet ms", verdana, arial, sans-serif',noteFontWeight:400,noteAlign:"center",messageFontSize:16,messageFontFamily:'"trebuchet ms", verdana, arial, sans-serif',messageFontWeight:400,wrap:!1,wrapPadding:10,labelBoxWidth:50,labelBoxHeight:20},gantt:{useMaxWidth:!0,titleTopMargin:25,barHeight:20,barGap:4,topPadding:50,rightPadding:75,leftPadding:75,gridLineStartPadding:35,fontSize:11,sectionFontSize:11,numberSectionStyles:4,axisFormat:"%Y-%m-%d",topAxis:!1,displayMode:"",weekday:"sunday"},journey:{useMaxWidth:!0,diagramMarginX:50,diagramMarginY:10,leftMargin:150,maxLabelWidth:360,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center",bottomMarginAdj:1,rightAngles:!1,taskFontSize:14,taskFontFamily:'"Open Sans", sans-serif',taskMargin:50,activationWidth:10,textPlacement:"fo",actorColours:["#8FBC8F","#7CFC00","#00FFFF","#20B2AA","#B0E0E6","#FFFFE0"],sectionFills:["#191970","#8B008B","#4B0082","#2F4F4F","#800000","#8B4513","#00008B"],sectionColours:["#fff"],titleColor:"",titleFontFamily:'"trebuchet ms", verdana, arial, sans-serif',titleFontSize:"4ex"},class:{useMaxWidth:!0,titleTopMargin:25,arrowMarkerAbsolute:!1,dividerMargin:10,padding:5,textHeight:10,defaultRenderer:"dagre-wrapper",htmlLabels:!1,hideEmptyMembersBox:!1},state:{useMaxWidth:!0,titleTopMargin:25,dividerMargin:10,sizeUnit:5,padding:8,textHeight:10,titleShift:-15,noteMargin:10,forkWidth:70,forkHeight:7,miniPadding:2,fontSizeFactor:5.02,fontSize:24,labelHeight:16,edgeLengthFactor:"20",compositTitleSize:35,radius:5,defaultRenderer:"dagre-wrapper"},er:{useMaxWidth:!0,titleTopMargin:25,diagramPadding:20,layoutDirection:"TB",minEntityWidth:100,minEntityHeight:75,entityPadding:15,nodeSpacing:140,rankSpacing:80,stroke:"gray",fill:"honeydew",fontSize:12},pie:{useMaxWidth:!0,textPosition:.75},quadrantChart:{useMaxWidth:!0,chartWidth:500,chartHeight:500,titleFontSize:20,titlePadding:10,quadrantPadding:5,xAxisLabelPadding:5,yAxisLabelPadding:5,xAxisLabelFontSize:16,yAxisLabelFontSize:16,quadrantLabelFontSize:16,quadrantTextTopPadding:5,pointTextPadding:5,pointLabelFontSize:12,pointRadius:5,xAxisPosition:"top",yAxisPosition:"left",quadrantInternalBorderStrokeWidth:1,quadrantExternalBorderStrokeWidth:2},xyChart:{useMaxWidth:!0,width:700,height:500,titleFontSize:20,titlePadding:10,showDataLabel:!1,showDataLabelOutsideBar:!1,showTitle:!0,xAxis:{$ref:"#/$defs/XYChartAxisConfig",showLabel:!0,labelFontSize:14,labelPadding:5,showTitle:!0,titleFontSize:16,titlePadding:5,showTick:!0,tickLength:5,tickWidth:2,showAxisLine:!0,axisLineWidth:2},yAxis:{$ref:"#/$defs/XYChartAxisConfig",showLabel:!0,labelFontSize:14,labelPadding:5,showTitle:!0,titleFontSize:16,titlePadding:5,showTick:!0,tickLength:5,tickWidth:2,showAxisLine:!0,axisLineWidth:2},chartOrientation:"vertical",plotReservedSpacePercent:50},requirement:{useMaxWidth:!0,rect_fill:"#f9f9f9",text_color:"#333",rect_border_size:"0.5px",rect_border_color:"#bbb",rect_min_width:200,rect_min_height:200,fontSize:14,rect_padding:10,line_height:20},mindmap:{useMaxWidth:!0,padding:10,maxNodeWidth:200,layoutAlgorithm:"cose-bilkent"},ishikawa:{useMaxWidth:!0,diagramPadding:20},kanban:{useMaxWidth:!0,padding:8,sectionWidth:200,ticketBaseUrl:""},timeline:{useMaxWidth:!0,diagramMarginX:50,diagramMarginY:10,leftMargin:150,width:150,height:50,boxMargin:10,boxTextMargin:5,noteMargin:10,messageMargin:35,messageAlign:"center",bottomMarginAdj:1,rightAngles:!1,taskFontSize:14,taskFontFamily:'"Open Sans", sans-serif',taskMargin:50,activationWidth:10,textPlacement:"fo",actorColours:["#8FBC8F","#7CFC00","#00FFFF","#20B2AA","#B0E0E6","#FFFFE0"],sectionFills:["#191970","#8B008B","#4B0082","#2F4F4F","#800000","#8B4513","#00008B"],sectionColours:["#fff"],disableMulticolor:!1},gitGraph:{useMaxWidth:!0,titleTopMargin:25,diagramPadding:8,nodeLabel:{width:75,height:100,x:-25,y:0},mainBranchName:"main",mainBranchOrder:0,showCommitLabel:!0,showBranches:!0,rotateCommitLabel:!0,parallelCommits:!1,arrowMarkerAbsolute:!1},c4:{useMaxWidth:!0,diagramMarginX:50,diagramMarginY:10,c4ShapeMargin:50,c4ShapePadding:20,width:216,height:60,boxMargin:10,c4ShapeInRow:4,nextLinePaddingX:0,c4BoundaryInRow:2,personFontSize:14,personFontFamily:'"Open Sans", sans-serif',personFontWeight:"normal",external_personFontSize:14,external_personFontFamily:'"Open Sans", sans-serif',external_personFontWeight:"normal",systemFontSize:14,systemFontFamily:'"Open Sans", sans-serif',systemFontWeight:"normal",external_systemFontSize:14,external_systemFontFamily:'"Open Sans", sans-serif',external_systemFontWeight:"normal",system_dbFontSize:14,system_dbFontFamily:'"Open Sans", sans-serif',system_dbFontWeight:"normal",external_system_dbFontSize:14,external_system_dbFontFamily:'"Open Sans", sans-serif',external_system_dbFontWeight:"normal",system_queueFontSize:14,system_queueFontFamily:'"Open Sans", sans-serif',system_queueFontWeight:"normal",external_system_queueFontSize:14,external_system_queueFontFamily:'"Open Sans", sans-serif',external_system_queueFontWeight:"normal",boundaryFontSize:14,boundaryFontFamily:'"Open Sans", sans-serif',boundaryFontWeight:"normal",messageFontSize:12,messageFontFamily:'"Open Sans", sans-serif',messageFontWeight:"normal",containerFontSize:14,containerFontFamily:'"Open Sans", sans-serif',containerFontWeight:"normal",external_containerFontSize:14,external_containerFontFamily:'"Open Sans", sans-serif',external_containerFontWeight:"normal",container_dbFontSize:14,container_dbFontFamily:'"Open Sans", sans-serif',container_dbFontWeight:"normal",external_container_dbFontSize:14,external_container_dbFontFamily:'"Open Sans", sans-serif',external_container_dbFontWeight:"normal",container_queueFontSize:14,container_queueFontFamily:'"Open Sans", sans-serif',container_queueFontWeight:"normal",external_container_queueFontSize:14,external_container_queueFontFamily:'"Open Sans", sans-serif',external_container_queueFontWeight:"normal",componentFontSize:14,componentFontFamily:'"Open Sans", sans-serif',componentFontWeight:"normal",external_componentFontSize:14,external_componentFontFamily:'"Open Sans", sans-serif',external_componentFontWeight:"normal",component_dbFontSize:14,component_dbFontFamily:'"Open Sans", sans-serif',component_dbFontWeight:"normal",external_component_dbFontSize:14,external_component_dbFontFamily:'"Open Sans", sans-serif',external_component_dbFontWeight:"normal",component_queueFontSize:14,component_queueFontFamily:'"Open Sans", sans-serif',component_queueFontWeight:"normal",external_component_queueFontSize:14,external_component_queueFontFamily:'"Open Sans", sans-serif',external_component_queueFontWeight:"normal",wrap:!0,wrapPadding:10,person_bg_color:"#08427B",person_border_color:"#073B6F",external_person_bg_color:"#686868",external_person_border_color:"#8A8A8A",system_bg_color:"#1168BD",system_border_color:"#3C7FC0",system_db_bg_color:"#1168BD",system_db_border_color:"#3C7FC0",system_queue_bg_color:"#1168BD",system_queue_border_color:"#3C7FC0",external_system_bg_color:"#999999",external_system_border_color:"#8A8A8A",external_system_db_bg_color:"#999999",external_system_db_border_color:"#8A8A8A",external_system_queue_bg_color:"#999999",external_system_queue_border_color:"#8A8A8A",container_bg_color:"#438DD5",container_border_color:"#3C7FC0",container_db_bg_color:"#438DD5",container_db_border_color:"#3C7FC0",container_queue_bg_color:"#438DD5",container_queue_border_color:"#3C7FC0",external_container_bg_color:"#B3B3B3",external_container_border_color:"#A6A6A6",external_container_db_bg_color:"#B3B3B3",external_container_db_border_color:"#A6A6A6",external_container_queue_bg_color:"#B3B3B3",external_container_queue_border_color:"#A6A6A6",component_bg_color:"#85BBF0",component_border_color:"#78A8D8",component_db_bg_color:"#85BBF0",component_db_border_color:"#78A8D8",component_queue_bg_color:"#85BBF0",component_queue_border_color:"#78A8D8",external_component_bg_color:"#CCCCCC",external_component_border_color:"#BFBFBF",external_component_db_bg_color:"#CCCCCC",external_component_db_border_color:"#BFBFBF",external_component_queue_bg_color:"#CCCCCC",external_component_queue_border_color:"#BFBFBF"},sankey:{useMaxWidth:!0,width:600,height:400,linkColor:"gradient",nodeAlignment:"justify",showValues:!0,prefix:"",suffix:""},block:{useMaxWidth:!0,padding:8},packet:{useMaxWidth:!0,rowHeight:32,bitWidth:32,bitsPerRow:32,showBits:!0,paddingX:5,paddingY:5},treeView:{useMaxWidth:!0,rowIndent:10,paddingX:5,paddingY:5,lineThickness:1},architecture:{useMaxWidth:!0,padding:40,iconSize:80,fontSize:16,randomize:!1},radar:{useMaxWidth:!0,width:600,height:600,marginTop:50,marginRight:50,marginBottom:50,marginLeft:50,axisScaleFactor:1,axisLabelFactor:1.05,curveTension:.17},venn:{useMaxWidth:!0,width:800,height:450,padding:8,useDebugLayout:!1},theme:"default",look:"classic",handDrawnSeed:0,layout:"dagre",maxTextSize:5e4,maxEdges:500,darkMode:!1,fontFamily:'"trebuchet ms", verdana, arial, sans-serif;',logLevel:5,securityLevel:"strict",startOnLoad:!0,arrowMarkerAbsolute:!1,secure:["secure","securityLevel","startOnLoad","maxTextSize","suppressErrorRendering","maxEdges"],legacyMathML:!1,forceLegacyMathML:!1,deterministicIds:!1,fontSize:16,markdownAutoWrap:!0,suppressErrorRendering:!1}});var Pj,Bj,Fj,fr,wa=P(()=>{"use strict";g4();Oj();Pj={...so,deterministicIDSeed:void 0,elk:{mergeEdges:!1,nodePlacementStrategy:"BRANDES_KOEPF",forceNodeModelOrder:!1,considerModelOrder:"NODES_AND_EDGES"},themeCSS:void 0,themeVariables:xl.default.getThemeVariables(),sequence:{...so.sequence,messageFont:o(function(){return{fontFamily:this.messageFontFamily,fontSize:this.messageFontSize,fontWeight:this.messageFontWeight}},"messageFont"),noteFont:o(function(){return{fontFamily:this.noteFontFamily,fontSize:this.noteFontSize,fontWeight:this.noteFontWeight}},"noteFont"),actorFont:o(function(){return{fontFamily:this.actorFontFamily,fontSize:this.actorFontSize,fontWeight:this.actorFontWeight}},"actorFont")},class:{hideEmptyMembersBox:!1},gantt:{...so.gantt,tickInterval:void 0,useWidth:void 0},c4:{...so.c4,useWidth:void 0,personFont:o(function(){return{fontFamily:this.personFontFamily,fontSize:this.personFontSize,fontWeight:this.personFontWeight}},"personFont"),flowchart:{...so.flowchart,inheritDir:!1},external_personFont:o(function(){return{fontFamily:this.external_personFontFamily,fontSize:this.external_personFontSize,fontWeight:this.external_personFontWeight}},"external_personFont"),systemFont:o(function(){return{fontFamily:this.systemFontFamily,fontSize:this.systemFontSize,fontWeight:this.systemFontWeight}},"systemFont"),external_systemFont:o(function(){return{fontFamily:this.external_systemFontFamily,fontSize:this.external_systemFontSize,fontWeight:this.external_systemFontWeight}},"external_systemFont"),system_dbFont:o(function(){return{fontFamily:this.system_dbFontFamily,fontSize:this.system_dbFontSize,fontWeight:this.system_dbFontWeight}},"system_dbFont"),external_system_dbFont:o(function(){return{fontFamily:this.external_system_dbFontFamily,fontSize:this.external_system_dbFontSize,fontWeight:this.external_system_dbFontWeight}},"external_system_dbFont"),system_queueFont:o(function(){return{fontFamily:this.system_queueFontFamily,fontSize:this.system_queueFontSize,fontWeight:this.system_queueFontWeight}},"system_queueFont"),external_system_queueFont:o(function(){return{fontFamily:this.external_system_queueFontFamily,fontSize:this.external_system_queueFontSize,fontWeight:this.external_system_queueFontWeight}},"external_system_queueFont"),containerFont:o(function(){return{fontFamily:this.containerFontFamily,fontSize:this.containerFontSize,fontWeight:this.containerFontWeight}},"containerFont"),external_containerFont:o(function(){return{fontFamily:this.external_containerFontFamily,fontSize:this.external_containerFontSize,fontWeight:this.external_containerFontWeight}},"external_containerFont"),container_dbFont:o(function(){return{fontFamily:this.container_dbFontFamily,fontSize:this.container_dbFontSize,fontWeight:this.container_dbFontWeight}},"container_dbFont"),external_container_dbFont:o(function(){return{fontFamily:this.external_container_dbFontFamily,fontSize:this.external_container_dbFontSize,fontWeight:this.external_container_dbFontWeight}},"external_container_dbFont"),container_queueFont:o(function(){return{fontFamily:this.container_queueFontFamily,fontSize:this.container_queueFontSize,fontWeight:this.container_queueFontWeight}},"container_queueFont"),external_container_queueFont:o(function(){return{fontFamily:this.external_container_queueFontFamily,fontSize:this.external_container_queueFontSize,fontWeight:this.external_container_queueFontWeight}},"external_container_queueFont"),componentFont:o(function(){return{fontFamily:this.componentFontFamily,fontSize:this.componentFontSize,fontWeight:this.componentFontWeight}},"componentFont"),external_componentFont:o(function(){return{fontFamily:this.external_componentFontFamily,fontSize:this.external_componentFontSize,fontWeight:this.external_componentFontWeight}},"external_componentFont"),component_dbFont:o(function(){return{fontFamily:this.component_dbFontFamily,fontSize:this.component_dbFontSize,fontWeight:this.component_dbFontWeight}},"component_dbFont"),external_component_dbFont:o(function(){return{fontFamily:this.external_component_dbFontFamily,fontSize:this.external_component_dbFontSize,fontWeight:this.external_component_dbFontWeight}},"external_component_dbFont"),component_queueFont:o(function(){return{fontFamily:this.component_queueFontFamily,fontSize:this.component_queueFontSize,fontWeight:this.component_queueFontWeight}},"component_queueFont"),external_component_queueFont:o(function(){return{fontFamily:this.external_component_queueFontFamily,fontSize:this.external_component_queueFontSize,fontWeight:this.external_component_queueFontWeight}},"external_component_queueFont"),boundaryFont:o(function(){return{fontFamily:this.boundaryFontFamily,fontSize:this.boundaryFontSize,fontWeight:this.boundaryFontWeight}},"boundaryFont"),messageFont:o(function(){return{fontFamily:this.messageFontFamily,fontSize:this.messageFontSize,fontWeight:this.messageFontWeight}},"messageFont")},pie:{...so.pie,useWidth:984},xyChart:{...so.xyChart,useWidth:void 0},requirement:{...so.requirement,useWidth:void 0},packet:{...so.packet},treeView:{...so.treeView,useWidth:void 0},radar:{...so.radar},ishikawa:{...so.ishikawa},treemap:{useMaxWidth:!0,padding:10,diagramPadding:8,showValues:!0,nodeWidth:100,nodeHeight:40,borderWidth:1,valueFontSize:12,labelFontSize:14,valueFormat:","},venn:{...so.venn}},Bj=o((t,e="")=>Object.keys(t).reduce((r,i)=>Array.isArray(t[i])?r:typeof t[i]=="object"&&t[i]!==null?[...r,e+i,...Bj(t[i],"")]:[...r,e+i],[]),"keyify"),Fj=new Set(Bj(Pj,"")),fr=Pj});var Eg,$8e,iD=P(()=>{"use strict";wa();bt();Eg=o(t=>{if(Q.debug("sanitizeDirective called with",t),!(typeof t!="object"||t==null)){if(Array.isArray(t)){t.forEach(e=>Eg(e));return}for(let e of Object.keys(t)){if(Q.debug("Checking key",e),e.startsWith("__")||e.includes("proto")||e.includes("constr")||!Fj.has(e)||t[e]==null){Q.debug("sanitize deleting key: ",e),delete t[e];continue}if(typeof t[e]=="object"){Q.debug("sanitizing object",e),Eg(t[e]);continue}let r=["themeCSS","fontFamily","altFontFamily"];for(let i of r)e.includes(i)&&(Q.debug("sanitizing css option",e),t[e]=$8e(t[e]))}if(t.themeVariables)for(let e of Object.keys(t.themeVariables)){let r=t.themeVariables[e];r?.match&&!r.match(/^[\d "#%(),.;A-Za-z]+$/)&&(t.themeVariables[e]="")}Q.debug("After sanitization",t)}},"sanitizeDirective"),$8e=o(t=>{let e=0,r=0;for(let i of t){if(e{"use strict";kg();bt();g4();wa();iD();Nf=Object.freeze(fr),ls=o(t=>!(t===!1||["false","null","0"].includes(String(t).trim().toLowerCase())),"evaluate"),oo=Yi({},Nf),Gp=[],Ix=Yi({},Nf),v4=o((t,e)=>{let r=Yi({},t),i={};for(let n of e)Vj(n),i=Yi(i,n);if(r=Yi(r,i),i.theme&&i.theme in xl){let n=Yi({},y4),a=Yi(n.themeVariables||{},i.themeVariables);r.theme&&r.theme in xl&&(r.themeVariables=xl[r.theme].getThemeVariables(a))}return Ix=r,Uj(Ix),Ix},"updateCurrentConfig"),nD=o(t=>(oo=Yi({},Nf),oo=Yi(oo,t),t.theme&&xl[t.theme]&&(oo.themeVariables=xl[t.theme].getThemeVariables(t.themeVariables)),v4(oo,Gp),oo),"setSiteConfig"),zj=o(t=>{y4=Yi({},t)},"saveConfigFromInitialize"),Gj=o(t=>(oo=Yi(oo,t),v4(oo,Gp),oo),"updateSiteConfig"),aD=o(()=>Yi({},oo),"getSiteConfig"),x4=o(t=>(Uj(t),Yi(Ix,t),Lt()),"setConfig"),Lt=o(()=>Yi({},Ix),"getConfig"),Vj=o(t=>{t&&(["secure",...oo.secure??[]].forEach(e=>{Object.hasOwn(t,e)&&(Q.debug(`Denied attempt to modify a secure key ${e}`,t[e]),delete t[e])}),Object.keys(t).forEach(e=>{e.startsWith("__")&&delete t[e]}),Object.keys(t).forEach(e=>{typeof t[e]=="string"&&(t[e].includes("<")||t[e].includes(">")||t[e].includes("url(data:"))&&delete t[e],typeof t[e]=="object"&&Vj(t[e])}))},"sanitize"),qj=o(t=>{Eg(t),t.fontFamily&&!t.themeVariables?.fontFamily&&(t.themeVariables={...t.themeVariables,fontFamily:t.fontFamily}),Gp.push(t),v4(oo,Gp)},"addDirective"),Mx=o((t=oo)=>{Gp=[],v4(t,Gp)},"reset"),z8e={LAZY_LOAD_DEPRECATED:"The configuration options lazyLoadedDiagrams and loadExternalDiagramsAtStartup are deprecated. Please use registerExternalDiagrams instead.",FLOWCHART_HTML_LABELS_DEPRECATED:"flowchart.htmlLabels is deprecated. Please use global htmlLabels instead."},$j={},Wj=o(t=>{$j[t]||(Q.warn(z8e[t]),$j[t]=!0)},"issueWarning"),Uj=o(t=>{t&&(t.lazyLoadedDiagrams||t.loadExternalDiagramsAtStartup)&&Wj("LAZY_LOAD_DEPRECATED")},"checkConfig"),Hj=o(()=>{let t={};y4&&(t=Yi(t,y4));for(let e of Gp)t=Yi(t,e);return t},"getUserDefinedConfig"),Or=o(t=>(t.flowchart?.htmlLabels!=null&&Wj("FLOWCHART_HTML_LABELS_DEPRECATED"),ls(t.htmlLabels??t.flowchart?.htmlLabels??!0)),"getEffectiveHtmlLabels")});function Is(t){return function(e){e instanceof RegExp&&(e.lastIndex=0);for(var r=arguments.length,i=new Array(r>1?r-1:0),n=1;n2&&arguments[2]!==void 0?arguments[2]:k4;Yj&&Yj(t,null);let i=e.length;for(;i--;){let n=e[i];if(typeof n=="string"){let a=r(n);a!==n&&(G8e(e)||(e[i]=a),n=a)}t[n]=!0}return t}function X8e(t){for(let e=0;e0&&arguments[0]!==void 0?arguments[0]:sDe(),e=o(xt=>nX(xt),"DOMPurify");if(e.version="3.3.1",e.removed=[],!t||!t.document||t.document.nodeType!==$x.document||!t.Element)return e.isSupported=!1,e;let{document:r}=t,i=r,n=i.currentScript,{DocumentFragment:a,HTMLTemplateElement:s,Node:l,Element:u,NodeFilter:h,NamedNodeMap:f=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:d,DOMParser:p,trustedTypes:m}=t,g=u.prototype,y=Fx(g,"cloneNode"),v=Fx(g,"remove"),x=Fx(g,"nextSibling"),b=Fx(g,"childNodes"),T=Fx(g,"parentNode");if(typeof s=="function"){let xt=r.createElement("template");xt.content&&xt.content.ownerDocument&&(r=xt.content.ownerDocument)}let w,k="",{implementation:C,createNodeIterator:E,createDocumentFragment:S,getElementsByTagName:L}=r,{importNode:M}=i,I=eX();e.isSupported=typeof tX=="function"&&typeof T=="function"&&C&&C.createHTMLDocument!==void 0;let{MUSTACHE_EXPR:A,ERB_EXPR:_,TMPLIT_EXPR:D,DATA_ATTR:N,ARIA_ATTR:R,IS_SCRIPT_OR_DATA:B,ATTR_WHITESPACE:O,CUSTOM_ELEMENT:$}=Jj,{IS_ALLOWED_URI:z}=Jj,F=null,V=Qr({},[...Xj,...lD,...cD,...uD,...Kj]),H=null,X=Qr({},[...Qj,...hD,...Zj,...T4]),W=Object.seal(fD(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Z=null,Y=null,ae=Object.seal(fD(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),J=!0,ee=!0,re=!1,te=!0,be=!1,de=!0,Ee=!1,Ne=!1,we=!1,Te=!1,De=!1,$e=!1,pe=!0,Je=!1,Ce="user-content-",Fe=!0,Ue=!1,qe={},Me=null,He=Qr({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),K=null,oe=Qr({},["audio","video","img","source","image","track"]),U=null,ue=Qr({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),G="http://www.w3.org/1998/Math/MathML",se="http://www.w3.org/2000/svg",le="http://www.w3.org/1999/xhtml",ke=le,me=!1,ye=null,Re=Qr({},[G,se,le],sD),ve=Qr({},["mi","mo","mn","ms","mtext"]),Oe=Qr({},["annotation-xml"]),We=Qr({},["title","style","font","a","script"]),Be=null,Qe=["application/xhtml+xml","text/html"],ce="text/html",it=null,fe=null,ut=r.createElement("form"),Nt=o(function(Ie){return Ie instanceof RegExp||Ie instanceof Function},"isRegexOrFunction"),Pt=o(function(){let Ie=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(fe&&fe===Ie)){if((!Ie||typeof Ie!="object")&&(Ie={}),Ie=Jc(Ie),Be=Qe.indexOf(Ie.PARSER_MEDIA_TYPE)===-1?ce:Ie.PARSER_MEDIA_TYPE,it=Be==="application/xhtml+xml"?sD:k4,F=lc(Ie,"ALLOWED_TAGS")?Qr({},Ie.ALLOWED_TAGS,it):V,H=lc(Ie,"ALLOWED_ATTR")?Qr({},Ie.ALLOWED_ATTR,it):X,ye=lc(Ie,"ALLOWED_NAMESPACES")?Qr({},Ie.ALLOWED_NAMESPACES,sD):Re,U=lc(Ie,"ADD_URI_SAFE_ATTR")?Qr(Jc(ue),Ie.ADD_URI_SAFE_ATTR,it):ue,K=lc(Ie,"ADD_DATA_URI_TAGS")?Qr(Jc(oe),Ie.ADD_DATA_URI_TAGS,it):oe,Me=lc(Ie,"FORBID_CONTENTS")?Qr({},Ie.FORBID_CONTENTS,it):He,Z=lc(Ie,"FORBID_TAGS")?Qr({},Ie.FORBID_TAGS,it):Jc({}),Y=lc(Ie,"FORBID_ATTR")?Qr({},Ie.FORBID_ATTR,it):Jc({}),qe=lc(Ie,"USE_PROFILES")?Ie.USE_PROFILES:!1,J=Ie.ALLOW_ARIA_ATTR!==!1,ee=Ie.ALLOW_DATA_ATTR!==!1,re=Ie.ALLOW_UNKNOWN_PROTOCOLS||!1,te=Ie.ALLOW_SELF_CLOSE_IN_ATTR!==!1,be=Ie.SAFE_FOR_TEMPLATES||!1,de=Ie.SAFE_FOR_XML!==!1,Ee=Ie.WHOLE_DOCUMENT||!1,Te=Ie.RETURN_DOM||!1,De=Ie.RETURN_DOM_FRAGMENT||!1,$e=Ie.RETURN_TRUSTED_TYPE||!1,we=Ie.FORCE_BODY||!1,pe=Ie.SANITIZE_DOM!==!1,Je=Ie.SANITIZE_NAMED_PROPS||!1,Fe=Ie.KEEP_CONTENT!==!1,Ue=Ie.IN_PLACE||!1,z=Ie.ALLOWED_URI_REGEXP||rX,ke=Ie.NAMESPACE||le,ve=Ie.MATHML_TEXT_INTEGRATION_POINTS||ve,Oe=Ie.HTML_INTEGRATION_POINTS||Oe,W=Ie.CUSTOM_ELEMENT_HANDLING||{},Ie.CUSTOM_ELEMENT_HANDLING&&Nt(Ie.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(W.tagNameCheck=Ie.CUSTOM_ELEMENT_HANDLING.tagNameCheck),Ie.CUSTOM_ELEMENT_HANDLING&&Nt(Ie.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(W.attributeNameCheck=Ie.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),Ie.CUSTOM_ELEMENT_HANDLING&&typeof Ie.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(W.allowCustomizedBuiltInElements=Ie.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),be&&(ee=!1),De&&(Te=!0),qe&&(F=Qr({},Kj),H=[],qe.html===!0&&(Qr(F,Xj),Qr(H,Qj)),qe.svg===!0&&(Qr(F,lD),Qr(H,hD),Qr(H,T4)),qe.svgFilters===!0&&(Qr(F,cD),Qr(H,hD),Qr(H,T4)),qe.mathMl===!0&&(Qr(F,uD),Qr(H,Zj),Qr(H,T4))),Ie.ADD_TAGS&&(typeof Ie.ADD_TAGS=="function"?ae.tagCheck=Ie.ADD_TAGS:(F===V&&(F=Jc(F)),Qr(F,Ie.ADD_TAGS,it))),Ie.ADD_ATTR&&(typeof Ie.ADD_ATTR=="function"?ae.attributeCheck=Ie.ADD_ATTR:(H===X&&(H=Jc(H)),Qr(H,Ie.ADD_ATTR,it))),Ie.ADD_URI_SAFE_ATTR&&Qr(U,Ie.ADD_URI_SAFE_ATTR,it),Ie.FORBID_CONTENTS&&(Me===He&&(Me=Jc(Me)),Qr(Me,Ie.FORBID_CONTENTS,it)),Ie.ADD_FORBID_CONTENTS&&(Me===He&&(Me=Jc(Me)),Qr(Me,Ie.ADD_FORBID_CONTENTS,it)),Fe&&(F["#text"]=!0),Ee&&Qr(F,["html","head","body"]),F.table&&(Qr(F,["tbody"]),delete Z.tbody),Ie.TRUSTED_TYPES_POLICY){if(typeof Ie.TRUSTED_TYPES_POLICY.createHTML!="function")throw Bx('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof Ie.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Bx('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');w=Ie.TRUSTED_TYPES_POLICY,k=w.createHTML("")}else w===void 0&&(w=oDe(m,n)),w!==null&&typeof k=="string"&&(k=w.createHTML(""));Ns&&Ns(Ie),fe=Ie}},"_parseConfig"),St=Qr({},[...lD,...cD,...K8e]),It=Qr({},[...uD,...Q8e]),ot=o(function(Ie){let ft=T(Ie);(!ft||!ft.tagName)&&(ft={namespaceURI:ke,tagName:"template"});let _t=k4(Ie.tagName),zr=k4(ft.tagName);return ye[Ie.namespaceURI]?Ie.namespaceURI===se?ft.namespaceURI===le?_t==="svg":ft.namespaceURI===G?_t==="svg"&&(zr==="annotation-xml"||ve[zr]):!!St[_t]:Ie.namespaceURI===G?ft.namespaceURI===le?_t==="math":ft.namespaceURI===se?_t==="math"&&Oe[zr]:!!It[_t]:Ie.namespaceURI===le?ft.namespaceURI===se&&!Oe[zr]||ft.namespaceURI===G&&!ve[zr]?!1:!It[_t]&&(We[_t]||!St[_t]):!!(Be==="application/xhtml+xml"&&ye[Ie.namespaceURI]):!1},"_checkValidNamespace"),ct=o(function(Ie){Ox(e.removed,{element:Ie});try{T(Ie).removeChild(Ie)}catch{v(Ie)}},"_forceRemove"),Dt=o(function(Ie,ft){try{Ox(e.removed,{attribute:ft.getAttributeNode(Ie),from:ft})}catch{Ox(e.removed,{attribute:null,from:ft})}if(ft.removeAttribute(Ie),Ie==="is")if(Te||De)try{ct(ft)}catch{}else try{ft.setAttribute(Ie,"")}catch{}},"_removeAttribute"),kt=o(function(Ie){let ft=null,_t=null;if(we)Ie=""+Ie;else{let ci=oD(Ie,/^[\r\n\t ]+/);_t=ci&&ci[0]}Be==="application/xhtml+xml"&&ke===le&&(Ie=''+Ie+"");let zr=w?w.createHTML(Ie):Ie;if(ke===le)try{ft=new p().parseFromString(zr,Be)}catch{}if(!ft||!ft.documentElement){ft=C.createDocument(ke,"template",null);try{ft.documentElement.innerHTML=me?k:zr}catch{}}let ri=ft.body||ft.documentElement;return Ie&&_t&&ri.insertBefore(r.createTextNode(_t),ri.childNodes[0]||null),ke===le?L.call(ft,Ee?"html":"body")[0]:Ee?ft.documentElement:ri},"_initDocument"),yt=o(function(Ie){return E.call(Ie.ownerDocument||Ie,Ie,h.SHOW_ELEMENT|h.SHOW_COMMENT|h.SHOW_TEXT|h.SHOW_PROCESSING_INSTRUCTION|h.SHOW_CDATA_SECTION,null)},"_createNodeIterator"),jt=o(function(Ie){return Ie instanceof d&&(typeof Ie.nodeName!="string"||typeof Ie.textContent!="string"||typeof Ie.removeChild!="function"||!(Ie.attributes instanceof f)||typeof Ie.removeAttribute!="function"||typeof Ie.setAttribute!="function"||typeof Ie.namespaceURI!="string"||typeof Ie.insertBefore!="function"||typeof Ie.hasChildNodes!="function")},"_isClobbered"),hr=o(function(Ie){return typeof l=="function"&&Ie instanceof l},"_isNode");function Qt(xt,Ie,ft){b4(xt,_t=>{_t.call(e,Ie,ft,fe)})}o(Qt,"_executeHooks");let Er=o(function(Ie){let ft=null;if(Qt(I.beforeSanitizeElements,Ie,null),jt(Ie))return ct(Ie),!0;let _t=it(Ie.nodeName);if(Qt(I.uponSanitizeElement,Ie,{tagName:_t,allowedTags:F}),de&&Ie.hasChildNodes()&&!hr(Ie.firstElementChild)&&Rs(/<[/\w!]/g,Ie.innerHTML)&&Rs(/<[/\w!]/g,Ie.textContent)||Ie.nodeType===$x.progressingInstruction||de&&Ie.nodeType===$x.comment&&Rs(/<[/\w]/g,Ie.data))return ct(Ie),!0;if(!(ae.tagCheck instanceof Function&&ae.tagCheck(_t))&&(!F[_t]||Z[_t])){if(!Z[_t]&&ir(_t)&&(W.tagNameCheck instanceof RegExp&&Rs(W.tagNameCheck,_t)||W.tagNameCheck instanceof Function&&W.tagNameCheck(_t)))return!1;if(Fe&&!Me[_t]){let zr=T(Ie)||Ie.parentNode,ri=b(Ie)||Ie.childNodes;if(ri&&zr){let ci=ri.length;for(let Ir=ci-1;Ir>=0;--Ir){let sa=y(ri[Ir],!0);sa.__removalCount=(Ie.__removalCount||0)+1,zr.insertBefore(sa,x(Ie))}}}return ct(Ie),!0}return Ie instanceof u&&!ot(Ie)||(_t==="noscript"||_t==="noembed"||_t==="noframes")&&Rs(/<\/no(script|embed|frames)/i,Ie.innerHTML)?(ct(Ie),!0):(be&&Ie.nodeType===$x.text&&(ft=Ie.textContent,b4([A,_,D],zr=>{ft=Px(ft,zr," ")}),Ie.textContent!==ft&&(Ox(e.removed,{element:Ie.cloneNode()}),Ie.textContent=ft)),Qt(I.afterSanitizeElements,Ie,null),!1)},"_sanitizeElements"),dr=o(function(Ie,ft,_t){if(pe&&(ft==="id"||ft==="name")&&(_t in r||_t in ut))return!1;if(!(ee&&!Y[ft]&&Rs(N,ft))){if(!(J&&Rs(R,ft))){if(!(ae.attributeCheck instanceof Function&&ae.attributeCheck(ft,Ie))){if(!H[ft]||Y[ft]){if(!(ir(Ie)&&(W.tagNameCheck instanceof RegExp&&Rs(W.tagNameCheck,Ie)||W.tagNameCheck instanceof Function&&W.tagNameCheck(Ie))&&(W.attributeNameCheck instanceof RegExp&&Rs(W.attributeNameCheck,ft)||W.attributeNameCheck instanceof Function&&W.attributeNameCheck(ft,Ie))||ft==="is"&&W.allowCustomizedBuiltInElements&&(W.tagNameCheck instanceof RegExp&&Rs(W.tagNameCheck,_t)||W.tagNameCheck instanceof Function&&W.tagNameCheck(_t))))return!1}else if(!U[ft]){if(!Rs(z,Px(_t,O,""))){if(!((ft==="src"||ft==="xlink:href"||ft==="href")&&Ie!=="script"&&H8e(_t,"data:")===0&&K[Ie])){if(!(re&&!Rs(B,Px(_t,O,"")))){if(_t)return!1}}}}}}}return!0},"_isValidAttribute"),ir=o(function(Ie){return Ie!=="annotation-xml"&&oD(Ie,$)},"_isBasicCustomElement"),pr=o(function(Ie){Qt(I.beforeSanitizeAttributes,Ie,null);let{attributes:ft}=Ie;if(!ft||jt(Ie))return;let _t={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:H,forceKeepAttr:void 0},zr=ft.length;for(;zr--;){let ri=ft[zr],{name:ci,namespaceURI:Ir,value:sa}=ri,qa=it(ci),Mi=sa,Ft=ci==="value"?Mi:Y8e(Mi);if(_t.attrName=qa,_t.attrValue=Ft,_t.keepAttr=!0,_t.forceKeepAttr=void 0,Qt(I.uponSanitizeAttribute,Ie,_t),Ft=_t.attrValue,Je&&(qa==="id"||qa==="name")&&(Dt(ci,Ie),Ft=Ce+Ft),de&&Rs(/((--!?|])>)|<\/(style|title|textarea)/i,Ft)){Dt(ci,Ie);continue}if(qa==="attributename"&&oD(Ft,"href")){Dt(ci,Ie);continue}if(_t.forceKeepAttr)continue;if(!_t.keepAttr){Dt(ci,Ie);continue}if(!te&&Rs(/\/>/i,Ft)){Dt(ci,Ie);continue}be&&b4([A,_,D],qt=>{Ft=Px(Ft,qt," ")});let Et=it(Ie.nodeName);if(!dr(Et,qa,Ft)){Dt(ci,Ie);continue}if(w&&typeof m=="object"&&typeof m.getAttributeType=="function"&&!Ir)switch(m.getAttributeType(Et,qa)){case"TrustedHTML":{Ft=w.createHTML(Ft);break}case"TrustedScriptURL":{Ft=w.createScriptURL(Ft);break}}if(Ft!==Mi)try{Ir?Ie.setAttributeNS(Ir,ci,Ft):Ie.setAttribute(ci,Ft),jt(Ie)?ct(Ie):jj(e.removed)}catch{Dt(ci,Ie)}}Qt(I.afterSanitizeAttributes,Ie,null)},"_sanitizeAttributes"),Ii=o(function xt(Ie){let ft=null,_t=yt(Ie);for(Qt(I.beforeSanitizeShadowDOM,Ie,null);ft=_t.nextNode();)Qt(I.uponSanitizeShadowNode,ft,null),Er(ft),pr(ft),ft.content instanceof a&&xt(ft.content);Qt(I.afterSanitizeShadowDOM,Ie,null)},"_sanitizeShadowDOM");return e.sanitize=function(xt){let Ie=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},ft=null,_t=null,zr=null,ri=null;if(me=!xt,me&&(xt=""),typeof xt!="string"&&!hr(xt))if(typeof xt.toString=="function"){if(xt=xt.toString(),typeof xt!="string")throw Bx("dirty is not a string, aborting")}else throw Bx("toString is not a function");if(!e.isSupported)return xt;if(Ne||Pt(Ie),e.removed=[],typeof xt=="string"&&(Ue=!1),Ue){if(xt.nodeName){let sa=it(xt.nodeName);if(!F[sa]||Z[sa])throw Bx("root node is forbidden and cannot be sanitized in-place")}}else if(xt instanceof l)ft=kt(""),_t=ft.ownerDocument.importNode(xt,!0),_t.nodeType===$x.element&&_t.nodeName==="BODY"||_t.nodeName==="HTML"?ft=_t:ft.appendChild(_t);else{if(!Te&&!be&&!Ee&&xt.indexOf("<")===-1)return w&&$e?w.createHTML(xt):xt;if(ft=kt(xt),!ft)return Te?null:$e?k:""}ft&&we&&ct(ft.firstChild);let ci=yt(Ue?xt:ft);for(;zr=ci.nextNode();)Er(zr),pr(zr),zr.content instanceof a&&Ii(zr.content);if(Ue)return xt;if(Te){if(De)for(ri=S.call(ft.ownerDocument);ft.firstChild;)ri.appendChild(ft.firstChild);else ri=ft;return(H.shadowroot||H.shadowrootmode)&&(ri=M.call(i,ri,!0)),ri}let Ir=Ee?ft.outerHTML:ft.innerHTML;return Ee&&F["!doctype"]&&ft.ownerDocument&&ft.ownerDocument.doctype&&ft.ownerDocument.doctype.name&&Rs(iX,ft.ownerDocument.doctype.name)&&(Ir=" +`+Ir),be&&b4([A,_,D],sa=>{Ir=Px(Ir,sa," ")}),w&&$e?w.createHTML(Ir):Ir},e.setConfig=function(){let xt=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Pt(xt),Ne=!0},e.clearConfig=function(){fe=null,Ne=!1},e.isValidAttribute=function(xt,Ie,ft){fe||Pt({});let _t=it(xt),zr=it(Ie);return dr(_t,zr,ft)},e.addHook=function(xt,Ie){typeof Ie=="function"&&Ox(I[xt],Ie)},e.removeHook=function(xt,Ie){if(Ie!==void 0){let ft=W8e(I[xt],Ie);return ft===-1?void 0:U8e(I[xt],ft,1)[0]}return jj(I[xt])},e.removeHooks=function(xt){I[xt]=[]},e.removeAllHooks=function(){I=eX()},e}var tX,Yj,G8e,V8e,q8e,Ns,bl,fD,dD,pD,b4,W8e,jj,Ox,U8e,k4,sD,oD,Px,H8e,Y8e,lc,Rs,Bx,Xj,lD,cD,K8e,uD,Q8e,Kj,Qj,hD,Zj,T4,Z8e,J8e,eDe,tDe,rDe,rX,iDe,nDe,iX,aDe,Jj,$x,sDe,oDe,eX,Tl,zx=P(()=>{"use strict";({entries:tX,setPrototypeOf:Yj,isFrozen:G8e,getPrototypeOf:V8e,getOwnPropertyDescriptor:q8e}=Object),{freeze:Ns,seal:bl,create:fD}=Object,{apply:dD,construct:pD}=typeof Reflect<"u"&&Reflect;Ns||(Ns=o(function(e){return e},"freeze"));bl||(bl=o(function(e){return e},"seal"));dD||(dD=o(function(e,r){for(var i=arguments.length,n=new Array(i>2?i-2:0),a=2;a1?r-1:0),n=1;n/gm),eDe=bl(/\$\{[\w\W]*/gm),tDe=bl(/^data-[\-\w.\u00B7-\uFFFF]+$/),rDe=bl(/^aria-[\-\w]+$/),rX=bl(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),iDe=bl(/^(?:\w+script|data):/i),nDe=bl(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),iX=bl(/^html$/i),aDe=bl(/^[a-z][.\w]*(-[.\w]+)+$/i),Jj=Object.freeze({__proto__:null,ARIA_ATTR:rDe,ATTR_WHITESPACE:nDe,CUSTOM_ELEMENT:aDe,DATA_ATTR:tDe,DOCTYPE_NAME:iX,ERB_EXPR:J8e,IS_ALLOWED_URI:rX,IS_SCRIPT_OR_DATA:iDe,MUSTACHE_EXPR:Z8e,TMPLIT_EXPR:eDe}),$x={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,progressingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},sDe=o(function(){return typeof window>"u"?null:window},"getGlobal"),oDe=o(function(e,r){if(typeof e!="object"||typeof e.createPolicy!="function")return null;let i=null,n="data-tt-policy-suffix";r&&r.hasAttribute(n)&&(i=r.getAttribute(n));let a="dompurify"+(i?"#"+i:"");try{return e.createPolicy(a,{createHTML(s){return s},createScriptURL(s){return s}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},"_createTrustedTypesPolicy"),eX=o(function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},"_createHooksMap");o(nX,"createDOMPurify");Tl=nX()});var PK={};ur(PK,{ParseError:()=>wt,SETTINGS_SCHEMA:()=>Wx,__defineFunction:()=>Bt,__defineMacro:()=>he,__defineSymbol:()=>q,__domTree:()=>OK,__parse:()=>RK,__renderToDomTree:()=>X4,__renderToHTMLTree:()=>IK,__setFontMetrics:()=>FX,default:()=>QLe,render:()=>iL,renderToString:()=>LK,version:()=>MK});function dDe(t){return String(t).replace(fDe,e=>hDe[e])}function yDe(t){if(t.default)return t.default;var e=t.type,r=Array.isArray(e)?e[0]:e;if(typeof r!="string")return r.enum[0];switch(r){case"boolean":return!1;case"string":return"";case"number":return 0;case"object":return{}}}function wDe(t){for(var e=0;e<_D.length;e++)for(var r=_D[e],i=0;i=n[0]&&t<=n[1])return r.name}return null}function BX(t){for(var e=0;e=M4[e]&&t<=M4[e+1])return!0;return!1}function FX(t,e){ru[t]=e}function GD(t,e,r){if(!ru[e])throw new Error("Font metrics not found for font: "+e+".");var i=t.charCodeAt(0),n=ru[e][i];if(!n&&t[0]in sX&&(i=sX[t[0]].charCodeAt(0),n=ru[e][i]),!n&&r==="text"&&BX(i)&&(n=ru[e][77]),n)return{depth:n[0],height:n[1],italic:n[2],skew:n[3],width:n[4]}}function ODe(t){var e;if(t>=5?e=0:t>=3?e=1:e=2,!mD[e]){var r=mD[e]={cssEmPerMu:C4.quad[e]/18};for(var i in C4)C4.hasOwnProperty(i)&&(r[i]=C4[i][e])}return mD[e]}function cX(t){if(t instanceof uo)return t;throw new Error("Expected symbolNode but got "+String(t)+".")}function zDe(t){if(t instanceof Wp)return t;throw new Error("Expected span but got "+String(t)+".")}function q(t,e,r,i,n,a){ji[t][n]={font:e,group:r,replace:i},a&&i&&(ji[t][i]=ji[t][n])}function Bt(t){for(var{type:e,names:r,props:i,handler:n,htmlBuilder:a,mathmlBuilder:s}=t,l={type:e,numArgs:i.numArgs,argTypes:i.argTypes,allowedInArgument:!!i.allowedInArgument,allowedInText:!!i.allowedInText,allowedInMath:i.allowedInMath===void 0?!0:i.allowedInMath,numOptionalArgs:i.numOptionalArgs||0,infix:!!i.infix,primitive:!!i.primitive,handler:n},u=0;u0&&(a.push(L4(s,e)),s=[]),a.push(i[l]));s.length>0&&a.push(L4(s,e));var h;r?(h=L4(ca(r,e,!0)),h.classes=["tag"],a.push(h)):n&&a.push(n);var f=Th(["katex-html"],a);if(f.setAttribute("aria-hidden","true"),h){var d=h.children[0];d.style.height=Rt(f.height+f.depth),f.depth&&(d.style.verticalAlign=Rt(-f.depth))}return f}function KX(t){return new qp(t)}function vD(t){if(!t)return!1;if(t.type==="mi"&&t.children.length===1){var e=t.children[0];return e instanceof Cl&&e.text==="."}else if(t.type==="mo"&&t.children.length===1&&t.getAttribute("separator")==="true"&&t.getAttribute("lspace")==="0em"&&t.getAttribute("rspace")==="0em"){var r=t.children[0];return r instanceof Cl&&r.text===","}else return!1}function pX(t,e,r,i,n){var a=ho(t,r),s;a.length===1&&a[0]instanceof Ms&&["mrow","mtable"].includes(a[0].type)?s=a[0]:s=new Ct.MathNode("mrow",a);var l=new Ct.MathNode("annotation",[new Ct.TextNode(e)]);l.setAttribute("encoding","application/x-tex");var u=new Ct.MathNode("semantics",[s,l]),h=new Ct.MathNode("math",[u]);h.setAttribute("xmlns","http://www.w3.org/1998/Math/MathML"),i&&h.setAttribute("display","block");var f=n?"katex":"katex-mathml";return je.makeSpan([f],[h])}function Gr(t,e){if(!t||t.type!==e)throw new Error("Expected node of type "+e+", but got "+(t?"node of type "+t.type:String(t)));return t}function UD(t){var e=U4(t);if(!e)throw new Error("Expected node of symbol group type, but got "+(t?"node of type "+t.type:String(t)));return e}function U4(t){return t&&(t.type==="atom"||VDe.hasOwnProperty(t.type))?t:null}function eK(t,e){var r=ca(t.body,e,!0);return vLe([t.mclass],r,e)}function tK(t,e){var r,i=ho(t.body,e);return t.mclass==="minner"?r=new Ct.MathNode("mpadded",i):t.mclass==="mord"?t.isCharacterBox?(r=i[0],r.type="mi"):r=new Ct.MathNode("mi",i):(t.isCharacterBox?(r=i[0],r.type="mo"):r=new Ct.MathNode("mo",i),t.mclass==="mbin"?(r.attributes.lspace="0.22em",r.attributes.rspace="0.22em"):t.mclass==="mpunct"?(r.attributes.lspace="0em",r.attributes.rspace="0.17em"):t.mclass==="mopen"||t.mclass==="mclose"?(r.attributes.lspace="0em",r.attributes.rspace="0em"):t.mclass==="minner"&&(r.attributes.lspace="0.0556em",r.attributes.width="+0.1111em")),r}function TLe(t,e,r){var i=xLe[t];switch(i){case"\\\\cdrightarrow":case"\\\\cdleftarrow":return r.callFunction(i,[e[0]],[e[1]]);case"\\uparrow":case"\\downarrow":{var n=r.callFunction("\\\\cdleft",[e[0]],[]),a={type:"atom",text:i,mode:"math",family:"rel"},s=r.callFunction("\\Big",[a],[]),l=r.callFunction("\\\\cdright",[e[1]],[]),u={type:"ordgroup",mode:"math",body:[n,s,l]};return r.callFunction("\\\\cdparent",[u],[])}case"\\\\cdlongequal":return r.callFunction("\\\\cdlongequal",[],[]);case"\\Vert":{var h={type:"textord",text:"\\Vert",mode:"math"};return r.callFunction("\\Big",[h],[])}default:return{type:"textord",text:" ",mode:"math"}}}function kLe(t){var e=[];for(t.gullet.beginGroup(),t.gullet.macros.set("\\cr","\\\\\\relax"),t.gullet.beginGroup();;){e.push(t.parseExpression(!1,"\\\\")),t.gullet.endGroup(),t.gullet.beginGroup();var r=t.fetch().text;if(r==="&"||r==="\\\\")t.consume();else if(r==="\\end"){e[e.length-1].length===0&&e.pop();break}else throw new wt("Expected \\\\ or \\cr or \\end",t.nextToken)}for(var i=[],n=[i],a=0;a-1))if("<>AV".indexOf(h)>-1)for(var d=0;d<2;d++){for(var p=!0,m=u+1;mAV=|." after @',s[u]);var g=TLe(h,f,t),y={type:"styling",body:[g],mode:"math",style:"display"};i.push(y),l=mX()}a%2===0?i.push(l):i.shift(),i=[],n.push(i)}t.gullet.endGroup(),t.gullet.endGroup();var v=new Array(n[0].length).fill({type:"align",align:"c",pregap:.25,postgap:.25});return{type:"array",mode:"math",body:n,arraystretch:1,addJot:!0,rowGaps:[null],cols:v,colSeparationType:"CD",hLinesBeforeRow:new Array(n.length+1).fill([])}}function Y4(t,e){var r=U4(t);if(r&&OLe.includes(r.text))return r;throw r?new wt("Invalid delimiter '"+r.text+"' after '"+e.funcName+"'",t):new wt("Invalid delimiter type '"+t.type+"'",t)}function vX(t){if(!t.body)throw new Error("Bug: The leftright ParseNode wasn't fully parsed.")}function nu(t){for(var{type:e,names:r,props:i,handler:n,htmlBuilder:a,mathmlBuilder:s}=t,l={type:e,numArgs:i.numArgs||0,allowedInText:!1,numOptionalArgs:0,handler:n},u=0;u1||!f)&&y.pop(),x.length{"use strict";co=class t{static{o(this,"SourceLocation")}constructor(e,r,i){this.lexer=void 0,this.start=void 0,this.end=void 0,this.lexer=e,this.start=r,this.end=i}static range(e,r){return r?!e||!e.loc||!r.loc||e.loc.lexer!==r.loc.lexer?null:new t(e.loc.lexer,e.loc.start,r.loc.end):e&&e.loc}},Ho=class t{static{o(this,"Token")}constructor(e,r){this.text=void 0,this.loc=void 0,this.noexpand=void 0,this.treatAsRelax=void 0,this.text=e,this.loc=r}range(e,r){return new t(r,co.range(this,e))}},wt=class t{static{o(this,"ParseError")}constructor(e,r){this.name=void 0,this.position=void 0,this.length=void 0,this.rawMessage=void 0;var i="KaTeX parse error: "+e,n,a,s=r&&r.loc;if(s&&s.start<=s.end){var l=s.lexer.input;n=s.start,a=s.end,n===l.length?i+=" at end of input: ":i+=" at position "+(n+1)+": ";var u=l.slice(n,a).replace(/[^]/g,"$&\u0332"),h;n>15?h="\u2026"+l.slice(n-15,n):h=l.slice(0,n);var f;a+15":">","<":"<",'"':""","'":"'"},fDe=/[&><"']/g;o(dDe,"escape");PX=o(function t(e){return e.type==="ordgroup"||e.type==="color"?e.body.length===1?t(e.body[0]):e:e.type==="font"?t(e.body):e},"getBaseElem"),pDe=o(function(e){var r=PX(e);return r.type==="mathord"||r.type==="textord"||r.type==="atom"},"isCharacterBox"),mDe=o(function(e){if(!e)throw new Error("Expected non-null, but got "+String(e));return e},"assert"),gDe=o(function(e){var r=/^[\x00-\x20]*([^\\/#?]*?)(:|�*58|�*3a|&colon)/i.exec(e);return r?r[2]!==":"||!/^[a-zA-Z][a-zA-Z0-9+\-.]*$/.test(r[1])?null:r[1].toLowerCase():"_relative"},"protocolFromUrl"),ui={deflt:lDe,escape:dDe,hyphenate:uDe,getBaseElem:PX,isCharacterBox:pDe,protocolFromUrl:gDe},Wx={displayMode:{type:"boolean",description:"Render math in display mode, which puts the math in display style (so \\int and \\sum are large, for example), and centers the math on the page on its own line.",cli:"-d, --display-mode"},output:{type:{enum:["htmlAndMathml","html","mathml"]},description:"Determines the markup language of the output.",cli:"-F, --format "},leqno:{type:"boolean",description:"Render display math in leqno style (left-justified tags)."},fleqn:{type:"boolean",description:"Render display math flush left."},throwOnError:{type:"boolean",default:!0,cli:"-t, --no-throw-on-error",cliDescription:"Render errors (in the color given by --error-color) instead of throwing a ParseError exception when encountering an error."},errorColor:{type:"string",default:"#cc0000",cli:"-c, --error-color ",cliDescription:"A color string given in the format 'rgb' or 'rrggbb' (no #). This option determines the color of errors rendered by the -t option.",cliProcessor:o(t=>"#"+t,"cliProcessor")},macros:{type:"object",cli:"-m, --macro ",cliDescription:"Define custom macro of the form '\\foo:expansion' (use multiple -m arguments for multiple macros).",cliDefault:[],cliProcessor:o((t,e)=>(e.push(t),e),"cliProcessor")},minRuleThickness:{type:"number",description:"Specifies a minimum thickness, in ems, for fraction lines, `\\sqrt` top lines, `{array}` vertical lines, `\\hline`, `\\hdashline`, `\\underline`, `\\overline`, and the borders of `\\fbox`, `\\boxed`, and `\\fcolorbox`.",processor:o(t=>Math.max(0,t),"processor"),cli:"--min-rule-thickness ",cliProcessor:parseFloat},colorIsTextColor:{type:"boolean",description:"Makes \\color behave like LaTeX's 2-argument \\textcolor, instead of LaTeX's one-argument \\color mode change.",cli:"-b, --color-is-text-color"},strict:{type:[{enum:["warn","ignore","error"]},"boolean","function"],description:"Turn on strict / LaTeX faithfulness mode, which throws an error if the input uses features that are not supported by LaTeX.",cli:"-S, --strict",cliDefault:!1},trust:{type:["boolean","function"],description:"Trust the input, enabling all HTML features such as \\url.",cli:"-T, --trust"},maxSize:{type:"number",default:1/0,description:"If non-zero, all user-specified sizes, e.g. in \\rule{500em}{500em}, will be capped to maxSize ems. Otherwise, elements and spaces can be arbitrarily large",processor:o(t=>Math.max(0,t),"processor"),cli:"-s, --max-size ",cliProcessor:parseInt},maxExpand:{type:"number",default:1e3,description:"Limit the number of macro expansions to the specified number, to prevent e.g. infinite macro loops. If set to Infinity, the macro expander will try to fully expand as in LaTeX.",processor:o(t=>Math.max(0,t),"processor"),cli:"-e, --max-expand ",cliProcessor:o(t=>t==="Infinity"?1/0:parseInt(t),"cliProcessor")},globalGroup:{type:"boolean",cli:!1}};o(yDe,"getDefaultValue");Hx=class{static{o(this,"Settings")}constructor(e){this.displayMode=void 0,this.output=void 0,this.leqno=void 0,this.fleqn=void 0,this.throwOnError=void 0,this.errorColor=void 0,this.macros=void 0,this.minRuleThickness=void 0,this.colorIsTextColor=void 0,this.strict=void 0,this.trust=void 0,this.maxSize=void 0,this.maxExpand=void 0,this.globalGroup=void 0,e=e||{};for(var r in Wx)if(Wx.hasOwnProperty(r)){var i=Wx[r];this[r]=e[r]!==void 0?i.processor?i.processor(e[r]):e[r]:yDe(i)}}reportNonstrict(e,r,i){var n=this.strict;if(typeof n=="function"&&(n=n(e,r,i)),!(!n||n==="ignore")){if(n===!0||n==="error")throw new wt("LaTeX-incompatible input and strict mode is set to 'error': "+(r+" ["+e+"]"),i);n==="warn"?typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+(r+" ["+e+"]")):typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to "+("unrecognized '"+n+"': "+r+" ["+e+"]"))}}useStrictBehavior(e,r,i){var n=this.strict;if(typeof n=="function")try{n=n(e,r,i)}catch{n="error"}return!n||n==="ignore"?!1:n===!0||n==="error"?!0:n==="warn"?(typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to 'warn': "+(r+" ["+e+"]")),!1):(typeof console<"u"&&console.warn("LaTeX-incompatible input and strict mode is set to "+("unrecognized '"+n+"': "+r+" ["+e+"]")),!1)}isTrusted(e){if(e.url&&!e.protocol){var r=ui.protocolFromUrl(e.url);if(r==null)return!1;e.protocol=r}var i=typeof this.trust=="function"?this.trust(e):this.trust;return!!i}},eu=class{static{o(this,"Style")}constructor(e,r,i){this.id=void 0,this.size=void 0,this.cramped=void 0,this.id=e,this.size=r,this.cramped=i}sup(){return tu[vDe[this.id]]}sub(){return tu[xDe[this.id]]}fracNum(){return tu[bDe[this.id]]}fracDen(){return tu[TDe[this.id]]}cramp(){return tu[kDe[this.id]]}text(){return tu[CDe[this.id]]}isTight(){return this.size>=2}},zD=0,O4=1,Ag=2,xh=3,Yx=4,kl=5,_g=6,Os=7,tu=[new eu(zD,0,!1),new eu(O4,0,!0),new eu(Ag,1,!1),new eu(xh,1,!0),new eu(Yx,2,!1),new eu(kl,2,!0),new eu(_g,3,!1),new eu(Os,3,!0)],vDe=[Yx,kl,Yx,kl,_g,Os,_g,Os],xDe=[kl,kl,kl,kl,Os,Os,Os,Os],bDe=[Ag,xh,Yx,kl,_g,Os,_g,Os],TDe=[xh,xh,kl,kl,Os,Os,Os,Os],kDe=[O4,O4,xh,xh,kl,kl,Os,Os],CDe=[zD,O4,Ag,xh,Ag,xh,Ag,xh],gr={DISPLAY:tu[zD],TEXT:tu[Ag],SCRIPT:tu[Yx],SCRIPTSCRIPT:tu[_g]},_D=[{name:"latin",blocks:[[256,591],[768,879]]},{name:"cyrillic",blocks:[[1024,1279]]},{name:"armenian",blocks:[[1328,1423]]},{name:"brahmic",blocks:[[2304,4255]]},{name:"georgian",blocks:[[4256,4351]]},{name:"cjk",blocks:[[12288,12543],[19968,40879],[65280,65376]]},{name:"hangul",blocks:[[44032,55215]]}];o(wDe,"scriptFromCodepoint");M4=[];_D.forEach(t=>t.blocks.forEach(e=>M4.push(...e)));o(BX,"supportedCodepoint");Sg=80,EDe=o(function(e,r){return"M95,"+(622+e+r)+` +c-2.7,0,-7.17,-2.7,-13.5,-8c-5.8,-5.3,-9.5,-10,-9.5,-14 +c0,-2,0.3,-3.3,1,-4c1.3,-2.7,23.83,-20.7,67.5,-54 +c44.2,-33.3,65.8,-50.3,66.5,-51c1.3,-1.3,3,-2,5,-2c4.7,0,8.7,3.3,12,10 +s173,378,173,378c0.7,0,35.3,-71,104,-213c68.7,-142,137.5,-285,206.5,-429 +c69,-144,104.5,-217.7,106.5,-221 +l`+e/2.075+" -"+e+` +c5.3,-9.3,12,-14,20,-14 +H400000v`+(40+e)+`H845.2724 +s-225.272,467,-225.272,467s-235,486,-235,486c-2.7,4.7,-9,7,-19,7 +c-6,0,-10,-1,-12,-3s-194,-422,-194,-422s-65,47,-65,47z +M`+(834+e)+" "+r+"h400000v"+(40+e)+"h-400000z"},"sqrtMain"),SDe=o(function(e,r){return"M263,"+(601+e+r)+`c0.7,0,18,39.7,52,119 +c34,79.3,68.167,158.7,102.5,238c34.3,79.3,51.8,119.3,52.5,120 +c340,-704.7,510.7,-1060.3,512,-1067 +l`+e/2.084+" -"+e+` +c4.7,-7.3,11,-11,19,-11 +H40000v`+(40+e)+`H1012.3 +s-271.3,567,-271.3,567c-38.7,80.7,-84,175,-136,283c-52,108,-89.167,185.3,-111.5,232 +c-22.3,46.7,-33.8,70.3,-34.5,71c-4.7,4.7,-12.3,7,-23,7s-12,-1,-12,-1 +s-109,-253,-109,-253c-72.7,-168,-109.3,-252,-110,-252c-10.7,8,-22,16.7,-34,26 +c-22,17.3,-33.3,26,-34,26s-26,-26,-26,-26s76,-59,76,-59s76,-60,76,-60z +M`+(1001+e)+" "+r+"h400000v"+(40+e)+"h-400000z"},"sqrtSize1"),ADe=o(function(e,r){return"M983 "+(10+e+r)+` +l`+e/3.13+" -"+e+` +c4,-6.7,10,-10,18,-10 H400000v`+(40+e)+` +H1013.1s-83.4,268,-264.1,840c-180.7,572,-277,876.3,-289,913c-4.7,4.7,-12.7,7,-24,7 +s-12,0,-12,0c-1.3,-3.3,-3.7,-11.7,-7,-25c-35.3,-125.3,-106.7,-373.3,-214,-744 +c-10,12,-21,25,-33,39s-32,39,-32,39c-6,-5.3,-15,-14,-27,-26s25,-30,25,-30 +c26.7,-32.7,52,-63,76,-91s52,-60,52,-60s208,722,208,722 +c56,-175.3,126.3,-397.3,211,-666c84.7,-268.7,153.8,-488.2,207.5,-658.5 +c53.7,-170.3,84.5,-266.8,92.5,-289.5z +M`+(1001+e)+" "+r+"h400000v"+(40+e)+"h-400000z"},"sqrtSize2"),_De=o(function(e,r){return"M424,"+(2398+e+r)+` +c-1.3,-0.7,-38.5,-172,-111.5,-514c-73,-342,-109.8,-513.3,-110.5,-514 +c0,-2,-10.7,14.3,-32,49c-4.7,7.3,-9.8,15.7,-15.5,25c-5.7,9.3,-9.8,16,-12.5,20 +s-5,7,-5,7c-4,-3.3,-8.3,-7.7,-13,-13s-13,-13,-13,-13s76,-122,76,-122s77,-121,77,-121 +s209,968,209,968c0,-2,84.7,-361.7,254,-1079c169.3,-717.3,254.7,-1077.7,256,-1081 +l`+e/4.223+" -"+e+`c4,-6.7,10,-10,18,-10 H400000 +v`+(40+e)+`H1014.6 +s-87.3,378.7,-272.6,1166c-185.3,787.3,-279.3,1182.3,-282,1185 +c-2,6,-10,9,-24,9 +c-8,0,-12,-0.7,-12,-2z M`+(1001+e)+" "+r+` +h400000v`+(40+e)+"h-400000z"},"sqrtSize3"),DDe=o(function(e,r){return"M473,"+(2713+e+r)+` +c339.3,-1799.3,509.3,-2700,510,-2702 l`+e/5.298+" -"+e+` +c3.3,-7.3,9.3,-11,18,-11 H400000v`+(40+e)+`H1017.7 +s-90.5,478,-276.2,1466c-185.7,988,-279.5,1483,-281.5,1485c-2,6,-10,9,-24,9 +c-8,0,-12,-0.7,-12,-2c0,-1.3,-5.3,-32,-16,-92c-50.7,-293.3,-119.7,-693.3,-207,-1200 +c0,-1.3,-5.3,8.7,-16,30c-10.7,21.3,-21.3,42.7,-32,64s-16,33,-16,33s-26,-26,-26,-26 +s76,-153,76,-153s77,-151,77,-151c0.7,0.7,35.7,202,105,604c67.3,400.7,102,602.7,104, +606zM`+(1001+e)+" "+r+"h400000v"+(40+e)+"H1017.7z"},"sqrtSize4"),LDe=o(function(e){var r=e/2;return"M400000 "+e+" H0 L"+r+" 0 l65 45 L145 "+(e-80)+" H400000z"},"phasePath"),RDe=o(function(e,r,i){var n=i-54-r-e;return"M702 "+(e+r)+"H400000"+(40+e)+` +H742v`+n+`l-4 4-4 4c-.667.7 -2 1.5-4 2.5s-4.167 1.833-6.5 2.5-5.5 1-9.5 1 +h-12l-28-84c-16.667-52-96.667 -294.333-240-727l-212 -643 -85 170 +c-4-3.333-8.333-7.667-13 -13l-13-13l77-155 77-156c66 199.333 139 419.667 +219 661 l218 661zM702 `+r+"H400000v"+(40+e)+"H742z"},"sqrtTall"),NDe=o(function(e,r,i){r=1e3*r;var n="";switch(e){case"sqrtMain":n=EDe(r,Sg);break;case"sqrtSize1":n=SDe(r,Sg);break;case"sqrtSize2":n=ADe(r,Sg);break;case"sqrtSize3":n=_De(r,Sg);break;case"sqrtSize4":n=DDe(r,Sg);break;case"sqrtTall":n=RDe(r,Sg,i)}return n},"sqrtPath"),IDe=o(function(e,r){switch(e){case"\u239C":return"M291 0 H417 V"+r+" H291z M291 0 H417 V"+r+" H291z";case"\u2223":return"M145 0 H188 V"+r+" H145z M145 0 H188 V"+r+" H145z";case"\u2225":return"M145 0 H188 V"+r+" H145z M145 0 H188 V"+r+" H145z"+("M367 0 H410 V"+r+" H367z M367 0 H410 V"+r+" H367z");case"\u239F":return"M457 0 H583 V"+r+" H457z M457 0 H583 V"+r+" H457z";case"\u23A2":return"M319 0 H403 V"+r+" H319z M319 0 H403 V"+r+" H319z";case"\u23A5":return"M263 0 H347 V"+r+" H263z M263 0 H347 V"+r+" H263z";case"\u23AA":return"M384 0 H504 V"+r+" H384z M384 0 H504 V"+r+" H384z";case"\u23D0":return"M312 0 H355 V"+r+" H312z M312 0 H355 V"+r+" H312z";case"\u2016":return"M257 0 H300 V"+r+" H257z M257 0 H300 V"+r+" H257z"+("M478 0 H521 V"+r+" H478z M478 0 H521 V"+r+" H478z");default:return""}},"innerPath"),aX={doubleleftarrow:`M262 157 +l10-10c34-36 62.7-77 86-123 3.3-8 5-13.3 5-16 0-5.3-6.7-8-20-8-7.3 + 0-12.2.5-14.5 1.5-2.3 1-4.8 4.5-7.5 10.5-49.3 97.3-121.7 169.3-217 216-28 + 14-57.3 25-88 33-6.7 2-11 3.8-13 5.5-2 1.7-3 4.2-3 7.5s1 5.8 3 7.5 +c2 1.7 6.3 3.5 13 5.5 68 17.3 128.2 47.8 180.5 91.5 52.3 43.7 93.8 96.2 124.5 + 157.5 9.3 8 15.3 12.3 18 13h6c12-.7 18-4 18-10 0-2-1.7-7-5-15-23.3-46-52-87 +-86-123l-10-10h399738v-40H218c328 0 0 0 0 0l-10-8c-26.7-20-65.7-43-117-69 2.7 +-2 6-3.7 10-5 36.7-16 72.3-37.3 107-64l10-8h399782v-40z +m8 0v40h399730v-40zm0 194v40h399730v-40z`,doublerightarrow:`M399738 392l +-10 10c-34 36-62.7 77-86 123-3.3 8-5 13.3-5 16 0 5.3 6.7 8 20 8 7.3 0 12.2-.5 + 14.5-1.5 2.3-1 4.8-4.5 7.5-10.5 49.3-97.3 121.7-169.3 217-216 28-14 57.3-25 88 +-33 6.7-2 11-3.8 13-5.5 2-1.7 3-4.2 3-7.5s-1-5.8-3-7.5c-2-1.7-6.3-3.5-13-5.5-68 +-17.3-128.2-47.8-180.5-91.5-52.3-43.7-93.8-96.2-124.5-157.5-9.3-8-15.3-12.3-18 +-13h-6c-12 .7-18 4-18 10 0 2 1.7 7 5 15 23.3 46 52 87 86 123l10 10H0v40h399782 +c-328 0 0 0 0 0l10 8c26.7 20 65.7 43 117 69-2.7 2-6 3.7-10 5-36.7 16-72.3 37.3 +-107 64l-10 8H0v40zM0 157v40h399730v-40zm0 194v40h399730v-40z`,leftarrow:`M400000 241H110l3-3c68.7-52.7 113.7-120 + 135-202 4-14.7 6-23 6-25 0-7.3-7-11-21-11-8 0-13.2.8-15.5 2.5-2.3 1.7-4.2 5.8 +-5.5 12.5-1.3 4.7-2.7 10.3-4 17-12 48.7-34.8 92-68.5 130S65.3 228.3 18 247 +c-10 4-16 7.7-18 11 0 8.7 6 14.3 18 17 47.3 18.7 87.8 47 121.5 85S196 441.3 208 + 490c.7 2 1.3 5 2 9s1.2 6.7 1.5 8c.3 1.3 1 3.3 2 6s2.2 4.5 3.5 5.5c1.3 1 3.3 + 1.8 6 2.5s6 1 10 1c14 0 21-3.7 21-11 0-2-2-10.3-6-25-20-79.3-65-146.7-135-202 + l-3-3h399890zM100 241v40h399900v-40z`,leftbrace:`M6 548l-6-6v-35l6-11c56-104 135.3-181.3 238-232 57.3-28.7 117 +-45 179-50h399577v120H403c-43.3 7-81 15-113 26-100.7 33-179.7 91-237 174-2.7 + 5-6 9-10 13-.7 1-7.3 1-20 1H6z`,leftbraceunder:`M0 6l6-6h17c12.688 0 19.313.3 20 1 4 4 7.313 8.3 10 13 + 35.313 51.3 80.813 93.8 136.5 127.5 55.688 33.7 117.188 55.8 184.5 66.5.688 + 0 2 .3 4 1 18.688 2.7 76 4.3 172 5h399450v120H429l-6-1c-124.688-8-235-61.7 +-331-161C60.687 138.7 32.312 99.3 7 54L0 41V6z`,leftgroup:`M400000 80 +H435C64 80 168.3 229.4 21 260c-5.9 1.2-18 0-18 0-2 0-3-1-3-3v-38C76 61 257 0 + 435 0h399565z`,leftgroupunder:`M400000 262 +H435C64 262 168.3 112.6 21 82c-5.9-1.2-18 0-18 0-2 0-3 1-3 3v38c76 158 257 219 + 435 219h399565z`,leftharpoon:`M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3 +-3.3 10.2-9.5 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5 +-18.3 3-21-1.3-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7 +-196 228-6.7 4.7-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40z`,leftharpoonplus:`M0 267c.7 5.3 3 10 7 14h399993v-40H93c3.3-3.3 10.2-9.5 + 20.5-18.5s17.8-15.8 22.5-20.5c50.7-52 88-110.3 112-175 4-11.3 5-18.3 3-21-1.3 +-4-7.3-6-18-6-8 0-13 .7-15 2s-4.7 6.7-8 16c-42 98.7-107.3 174.7-196 228-6.7 4.7 +-10.7 8-12 10-1.3 2-2 5.7-2 11zm100-26v40h399900v-40zM0 435v40h400000v-40z +m0 0v40h400000v-40z`,leftharpoondown:`M7 241c-4 4-6.333 8.667-7 14 0 5.333.667 9 2 11s5.333 + 5.333 12 10c90.667 54 156 130 196 228 3.333 10.667 6.333 16.333 9 17 2 .667 5 + 1 9 1h5c10.667 0 16.667-2 18-6 2-2.667 1-9.667-3-21-32-87.333-82.667-157.667 +-152-211l-3-3h399907v-40zM93 281 H400000 v-40L7 241z`,leftharpoondownplus:`M7 435c-4 4-6.3 8.7-7 14 0 5.3.7 9 2 11s5.3 5.3 12 + 10c90.7 54 156 130 196 228 3.3 10.7 6.3 16.3 9 17 2 .7 5 1 9 1h5c10.7 0 16.7 +-2 18-6 2-2.7 1-9.7-3-21-32-87.3-82.7-157.7-152-211l-3-3h399907v-40H7zm93 0 +v40h399900v-40zM0 241v40h399900v-40zm0 0v40h399900v-40z`,lefthook:`M400000 281 H103s-33-11.2-61-33.5S0 197.3 0 164s14.2-61.2 42.5 +-83.5C70.8 58.2 104 47 142 47 c16.7 0 25 6.7 25 20 0 12-8.7 18.7-26 20-40 3.3 +-68.7 15.7-86 37-10 12-15 25.3-15 40 0 22.7 9.8 40.7 29.5 54 19.7 13.3 43.5 21 + 71.5 23h399859zM103 281v-40h399897v40z`,leftlinesegment:`M40 281 V428 H0 V94 H40 V241 H400000 v40z +M40 281 V428 H0 V94 H40 V241 H400000 v40z`,leftmapsto:`M40 281 V448H0V74H40V241H400000v40z +M40 281 V448H0V74H40V241H400000v40z`,leftToFrom:`M0 147h400000v40H0zm0 214c68 40 115.7 95.7 143 167h22c15.3 0 23 +-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69-70-101l-7-8h399905v-40H95l7-8 +c28.7-32 52-65.7 70-101 10.7-23.3 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 265.3 + 68 321 0 361zm0-174v-40h399900v40zm100 154v40h399900v-40z`,longequal:`M0 50 h400000 v40H0z m0 194h40000v40H0z +M0 50 h400000 v40H0z m0 194h40000v40H0z`,midbrace:`M200428 334 +c-100.7-8.3-195.3-44-280-108-55.3-42-101.7-93-139-153l-9-14c-2.7 4-5.7 8.7-9 14 +-53.3 86.7-123.7 153-211 199-66.7 36-137.3 56.3-212 62H0V214h199568c178.3-11.7 + 311.7-78.3 403-201 6-8 9.7-12 11-12 .7-.7 6.7-1 18-1s17.3.3 18 1c1.3 0 5 4 11 + 12 44.7 59.3 101.3 106.3 170 141s145.3 54.3 229 60h199572v120z`,midbraceunder:`M199572 214 +c100.7 8.3 195.3 44 280 108 55.3 42 101.7 93 139 153l9 14c2.7-4 5.7-8.7 9-14 + 53.3-86.7 123.7-153 211-199 66.7-36 137.3-56.3 212-62h199568v120H200432c-178.3 + 11.7-311.7 78.3-403 201-6 8-9.7 12-11 12-.7.7-6.7 1-18 1s-17.3-.3-18-1c-1.3 0 +-5-4-11-12-44.7-59.3-101.3-106.3-170-141s-145.3-54.3-229-60H0V214z`,oiintSize1:`M512.6 71.6c272.6 0 320.3 106.8 320.3 178.2 0 70.8-47.7 177.6 +-320.3 177.6S193.1 320.6 193.1 249.8c0-71.4 46.9-178.2 319.5-178.2z +m368.1 178.2c0-86.4-60.9-215.4-368.1-215.4-306.4 0-367.3 129-367.3 215.4 0 85.8 +60.9 214.8 367.3 214.8 307.2 0 368.1-129 368.1-214.8z`,oiintSize2:`M757.8 100.1c384.7 0 451.1 137.6 451.1 230 0 91.3-66.4 228.8 +-451.1 228.8-386.3 0-452.7-137.5-452.7-228.8 0-92.4 66.4-230 452.7-230z +m502.4 230c0-111.2-82.4-277.2-502.4-277.2s-504 166-504 277.2 +c0 110 84 276 504 276s502.4-166 502.4-276z`,oiiintSize1:`M681.4 71.6c408.9 0 480.5 106.8 480.5 178.2 0 70.8-71.6 177.6 +-480.5 177.6S202.1 320.6 202.1 249.8c0-71.4 70.5-178.2 479.3-178.2z +m525.8 178.2c0-86.4-86.8-215.4-525.7-215.4-437.9 0-524.7 129-524.7 215.4 0 +85.8 86.8 214.8 524.7 214.8 438.9 0 525.7-129 525.7-214.8z`,oiiintSize2:`M1021.2 53c603.6 0 707.8 165.8 707.8 277.2 0 110-104.2 275.8 +-707.8 275.8-606 0-710.2-165.8-710.2-275.8C311 218.8 415.2 53 1021.2 53z +m770.4 277.1c0-131.2-126.4-327.6-770.5-327.6S248.4 198.9 248.4 330.1 +c0 130 128.8 326.4 772.7 326.4s770.5-196.4 770.5-326.4z`,rightarrow:`M0 241v40h399891c-47.3 35.3-84 78-110 128 +-16.7 32-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 + 11 8 0 13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 + 39-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85 +-40.5-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5 +-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67 + 151.7 139 205zm0 0v40h399900v-40z`,rightbrace:`M400000 542l +-6 6h-17c-12.7 0-19.3-.3-20-1-4-4-7.3-8.3-10-13-35.3-51.3-80.8-93.8-136.5-127.5 +s-117.2-55.8-184.5-66.5c-.7 0-2-.3-4-1-18.7-2.7-76-4.3-172-5H0V214h399571l6 1 +c124.7 8 235 61.7 331 161 31.3 33.3 59.7 72.7 85 118l7 13v35z`,rightbraceunder:`M399994 0l6 6v35l-6 11c-56 104-135.3 181.3-238 232-57.3 + 28.7-117 45-179 50H-300V214h399897c43.3-7 81-15 113-26 100.7-33 179.7-91 237 +-174 2.7-5 6-9 10-13 .7-1 7.3-1 20-1h17z`,rightgroup:`M0 80h399565c371 0 266.7 149.4 414 180 5.9 1.2 18 0 18 0 2 0 + 3-1 3-3v-38c-76-158-257-219-435-219H0z`,rightgroupunder:`M0 262h399565c371 0 266.7-149.4 414-180 5.9-1.2 18 0 18 + 0 2 0 3 1 3 3v38c-76 158-257 219-435 219H0z`,rightharpoon:`M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3 +-3.7-15.3-11-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2 +-10.7 0-16.7 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 + 69.2 92 94.5zm0 0v40h399900v-40z`,rightharpoonplus:`M0 241v40h399993c4.7-4.7 7-9.3 7-14 0-9.3-3.7-15.3-11 +-18-92.7-56.7-159-133.7-199-231-3.3-9.3-6-14.7-8-16-2-1.3-7-2-15-2-10.7 0-16.7 + 2-18 6-2 2.7-1 9.7 3 21 15.3 42 36.7 81.8 64 119.5 27.3 37.7 58 69.2 92 94.5z +m0 0v40h399900v-40z m100 194v40h399900v-40zm0 0v40h399900v-40z`,rightharpoondown:`M399747 511c0 7.3 6.7 11 20 11 8 0 13-.8 15-2.5s4.7-6.8 + 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 8.5-5.8 9.5 +-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3-64.7 57-92 95 +-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 241v40h399900v-40z`,rightharpoondownplus:`M399747 705c0 7.3 6.7 11 20 11 8 0 13-.8 + 15-2.5s4.7-6.8 8-15.5c40-94 99.3-166.3 178-217 13.3-8 20.3-12.3 21-13 5.3-3.3 + 8.5-5.8 9.5-7.5 1-1.7 1.5-5.2 1.5-10.5s-2.3-10.3-7-15H0v40h399908c-34 25.3 +-64.7 57-92 95-27.3 38-48.7 77.7-64 119-3.3 8.7-5 14-5 16zM0 435v40h399900v-40z +m0-194v40h400000v-40zm0 0v40h400000v-40z`,righthook:`M399859 241c-764 0 0 0 0 0 40-3.3 68.7-15.7 86-37 10-12 15-25.3 + 15-40 0-22.7-9.8-40.7-29.5-54-19.7-13.3-43.5-21-71.5-23-17.3-1.3-26-8-26-20 0 +-13.3 8.7-20 26-20 38 0 71 11.2 99 33.5 0 0 7 5.6 21 16.7 14 11.2 21 33.5 21 + 66.8s-14 61.2-42 83.5c-28 22.3-61 33.5-99 33.5L0 241z M0 281v-40h399859v40z`,rightlinesegment:`M399960 241 V94 h40 V428 h-40 V281 H0 v-40z +M399960 241 V94 h40 V428 h-40 V281 H0 v-40z`,rightToFrom:`M400000 167c-70.7-42-118-97.7-142-167h-23c-15.3 0-23 .3-23 + 1 0 1.3 5.3 13.7 16 37 18 35.3 41.3 69 70 101l7 8H0v40h399905l-7 8c-28.7 32 +-52 65.7-70 101-10.7 23.3-16 35.7-16 37 0 .7 7.7 1 23 1h23c24-69.3 71.3-125 142 +-167z M100 147v40h399900v-40zM0 341v40h399900v-40z`,twoheadleftarrow:`M0 167c68 40 + 115.7 95.7 143 167h22c15.3 0 23-.3 23-1 0-1.3-5.3-13.7-16-37-18-35.3-41.3-69 +-70-101l-7-8h125l9 7c50.7 39.3 85 86 103 140h46c0-4.7-6.3-18.7-19-42-18-35.3 +-40-67.3-66-96l-9-9h399716v-40H284l9-9c26-28.7 48-60.7 66-96 12.7-23.333 19 +-37.333 19-42h-46c-18 54-52.3 100.7-103 140l-9 7H95l7-8c28.7-32 52-65.7 70-101 + 10.7-23.333 16-35.7 16-37 0-.7-7.7-1-23-1h-22C115.7 71.3 68 127 0 167z`,twoheadrightarrow:`M400000 167 +c-68-40-115.7-95.7-143-167h-22c-15.3 0-23 .3-23 1 0 1.3 5.3 13.7 16 37 18 35.3 + 41.3 69 70 101l7 8h-125l-9-7c-50.7-39.3-85-86-103-140h-46c0 4.7 6.3 18.7 19 42 + 18 35.3 40 67.3 66 96l9 9H0v40h399716l-9 9c-26 28.7-48 60.7-66 96-12.7 23.333 +-19 37.333-19 42h46c18-54 52.3-100.7 103-140l9-7h125l-7 8c-28.7 32-52 65.7-70 + 101-10.7 23.333-16 35.7-16 37 0 .7 7.7 1 23 1h22c27.3-71.3 75-127 143-167z`,tilde1:`M200 55.538c-77 0-168 73.953-177 73.953-3 0-7 +-2.175-9-5.437L2 97c-1-2-2-4-2-6 0-4 2-7 5-9l20-12C116 12 171 0 207 0c86 0 + 114 68 191 68 78 0 168-68 177-68 4 0 7 2 9 5l12 19c1 2.175 2 4.35 2 6.525 0 + 4.35-2 7.613-5 9.788l-19 13.05c-92 63.077-116.937 75.308-183 76.128 +-68.267.847-113-73.952-191-73.952z`,tilde2:`M344 55.266c-142 0-300.638 81.316-311.5 86.418 +-8.01 3.762-22.5 10.91-23.5 5.562L1 120c-1-2-1-3-1-4 0-5 3-9 8-10l18.4-9C160.9 + 31.9 283 0 358 0c148 0 188 122 331 122s314-97 326-97c4 0 8 2 10 7l7 21.114 +c1 2.14 1 3.21 1 4.28 0 5.347-3 9.626-7 10.696l-22.3 12.622C852.6 158.372 751 + 181.476 676 181.476c-149 0-189-126.21-332-126.21z`,tilde3:`M786 59C457 59 32 175.242 13 175.242c-6 0-10-3.457 +-11-10.37L.15 138c-1-7 3-12 10-13l19.2-6.4C378.4 40.7 634.3 0 804.3 0c337 0 + 411.8 157 746.8 157 328 0 754-112 773-112 5 0 10 3 11 9l1 14.075c1 8.066-.697 + 16.595-6.697 17.492l-21.052 7.31c-367.9 98.146-609.15 122.696-778.15 122.696 + -338 0-409-156.573-744-156.573z`,tilde4:`M786 58C457 58 32 177.487 13 177.487c-6 0-10-3.345 +-11-10.035L.15 143c-1-7 3-12 10-13l22-6.7C381.2 35 637.15 0 807.15 0c337 0 409 + 177 744 177 328 0 754-127 773-127 5 0 10 3 11 9l1 14.794c1 7.805-3 13.38-9 + 14.495l-20.7 5.574c-366.85 99.79-607.3 139.372-776.3 139.372-338 0-409 + -175.236-744-175.236z`,vec:`M377 20c0-5.333 1.833-10 5.5-14S391 0 397 0c4.667 0 8.667 1.667 12 5 +3.333 2.667 6.667 9 10 19 6.667 24.667 20.333 43.667 41 57 7.333 4.667 11 +10.667 11 18 0 6-1 10-3 12s-6.667 5-14 9c-28.667 14.667-53.667 35.667-75 63 +-1.333 1.333-3.167 3.5-5.5 6.5s-4 4.833-5 5.5c-1 .667-2.5 1.333-4.5 2s-4.333 1 +-7 1c-4.667 0-9.167-1.833-13.5-5.5S337 184 337 178c0-12.667 15.667-32.333 47-59 +H213l-171-1c-8.667-6-13-12.333-13-19 0-4.667 4.333-11.333 13-20h359 +c-16-25.333-24-45-24-59z`,widehat1:`M529 0h5l519 115c5 1 9 5 9 10 0 1-1 2-1 3l-4 22 +c-1 5-5 9-11 9h-2L532 67 19 159h-2c-5 0-9-4-11-9l-5-22c-1-6 2-12 8-13z`,widehat2:`M1181 0h2l1171 176c6 0 10 5 10 11l-2 23c-1 6-5 10 +-11 10h-1L1182 67 15 220h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,widehat3:`M1181 0h2l1171 236c6 0 10 5 10 11l-2 23c-1 6-5 10 +-11 10h-1L1182 67 15 280h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,widehat4:`M1181 0h2l1171 296c6 0 10 5 10 11l-2 23c-1 6-5 10 +-11 10h-1L1182 67 15 340h-1c-6 0-10-4-11-10l-2-23c-1-6 4-11 10-11z`,widecheck1:`M529,159h5l519,-115c5,-1,9,-5,9,-10c0,-1,-1,-2,-1,-3l-4,-22c-1, +-5,-5,-9,-11,-9h-2l-512,92l-513,-92h-2c-5,0,-9,4,-11,9l-5,22c-1,6,2,12,8,13z`,widecheck2:`M1181,220h2l1171,-176c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10, +-11,-10h-1l-1168,153l-1167,-153h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z`,widecheck3:`M1181,280h2l1171,-236c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10, +-11,-10h-1l-1168,213l-1167,-213h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z`,widecheck4:`M1181,340h2l1171,-296c6,0,10,-5,10,-11l-2,-23c-1,-6,-5,-10, +-11,-10h-1l-1168,273l-1167,-273h-1c-6,0,-10,4,-11,10l-2,23c-1,6,4,11,10,11z`,baraboveleftarrow:`M400000 620h-399890l3 -3c68.7 -52.7 113.7 -120 135 -202 +c4 -14.7 6 -23 6 -25c0 -7.3 -7 -11 -21 -11c-8 0 -13.2 0.8 -15.5 2.5 +c-2.3 1.7 -4.2 5.8 -5.5 12.5c-1.3 4.7 -2.7 10.3 -4 17c-12 48.7 -34.8 92 -68.5 130 +s-74.2 66.3 -121.5 85c-10 4 -16 7.7 -18 11c0 8.7 6 14.3 18 17c47.3 18.7 87.8 47 +121.5 85s56.5 81.3 68.5 130c0.7 2 1.3 5 2 9s1.2 6.7 1.5 8c0.3 1.3 1 3.3 2 6 +s2.2 4.5 3.5 5.5c1.3 1 3.3 1.8 6 2.5s6 1 10 1c14 0 21 -3.7 21 -11 +c0 -2 -2 -10.3 -6 -25c-20 -79.3 -65 -146.7 -135 -202l-3 -3h399890z +M100 620v40h399900v-40z M0 241v40h399900v-40zM0 241v40h399900v-40z`,rightarrowabovebar:`M0 241v40h399891c-47.3 35.3-84 78-110 128-16.7 32 +-27.7 63.7-33 95 0 1.3-.2 2.7-.5 4-.3 1.3-.5 2.3-.5 3 0 7.3 6.7 11 20 11 8 0 +13.2-.8 15.5-2.5 2.3-1.7 4.2-5.5 5.5-11.5 2-13.3 5.7-27 11-41 14.7-44.7 39 +-84.5 73-119.5s73.7-60.2 119-75.5c6-2 9-5.7 9-11s-3-9-9-11c-45.3-15.3-85-40.5 +-119-75.5s-58.3-74.8-73-119.5c-4.7-14-8.3-27.3-11-40-1.3-6.7-3.2-10.8-5.5 +-12.5-2.3-1.7-7.5-2.5-15.5-2.5-14 0-21 3.7-21 11 0 2 2 10.3 6 25 20.7 83.3 67 +151.7 139 205zm96 379h399894v40H0zm0 0h399904v40H0z`,baraboveshortleftharpoon:`M507,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11 +c1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17 +c2,0.7,5,1,9,1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21 +c-32,-87.3,-82.7,-157.7,-152,-211c0,0,-3,-3,-3,-3l399351,0l0,-40 +c-398570,0,-399437,0,-399437,0z M593 435 v40 H399500 v-40z +M0 281 v-40 H399908 v40z M0 281 v-40 H399908 v40z`,rightharpoonaboveshortbar:`M0,241 l0,40c399126,0,399993,0,399993,0 +c4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199, +-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6 +c-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z +M0 241 v40 H399908 v-40z M0 475 v-40 H399500 v40z M0 475 v-40 H399500 v40z`,shortbaraboveleftharpoon:`M7,435c-4,4,-6.3,8.7,-7,14c0,5.3,0.7,9,2,11 +c1.3,2,5.3,5.3,12,10c90.7,54,156,130,196,228c3.3,10.7,6.3,16.3,9,17c2,0.7,5,1,9, +1c0,0,5,0,5,0c10.7,0,16.7,-2,18,-6c2,-2.7,1,-9.7,-3,-21c-32,-87.3,-82.7,-157.7, +-152,-211c0,0,-3,-3,-3,-3l399907,0l0,-40c-399126,0,-399993,0,-399993,0z +M93 435 v40 H400000 v-40z M500 241 v40 H400000 v-40z M500 241 v40 H400000 v-40z`,shortrightharpoonabovebar:`M53,241l0,40c398570,0,399437,0,399437,0 +c4.7,-4.7,7,-9.3,7,-14c0,-9.3,-3.7,-15.3,-11,-18c-92.7,-56.7,-159,-133.7,-199, +-231c-3.3,-9.3,-6,-14.7,-8,-16c-2,-1.3,-7,-2,-15,-2c-10.7,0,-16.7,2,-18,6 +c-2,2.7,-1,9.7,3,21c15.3,42,36.7,81.8,64,119.5c27.3,37.7,58,69.2,92,94.5z +M500 241 v40 H399408 v-40z M500 435 v40 H400000 v-40z`},MDe=o(function(e,r){switch(e){case"lbrack":return"M403 1759 V84 H666 V0 H319 V1759 v"+r+` v1759 h347 v-84 +H403z M403 1759 V0 H319 V1759 v`+r+" v1759 h84z";case"rbrack":return"M347 1759 V0 H0 V84 H263 V1759 v"+r+` v1759 H0 v84 H347z +M347 1759 V0 H263 V1759 v`+r+" v1759 h84z";case"vert":return"M145 15 v585 v"+r+` v585 c2.667,10,9.667,15,21,15 +c10,0,16.667,-5,20,-15 v-585 v`+-r+` v-585 c-2.667,-10,-9.667,-15,-21,-15 +c-10,0,-16.667,5,-20,15z M188 15 H145 v585 v`+r+" v585 h43z";case"doublevert":return"M145 15 v585 v"+r+` v585 c2.667,10,9.667,15,21,15 +c10,0,16.667,-5,20,-15 v-585 v`+-r+` v-585 c-2.667,-10,-9.667,-15,-21,-15 +c-10,0,-16.667,5,-20,15z M188 15 H145 v585 v`+r+` v585 h43z +M367 15 v585 v`+r+` v585 c2.667,10,9.667,15,21,15 +c10,0,16.667,-5,20,-15 v-585 v`+-r+` v-585 c-2.667,-10,-9.667,-15,-21,-15 +c-10,0,-16.667,5,-20,15z M410 15 H367 v585 v`+r+" v585 h43z";case"lfloor":return"M319 602 V0 H403 V602 v"+r+` v1715 h263 v84 H319z +MM319 602 V0 H403 V602 v`+r+" v1715 H319z";case"rfloor":return"M319 602 V0 H403 V602 v"+r+` v1799 H0 v-84 H319z +MM319 602 V0 H403 V602 v`+r+" v1715 H319z";case"lceil":return"M403 1759 V84 H666 V0 H319 V1759 v"+r+` v602 h84z +M403 1759 V0 H319 V1759 v`+r+" v602 h84z";case"rceil":return"M347 1759 V0 H0 V84 H263 V1759 v"+r+` v602 h84z +M347 1759 V0 h-84 V1759 v`+r+" v602 h84z";case"lparen":return`M863,9c0,-2,-2,-5,-6,-9c0,0,-17,0,-17,0c-12.7,0,-19.3,0.3,-20,1 +c-5.3,5.3,-10.3,11,-15,17c-242.7,294.7,-395.3,682,-458,1162c-21.3,163.3,-33.3,349, +-36,557 l0,`+(r+84)+`c0.2,6,0,26,0,60c2,159.3,10,310.7,24,454c53.3,528,210, +949.7,470,1265c4.7,6,9.7,11.7,15,17c0.7,0.7,7,1,19,1c0,0,18,0,18,0c4,-4,6,-7,6,-9 +c0,-2.7,-3.3,-8.7,-10,-18c-135.3,-192.7,-235.5,-414.3,-300.5,-665c-65,-250.7,-102.5, +-544.7,-112.5,-882c-2,-104,-3,-167,-3,-189 +l0,-`+(r+92)+`c0,-162.7,5.7,-314,17,-454c20.7,-272,63.7,-513,129,-723c65.3, +-210,155.3,-396.3,270,-559c6.7,-9.3,10,-15.3,10,-18z`;case"rparen":return`M76,0c-16.7,0,-25,3,-25,9c0,2,2,6.3,6,13c21.3,28.7,42.3,60.3, +63,95c96.7,156.7,172.8,332.5,228.5,527.5c55.7,195,92.8,416.5,111.5,664.5 +c11.3,139.3,17,290.7,17,454c0,28,1.7,43,3.3,45l0,`+(r+9)+` +c-3,4,-3.3,16.7,-3.3,38c0,162,-5.7,313.7,-17,455c-18.7,248,-55.8,469.3,-111.5,664 +c-55.7,194.7,-131.8,370.3,-228.5,527c-20.7,34.7,-41.7,66.3,-63,95c-2,3.3,-4,7,-6,11 +c0,7.3,5.7,11,17,11c0,0,11,0,11,0c9.3,0,14.3,-0.3,15,-1c5.3,-5.3,10.3,-11,15,-17 +c242.7,-294.7,395.3,-681.7,458,-1161c21.3,-164.7,33.3,-350.7,36,-558 +l0,-`+(r+144)+`c-2,-159.3,-10,-310.7,-24,-454c-53.3,-528,-210,-949.7, +-470,-1265c-4.7,-6,-9.7,-11.7,-15,-17c-0.7,-0.7,-6.7,-1,-18,-1z`;default:throw new Error("Unknown stretchy delimiter.")}},"tallDelim"),qp=class{static{o(this,"DocumentFragment")}constructor(e){this.children=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.children=e,this.classes=[],this.height=0,this.depth=0,this.maxFontSize=0,this.style={}}hasClass(e){return this.classes.includes(e)}toNode(){for(var e=document.createDocumentFragment(),r=0;rr.toText(),"toText");return this.children.map(e).join("")}},ru={"AMS-Regular":{32:[0,0,0,0,.25],65:[0,.68889,0,0,.72222],66:[0,.68889,0,0,.66667],67:[0,.68889,0,0,.72222],68:[0,.68889,0,0,.72222],69:[0,.68889,0,0,.66667],70:[0,.68889,0,0,.61111],71:[0,.68889,0,0,.77778],72:[0,.68889,0,0,.77778],73:[0,.68889,0,0,.38889],74:[.16667,.68889,0,0,.5],75:[0,.68889,0,0,.77778],76:[0,.68889,0,0,.66667],77:[0,.68889,0,0,.94445],78:[0,.68889,0,0,.72222],79:[.16667,.68889,0,0,.77778],80:[0,.68889,0,0,.61111],81:[.16667,.68889,0,0,.77778],82:[0,.68889,0,0,.72222],83:[0,.68889,0,0,.55556],84:[0,.68889,0,0,.66667],85:[0,.68889,0,0,.72222],86:[0,.68889,0,0,.72222],87:[0,.68889,0,0,1],88:[0,.68889,0,0,.72222],89:[0,.68889,0,0,.72222],90:[0,.68889,0,0,.66667],107:[0,.68889,0,0,.55556],160:[0,0,0,0,.25],165:[0,.675,.025,0,.75],174:[.15559,.69224,0,0,.94666],240:[0,.68889,0,0,.55556],295:[0,.68889,0,0,.54028],710:[0,.825,0,0,2.33334],732:[0,.9,0,0,2.33334],770:[0,.825,0,0,2.33334],771:[0,.9,0,0,2.33334],989:[.08167,.58167,0,0,.77778],1008:[0,.43056,.04028,0,.66667],8245:[0,.54986,0,0,.275],8463:[0,.68889,0,0,.54028],8487:[0,.68889,0,0,.72222],8498:[0,.68889,0,0,.55556],8502:[0,.68889,0,0,.66667],8503:[0,.68889,0,0,.44445],8504:[0,.68889,0,0,.66667],8513:[0,.68889,0,0,.63889],8592:[-.03598,.46402,0,0,.5],8594:[-.03598,.46402,0,0,.5],8602:[-.13313,.36687,0,0,1],8603:[-.13313,.36687,0,0,1],8606:[.01354,.52239,0,0,1],8608:[.01354,.52239,0,0,1],8610:[.01354,.52239,0,0,1.11111],8611:[.01354,.52239,0,0,1.11111],8619:[0,.54986,0,0,1],8620:[0,.54986,0,0,1],8621:[-.13313,.37788,0,0,1.38889],8622:[-.13313,.36687,0,0,1],8624:[0,.69224,0,0,.5],8625:[0,.69224,0,0,.5],8630:[0,.43056,0,0,1],8631:[0,.43056,0,0,1],8634:[.08198,.58198,0,0,.77778],8635:[.08198,.58198,0,0,.77778],8638:[.19444,.69224,0,0,.41667],8639:[.19444,.69224,0,0,.41667],8642:[.19444,.69224,0,0,.41667],8643:[.19444,.69224,0,0,.41667],8644:[.1808,.675,0,0,1],8646:[.1808,.675,0,0,1],8647:[.1808,.675,0,0,1],8648:[.19444,.69224,0,0,.83334],8649:[.1808,.675,0,0,1],8650:[.19444,.69224,0,0,.83334],8651:[.01354,.52239,0,0,1],8652:[.01354,.52239,0,0,1],8653:[-.13313,.36687,0,0,1],8654:[-.13313,.36687,0,0,1],8655:[-.13313,.36687,0,0,1],8666:[.13667,.63667,0,0,1],8667:[.13667,.63667,0,0,1],8669:[-.13313,.37788,0,0,1],8672:[-.064,.437,0,0,1.334],8674:[-.064,.437,0,0,1.334],8705:[0,.825,0,0,.5],8708:[0,.68889,0,0,.55556],8709:[.08167,.58167,0,0,.77778],8717:[0,.43056,0,0,.42917],8722:[-.03598,.46402,0,0,.5],8724:[.08198,.69224,0,0,.77778],8726:[.08167,.58167,0,0,.77778],8733:[0,.69224,0,0,.77778],8736:[0,.69224,0,0,.72222],8737:[0,.69224,0,0,.72222],8738:[.03517,.52239,0,0,.72222],8739:[.08167,.58167,0,0,.22222],8740:[.25142,.74111,0,0,.27778],8741:[.08167,.58167,0,0,.38889],8742:[.25142,.74111,0,0,.5],8756:[0,.69224,0,0,.66667],8757:[0,.69224,0,0,.66667],8764:[-.13313,.36687,0,0,.77778],8765:[-.13313,.37788,0,0,.77778],8769:[-.13313,.36687,0,0,.77778],8770:[-.03625,.46375,0,0,.77778],8774:[.30274,.79383,0,0,.77778],8776:[-.01688,.48312,0,0,.77778],8778:[.08167,.58167,0,0,.77778],8782:[.06062,.54986,0,0,.77778],8783:[.06062,.54986,0,0,.77778],8785:[.08198,.58198,0,0,.77778],8786:[.08198,.58198,0,0,.77778],8787:[.08198,.58198,0,0,.77778],8790:[0,.69224,0,0,.77778],8791:[.22958,.72958,0,0,.77778],8796:[.08198,.91667,0,0,.77778],8806:[.25583,.75583,0,0,.77778],8807:[.25583,.75583,0,0,.77778],8808:[.25142,.75726,0,0,.77778],8809:[.25142,.75726,0,0,.77778],8812:[.25583,.75583,0,0,.5],8814:[.20576,.70576,0,0,.77778],8815:[.20576,.70576,0,0,.77778],8816:[.30274,.79383,0,0,.77778],8817:[.30274,.79383,0,0,.77778],8818:[.22958,.72958,0,0,.77778],8819:[.22958,.72958,0,0,.77778],8822:[.1808,.675,0,0,.77778],8823:[.1808,.675,0,0,.77778],8828:[.13667,.63667,0,0,.77778],8829:[.13667,.63667,0,0,.77778],8830:[.22958,.72958,0,0,.77778],8831:[.22958,.72958,0,0,.77778],8832:[.20576,.70576,0,0,.77778],8833:[.20576,.70576,0,0,.77778],8840:[.30274,.79383,0,0,.77778],8841:[.30274,.79383,0,0,.77778],8842:[.13597,.63597,0,0,.77778],8843:[.13597,.63597,0,0,.77778],8847:[.03517,.54986,0,0,.77778],8848:[.03517,.54986,0,0,.77778],8858:[.08198,.58198,0,0,.77778],8859:[.08198,.58198,0,0,.77778],8861:[.08198,.58198,0,0,.77778],8862:[0,.675,0,0,.77778],8863:[0,.675,0,0,.77778],8864:[0,.675,0,0,.77778],8865:[0,.675,0,0,.77778],8872:[0,.69224,0,0,.61111],8873:[0,.69224,0,0,.72222],8874:[0,.69224,0,0,.88889],8876:[0,.68889,0,0,.61111],8877:[0,.68889,0,0,.61111],8878:[0,.68889,0,0,.72222],8879:[0,.68889,0,0,.72222],8882:[.03517,.54986,0,0,.77778],8883:[.03517,.54986,0,0,.77778],8884:[.13667,.63667,0,0,.77778],8885:[.13667,.63667,0,0,.77778],8888:[0,.54986,0,0,1.11111],8890:[.19444,.43056,0,0,.55556],8891:[.19444,.69224,0,0,.61111],8892:[.19444,.69224,0,0,.61111],8901:[0,.54986,0,0,.27778],8903:[.08167,.58167,0,0,.77778],8905:[.08167,.58167,0,0,.77778],8906:[.08167,.58167,0,0,.77778],8907:[0,.69224,0,0,.77778],8908:[0,.69224,0,0,.77778],8909:[-.03598,.46402,0,0,.77778],8910:[0,.54986,0,0,.76042],8911:[0,.54986,0,0,.76042],8912:[.03517,.54986,0,0,.77778],8913:[.03517,.54986,0,0,.77778],8914:[0,.54986,0,0,.66667],8915:[0,.54986,0,0,.66667],8916:[0,.69224,0,0,.66667],8918:[.0391,.5391,0,0,.77778],8919:[.0391,.5391,0,0,.77778],8920:[.03517,.54986,0,0,1.33334],8921:[.03517,.54986,0,0,1.33334],8922:[.38569,.88569,0,0,.77778],8923:[.38569,.88569,0,0,.77778],8926:[.13667,.63667,0,0,.77778],8927:[.13667,.63667,0,0,.77778],8928:[.30274,.79383,0,0,.77778],8929:[.30274,.79383,0,0,.77778],8934:[.23222,.74111,0,0,.77778],8935:[.23222,.74111,0,0,.77778],8936:[.23222,.74111,0,0,.77778],8937:[.23222,.74111,0,0,.77778],8938:[.20576,.70576,0,0,.77778],8939:[.20576,.70576,0,0,.77778],8940:[.30274,.79383,0,0,.77778],8941:[.30274,.79383,0,0,.77778],8994:[.19444,.69224,0,0,.77778],8995:[.19444,.69224,0,0,.77778],9416:[.15559,.69224,0,0,.90222],9484:[0,.69224,0,0,.5],9488:[0,.69224,0,0,.5],9492:[0,.37788,0,0,.5],9496:[0,.37788,0,0,.5],9585:[.19444,.68889,0,0,.88889],9586:[.19444,.74111,0,0,.88889],9632:[0,.675,0,0,.77778],9633:[0,.675,0,0,.77778],9650:[0,.54986,0,0,.72222],9651:[0,.54986,0,0,.72222],9654:[.03517,.54986,0,0,.77778],9660:[0,.54986,0,0,.72222],9661:[0,.54986,0,0,.72222],9664:[.03517,.54986,0,0,.77778],9674:[.11111,.69224,0,0,.66667],9733:[.19444,.69224,0,0,.94445],10003:[0,.69224,0,0,.83334],10016:[0,.69224,0,0,.83334],10731:[.11111,.69224,0,0,.66667],10846:[.19444,.75583,0,0,.61111],10877:[.13667,.63667,0,0,.77778],10878:[.13667,.63667,0,0,.77778],10885:[.25583,.75583,0,0,.77778],10886:[.25583,.75583,0,0,.77778],10887:[.13597,.63597,0,0,.77778],10888:[.13597,.63597,0,0,.77778],10889:[.26167,.75726,0,0,.77778],10890:[.26167,.75726,0,0,.77778],10891:[.48256,.98256,0,0,.77778],10892:[.48256,.98256,0,0,.77778],10901:[.13667,.63667,0,0,.77778],10902:[.13667,.63667,0,0,.77778],10933:[.25142,.75726,0,0,.77778],10934:[.25142,.75726,0,0,.77778],10935:[.26167,.75726,0,0,.77778],10936:[.26167,.75726,0,0,.77778],10937:[.26167,.75726,0,0,.77778],10938:[.26167,.75726,0,0,.77778],10949:[.25583,.75583,0,0,.77778],10950:[.25583,.75583,0,0,.77778],10955:[.28481,.79383,0,0,.77778],10956:[.28481,.79383,0,0,.77778],57350:[.08167,.58167,0,0,.22222],57351:[.08167,.58167,0,0,.38889],57352:[.08167,.58167,0,0,.77778],57353:[0,.43056,.04028,0,.66667],57356:[.25142,.75726,0,0,.77778],57357:[.25142,.75726,0,0,.77778],57358:[.41951,.91951,0,0,.77778],57359:[.30274,.79383,0,0,.77778],57360:[.30274,.79383,0,0,.77778],57361:[.41951,.91951,0,0,.77778],57366:[.25142,.75726,0,0,.77778],57367:[.25142,.75726,0,0,.77778],57368:[.25142,.75726,0,0,.77778],57369:[.25142,.75726,0,0,.77778],57370:[.13597,.63597,0,0,.77778],57371:[.13597,.63597,0,0,.77778]},"Caligraphic-Regular":{32:[0,0,0,0,.25],65:[0,.68333,0,.19445,.79847],66:[0,.68333,.03041,.13889,.65681],67:[0,.68333,.05834,.13889,.52653],68:[0,.68333,.02778,.08334,.77139],69:[0,.68333,.08944,.11111,.52778],70:[0,.68333,.09931,.11111,.71875],71:[.09722,.68333,.0593,.11111,.59487],72:[0,.68333,.00965,.11111,.84452],73:[0,.68333,.07382,0,.54452],74:[.09722,.68333,.18472,.16667,.67778],75:[0,.68333,.01445,.05556,.76195],76:[0,.68333,0,.13889,.68972],77:[0,.68333,0,.13889,1.2009],78:[0,.68333,.14736,.08334,.82049],79:[0,.68333,.02778,.11111,.79611],80:[0,.68333,.08222,.08334,.69556],81:[.09722,.68333,0,.11111,.81667],82:[0,.68333,0,.08334,.8475],83:[0,.68333,.075,.13889,.60556],84:[0,.68333,.25417,0,.54464],85:[0,.68333,.09931,.08334,.62583],86:[0,.68333,.08222,0,.61278],87:[0,.68333,.08222,.08334,.98778],88:[0,.68333,.14643,.13889,.7133],89:[.09722,.68333,.08222,.08334,.66834],90:[0,.68333,.07944,.13889,.72473],160:[0,0,0,0,.25]},"Fraktur-Regular":{32:[0,0,0,0,.25],33:[0,.69141,0,0,.29574],34:[0,.69141,0,0,.21471],38:[0,.69141,0,0,.73786],39:[0,.69141,0,0,.21201],40:[.24982,.74947,0,0,.38865],41:[.24982,.74947,0,0,.38865],42:[0,.62119,0,0,.27764],43:[.08319,.58283,0,0,.75623],44:[0,.10803,0,0,.27764],45:[.08319,.58283,0,0,.75623],46:[0,.10803,0,0,.27764],47:[.24982,.74947,0,0,.50181],48:[0,.47534,0,0,.50181],49:[0,.47534,0,0,.50181],50:[0,.47534,0,0,.50181],51:[.18906,.47534,0,0,.50181],52:[.18906,.47534,0,0,.50181],53:[.18906,.47534,0,0,.50181],54:[0,.69141,0,0,.50181],55:[.18906,.47534,0,0,.50181],56:[0,.69141,0,0,.50181],57:[.18906,.47534,0,0,.50181],58:[0,.47534,0,0,.21606],59:[.12604,.47534,0,0,.21606],61:[-.13099,.36866,0,0,.75623],63:[0,.69141,0,0,.36245],65:[0,.69141,0,0,.7176],66:[0,.69141,0,0,.88397],67:[0,.69141,0,0,.61254],68:[0,.69141,0,0,.83158],69:[0,.69141,0,0,.66278],70:[.12604,.69141,0,0,.61119],71:[0,.69141,0,0,.78539],72:[.06302,.69141,0,0,.7203],73:[0,.69141,0,0,.55448],74:[.12604,.69141,0,0,.55231],75:[0,.69141,0,0,.66845],76:[0,.69141,0,0,.66602],77:[0,.69141,0,0,1.04953],78:[0,.69141,0,0,.83212],79:[0,.69141,0,0,.82699],80:[.18906,.69141,0,0,.82753],81:[.03781,.69141,0,0,.82699],82:[0,.69141,0,0,.82807],83:[0,.69141,0,0,.82861],84:[0,.69141,0,0,.66899],85:[0,.69141,0,0,.64576],86:[0,.69141,0,0,.83131],87:[0,.69141,0,0,1.04602],88:[0,.69141,0,0,.71922],89:[.18906,.69141,0,0,.83293],90:[.12604,.69141,0,0,.60201],91:[.24982,.74947,0,0,.27764],93:[.24982,.74947,0,0,.27764],94:[0,.69141,0,0,.49965],97:[0,.47534,0,0,.50046],98:[0,.69141,0,0,.51315],99:[0,.47534,0,0,.38946],100:[0,.62119,0,0,.49857],101:[0,.47534,0,0,.40053],102:[.18906,.69141,0,0,.32626],103:[.18906,.47534,0,0,.5037],104:[.18906,.69141,0,0,.52126],105:[0,.69141,0,0,.27899],106:[0,.69141,0,0,.28088],107:[0,.69141,0,0,.38946],108:[0,.69141,0,0,.27953],109:[0,.47534,0,0,.76676],110:[0,.47534,0,0,.52666],111:[0,.47534,0,0,.48885],112:[.18906,.52396,0,0,.50046],113:[.18906,.47534,0,0,.48912],114:[0,.47534,0,0,.38919],115:[0,.47534,0,0,.44266],116:[0,.62119,0,0,.33301],117:[0,.47534,0,0,.5172],118:[0,.52396,0,0,.5118],119:[0,.52396,0,0,.77351],120:[.18906,.47534,0,0,.38865],121:[.18906,.47534,0,0,.49884],122:[.18906,.47534,0,0,.39054],160:[0,0,0,0,.25],8216:[0,.69141,0,0,.21471],8217:[0,.69141,0,0,.21471],58112:[0,.62119,0,0,.49749],58113:[0,.62119,0,0,.4983],58114:[.18906,.69141,0,0,.33328],58115:[.18906,.69141,0,0,.32923],58116:[.18906,.47534,0,0,.50343],58117:[0,.69141,0,0,.33301],58118:[0,.62119,0,0,.33409],58119:[0,.47534,0,0,.50073]},"Main-Bold":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.35],34:[0,.69444,0,0,.60278],35:[.19444,.69444,0,0,.95833],36:[.05556,.75,0,0,.575],37:[.05556,.75,0,0,.95833],38:[0,.69444,0,0,.89444],39:[0,.69444,0,0,.31944],40:[.25,.75,0,0,.44722],41:[.25,.75,0,0,.44722],42:[0,.75,0,0,.575],43:[.13333,.63333,0,0,.89444],44:[.19444,.15556,0,0,.31944],45:[0,.44444,0,0,.38333],46:[0,.15556,0,0,.31944],47:[.25,.75,0,0,.575],48:[0,.64444,0,0,.575],49:[0,.64444,0,0,.575],50:[0,.64444,0,0,.575],51:[0,.64444,0,0,.575],52:[0,.64444,0,0,.575],53:[0,.64444,0,0,.575],54:[0,.64444,0,0,.575],55:[0,.64444,0,0,.575],56:[0,.64444,0,0,.575],57:[0,.64444,0,0,.575],58:[0,.44444,0,0,.31944],59:[.19444,.44444,0,0,.31944],60:[.08556,.58556,0,0,.89444],61:[-.10889,.39111,0,0,.89444],62:[.08556,.58556,0,0,.89444],63:[0,.69444,0,0,.54305],64:[0,.69444,0,0,.89444],65:[0,.68611,0,0,.86944],66:[0,.68611,0,0,.81805],67:[0,.68611,0,0,.83055],68:[0,.68611,0,0,.88194],69:[0,.68611,0,0,.75555],70:[0,.68611,0,0,.72361],71:[0,.68611,0,0,.90416],72:[0,.68611,0,0,.9],73:[0,.68611,0,0,.43611],74:[0,.68611,0,0,.59444],75:[0,.68611,0,0,.90138],76:[0,.68611,0,0,.69166],77:[0,.68611,0,0,1.09166],78:[0,.68611,0,0,.9],79:[0,.68611,0,0,.86388],80:[0,.68611,0,0,.78611],81:[.19444,.68611,0,0,.86388],82:[0,.68611,0,0,.8625],83:[0,.68611,0,0,.63889],84:[0,.68611,0,0,.8],85:[0,.68611,0,0,.88472],86:[0,.68611,.01597,0,.86944],87:[0,.68611,.01597,0,1.18888],88:[0,.68611,0,0,.86944],89:[0,.68611,.02875,0,.86944],90:[0,.68611,0,0,.70277],91:[.25,.75,0,0,.31944],92:[.25,.75,0,0,.575],93:[.25,.75,0,0,.31944],94:[0,.69444,0,0,.575],95:[.31,.13444,.03194,0,.575],97:[0,.44444,0,0,.55902],98:[0,.69444,0,0,.63889],99:[0,.44444,0,0,.51111],100:[0,.69444,0,0,.63889],101:[0,.44444,0,0,.52708],102:[0,.69444,.10903,0,.35139],103:[.19444,.44444,.01597,0,.575],104:[0,.69444,0,0,.63889],105:[0,.69444,0,0,.31944],106:[.19444,.69444,0,0,.35139],107:[0,.69444,0,0,.60694],108:[0,.69444,0,0,.31944],109:[0,.44444,0,0,.95833],110:[0,.44444,0,0,.63889],111:[0,.44444,0,0,.575],112:[.19444,.44444,0,0,.63889],113:[.19444,.44444,0,0,.60694],114:[0,.44444,0,0,.47361],115:[0,.44444,0,0,.45361],116:[0,.63492,0,0,.44722],117:[0,.44444,0,0,.63889],118:[0,.44444,.01597,0,.60694],119:[0,.44444,.01597,0,.83055],120:[0,.44444,0,0,.60694],121:[.19444,.44444,.01597,0,.60694],122:[0,.44444,0,0,.51111],123:[.25,.75,0,0,.575],124:[.25,.75,0,0,.31944],125:[.25,.75,0,0,.575],126:[.35,.34444,0,0,.575],160:[0,0,0,0,.25],163:[0,.69444,0,0,.86853],168:[0,.69444,0,0,.575],172:[0,.44444,0,0,.76666],176:[0,.69444,0,0,.86944],177:[.13333,.63333,0,0,.89444],184:[.17014,0,0,0,.51111],198:[0,.68611,0,0,1.04166],215:[.13333,.63333,0,0,.89444],216:[.04861,.73472,0,0,.89444],223:[0,.69444,0,0,.59722],230:[0,.44444,0,0,.83055],247:[.13333,.63333,0,0,.89444],248:[.09722,.54167,0,0,.575],305:[0,.44444,0,0,.31944],338:[0,.68611,0,0,1.16944],339:[0,.44444,0,0,.89444],567:[.19444,.44444,0,0,.35139],710:[0,.69444,0,0,.575],711:[0,.63194,0,0,.575],713:[0,.59611,0,0,.575],714:[0,.69444,0,0,.575],715:[0,.69444,0,0,.575],728:[0,.69444,0,0,.575],729:[0,.69444,0,0,.31944],730:[0,.69444,0,0,.86944],732:[0,.69444,0,0,.575],733:[0,.69444,0,0,.575],915:[0,.68611,0,0,.69166],916:[0,.68611,0,0,.95833],920:[0,.68611,0,0,.89444],923:[0,.68611,0,0,.80555],926:[0,.68611,0,0,.76666],928:[0,.68611,0,0,.9],931:[0,.68611,0,0,.83055],933:[0,.68611,0,0,.89444],934:[0,.68611,0,0,.83055],936:[0,.68611,0,0,.89444],937:[0,.68611,0,0,.83055],8211:[0,.44444,.03194,0,.575],8212:[0,.44444,.03194,0,1.14999],8216:[0,.69444,0,0,.31944],8217:[0,.69444,0,0,.31944],8220:[0,.69444,0,0,.60278],8221:[0,.69444,0,0,.60278],8224:[.19444,.69444,0,0,.51111],8225:[.19444,.69444,0,0,.51111],8242:[0,.55556,0,0,.34444],8407:[0,.72444,.15486,0,.575],8463:[0,.69444,0,0,.66759],8465:[0,.69444,0,0,.83055],8467:[0,.69444,0,0,.47361],8472:[.19444,.44444,0,0,.74027],8476:[0,.69444,0,0,.83055],8501:[0,.69444,0,0,.70277],8592:[-.10889,.39111,0,0,1.14999],8593:[.19444,.69444,0,0,.575],8594:[-.10889,.39111,0,0,1.14999],8595:[.19444,.69444,0,0,.575],8596:[-.10889,.39111,0,0,1.14999],8597:[.25,.75,0,0,.575],8598:[.19444,.69444,0,0,1.14999],8599:[.19444,.69444,0,0,1.14999],8600:[.19444,.69444,0,0,1.14999],8601:[.19444,.69444,0,0,1.14999],8636:[-.10889,.39111,0,0,1.14999],8637:[-.10889,.39111,0,0,1.14999],8640:[-.10889,.39111,0,0,1.14999],8641:[-.10889,.39111,0,0,1.14999],8656:[-.10889,.39111,0,0,1.14999],8657:[.19444,.69444,0,0,.70277],8658:[-.10889,.39111,0,0,1.14999],8659:[.19444,.69444,0,0,.70277],8660:[-.10889,.39111,0,0,1.14999],8661:[.25,.75,0,0,.70277],8704:[0,.69444,0,0,.63889],8706:[0,.69444,.06389,0,.62847],8707:[0,.69444,0,0,.63889],8709:[.05556,.75,0,0,.575],8711:[0,.68611,0,0,.95833],8712:[.08556,.58556,0,0,.76666],8715:[.08556,.58556,0,0,.76666],8722:[.13333,.63333,0,0,.89444],8723:[.13333,.63333,0,0,.89444],8725:[.25,.75,0,0,.575],8726:[.25,.75,0,0,.575],8727:[-.02778,.47222,0,0,.575],8728:[-.02639,.47361,0,0,.575],8729:[-.02639,.47361,0,0,.575],8730:[.18,.82,0,0,.95833],8733:[0,.44444,0,0,.89444],8734:[0,.44444,0,0,1.14999],8736:[0,.69224,0,0,.72222],8739:[.25,.75,0,0,.31944],8741:[.25,.75,0,0,.575],8743:[0,.55556,0,0,.76666],8744:[0,.55556,0,0,.76666],8745:[0,.55556,0,0,.76666],8746:[0,.55556,0,0,.76666],8747:[.19444,.69444,.12778,0,.56875],8764:[-.10889,.39111,0,0,.89444],8768:[.19444,.69444,0,0,.31944],8771:[.00222,.50222,0,0,.89444],8773:[.027,.638,0,0,.894],8776:[.02444,.52444,0,0,.89444],8781:[.00222,.50222,0,0,.89444],8801:[.00222,.50222,0,0,.89444],8804:[.19667,.69667,0,0,.89444],8805:[.19667,.69667,0,0,.89444],8810:[.08556,.58556,0,0,1.14999],8811:[.08556,.58556,0,0,1.14999],8826:[.08556,.58556,0,0,.89444],8827:[.08556,.58556,0,0,.89444],8834:[.08556,.58556,0,0,.89444],8835:[.08556,.58556,0,0,.89444],8838:[.19667,.69667,0,0,.89444],8839:[.19667,.69667,0,0,.89444],8846:[0,.55556,0,0,.76666],8849:[.19667,.69667,0,0,.89444],8850:[.19667,.69667,0,0,.89444],8851:[0,.55556,0,0,.76666],8852:[0,.55556,0,0,.76666],8853:[.13333,.63333,0,0,.89444],8854:[.13333,.63333,0,0,.89444],8855:[.13333,.63333,0,0,.89444],8856:[.13333,.63333,0,0,.89444],8857:[.13333,.63333,0,0,.89444],8866:[0,.69444,0,0,.70277],8867:[0,.69444,0,0,.70277],8868:[0,.69444,0,0,.89444],8869:[0,.69444,0,0,.89444],8900:[-.02639,.47361,0,0,.575],8901:[-.02639,.47361,0,0,.31944],8902:[-.02778,.47222,0,0,.575],8968:[.25,.75,0,0,.51111],8969:[.25,.75,0,0,.51111],8970:[.25,.75,0,0,.51111],8971:[.25,.75,0,0,.51111],8994:[-.13889,.36111,0,0,1.14999],8995:[-.13889,.36111,0,0,1.14999],9651:[.19444,.69444,0,0,1.02222],9657:[-.02778,.47222,0,0,.575],9661:[.19444,.69444,0,0,1.02222],9667:[-.02778,.47222,0,0,.575],9711:[.19444,.69444,0,0,1.14999],9824:[.12963,.69444,0,0,.89444],9825:[.12963,.69444,0,0,.89444],9826:[.12963,.69444,0,0,.89444],9827:[.12963,.69444,0,0,.89444],9837:[0,.75,0,0,.44722],9838:[.19444,.69444,0,0,.44722],9839:[.19444,.69444,0,0,.44722],10216:[.25,.75,0,0,.44722],10217:[.25,.75,0,0,.44722],10815:[0,.68611,0,0,.9],10927:[.19667,.69667,0,0,.89444],10928:[.19667,.69667,0,0,.89444],57376:[.19444,.69444,0,0,0]},"Main-BoldItalic":{32:[0,0,0,0,.25],33:[0,.69444,.11417,0,.38611],34:[0,.69444,.07939,0,.62055],35:[.19444,.69444,.06833,0,.94444],37:[.05556,.75,.12861,0,.94444],38:[0,.69444,.08528,0,.88555],39:[0,.69444,.12945,0,.35555],40:[.25,.75,.15806,0,.47333],41:[.25,.75,.03306,0,.47333],42:[0,.75,.14333,0,.59111],43:[.10333,.60333,.03306,0,.88555],44:[.19444,.14722,0,0,.35555],45:[0,.44444,.02611,0,.41444],46:[0,.14722,0,0,.35555],47:[.25,.75,.15806,0,.59111],48:[0,.64444,.13167,0,.59111],49:[0,.64444,.13167,0,.59111],50:[0,.64444,.13167,0,.59111],51:[0,.64444,.13167,0,.59111],52:[.19444,.64444,.13167,0,.59111],53:[0,.64444,.13167,0,.59111],54:[0,.64444,.13167,0,.59111],55:[.19444,.64444,.13167,0,.59111],56:[0,.64444,.13167,0,.59111],57:[0,.64444,.13167,0,.59111],58:[0,.44444,.06695,0,.35555],59:[.19444,.44444,.06695,0,.35555],61:[-.10889,.39111,.06833,0,.88555],63:[0,.69444,.11472,0,.59111],64:[0,.69444,.09208,0,.88555],65:[0,.68611,0,0,.86555],66:[0,.68611,.0992,0,.81666],67:[0,.68611,.14208,0,.82666],68:[0,.68611,.09062,0,.87555],69:[0,.68611,.11431,0,.75666],70:[0,.68611,.12903,0,.72722],71:[0,.68611,.07347,0,.89527],72:[0,.68611,.17208,0,.8961],73:[0,.68611,.15681,0,.47166],74:[0,.68611,.145,0,.61055],75:[0,.68611,.14208,0,.89499],76:[0,.68611,0,0,.69777],77:[0,.68611,.17208,0,1.07277],78:[0,.68611,.17208,0,.8961],79:[0,.68611,.09062,0,.85499],80:[0,.68611,.0992,0,.78721],81:[.19444,.68611,.09062,0,.85499],82:[0,.68611,.02559,0,.85944],83:[0,.68611,.11264,0,.64999],84:[0,.68611,.12903,0,.7961],85:[0,.68611,.17208,0,.88083],86:[0,.68611,.18625,0,.86555],87:[0,.68611,.18625,0,1.15999],88:[0,.68611,.15681,0,.86555],89:[0,.68611,.19803,0,.86555],90:[0,.68611,.14208,0,.70888],91:[.25,.75,.1875,0,.35611],93:[.25,.75,.09972,0,.35611],94:[0,.69444,.06709,0,.59111],95:[.31,.13444,.09811,0,.59111],97:[0,.44444,.09426,0,.59111],98:[0,.69444,.07861,0,.53222],99:[0,.44444,.05222,0,.53222],100:[0,.69444,.10861,0,.59111],101:[0,.44444,.085,0,.53222],102:[.19444,.69444,.21778,0,.4],103:[.19444,.44444,.105,0,.53222],104:[0,.69444,.09426,0,.59111],105:[0,.69326,.11387,0,.35555],106:[.19444,.69326,.1672,0,.35555],107:[0,.69444,.11111,0,.53222],108:[0,.69444,.10861,0,.29666],109:[0,.44444,.09426,0,.94444],110:[0,.44444,.09426,0,.64999],111:[0,.44444,.07861,0,.59111],112:[.19444,.44444,.07861,0,.59111],113:[.19444,.44444,.105,0,.53222],114:[0,.44444,.11111,0,.50167],115:[0,.44444,.08167,0,.48694],116:[0,.63492,.09639,0,.385],117:[0,.44444,.09426,0,.62055],118:[0,.44444,.11111,0,.53222],119:[0,.44444,.11111,0,.76777],120:[0,.44444,.12583,0,.56055],121:[.19444,.44444,.105,0,.56166],122:[0,.44444,.13889,0,.49055],126:[.35,.34444,.11472,0,.59111],160:[0,0,0,0,.25],168:[0,.69444,.11473,0,.59111],176:[0,.69444,0,0,.94888],184:[.17014,0,0,0,.53222],198:[0,.68611,.11431,0,1.02277],216:[.04861,.73472,.09062,0,.88555],223:[.19444,.69444,.09736,0,.665],230:[0,.44444,.085,0,.82666],248:[.09722,.54167,.09458,0,.59111],305:[0,.44444,.09426,0,.35555],338:[0,.68611,.11431,0,1.14054],339:[0,.44444,.085,0,.82666],567:[.19444,.44444,.04611,0,.385],710:[0,.69444,.06709,0,.59111],711:[0,.63194,.08271,0,.59111],713:[0,.59444,.10444,0,.59111],714:[0,.69444,.08528,0,.59111],715:[0,.69444,0,0,.59111],728:[0,.69444,.10333,0,.59111],729:[0,.69444,.12945,0,.35555],730:[0,.69444,0,0,.94888],732:[0,.69444,.11472,0,.59111],733:[0,.69444,.11472,0,.59111],915:[0,.68611,.12903,0,.69777],916:[0,.68611,0,0,.94444],920:[0,.68611,.09062,0,.88555],923:[0,.68611,0,0,.80666],926:[0,.68611,.15092,0,.76777],928:[0,.68611,.17208,0,.8961],931:[0,.68611,.11431,0,.82666],933:[0,.68611,.10778,0,.88555],934:[0,.68611,.05632,0,.82666],936:[0,.68611,.10778,0,.88555],937:[0,.68611,.0992,0,.82666],8211:[0,.44444,.09811,0,.59111],8212:[0,.44444,.09811,0,1.18221],8216:[0,.69444,.12945,0,.35555],8217:[0,.69444,.12945,0,.35555],8220:[0,.69444,.16772,0,.62055],8221:[0,.69444,.07939,0,.62055]},"Main-Italic":{32:[0,0,0,0,.25],33:[0,.69444,.12417,0,.30667],34:[0,.69444,.06961,0,.51444],35:[.19444,.69444,.06616,0,.81777],37:[.05556,.75,.13639,0,.81777],38:[0,.69444,.09694,0,.76666],39:[0,.69444,.12417,0,.30667],40:[.25,.75,.16194,0,.40889],41:[.25,.75,.03694,0,.40889],42:[0,.75,.14917,0,.51111],43:[.05667,.56167,.03694,0,.76666],44:[.19444,.10556,0,0,.30667],45:[0,.43056,.02826,0,.35778],46:[0,.10556,0,0,.30667],47:[.25,.75,.16194,0,.51111],48:[0,.64444,.13556,0,.51111],49:[0,.64444,.13556,0,.51111],50:[0,.64444,.13556,0,.51111],51:[0,.64444,.13556,0,.51111],52:[.19444,.64444,.13556,0,.51111],53:[0,.64444,.13556,0,.51111],54:[0,.64444,.13556,0,.51111],55:[.19444,.64444,.13556,0,.51111],56:[0,.64444,.13556,0,.51111],57:[0,.64444,.13556,0,.51111],58:[0,.43056,.0582,0,.30667],59:[.19444,.43056,.0582,0,.30667],61:[-.13313,.36687,.06616,0,.76666],63:[0,.69444,.1225,0,.51111],64:[0,.69444,.09597,0,.76666],65:[0,.68333,0,0,.74333],66:[0,.68333,.10257,0,.70389],67:[0,.68333,.14528,0,.71555],68:[0,.68333,.09403,0,.755],69:[0,.68333,.12028,0,.67833],70:[0,.68333,.13305,0,.65277],71:[0,.68333,.08722,0,.77361],72:[0,.68333,.16389,0,.74333],73:[0,.68333,.15806,0,.38555],74:[0,.68333,.14028,0,.525],75:[0,.68333,.14528,0,.76888],76:[0,.68333,0,0,.62722],77:[0,.68333,.16389,0,.89666],78:[0,.68333,.16389,0,.74333],79:[0,.68333,.09403,0,.76666],80:[0,.68333,.10257,0,.67833],81:[.19444,.68333,.09403,0,.76666],82:[0,.68333,.03868,0,.72944],83:[0,.68333,.11972,0,.56222],84:[0,.68333,.13305,0,.71555],85:[0,.68333,.16389,0,.74333],86:[0,.68333,.18361,0,.74333],87:[0,.68333,.18361,0,.99888],88:[0,.68333,.15806,0,.74333],89:[0,.68333,.19383,0,.74333],90:[0,.68333,.14528,0,.61333],91:[.25,.75,.1875,0,.30667],93:[.25,.75,.10528,0,.30667],94:[0,.69444,.06646,0,.51111],95:[.31,.12056,.09208,0,.51111],97:[0,.43056,.07671,0,.51111],98:[0,.69444,.06312,0,.46],99:[0,.43056,.05653,0,.46],100:[0,.69444,.10333,0,.51111],101:[0,.43056,.07514,0,.46],102:[.19444,.69444,.21194,0,.30667],103:[.19444,.43056,.08847,0,.46],104:[0,.69444,.07671,0,.51111],105:[0,.65536,.1019,0,.30667],106:[.19444,.65536,.14467,0,.30667],107:[0,.69444,.10764,0,.46],108:[0,.69444,.10333,0,.25555],109:[0,.43056,.07671,0,.81777],110:[0,.43056,.07671,0,.56222],111:[0,.43056,.06312,0,.51111],112:[.19444,.43056,.06312,0,.51111],113:[.19444,.43056,.08847,0,.46],114:[0,.43056,.10764,0,.42166],115:[0,.43056,.08208,0,.40889],116:[0,.61508,.09486,0,.33222],117:[0,.43056,.07671,0,.53666],118:[0,.43056,.10764,0,.46],119:[0,.43056,.10764,0,.66444],120:[0,.43056,.12042,0,.46389],121:[.19444,.43056,.08847,0,.48555],122:[0,.43056,.12292,0,.40889],126:[.35,.31786,.11585,0,.51111],160:[0,0,0,0,.25],168:[0,.66786,.10474,0,.51111],176:[0,.69444,0,0,.83129],184:[.17014,0,0,0,.46],198:[0,.68333,.12028,0,.88277],216:[.04861,.73194,.09403,0,.76666],223:[.19444,.69444,.10514,0,.53666],230:[0,.43056,.07514,0,.71555],248:[.09722,.52778,.09194,0,.51111],338:[0,.68333,.12028,0,.98499],339:[0,.43056,.07514,0,.71555],710:[0,.69444,.06646,0,.51111],711:[0,.62847,.08295,0,.51111],713:[0,.56167,.10333,0,.51111],714:[0,.69444,.09694,0,.51111],715:[0,.69444,0,0,.51111],728:[0,.69444,.10806,0,.51111],729:[0,.66786,.11752,0,.30667],730:[0,.69444,0,0,.83129],732:[0,.66786,.11585,0,.51111],733:[0,.69444,.1225,0,.51111],915:[0,.68333,.13305,0,.62722],916:[0,.68333,0,0,.81777],920:[0,.68333,.09403,0,.76666],923:[0,.68333,0,0,.69222],926:[0,.68333,.15294,0,.66444],928:[0,.68333,.16389,0,.74333],931:[0,.68333,.12028,0,.71555],933:[0,.68333,.11111,0,.76666],934:[0,.68333,.05986,0,.71555],936:[0,.68333,.11111,0,.76666],937:[0,.68333,.10257,0,.71555],8211:[0,.43056,.09208,0,.51111],8212:[0,.43056,.09208,0,1.02222],8216:[0,.69444,.12417,0,.30667],8217:[0,.69444,.12417,0,.30667],8220:[0,.69444,.1685,0,.51444],8221:[0,.69444,.06961,0,.51444],8463:[0,.68889,0,0,.54028]},"Main-Regular":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.27778],34:[0,.69444,0,0,.5],35:[.19444,.69444,0,0,.83334],36:[.05556,.75,0,0,.5],37:[.05556,.75,0,0,.83334],38:[0,.69444,0,0,.77778],39:[0,.69444,0,0,.27778],40:[.25,.75,0,0,.38889],41:[.25,.75,0,0,.38889],42:[0,.75,0,0,.5],43:[.08333,.58333,0,0,.77778],44:[.19444,.10556,0,0,.27778],45:[0,.43056,0,0,.33333],46:[0,.10556,0,0,.27778],47:[.25,.75,0,0,.5],48:[0,.64444,0,0,.5],49:[0,.64444,0,0,.5],50:[0,.64444,0,0,.5],51:[0,.64444,0,0,.5],52:[0,.64444,0,0,.5],53:[0,.64444,0,0,.5],54:[0,.64444,0,0,.5],55:[0,.64444,0,0,.5],56:[0,.64444,0,0,.5],57:[0,.64444,0,0,.5],58:[0,.43056,0,0,.27778],59:[.19444,.43056,0,0,.27778],60:[.0391,.5391,0,0,.77778],61:[-.13313,.36687,0,0,.77778],62:[.0391,.5391,0,0,.77778],63:[0,.69444,0,0,.47222],64:[0,.69444,0,0,.77778],65:[0,.68333,0,0,.75],66:[0,.68333,0,0,.70834],67:[0,.68333,0,0,.72222],68:[0,.68333,0,0,.76389],69:[0,.68333,0,0,.68056],70:[0,.68333,0,0,.65278],71:[0,.68333,0,0,.78472],72:[0,.68333,0,0,.75],73:[0,.68333,0,0,.36111],74:[0,.68333,0,0,.51389],75:[0,.68333,0,0,.77778],76:[0,.68333,0,0,.625],77:[0,.68333,0,0,.91667],78:[0,.68333,0,0,.75],79:[0,.68333,0,0,.77778],80:[0,.68333,0,0,.68056],81:[.19444,.68333,0,0,.77778],82:[0,.68333,0,0,.73611],83:[0,.68333,0,0,.55556],84:[0,.68333,0,0,.72222],85:[0,.68333,0,0,.75],86:[0,.68333,.01389,0,.75],87:[0,.68333,.01389,0,1.02778],88:[0,.68333,0,0,.75],89:[0,.68333,.025,0,.75],90:[0,.68333,0,0,.61111],91:[.25,.75,0,0,.27778],92:[.25,.75,0,0,.5],93:[.25,.75,0,0,.27778],94:[0,.69444,0,0,.5],95:[.31,.12056,.02778,0,.5],97:[0,.43056,0,0,.5],98:[0,.69444,0,0,.55556],99:[0,.43056,0,0,.44445],100:[0,.69444,0,0,.55556],101:[0,.43056,0,0,.44445],102:[0,.69444,.07778,0,.30556],103:[.19444,.43056,.01389,0,.5],104:[0,.69444,0,0,.55556],105:[0,.66786,0,0,.27778],106:[.19444,.66786,0,0,.30556],107:[0,.69444,0,0,.52778],108:[0,.69444,0,0,.27778],109:[0,.43056,0,0,.83334],110:[0,.43056,0,0,.55556],111:[0,.43056,0,0,.5],112:[.19444,.43056,0,0,.55556],113:[.19444,.43056,0,0,.52778],114:[0,.43056,0,0,.39167],115:[0,.43056,0,0,.39445],116:[0,.61508,0,0,.38889],117:[0,.43056,0,0,.55556],118:[0,.43056,.01389,0,.52778],119:[0,.43056,.01389,0,.72222],120:[0,.43056,0,0,.52778],121:[.19444,.43056,.01389,0,.52778],122:[0,.43056,0,0,.44445],123:[.25,.75,0,0,.5],124:[.25,.75,0,0,.27778],125:[.25,.75,0,0,.5],126:[.35,.31786,0,0,.5],160:[0,0,0,0,.25],163:[0,.69444,0,0,.76909],167:[.19444,.69444,0,0,.44445],168:[0,.66786,0,0,.5],172:[0,.43056,0,0,.66667],176:[0,.69444,0,0,.75],177:[.08333,.58333,0,0,.77778],182:[.19444,.69444,0,0,.61111],184:[.17014,0,0,0,.44445],198:[0,.68333,0,0,.90278],215:[.08333,.58333,0,0,.77778],216:[.04861,.73194,0,0,.77778],223:[0,.69444,0,0,.5],230:[0,.43056,0,0,.72222],247:[.08333,.58333,0,0,.77778],248:[.09722,.52778,0,0,.5],305:[0,.43056,0,0,.27778],338:[0,.68333,0,0,1.01389],339:[0,.43056,0,0,.77778],567:[.19444,.43056,0,0,.30556],710:[0,.69444,0,0,.5],711:[0,.62847,0,0,.5],713:[0,.56778,0,0,.5],714:[0,.69444,0,0,.5],715:[0,.69444,0,0,.5],728:[0,.69444,0,0,.5],729:[0,.66786,0,0,.27778],730:[0,.69444,0,0,.75],732:[0,.66786,0,0,.5],733:[0,.69444,0,0,.5],915:[0,.68333,0,0,.625],916:[0,.68333,0,0,.83334],920:[0,.68333,0,0,.77778],923:[0,.68333,0,0,.69445],926:[0,.68333,0,0,.66667],928:[0,.68333,0,0,.75],931:[0,.68333,0,0,.72222],933:[0,.68333,0,0,.77778],934:[0,.68333,0,0,.72222],936:[0,.68333,0,0,.77778],937:[0,.68333,0,0,.72222],8211:[0,.43056,.02778,0,.5],8212:[0,.43056,.02778,0,1],8216:[0,.69444,0,0,.27778],8217:[0,.69444,0,0,.27778],8220:[0,.69444,0,0,.5],8221:[0,.69444,0,0,.5],8224:[.19444,.69444,0,0,.44445],8225:[.19444,.69444,0,0,.44445],8230:[0,.123,0,0,1.172],8242:[0,.55556,0,0,.275],8407:[0,.71444,.15382,0,.5],8463:[0,.68889,0,0,.54028],8465:[0,.69444,0,0,.72222],8467:[0,.69444,0,.11111,.41667],8472:[.19444,.43056,0,.11111,.63646],8476:[0,.69444,0,0,.72222],8501:[0,.69444,0,0,.61111],8592:[-.13313,.36687,0,0,1],8593:[.19444,.69444,0,0,.5],8594:[-.13313,.36687,0,0,1],8595:[.19444,.69444,0,0,.5],8596:[-.13313,.36687,0,0,1],8597:[.25,.75,0,0,.5],8598:[.19444,.69444,0,0,1],8599:[.19444,.69444,0,0,1],8600:[.19444,.69444,0,0,1],8601:[.19444,.69444,0,0,1],8614:[.011,.511,0,0,1],8617:[.011,.511,0,0,1.126],8618:[.011,.511,0,0,1.126],8636:[-.13313,.36687,0,0,1],8637:[-.13313,.36687,0,0,1],8640:[-.13313,.36687,0,0,1],8641:[-.13313,.36687,0,0,1],8652:[.011,.671,0,0,1],8656:[-.13313,.36687,0,0,1],8657:[.19444,.69444,0,0,.61111],8658:[-.13313,.36687,0,0,1],8659:[.19444,.69444,0,0,.61111],8660:[-.13313,.36687,0,0,1],8661:[.25,.75,0,0,.61111],8704:[0,.69444,0,0,.55556],8706:[0,.69444,.05556,.08334,.5309],8707:[0,.69444,0,0,.55556],8709:[.05556,.75,0,0,.5],8711:[0,.68333,0,0,.83334],8712:[.0391,.5391,0,0,.66667],8715:[.0391,.5391,0,0,.66667],8722:[.08333,.58333,0,0,.77778],8723:[.08333,.58333,0,0,.77778],8725:[.25,.75,0,0,.5],8726:[.25,.75,0,0,.5],8727:[-.03472,.46528,0,0,.5],8728:[-.05555,.44445,0,0,.5],8729:[-.05555,.44445,0,0,.5],8730:[.2,.8,0,0,.83334],8733:[0,.43056,0,0,.77778],8734:[0,.43056,0,0,1],8736:[0,.69224,0,0,.72222],8739:[.25,.75,0,0,.27778],8741:[.25,.75,0,0,.5],8743:[0,.55556,0,0,.66667],8744:[0,.55556,0,0,.66667],8745:[0,.55556,0,0,.66667],8746:[0,.55556,0,0,.66667],8747:[.19444,.69444,.11111,0,.41667],8764:[-.13313,.36687,0,0,.77778],8768:[.19444,.69444,0,0,.27778],8771:[-.03625,.46375,0,0,.77778],8773:[-.022,.589,0,0,.778],8776:[-.01688,.48312,0,0,.77778],8781:[-.03625,.46375,0,0,.77778],8784:[-.133,.673,0,0,.778],8801:[-.03625,.46375,0,0,.77778],8804:[.13597,.63597,0,0,.77778],8805:[.13597,.63597,0,0,.77778],8810:[.0391,.5391,0,0,1],8811:[.0391,.5391,0,0,1],8826:[.0391,.5391,0,0,.77778],8827:[.0391,.5391,0,0,.77778],8834:[.0391,.5391,0,0,.77778],8835:[.0391,.5391,0,0,.77778],8838:[.13597,.63597,0,0,.77778],8839:[.13597,.63597,0,0,.77778],8846:[0,.55556,0,0,.66667],8849:[.13597,.63597,0,0,.77778],8850:[.13597,.63597,0,0,.77778],8851:[0,.55556,0,0,.66667],8852:[0,.55556,0,0,.66667],8853:[.08333,.58333,0,0,.77778],8854:[.08333,.58333,0,0,.77778],8855:[.08333,.58333,0,0,.77778],8856:[.08333,.58333,0,0,.77778],8857:[.08333,.58333,0,0,.77778],8866:[0,.69444,0,0,.61111],8867:[0,.69444,0,0,.61111],8868:[0,.69444,0,0,.77778],8869:[0,.69444,0,0,.77778],8872:[.249,.75,0,0,.867],8900:[-.05555,.44445,0,0,.5],8901:[-.05555,.44445,0,0,.27778],8902:[-.03472,.46528,0,0,.5],8904:[.005,.505,0,0,.9],8942:[.03,.903,0,0,.278],8943:[-.19,.313,0,0,1.172],8945:[-.1,.823,0,0,1.282],8968:[.25,.75,0,0,.44445],8969:[.25,.75,0,0,.44445],8970:[.25,.75,0,0,.44445],8971:[.25,.75,0,0,.44445],8994:[-.14236,.35764,0,0,1],8995:[-.14236,.35764,0,0,1],9136:[.244,.744,0,0,.412],9137:[.244,.745,0,0,.412],9651:[.19444,.69444,0,0,.88889],9657:[-.03472,.46528,0,0,.5],9661:[.19444,.69444,0,0,.88889],9667:[-.03472,.46528,0,0,.5],9711:[.19444,.69444,0,0,1],9824:[.12963,.69444,0,0,.77778],9825:[.12963,.69444,0,0,.77778],9826:[.12963,.69444,0,0,.77778],9827:[.12963,.69444,0,0,.77778],9837:[0,.75,0,0,.38889],9838:[.19444,.69444,0,0,.38889],9839:[.19444,.69444,0,0,.38889],10216:[.25,.75,0,0,.38889],10217:[.25,.75,0,0,.38889],10222:[.244,.744,0,0,.412],10223:[.244,.745,0,0,.412],10229:[.011,.511,0,0,1.609],10230:[.011,.511,0,0,1.638],10231:[.011,.511,0,0,1.859],10232:[.024,.525,0,0,1.609],10233:[.024,.525,0,0,1.638],10234:[.024,.525,0,0,1.858],10236:[.011,.511,0,0,1.638],10815:[0,.68333,0,0,.75],10927:[.13597,.63597,0,0,.77778],10928:[.13597,.63597,0,0,.77778],57376:[.19444,.69444,0,0,0]},"Math-BoldItalic":{32:[0,0,0,0,.25],48:[0,.44444,0,0,.575],49:[0,.44444,0,0,.575],50:[0,.44444,0,0,.575],51:[.19444,.44444,0,0,.575],52:[.19444,.44444,0,0,.575],53:[.19444,.44444,0,0,.575],54:[0,.64444,0,0,.575],55:[.19444,.44444,0,0,.575],56:[0,.64444,0,0,.575],57:[.19444,.44444,0,0,.575],65:[0,.68611,0,0,.86944],66:[0,.68611,.04835,0,.8664],67:[0,.68611,.06979,0,.81694],68:[0,.68611,.03194,0,.93812],69:[0,.68611,.05451,0,.81007],70:[0,.68611,.15972,0,.68889],71:[0,.68611,0,0,.88673],72:[0,.68611,.08229,0,.98229],73:[0,.68611,.07778,0,.51111],74:[0,.68611,.10069,0,.63125],75:[0,.68611,.06979,0,.97118],76:[0,.68611,0,0,.75555],77:[0,.68611,.11424,0,1.14201],78:[0,.68611,.11424,0,.95034],79:[0,.68611,.03194,0,.83666],80:[0,.68611,.15972,0,.72309],81:[.19444,.68611,0,0,.86861],82:[0,.68611,.00421,0,.87235],83:[0,.68611,.05382,0,.69271],84:[0,.68611,.15972,0,.63663],85:[0,.68611,.11424,0,.80027],86:[0,.68611,.25555,0,.67778],87:[0,.68611,.15972,0,1.09305],88:[0,.68611,.07778,0,.94722],89:[0,.68611,.25555,0,.67458],90:[0,.68611,.06979,0,.77257],97:[0,.44444,0,0,.63287],98:[0,.69444,0,0,.52083],99:[0,.44444,0,0,.51342],100:[0,.69444,0,0,.60972],101:[0,.44444,0,0,.55361],102:[.19444,.69444,.11042,0,.56806],103:[.19444,.44444,.03704,0,.5449],104:[0,.69444,0,0,.66759],105:[0,.69326,0,0,.4048],106:[.19444,.69326,.0622,0,.47083],107:[0,.69444,.01852,0,.6037],108:[0,.69444,.0088,0,.34815],109:[0,.44444,0,0,1.0324],110:[0,.44444,0,0,.71296],111:[0,.44444,0,0,.58472],112:[.19444,.44444,0,0,.60092],113:[.19444,.44444,.03704,0,.54213],114:[0,.44444,.03194,0,.5287],115:[0,.44444,0,0,.53125],116:[0,.63492,0,0,.41528],117:[0,.44444,0,0,.68102],118:[0,.44444,.03704,0,.56666],119:[0,.44444,.02778,0,.83148],120:[0,.44444,0,0,.65903],121:[.19444,.44444,.03704,0,.59028],122:[0,.44444,.04213,0,.55509],160:[0,0,0,0,.25],915:[0,.68611,.15972,0,.65694],916:[0,.68611,0,0,.95833],920:[0,.68611,.03194,0,.86722],923:[0,.68611,0,0,.80555],926:[0,.68611,.07458,0,.84125],928:[0,.68611,.08229,0,.98229],931:[0,.68611,.05451,0,.88507],933:[0,.68611,.15972,0,.67083],934:[0,.68611,0,0,.76666],936:[0,.68611,.11653,0,.71402],937:[0,.68611,.04835,0,.8789],945:[0,.44444,0,0,.76064],946:[.19444,.69444,.03403,0,.65972],947:[.19444,.44444,.06389,0,.59003],948:[0,.69444,.03819,0,.52222],949:[0,.44444,0,0,.52882],950:[.19444,.69444,.06215,0,.50833],951:[.19444,.44444,.03704,0,.6],952:[0,.69444,.03194,0,.5618],953:[0,.44444,0,0,.41204],954:[0,.44444,0,0,.66759],955:[0,.69444,0,0,.67083],956:[.19444,.44444,0,0,.70787],957:[0,.44444,.06898,0,.57685],958:[.19444,.69444,.03021,0,.50833],959:[0,.44444,0,0,.58472],960:[0,.44444,.03704,0,.68241],961:[.19444,.44444,0,0,.6118],962:[.09722,.44444,.07917,0,.42361],963:[0,.44444,.03704,0,.68588],964:[0,.44444,.13472,0,.52083],965:[0,.44444,.03704,0,.63055],966:[.19444,.44444,0,0,.74722],967:[.19444,.44444,0,0,.71805],968:[.19444,.69444,.03704,0,.75833],969:[0,.44444,.03704,0,.71782],977:[0,.69444,0,0,.69155],981:[.19444,.69444,0,0,.7125],982:[0,.44444,.03194,0,.975],1009:[.19444,.44444,0,0,.6118],1013:[0,.44444,0,0,.48333],57649:[0,.44444,0,0,.39352],57911:[.19444,.44444,0,0,.43889]},"Math-Italic":{32:[0,0,0,0,.25],48:[0,.43056,0,0,.5],49:[0,.43056,0,0,.5],50:[0,.43056,0,0,.5],51:[.19444,.43056,0,0,.5],52:[.19444,.43056,0,0,.5],53:[.19444,.43056,0,0,.5],54:[0,.64444,0,0,.5],55:[.19444,.43056,0,0,.5],56:[0,.64444,0,0,.5],57:[.19444,.43056,0,0,.5],65:[0,.68333,0,.13889,.75],66:[0,.68333,.05017,.08334,.75851],67:[0,.68333,.07153,.08334,.71472],68:[0,.68333,.02778,.05556,.82792],69:[0,.68333,.05764,.08334,.7382],70:[0,.68333,.13889,.08334,.64306],71:[0,.68333,0,.08334,.78625],72:[0,.68333,.08125,.05556,.83125],73:[0,.68333,.07847,.11111,.43958],74:[0,.68333,.09618,.16667,.55451],75:[0,.68333,.07153,.05556,.84931],76:[0,.68333,0,.02778,.68056],77:[0,.68333,.10903,.08334,.97014],78:[0,.68333,.10903,.08334,.80347],79:[0,.68333,.02778,.08334,.76278],80:[0,.68333,.13889,.08334,.64201],81:[.19444,.68333,0,.08334,.79056],82:[0,.68333,.00773,.08334,.75929],83:[0,.68333,.05764,.08334,.6132],84:[0,.68333,.13889,.08334,.58438],85:[0,.68333,.10903,.02778,.68278],86:[0,.68333,.22222,0,.58333],87:[0,.68333,.13889,0,.94445],88:[0,.68333,.07847,.08334,.82847],89:[0,.68333,.22222,0,.58056],90:[0,.68333,.07153,.08334,.68264],97:[0,.43056,0,0,.52859],98:[0,.69444,0,0,.42917],99:[0,.43056,0,.05556,.43276],100:[0,.69444,0,.16667,.52049],101:[0,.43056,0,.05556,.46563],102:[.19444,.69444,.10764,.16667,.48959],103:[.19444,.43056,.03588,.02778,.47697],104:[0,.69444,0,0,.57616],105:[0,.65952,0,0,.34451],106:[.19444,.65952,.05724,0,.41181],107:[0,.69444,.03148,0,.5206],108:[0,.69444,.01968,.08334,.29838],109:[0,.43056,0,0,.87801],110:[0,.43056,0,0,.60023],111:[0,.43056,0,.05556,.48472],112:[.19444,.43056,0,.08334,.50313],113:[.19444,.43056,.03588,.08334,.44641],114:[0,.43056,.02778,.05556,.45116],115:[0,.43056,0,.05556,.46875],116:[0,.61508,0,.08334,.36111],117:[0,.43056,0,.02778,.57246],118:[0,.43056,.03588,.02778,.48472],119:[0,.43056,.02691,.08334,.71592],120:[0,.43056,0,.02778,.57153],121:[.19444,.43056,.03588,.05556,.49028],122:[0,.43056,.04398,.05556,.46505],160:[0,0,0,0,.25],915:[0,.68333,.13889,.08334,.61528],916:[0,.68333,0,.16667,.83334],920:[0,.68333,.02778,.08334,.76278],923:[0,.68333,0,.16667,.69445],926:[0,.68333,.07569,.08334,.74236],928:[0,.68333,.08125,.05556,.83125],931:[0,.68333,.05764,.08334,.77986],933:[0,.68333,.13889,.05556,.58333],934:[0,.68333,0,.08334,.66667],936:[0,.68333,.11,.05556,.61222],937:[0,.68333,.05017,.08334,.7724],945:[0,.43056,.0037,.02778,.6397],946:[.19444,.69444,.05278,.08334,.56563],947:[.19444,.43056,.05556,0,.51773],948:[0,.69444,.03785,.05556,.44444],949:[0,.43056,0,.08334,.46632],950:[.19444,.69444,.07378,.08334,.4375],951:[.19444,.43056,.03588,.05556,.49653],952:[0,.69444,.02778,.08334,.46944],953:[0,.43056,0,.05556,.35394],954:[0,.43056,0,0,.57616],955:[0,.69444,0,0,.58334],956:[.19444,.43056,0,.02778,.60255],957:[0,.43056,.06366,.02778,.49398],958:[.19444,.69444,.04601,.11111,.4375],959:[0,.43056,0,.05556,.48472],960:[0,.43056,.03588,0,.57003],961:[.19444,.43056,0,.08334,.51702],962:[.09722,.43056,.07986,.08334,.36285],963:[0,.43056,.03588,0,.57141],964:[0,.43056,.1132,.02778,.43715],965:[0,.43056,.03588,.02778,.54028],966:[.19444,.43056,0,.08334,.65417],967:[.19444,.43056,0,.05556,.62569],968:[.19444,.69444,.03588,.11111,.65139],969:[0,.43056,.03588,0,.62245],977:[0,.69444,0,.08334,.59144],981:[.19444,.69444,0,.08334,.59583],982:[0,.43056,.02778,0,.82813],1009:[.19444,.43056,0,.08334,.51702],1013:[0,.43056,0,.05556,.4059],57649:[0,.43056,0,.02778,.32246],57911:[.19444,.43056,0,.08334,.38403]},"SansSerif-Bold":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.36667],34:[0,.69444,0,0,.55834],35:[.19444,.69444,0,0,.91667],36:[.05556,.75,0,0,.55],37:[.05556,.75,0,0,1.02912],38:[0,.69444,0,0,.83056],39:[0,.69444,0,0,.30556],40:[.25,.75,0,0,.42778],41:[.25,.75,0,0,.42778],42:[0,.75,0,0,.55],43:[.11667,.61667,0,0,.85556],44:[.10556,.13056,0,0,.30556],45:[0,.45833,0,0,.36667],46:[0,.13056,0,0,.30556],47:[.25,.75,0,0,.55],48:[0,.69444,0,0,.55],49:[0,.69444,0,0,.55],50:[0,.69444,0,0,.55],51:[0,.69444,0,0,.55],52:[0,.69444,0,0,.55],53:[0,.69444,0,0,.55],54:[0,.69444,0,0,.55],55:[0,.69444,0,0,.55],56:[0,.69444,0,0,.55],57:[0,.69444,0,0,.55],58:[0,.45833,0,0,.30556],59:[.10556,.45833,0,0,.30556],61:[-.09375,.40625,0,0,.85556],63:[0,.69444,0,0,.51945],64:[0,.69444,0,0,.73334],65:[0,.69444,0,0,.73334],66:[0,.69444,0,0,.73334],67:[0,.69444,0,0,.70278],68:[0,.69444,0,0,.79445],69:[0,.69444,0,0,.64167],70:[0,.69444,0,0,.61111],71:[0,.69444,0,0,.73334],72:[0,.69444,0,0,.79445],73:[0,.69444,0,0,.33056],74:[0,.69444,0,0,.51945],75:[0,.69444,0,0,.76389],76:[0,.69444,0,0,.58056],77:[0,.69444,0,0,.97778],78:[0,.69444,0,0,.79445],79:[0,.69444,0,0,.79445],80:[0,.69444,0,0,.70278],81:[.10556,.69444,0,0,.79445],82:[0,.69444,0,0,.70278],83:[0,.69444,0,0,.61111],84:[0,.69444,0,0,.73334],85:[0,.69444,0,0,.76389],86:[0,.69444,.01528,0,.73334],87:[0,.69444,.01528,0,1.03889],88:[0,.69444,0,0,.73334],89:[0,.69444,.0275,0,.73334],90:[0,.69444,0,0,.67223],91:[.25,.75,0,0,.34306],93:[.25,.75,0,0,.34306],94:[0,.69444,0,0,.55],95:[.35,.10833,.03056,0,.55],97:[0,.45833,0,0,.525],98:[0,.69444,0,0,.56111],99:[0,.45833,0,0,.48889],100:[0,.69444,0,0,.56111],101:[0,.45833,0,0,.51111],102:[0,.69444,.07639,0,.33611],103:[.19444,.45833,.01528,0,.55],104:[0,.69444,0,0,.56111],105:[0,.69444,0,0,.25556],106:[.19444,.69444,0,0,.28611],107:[0,.69444,0,0,.53056],108:[0,.69444,0,0,.25556],109:[0,.45833,0,0,.86667],110:[0,.45833,0,0,.56111],111:[0,.45833,0,0,.55],112:[.19444,.45833,0,0,.56111],113:[.19444,.45833,0,0,.56111],114:[0,.45833,.01528,0,.37222],115:[0,.45833,0,0,.42167],116:[0,.58929,0,0,.40417],117:[0,.45833,0,0,.56111],118:[0,.45833,.01528,0,.5],119:[0,.45833,.01528,0,.74445],120:[0,.45833,0,0,.5],121:[.19444,.45833,.01528,0,.5],122:[0,.45833,0,0,.47639],126:[.35,.34444,0,0,.55],160:[0,0,0,0,.25],168:[0,.69444,0,0,.55],176:[0,.69444,0,0,.73334],180:[0,.69444,0,0,.55],184:[.17014,0,0,0,.48889],305:[0,.45833,0,0,.25556],567:[.19444,.45833,0,0,.28611],710:[0,.69444,0,0,.55],711:[0,.63542,0,0,.55],713:[0,.63778,0,0,.55],728:[0,.69444,0,0,.55],729:[0,.69444,0,0,.30556],730:[0,.69444,0,0,.73334],732:[0,.69444,0,0,.55],733:[0,.69444,0,0,.55],915:[0,.69444,0,0,.58056],916:[0,.69444,0,0,.91667],920:[0,.69444,0,0,.85556],923:[0,.69444,0,0,.67223],926:[0,.69444,0,0,.73334],928:[0,.69444,0,0,.79445],931:[0,.69444,0,0,.79445],933:[0,.69444,0,0,.85556],934:[0,.69444,0,0,.79445],936:[0,.69444,0,0,.85556],937:[0,.69444,0,0,.79445],8211:[0,.45833,.03056,0,.55],8212:[0,.45833,.03056,0,1.10001],8216:[0,.69444,0,0,.30556],8217:[0,.69444,0,0,.30556],8220:[0,.69444,0,0,.55834],8221:[0,.69444,0,0,.55834]},"SansSerif-Italic":{32:[0,0,0,0,.25],33:[0,.69444,.05733,0,.31945],34:[0,.69444,.00316,0,.5],35:[.19444,.69444,.05087,0,.83334],36:[.05556,.75,.11156,0,.5],37:[.05556,.75,.03126,0,.83334],38:[0,.69444,.03058,0,.75834],39:[0,.69444,.07816,0,.27778],40:[.25,.75,.13164,0,.38889],41:[.25,.75,.02536,0,.38889],42:[0,.75,.11775,0,.5],43:[.08333,.58333,.02536,0,.77778],44:[.125,.08333,0,0,.27778],45:[0,.44444,.01946,0,.33333],46:[0,.08333,0,0,.27778],47:[.25,.75,.13164,0,.5],48:[0,.65556,.11156,0,.5],49:[0,.65556,.11156,0,.5],50:[0,.65556,.11156,0,.5],51:[0,.65556,.11156,0,.5],52:[0,.65556,.11156,0,.5],53:[0,.65556,.11156,0,.5],54:[0,.65556,.11156,0,.5],55:[0,.65556,.11156,0,.5],56:[0,.65556,.11156,0,.5],57:[0,.65556,.11156,0,.5],58:[0,.44444,.02502,0,.27778],59:[.125,.44444,.02502,0,.27778],61:[-.13,.37,.05087,0,.77778],63:[0,.69444,.11809,0,.47222],64:[0,.69444,.07555,0,.66667],65:[0,.69444,0,0,.66667],66:[0,.69444,.08293,0,.66667],67:[0,.69444,.11983,0,.63889],68:[0,.69444,.07555,0,.72223],69:[0,.69444,.11983,0,.59722],70:[0,.69444,.13372,0,.56945],71:[0,.69444,.11983,0,.66667],72:[0,.69444,.08094,0,.70834],73:[0,.69444,.13372,0,.27778],74:[0,.69444,.08094,0,.47222],75:[0,.69444,.11983,0,.69445],76:[0,.69444,0,0,.54167],77:[0,.69444,.08094,0,.875],78:[0,.69444,.08094,0,.70834],79:[0,.69444,.07555,0,.73611],80:[0,.69444,.08293,0,.63889],81:[.125,.69444,.07555,0,.73611],82:[0,.69444,.08293,0,.64584],83:[0,.69444,.09205,0,.55556],84:[0,.69444,.13372,0,.68056],85:[0,.69444,.08094,0,.6875],86:[0,.69444,.1615,0,.66667],87:[0,.69444,.1615,0,.94445],88:[0,.69444,.13372,0,.66667],89:[0,.69444,.17261,0,.66667],90:[0,.69444,.11983,0,.61111],91:[.25,.75,.15942,0,.28889],93:[.25,.75,.08719,0,.28889],94:[0,.69444,.0799,0,.5],95:[.35,.09444,.08616,0,.5],97:[0,.44444,.00981,0,.48056],98:[0,.69444,.03057,0,.51667],99:[0,.44444,.08336,0,.44445],100:[0,.69444,.09483,0,.51667],101:[0,.44444,.06778,0,.44445],102:[0,.69444,.21705,0,.30556],103:[.19444,.44444,.10836,0,.5],104:[0,.69444,.01778,0,.51667],105:[0,.67937,.09718,0,.23889],106:[.19444,.67937,.09162,0,.26667],107:[0,.69444,.08336,0,.48889],108:[0,.69444,.09483,0,.23889],109:[0,.44444,.01778,0,.79445],110:[0,.44444,.01778,0,.51667],111:[0,.44444,.06613,0,.5],112:[.19444,.44444,.0389,0,.51667],113:[.19444,.44444,.04169,0,.51667],114:[0,.44444,.10836,0,.34167],115:[0,.44444,.0778,0,.38333],116:[0,.57143,.07225,0,.36111],117:[0,.44444,.04169,0,.51667],118:[0,.44444,.10836,0,.46111],119:[0,.44444,.10836,0,.68334],120:[0,.44444,.09169,0,.46111],121:[.19444,.44444,.10836,0,.46111],122:[0,.44444,.08752,0,.43472],126:[.35,.32659,.08826,0,.5],160:[0,0,0,0,.25],168:[0,.67937,.06385,0,.5],176:[0,.69444,0,0,.73752],184:[.17014,0,0,0,.44445],305:[0,.44444,.04169,0,.23889],567:[.19444,.44444,.04169,0,.26667],710:[0,.69444,.0799,0,.5],711:[0,.63194,.08432,0,.5],713:[0,.60889,.08776,0,.5],714:[0,.69444,.09205,0,.5],715:[0,.69444,0,0,.5],728:[0,.69444,.09483,0,.5],729:[0,.67937,.07774,0,.27778],730:[0,.69444,0,0,.73752],732:[0,.67659,.08826,0,.5],733:[0,.69444,.09205,0,.5],915:[0,.69444,.13372,0,.54167],916:[0,.69444,0,0,.83334],920:[0,.69444,.07555,0,.77778],923:[0,.69444,0,0,.61111],926:[0,.69444,.12816,0,.66667],928:[0,.69444,.08094,0,.70834],931:[0,.69444,.11983,0,.72222],933:[0,.69444,.09031,0,.77778],934:[0,.69444,.04603,0,.72222],936:[0,.69444,.09031,0,.77778],937:[0,.69444,.08293,0,.72222],8211:[0,.44444,.08616,0,.5],8212:[0,.44444,.08616,0,1],8216:[0,.69444,.07816,0,.27778],8217:[0,.69444,.07816,0,.27778],8220:[0,.69444,.14205,0,.5],8221:[0,.69444,.00316,0,.5]},"SansSerif-Regular":{32:[0,0,0,0,.25],33:[0,.69444,0,0,.31945],34:[0,.69444,0,0,.5],35:[.19444,.69444,0,0,.83334],36:[.05556,.75,0,0,.5],37:[.05556,.75,0,0,.83334],38:[0,.69444,0,0,.75834],39:[0,.69444,0,0,.27778],40:[.25,.75,0,0,.38889],41:[.25,.75,0,0,.38889],42:[0,.75,0,0,.5],43:[.08333,.58333,0,0,.77778],44:[.125,.08333,0,0,.27778],45:[0,.44444,0,0,.33333],46:[0,.08333,0,0,.27778],47:[.25,.75,0,0,.5],48:[0,.65556,0,0,.5],49:[0,.65556,0,0,.5],50:[0,.65556,0,0,.5],51:[0,.65556,0,0,.5],52:[0,.65556,0,0,.5],53:[0,.65556,0,0,.5],54:[0,.65556,0,0,.5],55:[0,.65556,0,0,.5],56:[0,.65556,0,0,.5],57:[0,.65556,0,0,.5],58:[0,.44444,0,0,.27778],59:[.125,.44444,0,0,.27778],61:[-.13,.37,0,0,.77778],63:[0,.69444,0,0,.47222],64:[0,.69444,0,0,.66667],65:[0,.69444,0,0,.66667],66:[0,.69444,0,0,.66667],67:[0,.69444,0,0,.63889],68:[0,.69444,0,0,.72223],69:[0,.69444,0,0,.59722],70:[0,.69444,0,0,.56945],71:[0,.69444,0,0,.66667],72:[0,.69444,0,0,.70834],73:[0,.69444,0,0,.27778],74:[0,.69444,0,0,.47222],75:[0,.69444,0,0,.69445],76:[0,.69444,0,0,.54167],77:[0,.69444,0,0,.875],78:[0,.69444,0,0,.70834],79:[0,.69444,0,0,.73611],80:[0,.69444,0,0,.63889],81:[.125,.69444,0,0,.73611],82:[0,.69444,0,0,.64584],83:[0,.69444,0,0,.55556],84:[0,.69444,0,0,.68056],85:[0,.69444,0,0,.6875],86:[0,.69444,.01389,0,.66667],87:[0,.69444,.01389,0,.94445],88:[0,.69444,0,0,.66667],89:[0,.69444,.025,0,.66667],90:[0,.69444,0,0,.61111],91:[.25,.75,0,0,.28889],93:[.25,.75,0,0,.28889],94:[0,.69444,0,0,.5],95:[.35,.09444,.02778,0,.5],97:[0,.44444,0,0,.48056],98:[0,.69444,0,0,.51667],99:[0,.44444,0,0,.44445],100:[0,.69444,0,0,.51667],101:[0,.44444,0,0,.44445],102:[0,.69444,.06944,0,.30556],103:[.19444,.44444,.01389,0,.5],104:[0,.69444,0,0,.51667],105:[0,.67937,0,0,.23889],106:[.19444,.67937,0,0,.26667],107:[0,.69444,0,0,.48889],108:[0,.69444,0,0,.23889],109:[0,.44444,0,0,.79445],110:[0,.44444,0,0,.51667],111:[0,.44444,0,0,.5],112:[.19444,.44444,0,0,.51667],113:[.19444,.44444,0,0,.51667],114:[0,.44444,.01389,0,.34167],115:[0,.44444,0,0,.38333],116:[0,.57143,0,0,.36111],117:[0,.44444,0,0,.51667],118:[0,.44444,.01389,0,.46111],119:[0,.44444,.01389,0,.68334],120:[0,.44444,0,0,.46111],121:[.19444,.44444,.01389,0,.46111],122:[0,.44444,0,0,.43472],126:[.35,.32659,0,0,.5],160:[0,0,0,0,.25],168:[0,.67937,0,0,.5],176:[0,.69444,0,0,.66667],184:[.17014,0,0,0,.44445],305:[0,.44444,0,0,.23889],567:[.19444,.44444,0,0,.26667],710:[0,.69444,0,0,.5],711:[0,.63194,0,0,.5],713:[0,.60889,0,0,.5],714:[0,.69444,0,0,.5],715:[0,.69444,0,0,.5],728:[0,.69444,0,0,.5],729:[0,.67937,0,0,.27778],730:[0,.69444,0,0,.66667],732:[0,.67659,0,0,.5],733:[0,.69444,0,0,.5],915:[0,.69444,0,0,.54167],916:[0,.69444,0,0,.83334],920:[0,.69444,0,0,.77778],923:[0,.69444,0,0,.61111],926:[0,.69444,0,0,.66667],928:[0,.69444,0,0,.70834],931:[0,.69444,0,0,.72222],933:[0,.69444,0,0,.77778],934:[0,.69444,0,0,.72222],936:[0,.69444,0,0,.77778],937:[0,.69444,0,0,.72222],8211:[0,.44444,.02778,0,.5],8212:[0,.44444,.02778,0,1],8216:[0,.69444,0,0,.27778],8217:[0,.69444,0,0,.27778],8220:[0,.69444,0,0,.5],8221:[0,.69444,0,0,.5]},"Script-Regular":{32:[0,0,0,0,.25],65:[0,.7,.22925,0,.80253],66:[0,.7,.04087,0,.90757],67:[0,.7,.1689,0,.66619],68:[0,.7,.09371,0,.77443],69:[0,.7,.18583,0,.56162],70:[0,.7,.13634,0,.89544],71:[0,.7,.17322,0,.60961],72:[0,.7,.29694,0,.96919],73:[0,.7,.19189,0,.80907],74:[.27778,.7,.19189,0,1.05159],75:[0,.7,.31259,0,.91364],76:[0,.7,.19189,0,.87373],77:[0,.7,.15981,0,1.08031],78:[0,.7,.3525,0,.9015],79:[0,.7,.08078,0,.73787],80:[0,.7,.08078,0,1.01262],81:[0,.7,.03305,0,.88282],82:[0,.7,.06259,0,.85],83:[0,.7,.19189,0,.86767],84:[0,.7,.29087,0,.74697],85:[0,.7,.25815,0,.79996],86:[0,.7,.27523,0,.62204],87:[0,.7,.27523,0,.80532],88:[0,.7,.26006,0,.94445],89:[0,.7,.2939,0,.70961],90:[0,.7,.24037,0,.8212],160:[0,0,0,0,.25]},"Size1-Regular":{32:[0,0,0,0,.25],40:[.35001,.85,0,0,.45834],41:[.35001,.85,0,0,.45834],47:[.35001,.85,0,0,.57778],91:[.35001,.85,0,0,.41667],92:[.35001,.85,0,0,.57778],93:[.35001,.85,0,0,.41667],123:[.35001,.85,0,0,.58334],125:[.35001,.85,0,0,.58334],160:[0,0,0,0,.25],710:[0,.72222,0,0,.55556],732:[0,.72222,0,0,.55556],770:[0,.72222,0,0,.55556],771:[0,.72222,0,0,.55556],8214:[-99e-5,.601,0,0,.77778],8593:[1e-5,.6,0,0,.66667],8595:[1e-5,.6,0,0,.66667],8657:[1e-5,.6,0,0,.77778],8659:[1e-5,.6,0,0,.77778],8719:[.25001,.75,0,0,.94445],8720:[.25001,.75,0,0,.94445],8721:[.25001,.75,0,0,1.05556],8730:[.35001,.85,0,0,1],8739:[-.00599,.606,0,0,.33333],8741:[-.00599,.606,0,0,.55556],8747:[.30612,.805,.19445,0,.47222],8748:[.306,.805,.19445,0,.47222],8749:[.306,.805,.19445,0,.47222],8750:[.30612,.805,.19445,0,.47222],8896:[.25001,.75,0,0,.83334],8897:[.25001,.75,0,0,.83334],8898:[.25001,.75,0,0,.83334],8899:[.25001,.75,0,0,.83334],8968:[.35001,.85,0,0,.47222],8969:[.35001,.85,0,0,.47222],8970:[.35001,.85,0,0,.47222],8971:[.35001,.85,0,0,.47222],9168:[-99e-5,.601,0,0,.66667],10216:[.35001,.85,0,0,.47222],10217:[.35001,.85,0,0,.47222],10752:[.25001,.75,0,0,1.11111],10753:[.25001,.75,0,0,1.11111],10754:[.25001,.75,0,0,1.11111],10756:[.25001,.75,0,0,.83334],10758:[.25001,.75,0,0,.83334]},"Size2-Regular":{32:[0,0,0,0,.25],40:[.65002,1.15,0,0,.59722],41:[.65002,1.15,0,0,.59722],47:[.65002,1.15,0,0,.81111],91:[.65002,1.15,0,0,.47222],92:[.65002,1.15,0,0,.81111],93:[.65002,1.15,0,0,.47222],123:[.65002,1.15,0,0,.66667],125:[.65002,1.15,0,0,.66667],160:[0,0,0,0,.25],710:[0,.75,0,0,1],732:[0,.75,0,0,1],770:[0,.75,0,0,1],771:[0,.75,0,0,1],8719:[.55001,1.05,0,0,1.27778],8720:[.55001,1.05,0,0,1.27778],8721:[.55001,1.05,0,0,1.44445],8730:[.65002,1.15,0,0,1],8747:[.86225,1.36,.44445,0,.55556],8748:[.862,1.36,.44445,0,.55556],8749:[.862,1.36,.44445,0,.55556],8750:[.86225,1.36,.44445,0,.55556],8896:[.55001,1.05,0,0,1.11111],8897:[.55001,1.05,0,0,1.11111],8898:[.55001,1.05,0,0,1.11111],8899:[.55001,1.05,0,0,1.11111],8968:[.65002,1.15,0,0,.52778],8969:[.65002,1.15,0,0,.52778],8970:[.65002,1.15,0,0,.52778],8971:[.65002,1.15,0,0,.52778],10216:[.65002,1.15,0,0,.61111],10217:[.65002,1.15,0,0,.61111],10752:[.55001,1.05,0,0,1.51112],10753:[.55001,1.05,0,0,1.51112],10754:[.55001,1.05,0,0,1.51112],10756:[.55001,1.05,0,0,1.11111],10758:[.55001,1.05,0,0,1.11111]},"Size3-Regular":{32:[0,0,0,0,.25],40:[.95003,1.45,0,0,.73611],41:[.95003,1.45,0,0,.73611],47:[.95003,1.45,0,0,1.04445],91:[.95003,1.45,0,0,.52778],92:[.95003,1.45,0,0,1.04445],93:[.95003,1.45,0,0,.52778],123:[.95003,1.45,0,0,.75],125:[.95003,1.45,0,0,.75],160:[0,0,0,0,.25],710:[0,.75,0,0,1.44445],732:[0,.75,0,0,1.44445],770:[0,.75,0,0,1.44445],771:[0,.75,0,0,1.44445],8730:[.95003,1.45,0,0,1],8968:[.95003,1.45,0,0,.58334],8969:[.95003,1.45,0,0,.58334],8970:[.95003,1.45,0,0,.58334],8971:[.95003,1.45,0,0,.58334],10216:[.95003,1.45,0,0,.75],10217:[.95003,1.45,0,0,.75]},"Size4-Regular":{32:[0,0,0,0,.25],40:[1.25003,1.75,0,0,.79167],41:[1.25003,1.75,0,0,.79167],47:[1.25003,1.75,0,0,1.27778],91:[1.25003,1.75,0,0,.58334],92:[1.25003,1.75,0,0,1.27778],93:[1.25003,1.75,0,0,.58334],123:[1.25003,1.75,0,0,.80556],125:[1.25003,1.75,0,0,.80556],160:[0,0,0,0,.25],710:[0,.825,0,0,1.8889],732:[0,.825,0,0,1.8889],770:[0,.825,0,0,1.8889],771:[0,.825,0,0,1.8889],8730:[1.25003,1.75,0,0,1],8968:[1.25003,1.75,0,0,.63889],8969:[1.25003,1.75,0,0,.63889],8970:[1.25003,1.75,0,0,.63889],8971:[1.25003,1.75,0,0,.63889],9115:[.64502,1.155,0,0,.875],9116:[1e-5,.6,0,0,.875],9117:[.64502,1.155,0,0,.875],9118:[.64502,1.155,0,0,.875],9119:[1e-5,.6,0,0,.875],9120:[.64502,1.155,0,0,.875],9121:[.64502,1.155,0,0,.66667],9122:[-99e-5,.601,0,0,.66667],9123:[.64502,1.155,0,0,.66667],9124:[.64502,1.155,0,0,.66667],9125:[-99e-5,.601,0,0,.66667],9126:[.64502,1.155,0,0,.66667],9127:[1e-5,.9,0,0,.88889],9128:[.65002,1.15,0,0,.88889],9129:[.90001,0,0,0,.88889],9130:[0,.3,0,0,.88889],9131:[1e-5,.9,0,0,.88889],9132:[.65002,1.15,0,0,.88889],9133:[.90001,0,0,0,.88889],9143:[.88502,.915,0,0,1.05556],10216:[1.25003,1.75,0,0,.80556],10217:[1.25003,1.75,0,0,.80556],57344:[-.00499,.605,0,0,1.05556],57345:[-.00499,.605,0,0,1.05556],57680:[0,.12,0,0,.45],57681:[0,.12,0,0,.45],57682:[0,.12,0,0,.45],57683:[0,.12,0,0,.45]},"Typewriter-Regular":{32:[0,0,0,0,.525],33:[0,.61111,0,0,.525],34:[0,.61111,0,0,.525],35:[0,.61111,0,0,.525],36:[.08333,.69444,0,0,.525],37:[.08333,.69444,0,0,.525],38:[0,.61111,0,0,.525],39:[0,.61111,0,0,.525],40:[.08333,.69444,0,0,.525],41:[.08333,.69444,0,0,.525],42:[0,.52083,0,0,.525],43:[-.08056,.53055,0,0,.525],44:[.13889,.125,0,0,.525],45:[-.08056,.53055,0,0,.525],46:[0,.125,0,0,.525],47:[.08333,.69444,0,0,.525],48:[0,.61111,0,0,.525],49:[0,.61111,0,0,.525],50:[0,.61111,0,0,.525],51:[0,.61111,0,0,.525],52:[0,.61111,0,0,.525],53:[0,.61111,0,0,.525],54:[0,.61111,0,0,.525],55:[0,.61111,0,0,.525],56:[0,.61111,0,0,.525],57:[0,.61111,0,0,.525],58:[0,.43056,0,0,.525],59:[.13889,.43056,0,0,.525],60:[-.05556,.55556,0,0,.525],61:[-.19549,.41562,0,0,.525],62:[-.05556,.55556,0,0,.525],63:[0,.61111,0,0,.525],64:[0,.61111,0,0,.525],65:[0,.61111,0,0,.525],66:[0,.61111,0,0,.525],67:[0,.61111,0,0,.525],68:[0,.61111,0,0,.525],69:[0,.61111,0,0,.525],70:[0,.61111,0,0,.525],71:[0,.61111,0,0,.525],72:[0,.61111,0,0,.525],73:[0,.61111,0,0,.525],74:[0,.61111,0,0,.525],75:[0,.61111,0,0,.525],76:[0,.61111,0,0,.525],77:[0,.61111,0,0,.525],78:[0,.61111,0,0,.525],79:[0,.61111,0,0,.525],80:[0,.61111,0,0,.525],81:[.13889,.61111,0,0,.525],82:[0,.61111,0,0,.525],83:[0,.61111,0,0,.525],84:[0,.61111,0,0,.525],85:[0,.61111,0,0,.525],86:[0,.61111,0,0,.525],87:[0,.61111,0,0,.525],88:[0,.61111,0,0,.525],89:[0,.61111,0,0,.525],90:[0,.61111,0,0,.525],91:[.08333,.69444,0,0,.525],92:[.08333,.69444,0,0,.525],93:[.08333,.69444,0,0,.525],94:[0,.61111,0,0,.525],95:[.09514,0,0,0,.525],96:[0,.61111,0,0,.525],97:[0,.43056,0,0,.525],98:[0,.61111,0,0,.525],99:[0,.43056,0,0,.525],100:[0,.61111,0,0,.525],101:[0,.43056,0,0,.525],102:[0,.61111,0,0,.525],103:[.22222,.43056,0,0,.525],104:[0,.61111,0,0,.525],105:[0,.61111,0,0,.525],106:[.22222,.61111,0,0,.525],107:[0,.61111,0,0,.525],108:[0,.61111,0,0,.525],109:[0,.43056,0,0,.525],110:[0,.43056,0,0,.525],111:[0,.43056,0,0,.525],112:[.22222,.43056,0,0,.525],113:[.22222,.43056,0,0,.525],114:[0,.43056,0,0,.525],115:[0,.43056,0,0,.525],116:[0,.55358,0,0,.525],117:[0,.43056,0,0,.525],118:[0,.43056,0,0,.525],119:[0,.43056,0,0,.525],120:[0,.43056,0,0,.525],121:[.22222,.43056,0,0,.525],122:[0,.43056,0,0,.525],123:[.08333,.69444,0,0,.525],124:[.08333,.69444,0,0,.525],125:[.08333,.69444,0,0,.525],126:[0,.61111,0,0,.525],127:[0,.61111,0,0,.525],160:[0,0,0,0,.525],176:[0,.61111,0,0,.525],184:[.19445,0,0,0,.525],305:[0,.43056,0,0,.525],567:[.22222,.43056,0,0,.525],711:[0,.56597,0,0,.525],713:[0,.56555,0,0,.525],714:[0,.61111,0,0,.525],715:[0,.61111,0,0,.525],728:[0,.61111,0,0,.525],730:[0,.61111,0,0,.525],770:[0,.61111,0,0,.525],771:[0,.61111,0,0,.525],776:[0,.61111,0,0,.525],915:[0,.61111,0,0,.525],916:[0,.61111,0,0,.525],920:[0,.61111,0,0,.525],923:[0,.61111,0,0,.525],926:[0,.61111,0,0,.525],928:[0,.61111,0,0,.525],931:[0,.61111,0,0,.525],933:[0,.61111,0,0,.525],934:[0,.61111,0,0,.525],936:[0,.61111,0,0,.525],937:[0,.61111,0,0,.525],8216:[0,.61111,0,0,.525],8217:[0,.61111,0,0,.525],8242:[0,.61111,0,0,.525],9251:[.11111,.21944,0,0,.525]}},C4={slant:[.25,.25,.25],space:[0,0,0],stretch:[0,0,0],shrink:[0,0,0],xHeight:[.431,.431,.431],quad:[1,1.171,1.472],extraSpace:[0,0,0],num1:[.677,.732,.925],num2:[.394,.384,.387],num3:[.444,.471,.504],denom1:[.686,.752,1.025],denom2:[.345,.344,.532],sup1:[.413,.503,.504],sup2:[.363,.431,.404],sup3:[.289,.286,.294],sub1:[.15,.143,.2],sub2:[.247,.286,.4],supDrop:[.386,.353,.494],subDrop:[.05,.071,.1],delim1:[2.39,1.7,1.98],delim2:[1.01,1.157,1.42],axisHeight:[.25,.25,.25],defaultRuleThickness:[.04,.049,.049],bigOpSpacing1:[.111,.111,.111],bigOpSpacing2:[.166,.166,.166],bigOpSpacing3:[.2,.2,.2],bigOpSpacing4:[.6,.611,.611],bigOpSpacing5:[.1,.143,.143],sqrtRuleThickness:[.04,.04,.04],ptPerEm:[10,10,10],doubleRuleSep:[.2,.2,.2],arrayRuleWidth:[.04,.04,.04],fboxsep:[.3,.3,.3],fboxrule:[.04,.04,.04]},sX={\u00C5:"A",\u00D0:"D",\u00DE:"o",\u00E5:"a",\u00F0:"d",\u00FE:"o",\u0410:"A",\u0411:"B",\u0412:"B",\u0413:"F",\u0414:"A",\u0415:"E",\u0416:"K",\u0417:"3",\u0418:"N",\u0419:"N",\u041A:"K",\u041B:"N",\u041C:"M",\u041D:"H",\u041E:"O",\u041F:"N",\u0420:"P",\u0421:"C",\u0422:"T",\u0423:"y",\u0424:"O",\u0425:"X",\u0426:"U",\u0427:"h",\u0428:"W",\u0429:"W",\u042A:"B",\u042B:"X",\u042C:"B",\u042D:"3",\u042E:"X",\u042F:"R",\u0430:"a",\u0431:"b",\u0432:"a",\u0433:"r",\u0434:"y",\u0435:"e",\u0436:"m",\u0437:"e",\u0438:"n",\u0439:"n",\u043A:"n",\u043B:"n",\u043C:"m",\u043D:"n",\u043E:"o",\u043F:"n",\u0440:"p",\u0441:"c",\u0442:"o",\u0443:"y",\u0444:"b",\u0445:"x",\u0446:"n",\u0447:"n",\u0448:"w",\u0449:"w",\u044A:"a",\u044B:"m",\u044C:"a",\u044D:"e",\u044E:"m",\u044F:"r"};o(FX,"setFontMetrics");o(GD,"getCharacterMetrics");mD={};o(ODe,"getGlobalMetrics");PDe=[[1,1,1],[2,1,1],[3,1,1],[4,2,1],[5,2,1],[6,3,1],[7,4,2],[8,6,3],[9,7,6],[10,8,7],[11,10,9]],oX=[.5,.6,.7,.8,.9,1,1.2,1.44,1.728,2.074,2.488],lX=o(function(e,r){return r.size<2?e:PDe[e-1][r.size-1]},"sizeAtStyle"),P4=class t{static{o(this,"Options")}constructor(e){this.style=void 0,this.color=void 0,this.size=void 0,this.textSize=void 0,this.phantom=void 0,this.font=void 0,this.fontFamily=void 0,this.fontWeight=void 0,this.fontShape=void 0,this.sizeMultiplier=void 0,this.maxSize=void 0,this.minRuleThickness=void 0,this._fontMetrics=void 0,this.style=e.style,this.color=e.color,this.size=e.size||t.BASESIZE,this.textSize=e.textSize||this.size,this.phantom=!!e.phantom,this.font=e.font||"",this.fontFamily=e.fontFamily||"",this.fontWeight=e.fontWeight||"",this.fontShape=e.fontShape||"",this.sizeMultiplier=oX[this.size-1],this.maxSize=e.maxSize,this.minRuleThickness=e.minRuleThickness,this._fontMetrics=void 0}extend(e){var r={style:this.style,size:this.size,textSize:this.textSize,color:this.color,phantom:this.phantom,font:this.font,fontFamily:this.fontFamily,fontWeight:this.fontWeight,fontShape:this.fontShape,maxSize:this.maxSize,minRuleThickness:this.minRuleThickness};for(var i in e)e.hasOwnProperty(i)&&(r[i]=e[i]);return new t(r)}havingStyle(e){return this.style===e?this:this.extend({style:e,size:lX(this.textSize,e)})}havingCrampedStyle(){return this.havingStyle(this.style.cramp())}havingSize(e){return this.size===e&&this.textSize===e?this:this.extend({style:this.style.text(),size:e,textSize:e,sizeMultiplier:oX[e-1]})}havingBaseStyle(e){e=e||this.style.text();var r=lX(t.BASESIZE,e);return this.size===r&&this.textSize===t.BASESIZE&&this.style===e?this:this.extend({style:e,size:r})}havingBaseSizing(){var e;switch(this.style.id){case 4:case 5:e=3;break;case 6:case 7:e=1;break;default:e=6}return this.extend({style:this.style.text(),size:e})}withColor(e){return this.extend({color:e})}withPhantom(){return this.extend({phantom:!0})}withFont(e){return this.extend({font:e})}withTextFontFamily(e){return this.extend({fontFamily:e,font:""})}withTextFontWeight(e){return this.extend({fontWeight:e,font:""})}withTextFontShape(e){return this.extend({fontShape:e,font:""})}sizingClasses(e){return e.size!==this.size?["sizing","reset-size"+e.size,"size"+this.size]:[]}baseSizingClasses(){return this.size!==t.BASESIZE?["sizing","reset-size"+this.size,"size"+t.BASESIZE]:[]}fontMetrics(){return this._fontMetrics||(this._fontMetrics=ODe(this.size)),this._fontMetrics}getColor(){return this.phantom?"transparent":this.color}};P4.BASESIZE=6;DD={pt:1,mm:7227/2540,cm:7227/254,in:72.27,bp:803/800,pc:12,dd:1238/1157,cc:14856/1157,nd:685/642,nc:1370/107,sp:1/65536,px:803/800},BDe={ex:!0,em:!0,mu:!0},$X=o(function(e){return typeof e!="string"&&(e=e.unit),e in DD||e in BDe||e==="ex"},"validUnit"),wn=o(function(e,r){var i;if(e.unit in DD)i=DD[e.unit]/r.fontMetrics().ptPerEm/r.sizeMultiplier;else if(e.unit==="mu")i=r.fontMetrics().cssEmPerMu;else{var n;if(r.style.isTight()?n=r.havingStyle(r.style.text()):n=r,e.unit==="ex")i=n.fontMetrics().xHeight;else if(e.unit==="em")i=n.fontMetrics().quad;else throw new wt("Invalid unit: '"+e.unit+"'");n!==r&&(i*=n.sizeMultiplier/r.sizeMultiplier)}return Math.min(e.number*i,r.maxSize)},"calculateSize"),Rt=o(function(e){return+e.toFixed(4)+"em"},"makeEm"),Of=o(function(e){return e.filter(r=>r).join(" ")},"createClass"),zX=o(function(e,r,i){if(this.classes=e||[],this.attributes={},this.height=0,this.depth=0,this.maxFontSize=0,this.style=i||{},r){r.style.isTight()&&this.classes.push("mtight");var n=r.getColor();n&&(this.style.color=n)}},"initNode"),GX=o(function(e){var r=document.createElement(e);r.className=Of(this.classes);for(var i in this.style)this.style.hasOwnProperty(i)&&(r.style[i]=this.style[i]);for(var n in this.attributes)this.attributes.hasOwnProperty(n)&&r.setAttribute(n,this.attributes[n]);for(var a=0;a/=\x00-\x1f]/,VX=o(function(e){var r="<"+e;this.classes.length&&(r+=' class="'+ui.escape(Of(this.classes))+'"');var i="";for(var n in this.style)this.style.hasOwnProperty(n)&&(i+=ui.hyphenate(n)+":"+this.style[n]+";");i&&(r+=' style="'+ui.escape(i)+'"');for(var a in this.attributes)if(this.attributes.hasOwnProperty(a)){if(FDe.test(a))throw new wt("Invalid attribute name '"+a+"'");r+=" "+a+'="'+ui.escape(this.attributes[a])+'"'}r+=">";for(var s=0;s",r},"toMarkup"),Wp=class{static{o(this,"Span")}constructor(e,r,i,n){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.width=void 0,this.maxFontSize=void 0,this.style=void 0,zX.call(this,e,i,n),this.children=r||[]}setAttribute(e,r){this.attributes[e]=r}hasClass(e){return this.classes.includes(e)}toNode(){return GX.call(this,"span")}toMarkup(){return VX.call(this,"span")}},jx=class{static{o(this,"Anchor")}constructor(e,r,i,n){this.children=void 0,this.attributes=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,zX.call(this,r,n),this.children=i||[],this.setAttribute("href",e)}setAttribute(e,r){this.attributes[e]=r}hasClass(e){return this.classes.includes(e)}toNode(){return GX.call(this,"a")}toMarkup(){return VX.call(this,"a")}},LD=class{static{o(this,"Img")}constructor(e,r,i){this.src=void 0,this.alt=void 0,this.classes=void 0,this.height=void 0,this.depth=void 0,this.maxFontSize=void 0,this.style=void 0,this.alt=r,this.src=e,this.classes=["mord"],this.style=i}hasClass(e){return this.classes.includes(e)}toNode(){var e=document.createElement("img");e.src=this.src,e.alt=this.alt,e.className="mord";for(var r in this.style)this.style.hasOwnProperty(r)&&(e.style[r]=this.style[r]);return e}toMarkup(){var e=''+ui.escape(this.alt)+'0&&(r=document.createElement("span"),r.style.marginRight=Rt(this.italic)),this.classes.length>0&&(r=r||document.createElement("span"),r.className=Of(this.classes));for(var i in this.style)this.style.hasOwnProperty(i)&&(r=r||document.createElement("span"),r.style[i]=this.style[i]);return r?(r.appendChild(e),r):e}toMarkup(){var e=!1,r="0&&(i+="margin-right:"+this.italic+"em;");for(var n in this.style)this.style.hasOwnProperty(n)&&(i+=ui.hyphenate(n)+":"+this.style[n]+";");i&&(e=!0,r+=' style="'+ui.escape(i)+'"');var a=ui.escape(this.text);return e?(r+=">",r+=a,r+="",r):a}},uc=class{static{o(this,"SvgNode")}constructor(e,r){this.children=void 0,this.attributes=void 0,this.children=e||[],this.attributes=r||{}}toNode(){var e="http://www.w3.org/2000/svg",r=document.createElementNS(e,"svg");for(var i in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,i)&&r.setAttribute(i,this.attributes[i]);for(var n=0;n':''}},Xx=class{static{o(this,"LineNode")}constructor(e){this.attributes=void 0,this.attributes=e||{}}toNode(){var e="http://www.w3.org/2000/svg",r=document.createElementNS(e,"line");for(var i in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,i)&&r.setAttribute(i,this.attributes[i]);return r}toMarkup(){var e="","\\gt",!0);q(j,ne,Le,"\u2208","\\in",!0);q(j,ne,Le,"\uE020","\\@not");q(j,ne,Le,"\u2282","\\subset",!0);q(j,ne,Le,"\u2283","\\supset",!0);q(j,ne,Le,"\u2286","\\subseteq",!0);q(j,ne,Le,"\u2287","\\supseteq",!0);q(j,_e,Le,"\u2288","\\nsubseteq",!0);q(j,_e,Le,"\u2289","\\nsupseteq",!0);q(j,ne,Le,"\u22A8","\\models");q(j,ne,Le,"\u2190","\\leftarrow",!0);q(j,ne,Le,"\u2264","\\le");q(j,ne,Le,"\u2264","\\leq",!0);q(j,ne,Le,"<","\\lt",!0);q(j,ne,Le,"\u2192","\\rightarrow",!0);q(j,ne,Le,"\u2192","\\to");q(j,_e,Le,"\u2271","\\ngeq",!0);q(j,_e,Le,"\u2270","\\nleq",!0);q(j,ne,Ch,"\xA0","\\ ");q(j,ne,Ch,"\xA0","\\space");q(j,ne,Ch,"\xA0","\\nobreakspace");q(gt,ne,Ch,"\xA0","\\ ");q(gt,ne,Ch,"\xA0"," ");q(gt,ne,Ch,"\xA0","\\space");q(gt,ne,Ch,"\xA0","\\nobreakspace");q(j,ne,Ch,null,"\\nobreak");q(j,ne,Ch,null,"\\allowbreak");q(j,ne,q4,",",",");q(j,ne,q4,";",";");q(j,_e,$t,"\u22BC","\\barwedge",!0);q(j,_e,$t,"\u22BB","\\veebar",!0);q(j,ne,$t,"\u2299","\\odot",!0);q(j,ne,$t,"\u2295","\\oplus",!0);q(j,ne,$t,"\u2297","\\otimes",!0);q(j,ne,ze,"\u2202","\\partial",!0);q(j,ne,$t,"\u2298","\\oslash",!0);q(j,_e,$t,"\u229A","\\circledcirc",!0);q(j,_e,$t,"\u22A1","\\boxdot",!0);q(j,ne,$t,"\u25B3","\\bigtriangleup");q(j,ne,$t,"\u25BD","\\bigtriangledown");q(j,ne,$t,"\u2020","\\dagger");q(j,ne,$t,"\u22C4","\\diamond");q(j,ne,$t,"\u22C6","\\star");q(j,ne,$t,"\u25C3","\\triangleleft");q(j,ne,$t,"\u25B9","\\triangleright");q(j,ne,Yo,"{","\\{");q(gt,ne,ze,"{","\\{");q(gt,ne,ze,"{","\\textbraceleft");q(j,ne,Ps,"}","\\}");q(gt,ne,ze,"}","\\}");q(gt,ne,ze,"}","\\textbraceright");q(j,ne,Yo,"{","\\lbrace");q(j,ne,Ps,"}","\\rbrace");q(j,ne,Yo,"[","\\lbrack",!0);q(gt,ne,ze,"[","\\lbrack",!0);q(j,ne,Ps,"]","\\rbrack",!0);q(gt,ne,ze,"]","\\rbrack",!0);q(j,ne,Yo,"(","\\lparen",!0);q(j,ne,Ps,")","\\rparen",!0);q(gt,ne,ze,"<","\\textless",!0);q(gt,ne,ze,">","\\textgreater",!0);q(j,ne,Yo,"\u230A","\\lfloor",!0);q(j,ne,Ps,"\u230B","\\rfloor",!0);q(j,ne,Yo,"\u2308","\\lceil",!0);q(j,ne,Ps,"\u2309","\\rceil",!0);q(j,ne,ze,"\\","\\backslash");q(j,ne,ze,"\u2223","|");q(j,ne,ze,"\u2223","\\vert");q(gt,ne,ze,"|","\\textbar",!0);q(j,ne,ze,"\u2225","\\|");q(j,ne,ze,"\u2225","\\Vert");q(gt,ne,ze,"\u2225","\\textbardbl");q(gt,ne,ze,"~","\\textasciitilde");q(gt,ne,ze,"\\","\\textbackslash");q(gt,ne,ze,"^","\\textasciicircum");q(j,ne,Le,"\u2191","\\uparrow",!0);q(j,ne,Le,"\u21D1","\\Uparrow",!0);q(j,ne,Le,"\u2193","\\downarrow",!0);q(j,ne,Le,"\u21D3","\\Downarrow",!0);q(j,ne,Le,"\u2195","\\updownarrow",!0);q(j,ne,Le,"\u21D5","\\Updownarrow",!0);q(j,ne,Kn,"\u2210","\\coprod");q(j,ne,Kn,"\u22C1","\\bigvee");q(j,ne,Kn,"\u22C0","\\bigwedge");q(j,ne,Kn,"\u2A04","\\biguplus");q(j,ne,Kn,"\u22C2","\\bigcap");q(j,ne,Kn,"\u22C3","\\bigcup");q(j,ne,Kn,"\u222B","\\int");q(j,ne,Kn,"\u222B","\\intop");q(j,ne,Kn,"\u222C","\\iint");q(j,ne,Kn,"\u222D","\\iiint");q(j,ne,Kn,"\u220F","\\prod");q(j,ne,Kn,"\u2211","\\sum");q(j,ne,Kn,"\u2A02","\\bigotimes");q(j,ne,Kn,"\u2A01","\\bigoplus");q(j,ne,Kn,"\u2A00","\\bigodot");q(j,ne,Kn,"\u222E","\\oint");q(j,ne,Kn,"\u222F","\\oiint");q(j,ne,Kn,"\u2230","\\oiiint");q(j,ne,Kn,"\u2A06","\\bigsqcup");q(j,ne,Kn,"\u222B","\\smallint");q(gt,ne,Dg,"\u2026","\\textellipsis");q(j,ne,Dg,"\u2026","\\mathellipsis");q(gt,ne,Dg,"\u2026","\\ldots",!0);q(j,ne,Dg,"\u2026","\\ldots",!0);q(j,ne,Dg,"\u22EF","\\@cdots",!0);q(j,ne,Dg,"\u22F1","\\ddots",!0);q(j,ne,ze,"\u22EE","\\varvdots");q(gt,ne,ze,"\u22EE","\\varvdots");q(j,ne,hn,"\u02CA","\\acute");q(j,ne,hn,"\u02CB","\\grave");q(j,ne,hn,"\xA8","\\ddot");q(j,ne,hn,"~","\\tilde");q(j,ne,hn,"\u02C9","\\bar");q(j,ne,hn,"\u02D8","\\breve");q(j,ne,hn,"\u02C7","\\check");q(j,ne,hn,"^","\\hat");q(j,ne,hn,"\u20D7","\\vec");q(j,ne,hn,"\u02D9","\\dot");q(j,ne,hn,"\u02DA","\\mathring");q(j,ne,mr,"\uE131","\\@imath");q(j,ne,mr,"\uE237","\\@jmath");q(j,ne,ze,"\u0131","\u0131");q(j,ne,ze,"\u0237","\u0237");q(gt,ne,ze,"\u0131","\\i",!0);q(gt,ne,ze,"\u0237","\\j",!0);q(gt,ne,ze,"\xDF","\\ss",!0);q(gt,ne,ze,"\xE6","\\ae",!0);q(gt,ne,ze,"\u0153","\\oe",!0);q(gt,ne,ze,"\xF8","\\o",!0);q(gt,ne,ze,"\xC6","\\AE",!0);q(gt,ne,ze,"\u0152","\\OE",!0);q(gt,ne,ze,"\xD8","\\O",!0);q(gt,ne,hn,"\u02CA","\\'");q(gt,ne,hn,"\u02CB","\\`");q(gt,ne,hn,"\u02C6","\\^");q(gt,ne,hn,"\u02DC","\\~");q(gt,ne,hn,"\u02C9","\\=");q(gt,ne,hn,"\u02D8","\\u");q(gt,ne,hn,"\u02D9","\\.");q(gt,ne,hn,"\xB8","\\c");q(gt,ne,hn,"\u02DA","\\r");q(gt,ne,hn,"\u02C7","\\v");q(gt,ne,hn,"\xA8",'\\"');q(gt,ne,hn,"\u02DD","\\H");q(gt,ne,hn,"\u25EF","\\textcircled");qX={"--":!0,"---":!0,"``":!0,"''":!0};q(gt,ne,ze,"\u2013","--",!0);q(gt,ne,ze,"\u2013","\\textendash");q(gt,ne,ze,"\u2014","---",!0);q(gt,ne,ze,"\u2014","\\textemdash");q(gt,ne,ze,"\u2018","`",!0);q(gt,ne,ze,"\u2018","\\textquoteleft");q(gt,ne,ze,"\u2019","'",!0);q(gt,ne,ze,"\u2019","\\textquoteright");q(gt,ne,ze,"\u201C","``",!0);q(gt,ne,ze,"\u201C","\\textquotedblleft");q(gt,ne,ze,"\u201D","''",!0);q(gt,ne,ze,"\u201D","\\textquotedblright");q(j,ne,ze,"\xB0","\\degree",!0);q(gt,ne,ze,"\xB0","\\degree");q(gt,ne,ze,"\xB0","\\textdegree",!0);q(j,ne,ze,"\xA3","\\pounds");q(j,ne,ze,"\xA3","\\mathsterling",!0);q(gt,ne,ze,"\xA3","\\pounds");q(gt,ne,ze,"\xA3","\\textsterling",!0);q(j,_e,ze,"\u2720","\\maltese");q(gt,_e,ze,"\u2720","\\maltese");uX='0123456789/@."';for(w4=0;w40)return cc(a,h,n,r,s.concat(f));if(u){var d,p;if(u==="boldsymbol"){var m=UDe(a,n,r,s,i);d=m.fontName,p=[m.fontClass]}else l?(d=HX[u].fontName,p=[u]):(d=D4(u,r.fontWeight,r.fontShape),p=[u,r.fontWeight,r.fontShape]);if(W4(a,d,n).metrics)return cc(a,d,n,r,s.concat(p));if(qX.hasOwnProperty(a)&&d.slice(0,10)==="Typewriter"){for(var g=[],y=0;y{if(Of(t.classes)!==Of(e.classes)||t.skew!==e.skew||t.maxFontSize!==e.maxFontSize)return!1;if(t.classes.length===1){var r=t.classes[0];if(r==="mbin"||r==="mord")return!1}for(var i in t.style)if(t.style.hasOwnProperty(i)&&t.style[i]!==e.style[i])return!1;for(var n in e.style)if(e.style.hasOwnProperty(n)&&t.style[n]!==e.style[n])return!1;return!0},"canCombine"),jDe=o(t=>{for(var e=0;er&&(r=s.height),s.depth>i&&(i=s.depth),s.maxFontSize>n&&(n=s.maxFontSize)}e.height=r,e.depth=i,e.maxFontSize=n},"sizeElementFromChildren"),lo=o(function(e,r,i,n){var a=new Wp(e,r,i,n);return VD(a),a},"makeSpan"),WX=o((t,e,r,i)=>new Wp(t,e,r,i),"makeSvgSpan"),XDe=o(function(e,r,i){var n=lo([e],[],r);return n.height=Math.max(i||r.fontMetrics().defaultRuleThickness,r.minRuleThickness),n.style.borderBottomWidth=Rt(n.height),n.maxFontSize=1,n},"makeLineSpan"),KDe=o(function(e,r,i,n){var a=new jx(e,r,i,n);return VD(a),a},"makeAnchor"),UX=o(function(e){var r=new qp(e);return VD(r),r},"makeFragment"),QDe=o(function(e,r){return e instanceof qp?lo([],[e],r):e},"wrapFragment"),ZDe=o(function(e){if(e.positionType==="individualShift"){for(var r=e.children,i=[r[0]],n=-r[0].shift-r[0].elem.depth,a=n,s=1;s{var r=lo(["mspace"],[],e),i=wn(t,e);return r.style.marginRight=Rt(i),r},"makeGlue"),D4=o(function(e,r,i){var n="";switch(e){case"amsrm":n="AMS";break;case"textrm":n="Main";break;case"textsf":n="SansSerif";break;case"texttt":n="Typewriter";break;default:n=e}var a;return r==="textbf"&&i==="textit"?a="BoldItalic":r==="textbf"?a="Bold":r==="textit"?a="Italic":a="Regular",n+"-"+a},"retrieveTextFontName"),HX={mathbf:{variant:"bold",fontName:"Main-Bold"},mathrm:{variant:"normal",fontName:"Main-Regular"},textit:{variant:"italic",fontName:"Main-Italic"},mathit:{variant:"italic",fontName:"Main-Italic"},mathnormal:{variant:"italic",fontName:"Math-Italic"},mathsfit:{variant:"sans-serif-italic",fontName:"SansSerif-Italic"},mathbb:{variant:"double-struck",fontName:"AMS-Regular"},mathcal:{variant:"script",fontName:"Caligraphic-Regular"},mathfrak:{variant:"fraktur",fontName:"Fraktur-Regular"},mathscr:{variant:"script",fontName:"Script-Regular"},mathsf:{variant:"sans-serif",fontName:"SansSerif-Regular"},mathtt:{variant:"monospace",fontName:"Typewriter-Regular"}},YX={vec:["vec",.471,.714],oiintSize1:["oiintSize1",.957,.499],oiintSize2:["oiintSize2",1.472,.659],oiiintSize1:["oiiintSize1",1.304,.499],oiiintSize2:["oiiintSize2",1.98,.659]},tLe=o(function(e,r){var[i,n,a]=YX[e],s=new iu(i),l=new uc([s],{width:Rt(n),height:Rt(a),style:"width:"+Rt(n),viewBox:"0 0 "+1e3*n+" "+1e3*a,preserveAspectRatio:"xMinYMin"}),u=WX(["overlay"],[l],r);return u.height=a,u.style.height=Rt(a),u.style.width=Rt(n),u},"staticSvg"),je={fontMap:HX,makeSymbol:cc,mathsym:WDe,makeSpan:lo,makeSvgSpan:WX,makeLineSpan:XDe,makeAnchor:KDe,makeFragment:UX,wrapFragment:QDe,makeVList:JDe,makeOrd:HDe,makeGlue:eLe,staticSvg:tLe,svgData:YX,tryCombineChars:jDe},Cn={number:3,unit:"mu"},Vp={number:4,unit:"mu"},vh={number:5,unit:"mu"},rLe={mord:{mop:Cn,mbin:Vp,mrel:vh,minner:Cn},mop:{mord:Cn,mop:Cn,mrel:vh,minner:Cn},mbin:{mord:Vp,mop:Vp,mopen:Vp,minner:Vp},mrel:{mord:vh,mop:vh,mopen:vh,minner:vh},mopen:{},mclose:{mop:Cn,mbin:Vp,mrel:vh,minner:Cn},mpunct:{mord:Cn,mop:Cn,mrel:vh,mopen:Cn,mclose:Cn,mpunct:Cn,minner:Cn},minner:{mord:Cn,mop:Cn,mbin:Vp,mrel:vh,mopen:Cn,mpunct:Cn,minner:Cn}},iLe={mord:{mop:Cn},mop:{mord:Cn,mop:Cn},mbin:{},mrel:{},mopen:{},mclose:{mop:Cn},mpunct:{},minner:{mop:Cn}},jX={},F4={},$4={};o(Bt,"defineFunction");o(Up,"defineFunctionBuilders");z4=o(function(e){return e.type==="ordgroup"&&e.body.length===1?e.body[0]:e},"normalizeArgument"),$n=o(function(e){return e.type==="ordgroup"?e.body:[e]},"ordargument"),Th=je.makeSpan,nLe=["leftmost","mbin","mopen","mrel","mop","mpunct"],aLe=["rightmost","mrel","mclose","mpunct"],sLe={display:gr.DISPLAY,text:gr.TEXT,script:gr.SCRIPT,scriptscript:gr.SCRIPTSCRIPT},oLe={mord:"mord",mop:"mop",mbin:"mbin",mrel:"mrel",mopen:"mopen",mclose:"mclose",mpunct:"mpunct",minner:"minner"},ca=o(function(e,r,i,n){n===void 0&&(n=[null,null]);for(var a=[],s=0;s{var v=y.classes[0],x=g.classes[0];v==="mbin"&&aLe.includes(x)?y.classes[0]="mord":x==="mbin"&&nLe.includes(v)&&(g.classes[0]="mord")},{node:d},p,m),dX(a,(g,y)=>{var v=ND(y),x=ND(g),b=v&&x?g.hasClass("mtight")?iLe[v][x]:rLe[v][x]:null;if(b)return je.makeGlue(b,h)},{node:d},p,m),a},"buildExpression"),dX=o(function t(e,r,i,n,a){n&&e.push(n);for(var s=0;sp=>{e.splice(d+1,0,p),s++})(s)}n&&e.pop()},"traverseNonSpaceNodes"),XX=o(function(e){return e instanceof qp||e instanceof jx||e instanceof Wp&&e.hasClass("enclosing")?e:null},"checkPartialGroup"),lLe=o(function t(e,r){var i=XX(e);if(i){var n=i.children;if(n.length){if(r==="right")return t(n[n.length-1],"right");if(r==="left")return t(n[0],"left")}}return e},"getOutermostNode"),ND=o(function(e,r){return e?(r&&(e=lLe(e,r)),oLe[e.classes[0]]||null):null},"getTypeOfDomTree"),Kx=o(function(e,r){var i=["nulldelimiter"].concat(e.baseSizingClasses());return Th(r.concat(i))},"makeNullDelimiter"),ii=o(function(e,r,i){if(!e)return Th();if(F4[e.type]){var n=F4[e.type](e,r);if(i&&r.size!==i.size){n=Th(r.sizingClasses(i),[n],r);var a=r.sizeMultiplier/i.sizeMultiplier;n.height*=a,n.depth*=a}return n}else throw new wt("Got group of unknown type: '"+e.type+"'")},"buildGroup");o(L4,"buildHTMLUnbreakable");o(ID,"buildHTML");o(KX,"newDocumentFragment");Ms=class{static{o(this,"MathNode")}constructor(e,r,i){this.type=void 0,this.attributes=void 0,this.children=void 0,this.classes=void 0,this.type=e,this.attributes={},this.children=r||[],this.classes=i||[]}setAttribute(e,r){this.attributes[e]=r}getAttribute(e){return this.attributes[e]}toNode(){var e=document.createElementNS("http://www.w3.org/1998/Math/MathML",this.type);for(var r in this.attributes)Object.prototype.hasOwnProperty.call(this.attributes,r)&&e.setAttribute(r,this.attributes[r]);this.classes.length>0&&(e.className=Of(this.classes));for(var i=0;i0&&(e+=' class ="'+ui.escape(Of(this.classes))+'"'),e+=">";for(var i=0;i",e}toText(){return this.children.map(e=>e.toText()).join("")}},Cl=class{static{o(this,"TextNode")}constructor(e){this.text=void 0,this.text=e}toNode(){return document.createTextNode(this.text)}toMarkup(){return ui.escape(this.toText())}toText(){return this.text}},MD=class{static{o(this,"SpaceNode")}constructor(e){this.width=void 0,this.character=void 0,this.width=e,e>=.05555&&e<=.05556?this.character="\u200A":e>=.1666&&e<=.1667?this.character="\u2009":e>=.2222&&e<=.2223?this.character="\u2005":e>=.2777&&e<=.2778?this.character="\u2005\u200A":e>=-.05556&&e<=-.05555?this.character="\u200A\u2063":e>=-.1667&&e<=-.1666?this.character="\u2009\u2063":e>=-.2223&&e<=-.2222?this.character="\u205F\u2063":e>=-.2778&&e<=-.2777?this.character="\u2005\u2063":this.character=null}toNode(){if(this.character)return document.createTextNode(this.character);var e=document.createElementNS("http://www.w3.org/1998/Math/MathML","mspace");return e.setAttribute("width",Rt(this.width)),e}toMarkup(){return this.character?""+this.character+"":''}toText(){return this.character?this.character:" "}},Ct={MathNode:Ms,TextNode:Cl,SpaceNode:MD,newDocumentFragment:KX},wl=o(function(e,r,i){return ji[r][e]&&ji[r][e].replace&&e.charCodeAt(0)!==55349&&!(qX.hasOwnProperty(e)&&i&&(i.fontFamily&&i.fontFamily.slice(4,6)==="tt"||i.font&&i.font.slice(4,6)==="tt"))&&(e=ji[r][e].replace),new Ct.TextNode(e)},"makeText"),qD=o(function(e){return e.length===1?e[0]:new Ct.MathNode("mrow",e)},"makeRow"),WD=o(function(e,r){if(r.fontFamily==="texttt")return"monospace";if(r.fontFamily==="textsf")return r.fontShape==="textit"&&r.fontWeight==="textbf"?"sans-serif-bold-italic":r.fontShape==="textit"?"sans-serif-italic":r.fontWeight==="textbf"?"bold-sans-serif":"sans-serif";if(r.fontShape==="textit"&&r.fontWeight==="textbf")return"bold-italic";if(r.fontShape==="textit")return"italic";if(r.fontWeight==="textbf")return"bold";var i=r.font;if(!i||i==="mathnormal")return null;var n=e.mode;if(i==="mathit")return"italic";if(i==="boldsymbol")return e.type==="textord"?"bold":"bold-italic";if(i==="mathbf")return"bold";if(i==="mathbb")return"double-struck";if(i==="mathsfit")return"sans-serif-italic";if(i==="mathfrak")return"fraktur";if(i==="mathscr"||i==="mathcal")return"script";if(i==="mathsf")return"sans-serif";if(i==="mathtt")return"monospace";var a=e.text;if(["\\imath","\\jmath"].includes(a))return null;ji[n][a]&&ji[n][a].replace&&(a=ji[n][a].replace);var s=je.fontMap[i].fontName;return GD(a,s,n)?je.fontMap[i].variant:null},"getVariant");o(vD,"isNumberPunctuation");ho=o(function(e,r,i){if(e.length===1){var n=$i(e[0],r);return i&&n instanceof Ms&&n.type==="mo"&&(n.setAttribute("lspace","0em"),n.setAttribute("rspace","0em")),[n]}for(var a=[],s,l=0;l=1&&(s.type==="mn"||vD(s))){var h=u.children[0];h instanceof Ms&&h.type==="mn"&&(h.children=[...s.children,...h.children],a.pop())}else if(s.type==="mi"&&s.children.length===1){var f=s.children[0];if(f instanceof Cl&&f.text==="\u0338"&&(u.type==="mo"||u.type==="mi"||u.type==="mn")){var d=u.children[0];d instanceof Cl&&d.text.length>0&&(d.text=d.text.slice(0,1)+"\u0338"+d.text.slice(1),a.pop())}}}a.push(u),s=u}return a},"buildExpression"),Pf=o(function(e,r,i){return qD(ho(e,r,i))},"buildExpressionRow"),$i=o(function(e,r){if(!e)return new Ct.MathNode("mrow");if($4[e.type]){var i=$4[e.type](e,r);return i}else throw new wt("Got group of unknown type: '"+e.type+"'")},"buildGroup");o(pX,"buildMathML");QX=o(function(e){return new P4({style:e.displayMode?gr.DISPLAY:gr.TEXT,maxSize:e.maxSize,minRuleThickness:e.minRuleThickness})},"optionsFromSettings"),ZX=o(function(e,r){if(r.displayMode){var i=["katex-display"];r.leqno&&i.push("leqno"),r.fleqn&&i.push("fleqn"),e=je.makeSpan(i,[e])}return e},"displayWrap"),cLe=o(function(e,r,i){var n=QX(i),a;if(i.output==="mathml")return pX(e,r,n,i.displayMode,!0);if(i.output==="html"){var s=ID(e,n);a=je.makeSpan(["katex"],[s])}else{var l=pX(e,r,n,i.displayMode,!1),u=ID(e,n);a=je.makeSpan(["katex"],[l,u])}return ZX(a,i)},"buildTree"),uLe=o(function(e,r,i){var n=QX(i),a=ID(e,n),s=je.makeSpan(["katex"],[a]);return ZX(s,i)},"buildHTMLTree"),hLe={widehat:"^",widecheck:"\u02C7",widetilde:"~",utilde:"~",overleftarrow:"\u2190",underleftarrow:"\u2190",xleftarrow:"\u2190",overrightarrow:"\u2192",underrightarrow:"\u2192",xrightarrow:"\u2192",underbrace:"\u23DF",overbrace:"\u23DE",overgroup:"\u23E0",undergroup:"\u23E1",overleftrightarrow:"\u2194",underleftrightarrow:"\u2194",xleftrightarrow:"\u2194",Overrightarrow:"\u21D2",xRightarrow:"\u21D2",overleftharpoon:"\u21BC",xleftharpoonup:"\u21BC",overrightharpoon:"\u21C0",xrightharpoonup:"\u21C0",xLeftarrow:"\u21D0",xLeftrightarrow:"\u21D4",xhookleftarrow:"\u21A9",xhookrightarrow:"\u21AA",xmapsto:"\u21A6",xrightharpoondown:"\u21C1",xleftharpoondown:"\u21BD",xrightleftharpoons:"\u21CC",xleftrightharpoons:"\u21CB",xtwoheadleftarrow:"\u219E",xtwoheadrightarrow:"\u21A0",xlongequal:"=",xtofrom:"\u21C4",xrightleftarrows:"\u21C4",xrightequilibrium:"\u21CC",xleftequilibrium:"\u21CB","\\cdrightarrow":"\u2192","\\cdleftarrow":"\u2190","\\cdlongequal":"="},fLe=o(function(e){var r=new Ct.MathNode("mo",[new Ct.TextNode(hLe[e.replace(/^\\/,"")])]);return r.setAttribute("stretchy","true"),r},"mathMLnode"),dLe={overrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],overleftarrow:[["leftarrow"],.888,522,"xMinYMin"],underrightarrow:[["rightarrow"],.888,522,"xMaxYMin"],underleftarrow:[["leftarrow"],.888,522,"xMinYMin"],xrightarrow:[["rightarrow"],1.469,522,"xMaxYMin"],"\\cdrightarrow":[["rightarrow"],3,522,"xMaxYMin"],xleftarrow:[["leftarrow"],1.469,522,"xMinYMin"],"\\cdleftarrow":[["leftarrow"],3,522,"xMinYMin"],Overrightarrow:[["doublerightarrow"],.888,560,"xMaxYMin"],xRightarrow:[["doublerightarrow"],1.526,560,"xMaxYMin"],xLeftarrow:[["doubleleftarrow"],1.526,560,"xMinYMin"],overleftharpoon:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoonup:[["leftharpoon"],.888,522,"xMinYMin"],xleftharpoondown:[["leftharpoondown"],.888,522,"xMinYMin"],overrightharpoon:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoonup:[["rightharpoon"],.888,522,"xMaxYMin"],xrightharpoondown:[["rightharpoondown"],.888,522,"xMaxYMin"],xlongequal:[["longequal"],.888,334,"xMinYMin"],"\\cdlongequal":[["longequal"],3,334,"xMinYMin"],xtwoheadleftarrow:[["twoheadleftarrow"],.888,334,"xMinYMin"],xtwoheadrightarrow:[["twoheadrightarrow"],.888,334,"xMaxYMin"],overleftrightarrow:[["leftarrow","rightarrow"],.888,522],overbrace:[["leftbrace","midbrace","rightbrace"],1.6,548],underbrace:[["leftbraceunder","midbraceunder","rightbraceunder"],1.6,548],underleftrightarrow:[["leftarrow","rightarrow"],.888,522],xleftrightarrow:[["leftarrow","rightarrow"],1.75,522],xLeftrightarrow:[["doubleleftarrow","doublerightarrow"],1.75,560],xrightleftharpoons:[["leftharpoondownplus","rightharpoonplus"],1.75,716],xleftrightharpoons:[["leftharpoonplus","rightharpoondownplus"],1.75,716],xhookleftarrow:[["leftarrow","righthook"],1.08,522],xhookrightarrow:[["lefthook","rightarrow"],1.08,522],overlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],underlinesegment:[["leftlinesegment","rightlinesegment"],.888,522],overgroup:[["leftgroup","rightgroup"],.888,342],undergroup:[["leftgroupunder","rightgroupunder"],.888,342],xmapsto:[["leftmapsto","rightarrow"],1.5,522],xtofrom:[["leftToFrom","rightToFrom"],1.75,528],xrightleftarrows:[["baraboveleftarrow","rightarrowabovebar"],1.75,901],xrightequilibrium:[["baraboveshortleftharpoon","rightharpoonaboveshortbar"],1.75,716],xleftequilibrium:[["shortbaraboveleftharpoon","shortrightharpoonabovebar"],1.75,716]},pLe=o(function(e){return e.type==="ordgroup"?e.body.length:1},"groupLength"),mLe=o(function(e,r){function i(){var l=4e5,u=e.label.slice(1);if(["widehat","widecheck","widetilde","utilde"].includes(u)){var h=e,f=pLe(h.base),d,p,m;if(f>5)u==="widehat"||u==="widecheck"?(d=420,l=2364,m=.42,p=u+"4"):(d=312,l=2340,m=.34,p="tilde4");else{var g=[1,1,2,2,3,3][f];u==="widehat"||u==="widecheck"?(l=[0,1062,2364,2364,2364][g],d=[0,239,300,360,420][g],m=[0,.24,.3,.3,.36,.42][g],p=u+g):(l=[0,600,1033,2339,2340][g],d=[0,260,286,306,312][g],m=[0,.26,.286,.3,.306,.34][g],p="tilde"+g)}var y=new iu(p),v=new uc([y],{width:"100%",height:Rt(m),viewBox:"0 0 "+l+" "+d,preserveAspectRatio:"none"});return{span:je.makeSvgSpan([],[v],r),minWidth:0,height:m}}else{var x=[],b=dLe[u],[T,w,k]=b,C=k/1e3,E=T.length,S,L;if(E===1){var M=b[3];S=["hide-tail"],L=[M]}else if(E===2)S=["halfarrow-left","halfarrow-right"],L=["xMinYMin","xMaxYMin"];else if(E===3)S=["brace-left","brace-center","brace-right"],L=["xMinYMin","xMidYMin","xMaxYMin"];else throw new Error(`Correct katexImagesData or update code here to support + `+E+" children.");for(var I=0;I0&&(n.style.minWidth=Rt(a)),n},"svgSpan"),gLe=o(function(e,r,i,n,a){var s,l=e.height+e.depth+i+n;if(/fbox|color|angl/.test(r)){if(s=je.makeSpan(["stretchy",r],[],a),r==="fbox"){var u=a.color&&a.getColor();u&&(s.style.borderColor=u)}}else{var h=[];/^[bx]cancel$/.test(r)&&h.push(new Xx({x1:"0",y1:"0",x2:"100%",y2:"100%","stroke-width":"0.046em"})),/^x?cancel$/.test(r)&&h.push(new Xx({x1:"0",y1:"100%",x2:"100%",y2:"0","stroke-width":"0.046em"}));var f=new uc(h,{width:"100%",height:Rt(l)});s=je.makeSvgSpan([],[f],a)}return s.height=l,s.style.height=Rt(l),s},"encloseSpan"),kh={encloseSpan:gLe,mathMLnode:fLe,svgSpan:mLe};o(Gr,"assertNodeType");o(UD,"assertSymbolNodeType");o(U4,"checkSymbolNodeType");HD=o((t,e)=>{var r,i,n;t&&t.type==="supsub"?(i=Gr(t.base,"accent"),r=i.base,t.base=r,n=zDe(ii(t,e)),t.base=i):(i=Gr(t,"accent"),r=i.base);var a=ii(r,e.havingCrampedStyle()),s=i.isShifty&&ui.isCharacterBox(r),l=0;if(s){var u=ui.getBaseElem(r),h=ii(u,e.havingCrampedStyle());l=cX(h).skew}var f=i.label==="\\c",d=f?a.height+a.depth:Math.min(a.height,e.fontMetrics().xHeight),p;if(i.isStretchy)p=kh.svgSpan(i,e),p=je.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:a},{type:"elem",elem:p,wrapperClasses:["svg-align"],wrapperStyle:l>0?{width:"calc(100% - "+Rt(2*l)+")",marginLeft:Rt(2*l)}:void 0}]},e);else{var m,g;i.label==="\\vec"?(m=je.staticSvg("vec",e),g=je.svgData.vec[1]):(m=je.makeOrd({mode:i.mode,text:i.label},e,"textord"),m=cX(m),m.italic=0,g=m.width,f&&(d+=m.depth)),p=je.makeSpan(["accent-body"],[m]);var y=i.label==="\\textcircled";y&&(p.classes.push("accent-full"),d=a.height);var v=l;y||(v-=g/2),p.style.left=Rt(v),i.label==="\\textcircled"&&(p.style.top=".2em"),p=je.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:a},{type:"kern",size:-d},{type:"elem",elem:p}]},e)}var x=je.makeSpan(["mord","accent"],[p],e);return n?(n.children[0]=x,n.height=Math.max(x.height,n.height),n.classes[0]="mord",n):x},"htmlBuilder$a"),JX=o((t,e)=>{var r=t.isStretchy?kh.mathMLnode(t.label):new Ct.MathNode("mo",[wl(t.label,t.mode)]),i=new Ct.MathNode("mover",[$i(t.base,e),r]);return i.setAttribute("accent","true"),i},"mathmlBuilder$9"),yLe=new RegExp(["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring"].map(t=>"\\"+t).join("|"));Bt({type:"accent",names:["\\acute","\\grave","\\ddot","\\tilde","\\bar","\\breve","\\check","\\hat","\\vec","\\dot","\\mathring","\\widecheck","\\widehat","\\widetilde","\\overrightarrow","\\overleftarrow","\\Overrightarrow","\\overleftrightarrow","\\overgroup","\\overlinesegment","\\overleftharpoon","\\overrightharpoon"],props:{numArgs:1},handler:o((t,e)=>{var r=z4(e[0]),i=!yLe.test(t.funcName),n=!i||t.funcName==="\\widehat"||t.funcName==="\\widetilde"||t.funcName==="\\widecheck";return{type:"accent",mode:t.parser.mode,label:t.funcName,isStretchy:i,isShifty:n,base:r}},"handler"),htmlBuilder:HD,mathmlBuilder:JX});Bt({type:"accent",names:["\\'","\\`","\\^","\\~","\\=","\\u","\\.",'\\"',"\\c","\\r","\\H","\\v","\\textcircled"],props:{numArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:["primitive"]},handler:o((t,e)=>{var r=e[0],i=t.parser.mode;return i==="math"&&(t.parser.settings.reportNonstrict("mathVsTextAccents","LaTeX's accent "+t.funcName+" works only in text mode"),i="text"),{type:"accent",mode:i,label:t.funcName,isStretchy:!1,isShifty:!0,base:r}},"handler"),htmlBuilder:HD,mathmlBuilder:JX});Bt({type:"accentUnder",names:["\\underleftarrow","\\underrightarrow","\\underleftrightarrow","\\undergroup","\\underlinesegment","\\utilde"],props:{numArgs:1},handler:o((t,e)=>{var{parser:r,funcName:i}=t,n=e[0];return{type:"accentUnder",mode:r.mode,label:i,base:n}},"handler"),htmlBuilder:o((t,e)=>{var r=ii(t.base,e),i=kh.svgSpan(t,e),n=t.label==="\\utilde"?.12:0,a=je.makeVList({positionType:"top",positionData:r.height,children:[{type:"elem",elem:i,wrapperClasses:["svg-align"]},{type:"kern",size:n},{type:"elem",elem:r}]},e);return je.makeSpan(["mord","accentunder"],[a],e)},"htmlBuilder"),mathmlBuilder:o((t,e)=>{var r=kh.mathMLnode(t.label),i=new Ct.MathNode("munder",[$i(t.base,e),r]);return i.setAttribute("accentunder","true"),i},"mathmlBuilder")});R4=o(t=>{var e=new Ct.MathNode("mpadded",t?[t]:[]);return e.setAttribute("width","+0.6em"),e.setAttribute("lspace","0.3em"),e},"paddedNode");Bt({type:"xArrow",names:["\\xleftarrow","\\xrightarrow","\\xLeftarrow","\\xRightarrow","\\xleftrightarrow","\\xLeftrightarrow","\\xhookleftarrow","\\xhookrightarrow","\\xmapsto","\\xrightharpoondown","\\xrightharpoonup","\\xleftharpoondown","\\xleftharpoonup","\\xrightleftharpoons","\\xleftrightharpoons","\\xlongequal","\\xtwoheadrightarrow","\\xtwoheadleftarrow","\\xtofrom","\\xrightleftarrows","\\xrightequilibrium","\\xleftequilibrium","\\\\cdrightarrow","\\\\cdleftarrow","\\\\cdlongequal"],props:{numArgs:1,numOptionalArgs:1},handler(t,e,r){var{parser:i,funcName:n}=t;return{type:"xArrow",mode:i.mode,label:n,body:e[0],below:r[0]}},htmlBuilder(t,e){var r=e.style,i=e.havingStyle(r.sup()),n=je.wrapFragment(ii(t.body,i,e),e),a=t.label.slice(0,2)==="\\x"?"x":"cd";n.classes.push(a+"-arrow-pad");var s;t.below&&(i=e.havingStyle(r.sub()),s=je.wrapFragment(ii(t.below,i,e),e),s.classes.push(a+"-arrow-pad"));var l=kh.svgSpan(t,e),u=-e.fontMetrics().axisHeight+.5*l.height,h=-e.fontMetrics().axisHeight-.5*l.height-.111;(n.depth>.25||t.label==="\\xleftequilibrium")&&(h-=n.depth);var f;if(s){var d=-e.fontMetrics().axisHeight+s.height+.5*l.height+.111;f=je.makeVList({positionType:"individualShift",children:[{type:"elem",elem:n,shift:h},{type:"elem",elem:l,shift:u},{type:"elem",elem:s,shift:d}]},e)}else f=je.makeVList({positionType:"individualShift",children:[{type:"elem",elem:n,shift:h},{type:"elem",elem:l,shift:u}]},e);return f.children[0].children[0].children[1].classes.push("svg-align"),je.makeSpan(["mrel","x-arrow"],[f],e)},mathmlBuilder(t,e){var r=kh.mathMLnode(t.label);r.setAttribute("minsize",t.label.charAt(0)==="x"?"1.75em":"3.0em");var i;if(t.body){var n=R4($i(t.body,e));if(t.below){var a=R4($i(t.below,e));i=new Ct.MathNode("munderover",[r,a,n])}else i=new Ct.MathNode("mover",[r,n])}else if(t.below){var s=R4($i(t.below,e));i=new Ct.MathNode("munder",[r,s])}else i=R4(),i=new Ct.MathNode("mover",[r,i]);return i}});vLe=je.makeSpan;o(eK,"htmlBuilder$9");o(tK,"mathmlBuilder$8");Bt({type:"mclass",names:["\\mathord","\\mathbin","\\mathrel","\\mathopen","\\mathclose","\\mathpunct","\\mathinner"],props:{numArgs:1,primitive:!0},handler(t,e){var{parser:r,funcName:i}=t,n=e[0];return{type:"mclass",mode:r.mode,mclass:"m"+i.slice(5),body:$n(n),isCharacterBox:ui.isCharacterBox(n)}},htmlBuilder:eK,mathmlBuilder:tK});H4=o(t=>{var e=t.type==="ordgroup"&&t.body.length?t.body[0]:t;return e.type==="atom"&&(e.family==="bin"||e.family==="rel")?"m"+e.family:"mord"},"binrelClass");Bt({type:"mclass",names:["\\@binrel"],props:{numArgs:2},handler(t,e){var{parser:r}=t;return{type:"mclass",mode:r.mode,mclass:H4(e[0]),body:$n(e[1]),isCharacterBox:ui.isCharacterBox(e[1])}}});Bt({type:"mclass",names:["\\stackrel","\\overset","\\underset"],props:{numArgs:2},handler(t,e){var{parser:r,funcName:i}=t,n=e[1],a=e[0],s;i!=="\\stackrel"?s=H4(n):s="mrel";var l={type:"op",mode:n.mode,limits:!0,alwaysHandleSupSub:!0,parentIsSupSub:!1,symbol:!1,suppressBaseShift:i!=="\\stackrel",body:$n(n)},u={type:"supsub",mode:a.mode,base:l,sup:i==="\\underset"?null:a,sub:i==="\\underset"?a:null};return{type:"mclass",mode:r.mode,mclass:s,body:[u],isCharacterBox:ui.isCharacterBox(u)}},htmlBuilder:eK,mathmlBuilder:tK});Bt({type:"pmb",names:["\\pmb"],props:{numArgs:1,allowedInText:!0},handler(t,e){var{parser:r}=t;return{type:"pmb",mode:r.mode,mclass:H4(e[0]),body:$n(e[0])}},htmlBuilder(t,e){var r=ca(t.body,e,!0),i=je.makeSpan([t.mclass],r,e);return i.style.textShadow="0.02em 0.01em 0.04px",i},mathmlBuilder(t,e){var r=ho(t.body,e),i=new Ct.MathNode("mstyle",r);return i.setAttribute("style","text-shadow: 0.02em 0.01em 0.04px"),i}});xLe={">":"\\\\cdrightarrow","<":"\\\\cdleftarrow","=":"\\\\cdlongequal",A:"\\uparrow",V:"\\downarrow","|":"\\Vert",".":"no arrow"},mX=o(()=>({type:"styling",body:[],mode:"math",style:"display"}),"newCell"),gX=o(t=>t.type==="textord"&&t.text==="@","isStartOfArrow"),bLe=o((t,e)=>(t.type==="mathord"||t.type==="atom")&&t.text===e,"isLabelEnd");o(TLe,"cdArrow");o(kLe,"parseCD");Bt({type:"cdlabel",names:["\\\\cdleft","\\\\cdright"],props:{numArgs:1},handler(t,e){var{parser:r,funcName:i}=t;return{type:"cdlabel",mode:r.mode,side:i.slice(4),label:e[0]}},htmlBuilder(t,e){var r=e.havingStyle(e.style.sup()),i=je.wrapFragment(ii(t.label,r,e),e);return i.classes.push("cd-label-"+t.side),i.style.bottom=Rt(.8-i.depth),i.height=0,i.depth=0,i},mathmlBuilder(t,e){var r=new Ct.MathNode("mrow",[$i(t.label,e)]);return r=new Ct.MathNode("mpadded",[r]),r.setAttribute("width","0"),t.side==="left"&&r.setAttribute("lspace","-1width"),r.setAttribute("voffset","0.7em"),r=new Ct.MathNode("mstyle",[r]),r.setAttribute("displaystyle","false"),r.setAttribute("scriptlevel","1"),r}});Bt({type:"cdlabelparent",names:["\\\\cdparent"],props:{numArgs:1},handler(t,e){var{parser:r}=t;return{type:"cdlabelparent",mode:r.mode,fragment:e[0]}},htmlBuilder(t,e){var r=je.wrapFragment(ii(t.fragment,e),e);return r.classes.push("cd-vert-arrow"),r},mathmlBuilder(t,e){return new Ct.MathNode("mrow",[$i(t.fragment,e)])}});Bt({type:"textord",names:["\\@char"],props:{numArgs:1,allowedInText:!0},handler(t,e){for(var{parser:r}=t,i=Gr(e[0],"ordgroup"),n=i.body,a="",s=0;s=1114111)throw new wt("\\@char with invalid code point "+a);return u<=65535?h=String.fromCharCode(u):(u-=65536,h=String.fromCharCode((u>>10)+55296,(u&1023)+56320)),{type:"textord",mode:r.mode,text:h}}});rK=o((t,e)=>{var r=ca(t.body,e.withColor(t.color),!1);return je.makeFragment(r)},"htmlBuilder$8"),iK=o((t,e)=>{var r=ho(t.body,e.withColor(t.color)),i=new Ct.MathNode("mstyle",r);return i.setAttribute("mathcolor",t.color),i},"mathmlBuilder$7");Bt({type:"color",names:["\\textcolor"],props:{numArgs:2,allowedInText:!0,argTypes:["color","original"]},handler(t,e){var{parser:r}=t,i=Gr(e[0],"color-token").color,n=e[1];return{type:"color",mode:r.mode,color:i,body:$n(n)}},htmlBuilder:rK,mathmlBuilder:iK});Bt({type:"color",names:["\\color"],props:{numArgs:1,allowedInText:!0,argTypes:["color"]},handler(t,e){var{parser:r,breakOnTokenText:i}=t,n=Gr(e[0],"color-token").color;r.gullet.macros.set("\\current@color",n);var a=r.parseExpression(!0,i);return{type:"color",mode:r.mode,color:n,body:a}},htmlBuilder:rK,mathmlBuilder:iK});Bt({type:"cr",names:["\\\\"],props:{numArgs:0,numOptionalArgs:0,allowedInText:!0},handler(t,e,r){var{parser:i}=t,n=i.gullet.future().text==="["?i.parseSizeGroup(!0):null,a=!i.settings.displayMode||!i.settings.useStrictBehavior("newLineInDisplayMode","In LaTeX, \\\\ or \\newline does nothing in display mode");return{type:"cr",mode:i.mode,newLine:a,size:n&&Gr(n,"size").value}},htmlBuilder(t,e){var r=je.makeSpan(["mspace"],[],e);return t.newLine&&(r.classes.push("newline"),t.size&&(r.style.marginTop=Rt(wn(t.size,e)))),r},mathmlBuilder(t,e){var r=new Ct.MathNode("mspace");return t.newLine&&(r.setAttribute("linebreak","newline"),t.size&&r.setAttribute("height",Rt(wn(t.size,e)))),r}});OD={"\\global":"\\global","\\long":"\\\\globallong","\\\\globallong":"\\\\globallong","\\def":"\\gdef","\\gdef":"\\gdef","\\edef":"\\xdef","\\xdef":"\\xdef","\\let":"\\\\globallet","\\futurelet":"\\\\globalfuture"},nK=o(t=>{var e=t.text;if(/^(?:[\\{}$&#^_]|EOF)$/.test(e))throw new wt("Expected a control sequence",t);return e},"checkControlSequence"),CLe=o(t=>{var e=t.gullet.popToken();return e.text==="="&&(e=t.gullet.popToken(),e.text===" "&&(e=t.gullet.popToken())),e},"getRHS"),aK=o((t,e,r,i)=>{var n=t.gullet.macros.get(r.text);n==null&&(r.noexpand=!0,n={tokens:[r],numArgs:0,unexpandable:!t.gullet.isExpandable(r.text)}),t.gullet.macros.set(e,n,i)},"letCommand");Bt({type:"internal",names:["\\global","\\long","\\\\globallong"],props:{numArgs:0,allowedInText:!0},handler(t){var{parser:e,funcName:r}=t;e.consumeSpaces();var i=e.fetch();if(OD[i.text])return(r==="\\global"||r==="\\\\globallong")&&(i.text=OD[i.text]),Gr(e.parseFunction(),"internal");throw new wt("Invalid token after macro prefix",i)}});Bt({type:"internal",names:["\\def","\\gdef","\\edef","\\xdef"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(t){var{parser:e,funcName:r}=t,i=e.gullet.popToken(),n=i.text;if(/^(?:[\\{}$&#^_]|EOF)$/.test(n))throw new wt("Expected a control sequence",i);for(var a=0,s,l=[[]];e.gullet.future().text!=="{";)if(i=e.gullet.popToken(),i.text==="#"){if(e.gullet.future().text==="{"){s=e.gullet.future(),l[a].push("{");break}if(i=e.gullet.popToken(),!/^[1-9]$/.test(i.text))throw new wt('Invalid argument number "'+i.text+'"');if(parseInt(i.text)!==a+1)throw new wt('Argument number "'+i.text+'" out of order');a++,l.push([])}else{if(i.text==="EOF")throw new wt("Expected a macro definition");l[a].push(i.text)}var{tokens:u}=e.gullet.consumeArg();return s&&u.unshift(s),(r==="\\edef"||r==="\\xdef")&&(u=e.gullet.expandTokens(u),u.reverse()),e.gullet.macros.set(n,{tokens:u,numArgs:a,delimiters:l},r===OD[r]),{type:"internal",mode:e.mode}}});Bt({type:"internal",names:["\\let","\\\\globallet"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(t){var{parser:e,funcName:r}=t,i=nK(e.gullet.popToken());e.gullet.consumeSpaces();var n=CLe(e);return aK(e,i,n,r==="\\\\globallet"),{type:"internal",mode:e.mode}}});Bt({type:"internal",names:["\\futurelet","\\\\globalfuture"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(t){var{parser:e,funcName:r}=t,i=nK(e.gullet.popToken()),n=e.gullet.popToken(),a=e.gullet.popToken();return aK(e,i,a,r==="\\\\globalfuture"),e.gullet.pushToken(a),e.gullet.pushToken(n),{type:"internal",mode:e.mode}}});qx=o(function(e,r,i){var n=ji.math[e]&&ji.math[e].replace,a=GD(n||e,r,i);if(!a)throw new Error("Unsupported symbol "+e+" and font size "+r+".");return a},"getMetrics"),YD=o(function(e,r,i,n){var a=i.havingBaseStyle(r),s=je.makeSpan(n.concat(a.sizingClasses(i)),[e],i),l=a.sizeMultiplier/i.sizeMultiplier;return s.height*=l,s.depth*=l,s.maxFontSize=a.sizeMultiplier,s},"styleWrap"),sK=o(function(e,r,i){var n=r.havingBaseStyle(i),a=(1-r.sizeMultiplier/n.sizeMultiplier)*r.fontMetrics().axisHeight;e.classes.push("delimcenter"),e.style.top=Rt(a),e.height-=a,e.depth+=a},"centerSpan"),wLe=o(function(e,r,i,n,a,s){var l=je.makeSymbol(e,"Main-Regular",a,n),u=YD(l,r,n,s);return i&&sK(u,n,r),u},"makeSmallDelim"),ELe=o(function(e,r,i,n){return je.makeSymbol(e,"Size"+r+"-Regular",i,n)},"mathrmSize"),oK=o(function(e,r,i,n,a,s){var l=ELe(e,r,a,n),u=YD(je.makeSpan(["delimsizing","size"+r],[l],n),gr.TEXT,n,s);return i&&sK(u,n,gr.TEXT),u},"makeLargeDelim"),xD=o(function(e,r,i){var n;r==="Size1-Regular"?n="delim-size1":n="delim-size4";var a=je.makeSpan(["delimsizinginner",n],[je.makeSpan([],[je.makeSymbol(e,r,i)])]);return{type:"elem",elem:a}},"makeGlyphSpan"),bD=o(function(e,r,i){var n=ru["Size4-Regular"][e.charCodeAt(0)]?ru["Size4-Regular"][e.charCodeAt(0)][4]:ru["Size1-Regular"][e.charCodeAt(0)][4],a=new iu("inner",IDe(e,Math.round(1e3*r))),s=new uc([a],{width:Rt(n),height:Rt(r),style:"width:"+Rt(n),viewBox:"0 0 "+1e3*n+" "+Math.round(1e3*r),preserveAspectRatio:"xMinYMin"}),l=je.makeSvgSpan([],[s],i);return l.height=r,l.style.height=Rt(r),l.style.width=Rt(n),{type:"elem",elem:l}},"makeInner"),PD=.008,N4={type:"kern",size:-1*PD},SLe=["|","\\lvert","\\rvert","\\vert"],ALe=["\\|","\\lVert","\\rVert","\\Vert"],lK=o(function(e,r,i,n,a,s){var l,u,h,f,d="",p=0;l=h=f=e,u=null;var m="Size1-Regular";e==="\\uparrow"?h=f="\u23D0":e==="\\Uparrow"?h=f="\u2016":e==="\\downarrow"?l=h="\u23D0":e==="\\Downarrow"?l=h="\u2016":e==="\\updownarrow"?(l="\\uparrow",h="\u23D0",f="\\downarrow"):e==="\\Updownarrow"?(l="\\Uparrow",h="\u2016",f="\\Downarrow"):SLe.includes(e)?(h="\u2223",d="vert",p=333):ALe.includes(e)?(h="\u2225",d="doublevert",p=556):e==="["||e==="\\lbrack"?(l="\u23A1",h="\u23A2",f="\u23A3",m="Size4-Regular",d="lbrack",p=667):e==="]"||e==="\\rbrack"?(l="\u23A4",h="\u23A5",f="\u23A6",m="Size4-Regular",d="rbrack",p=667):e==="\\lfloor"||e==="\u230A"?(h=l="\u23A2",f="\u23A3",m="Size4-Regular",d="lfloor",p=667):e==="\\lceil"||e==="\u2308"?(l="\u23A1",h=f="\u23A2",m="Size4-Regular",d="lceil",p=667):e==="\\rfloor"||e==="\u230B"?(h=l="\u23A5",f="\u23A6",m="Size4-Regular",d="rfloor",p=667):e==="\\rceil"||e==="\u2309"?(l="\u23A4",h=f="\u23A5",m="Size4-Regular",d="rceil",p=667):e==="("||e==="\\lparen"?(l="\u239B",h="\u239C",f="\u239D",m="Size4-Regular",d="lparen",p=875):e===")"||e==="\\rparen"?(l="\u239E",h="\u239F",f="\u23A0",m="Size4-Regular",d="rparen",p=875):e==="\\{"||e==="\\lbrace"?(l="\u23A7",u="\u23A8",f="\u23A9",h="\u23AA",m="Size4-Regular"):e==="\\}"||e==="\\rbrace"?(l="\u23AB",u="\u23AC",f="\u23AD",h="\u23AA",m="Size4-Regular"):e==="\\lgroup"||e==="\u27EE"?(l="\u23A7",f="\u23A9",h="\u23AA",m="Size4-Regular"):e==="\\rgroup"||e==="\u27EF"?(l="\u23AB",f="\u23AD",h="\u23AA",m="Size4-Regular"):e==="\\lmoustache"||e==="\u23B0"?(l="\u23A7",f="\u23AD",h="\u23AA",m="Size4-Regular"):(e==="\\rmoustache"||e==="\u23B1")&&(l="\u23AB",f="\u23A9",h="\u23AA",m="Size4-Regular");var g=qx(l,m,a),y=g.height+g.depth,v=qx(h,m,a),x=v.height+v.depth,b=qx(f,m,a),T=b.height+b.depth,w=0,k=1;if(u!==null){var C=qx(u,m,a);w=C.height+C.depth,k=2}var E=y+T+w,S=Math.max(0,Math.ceil((r-E)/(k*x))),L=E+S*k*x,M=n.fontMetrics().axisHeight;i&&(M*=n.sizeMultiplier);var I=L/2-M,A=[];if(d.length>0){var _=L-y-T,D=Math.round(L*1e3),N=MDe(d,Math.round(_*1e3)),R=new iu(d,N),B=(p/1e3).toFixed(3)+"em",O=(D/1e3).toFixed(3)+"em",$=new uc([R],{width:B,height:O,viewBox:"0 0 "+p+" "+D}),z=je.makeSvgSpan([],[$],n);z.height=D/1e3,z.style.width=B,z.style.height=O,A.push({type:"elem",elem:z})}else{if(A.push(xD(f,m,a)),A.push(N4),u===null){var F=L-y-T+2*PD;A.push(bD(h,F,n))}else{var V=(L-y-T-w)/2+2*PD;A.push(bD(h,V,n)),A.push(N4),A.push(xD(u,m,a)),A.push(N4),A.push(bD(h,V,n))}A.push(N4),A.push(xD(l,m,a))}var H=n.havingBaseStyle(gr.TEXT),X=je.makeVList({positionType:"bottom",positionData:I,children:A},H);return YD(je.makeSpan(["delimsizing","mult"],[X],H),gr.TEXT,n,s)},"makeStackedDelim"),TD=80,kD=.08,CD=o(function(e,r,i,n,a){var s=NDe(e,n,i),l=new iu(e,s),u=new uc([l],{width:"400em",height:Rt(r),viewBox:"0 0 400000 "+i,preserveAspectRatio:"xMinYMin slice"});return je.makeSvgSpan(["hide-tail"],[u],a)},"sqrtSvg"),_Le=o(function(e,r){var i=r.havingBaseSizing(),n=fK("\\surd",e*i.sizeMultiplier,hK,i),a=i.sizeMultiplier,s=Math.max(0,r.minRuleThickness-r.fontMetrics().sqrtRuleThickness),l,u=0,h=0,f=0,d;return n.type==="small"?(f=1e3+1e3*s+TD,e<1?a=1:e<1.4&&(a=.7),u=(1+s+kD)/a,h=(1+s)/a,l=CD("sqrtMain",u,f,s,r),l.style.minWidth="0.853em",d=.833/a):n.type==="large"?(f=(1e3+TD)*Ux[n.size],h=(Ux[n.size]+s)/a,u=(Ux[n.size]+s+kD)/a,l=CD("sqrtSize"+n.size,u,f,s,r),l.style.minWidth="1.02em",d=1/a):(u=e+s+kD,h=e+s,f=Math.floor(1e3*e+s)+TD,l=CD("sqrtTall",u,f,s,r),l.style.minWidth="0.742em",d=1.056),l.height=h,l.style.height=Rt(u),{span:l,advanceWidth:d,ruleWidth:(r.fontMetrics().sqrtRuleThickness+s)*a}},"makeSqrtImage"),cK=["(","\\lparen",")","\\rparen","[","\\lbrack","]","\\rbrack","\\{","\\lbrace","\\}","\\rbrace","\\lfloor","\\rfloor","\u230A","\u230B","\\lceil","\\rceil","\u2308","\u2309","\\surd"],DLe=["\\uparrow","\\downarrow","\\updownarrow","\\Uparrow","\\Downarrow","\\Updownarrow","|","\\|","\\vert","\\Vert","\\lvert","\\rvert","\\lVert","\\rVert","\\lgroup","\\rgroup","\u27EE","\u27EF","\\lmoustache","\\rmoustache","\u23B0","\u23B1"],uK=["<",">","\\langle","\\rangle","/","\\backslash","\\lt","\\gt"],Ux=[0,1.2,1.8,2.4,3],LLe=o(function(e,r,i,n,a){if(e==="<"||e==="\\lt"||e==="\u27E8"?e="\\langle":(e===">"||e==="\\gt"||e==="\u27E9")&&(e="\\rangle"),cK.includes(e)||uK.includes(e))return oK(e,r,!1,i,n,a);if(DLe.includes(e))return lK(e,Ux[r],!1,i,n,a);throw new wt("Illegal delimiter: '"+e+"'")},"makeSizedDelim"),RLe=[{type:"small",style:gr.SCRIPTSCRIPT},{type:"small",style:gr.SCRIPT},{type:"small",style:gr.TEXT},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4}],NLe=[{type:"small",style:gr.SCRIPTSCRIPT},{type:"small",style:gr.SCRIPT},{type:"small",style:gr.TEXT},{type:"stack"}],hK=[{type:"small",style:gr.SCRIPTSCRIPT},{type:"small",style:gr.SCRIPT},{type:"small",style:gr.TEXT},{type:"large",size:1},{type:"large",size:2},{type:"large",size:3},{type:"large",size:4},{type:"stack"}],ILe=o(function(e){if(e.type==="small")return"Main-Regular";if(e.type==="large")return"Size"+e.size+"-Regular";if(e.type==="stack")return"Size4-Regular";throw new Error("Add support for delim type '"+e.type+"' here.")},"delimTypeToFont"),fK=o(function(e,r,i,n){for(var a=Math.min(2,3-n.style.size),s=a;sr)return i[s]}return i[i.length-1]},"traverseSequence"),dK=o(function(e,r,i,n,a,s){e==="<"||e==="\\lt"||e==="\u27E8"?e="\\langle":(e===">"||e==="\\gt"||e==="\u27E9")&&(e="\\rangle");var l;uK.includes(e)?l=RLe:cK.includes(e)?l=hK:l=NLe;var u=fK(e,r,l,n);return u.type==="small"?wLe(e,u.style,i,n,a,s):u.type==="large"?oK(e,u.size,i,n,a,s):lK(e,r,i,n,a,s)},"makeCustomSizedDelim"),MLe=o(function(e,r,i,n,a,s){var l=n.fontMetrics().axisHeight*n.sizeMultiplier,u=901,h=5/n.fontMetrics().ptPerEm,f=Math.max(r-l,i+l),d=Math.max(f/500*u,2*f-h);return dK(e,d,!0,n,a,s)},"makeLeftRightDelim"),bh={sqrtImage:_Le,sizedDelim:LLe,sizeToMaxHeight:Ux,customSizedDelim:dK,leftRightDelim:MLe},yX={"\\bigl":{mclass:"mopen",size:1},"\\Bigl":{mclass:"mopen",size:2},"\\biggl":{mclass:"mopen",size:3},"\\Biggl":{mclass:"mopen",size:4},"\\bigr":{mclass:"mclose",size:1},"\\Bigr":{mclass:"mclose",size:2},"\\biggr":{mclass:"mclose",size:3},"\\Biggr":{mclass:"mclose",size:4},"\\bigm":{mclass:"mrel",size:1},"\\Bigm":{mclass:"mrel",size:2},"\\biggm":{mclass:"mrel",size:3},"\\Biggm":{mclass:"mrel",size:4},"\\big":{mclass:"mord",size:1},"\\Big":{mclass:"mord",size:2},"\\bigg":{mclass:"mord",size:3},"\\Bigg":{mclass:"mord",size:4}},OLe=["(","\\lparen",")","\\rparen","[","\\lbrack","]","\\rbrack","\\{","\\lbrace","\\}","\\rbrace","\\lfloor","\\rfloor","\u230A","\u230B","\\lceil","\\rceil","\u2308","\u2309","<",">","\\langle","\u27E8","\\rangle","\u27E9","\\lt","\\gt","\\lvert","\\rvert","\\lVert","\\rVert","\\lgroup","\\rgroup","\u27EE","\u27EF","\\lmoustache","\\rmoustache","\u23B0","\u23B1","/","\\backslash","|","\\vert","\\|","\\Vert","\\uparrow","\\Uparrow","\\downarrow","\\Downarrow","\\updownarrow","\\Updownarrow","."];o(Y4,"checkDelimiter");Bt({type:"delimsizing",names:["\\bigl","\\Bigl","\\biggl","\\Biggl","\\bigr","\\Bigr","\\biggr","\\Biggr","\\bigm","\\Bigm","\\biggm","\\Biggm","\\big","\\Big","\\bigg","\\Bigg"],props:{numArgs:1,argTypes:["primitive"]},handler:o((t,e)=>{var r=Y4(e[0],t);return{type:"delimsizing",mode:t.parser.mode,size:yX[t.funcName].size,mclass:yX[t.funcName].mclass,delim:r.text}},"handler"),htmlBuilder:o((t,e)=>t.delim==="."?je.makeSpan([t.mclass]):bh.sizedDelim(t.delim,t.size,e,t.mode,[t.mclass]),"htmlBuilder"),mathmlBuilder:o(t=>{var e=[];t.delim!=="."&&e.push(wl(t.delim,t.mode));var r=new Ct.MathNode("mo",e);t.mclass==="mopen"||t.mclass==="mclose"?r.setAttribute("fence","true"):r.setAttribute("fence","false"),r.setAttribute("stretchy","true");var i=Rt(bh.sizeToMaxHeight[t.size]);return r.setAttribute("minsize",i),r.setAttribute("maxsize",i),r},"mathmlBuilder")});o(vX,"assertParsed");Bt({type:"leftright-right",names:["\\right"],props:{numArgs:1,primitive:!0},handler:o((t,e)=>{var r=t.parser.gullet.macros.get("\\current@color");if(r&&typeof r!="string")throw new wt("\\current@color set to non-string in \\right");return{type:"leftright-right",mode:t.parser.mode,delim:Y4(e[0],t).text,color:r}},"handler")});Bt({type:"leftright",names:["\\left"],props:{numArgs:1,primitive:!0},handler:o((t,e)=>{var r=Y4(e[0],t),i=t.parser;++i.leftrightDepth;var n=i.parseExpression(!1);--i.leftrightDepth,i.expect("\\right",!1);var a=Gr(i.parseFunction(),"leftright-right");return{type:"leftright",mode:i.mode,body:n,left:r.text,right:a.delim,rightColor:a.color}},"handler"),htmlBuilder:o((t,e)=>{vX(t);for(var r=ca(t.body,e,!0,["mopen","mclose"]),i=0,n=0,a=!1,s=0;s{vX(t);var r=ho(t.body,e);if(t.left!=="."){var i=new Ct.MathNode("mo",[wl(t.left,t.mode)]);i.setAttribute("fence","true"),r.unshift(i)}if(t.right!=="."){var n=new Ct.MathNode("mo",[wl(t.right,t.mode)]);n.setAttribute("fence","true"),t.rightColor&&n.setAttribute("mathcolor",t.rightColor),r.push(n)}return qD(r)},"mathmlBuilder")});Bt({type:"middle",names:["\\middle"],props:{numArgs:1,primitive:!0},handler:o((t,e)=>{var r=Y4(e[0],t);if(!t.parser.leftrightDepth)throw new wt("\\middle without preceding \\left",r);return{type:"middle",mode:t.parser.mode,delim:r.text}},"handler"),htmlBuilder:o((t,e)=>{var r;if(t.delim===".")r=Kx(e,[]);else{r=bh.sizedDelim(t.delim,1,e,t.mode,[]);var i={delim:t.delim,options:e};r.isMiddle=i}return r},"htmlBuilder"),mathmlBuilder:o((t,e)=>{var r=t.delim==="\\vert"||t.delim==="|"?wl("|","text"):wl(t.delim,t.mode),i=new Ct.MathNode("mo",[r]);return i.setAttribute("fence","true"),i.setAttribute("lspace","0.05em"),i.setAttribute("rspace","0.05em"),i},"mathmlBuilder")});jD=o((t,e)=>{var r=je.wrapFragment(ii(t.body,e),e),i=t.label.slice(1),n=e.sizeMultiplier,a,s=0,l=ui.isCharacterBox(t.body);if(i==="sout")a=je.makeSpan(["stretchy","sout"]),a.height=e.fontMetrics().defaultRuleThickness/n,s=-.5*e.fontMetrics().xHeight;else if(i==="phase"){var u=wn({number:.6,unit:"pt"},e),h=wn({number:.35,unit:"ex"},e),f=e.havingBaseSizing();n=n/f.sizeMultiplier;var d=r.height+r.depth+u+h;r.style.paddingLeft=Rt(d/2+u);var p=Math.floor(1e3*d*n),m=LDe(p),g=new uc([new iu("phase",m)],{width:"400em",height:Rt(p/1e3),viewBox:"0 0 400000 "+p,preserveAspectRatio:"xMinYMin slice"});a=je.makeSvgSpan(["hide-tail"],[g],e),a.style.height=Rt(d),s=r.depth+u+h}else{/cancel/.test(i)?l||r.classes.push("cancel-pad"):i==="angl"?r.classes.push("anglpad"):r.classes.push("boxpad");var y=0,v=0,x=0;/box/.test(i)?(x=Math.max(e.fontMetrics().fboxrule,e.minRuleThickness),y=e.fontMetrics().fboxsep+(i==="colorbox"?0:x),v=y):i==="angl"?(x=Math.max(e.fontMetrics().defaultRuleThickness,e.minRuleThickness),y=4*x,v=Math.max(0,.25-r.depth)):(y=l?.2:0,v=y),a=kh.encloseSpan(r,i,y,v,e),/fbox|boxed|fcolorbox/.test(i)?(a.style.borderStyle="solid",a.style.borderWidth=Rt(x)):i==="angl"&&x!==.049&&(a.style.borderTopWidth=Rt(x),a.style.borderRightWidth=Rt(x)),s=r.depth+v,t.backgroundColor&&(a.style.backgroundColor=t.backgroundColor,t.borderColor&&(a.style.borderColor=t.borderColor))}var b;if(t.backgroundColor)b=je.makeVList({positionType:"individualShift",children:[{type:"elem",elem:a,shift:s},{type:"elem",elem:r,shift:0}]},e);else{var T=/cancel|phase/.test(i)?["svg-align"]:[];b=je.makeVList({positionType:"individualShift",children:[{type:"elem",elem:r,shift:0},{type:"elem",elem:a,shift:s,wrapperClasses:T}]},e)}return/cancel/.test(i)&&(b.height=r.height,b.depth=r.depth),/cancel/.test(i)&&!l?je.makeSpan(["mord","cancel-lap"],[b],e):je.makeSpan(["mord"],[b],e)},"htmlBuilder$7"),XD=o((t,e)=>{var r=0,i=new Ct.MathNode(t.label.indexOf("colorbox")>-1?"mpadded":"menclose",[$i(t.body,e)]);switch(t.label){case"\\cancel":i.setAttribute("notation","updiagonalstrike");break;case"\\bcancel":i.setAttribute("notation","downdiagonalstrike");break;case"\\phase":i.setAttribute("notation","phasorangle");break;case"\\sout":i.setAttribute("notation","horizontalstrike");break;case"\\fbox":i.setAttribute("notation","box");break;case"\\angl":i.setAttribute("notation","actuarial");break;case"\\fcolorbox":case"\\colorbox":if(r=e.fontMetrics().fboxsep*e.fontMetrics().ptPerEm,i.setAttribute("width","+"+2*r+"pt"),i.setAttribute("height","+"+2*r+"pt"),i.setAttribute("lspace",r+"pt"),i.setAttribute("voffset",r+"pt"),t.label==="\\fcolorbox"){var n=Math.max(e.fontMetrics().fboxrule,e.minRuleThickness);i.setAttribute("style","border: "+n+"em solid "+String(t.borderColor))}break;case"\\xcancel":i.setAttribute("notation","updiagonalstrike downdiagonalstrike");break}return t.backgroundColor&&i.setAttribute("mathbackground",t.backgroundColor),i},"mathmlBuilder$6");Bt({type:"enclose",names:["\\colorbox"],props:{numArgs:2,allowedInText:!0,argTypes:["color","text"]},handler(t,e,r){var{parser:i,funcName:n}=t,a=Gr(e[0],"color-token").color,s=e[1];return{type:"enclose",mode:i.mode,label:n,backgroundColor:a,body:s}},htmlBuilder:jD,mathmlBuilder:XD});Bt({type:"enclose",names:["\\fcolorbox"],props:{numArgs:3,allowedInText:!0,argTypes:["color","color","text"]},handler(t,e,r){var{parser:i,funcName:n}=t,a=Gr(e[0],"color-token").color,s=Gr(e[1],"color-token").color,l=e[2];return{type:"enclose",mode:i.mode,label:n,backgroundColor:s,borderColor:a,body:l}},htmlBuilder:jD,mathmlBuilder:XD});Bt({type:"enclose",names:["\\fbox"],props:{numArgs:1,argTypes:["hbox"],allowedInText:!0},handler(t,e){var{parser:r}=t;return{type:"enclose",mode:r.mode,label:"\\fbox",body:e[0]}}});Bt({type:"enclose",names:["\\cancel","\\bcancel","\\xcancel","\\sout","\\phase"],props:{numArgs:1},handler(t,e){var{parser:r,funcName:i}=t,n=e[0];return{type:"enclose",mode:r.mode,label:i,body:n}},htmlBuilder:jD,mathmlBuilder:XD});Bt({type:"enclose",names:["\\angl"],props:{numArgs:1,argTypes:["hbox"],allowedInText:!1},handler(t,e){var{parser:r}=t;return{type:"enclose",mode:r.mode,label:"\\angl",body:e[0]}}});pK={};o(nu,"defineEnvironment");mK={};o(he,"defineMacro");o(xX,"getHLines");j4=o(t=>{var e=t.parser.settings;if(!e.displayMode)throw new wt("{"+t.envName+"} can be used only in display mode.")},"validateAmsEnvironmentContext");o(KD,"getAutoTag");o(Bf,"parseArray");o(QD,"dCellStyle");au=o(function(e,r){var i,n,a=e.body.length,s=e.hLinesBeforeRow,l=0,u=new Array(a),h=[],f=Math.max(r.fontMetrics().arrayRuleWidth,r.minRuleThickness),d=1/r.fontMetrics().ptPerEm,p=5*d;if(e.colSeparationType&&e.colSeparationType==="small"){var m=r.havingStyle(gr.SCRIPT).sizeMultiplier;p=.2778*(m/r.sizeMultiplier)}var g=e.colSeparationType==="CD"?wn({number:3,unit:"ex"},r):12*d,y=3*d,v=e.arraystretch*g,x=.7*v,b=.3*v,T=0;function w(Te){for(var De=0;De0&&(T+=.25),h.push({pos:T,isDashed:Te[De]})}for(o(w,"setHLinePos"),w(s[0]),i=0;i0&&(I+=b,ETe))for(i=0;i=l)){var Y=void 0;(n>0||e.hskipBeforeAndAfter)&&(Y=ui.deflt(V.pregap,p),Y!==0&&(N=je.makeSpan(["arraycolsep"],[]),N.style.width=Rt(Y),D.push(N)));var ae=[];for(i=0;i0){for(var te=je.makeLineSpan("hline",r,f),be=je.makeLineSpan("hdashline",r,f),de=[{type:"elem",elem:u,shift:0}];h.length>0;){var Ee=h.pop(),Ne=Ee.pos-A;Ee.isDashed?de.push({type:"elem",elem:be,shift:Ne}):de.push({type:"elem",elem:te,shift:Ne})}u=je.makeVList({positionType:"individualShift",children:de},r)}if(B.length===0)return je.makeSpan(["mord"],[u],r);var we=je.makeVList({positionType:"individualShift",children:B},r);return we=je.makeSpan(["tag"],[we],r),je.makeFragment([u,we])},"htmlBuilder"),PLe={c:"center ",l:"left ",r:"right "},su=o(function(e,r){for(var i=[],n=new Ct.MathNode("mtd",[],["mtr-glue"]),a=new Ct.MathNode("mtd",[],["mml-eqn-num"]),s=0;s0){var g=e.cols,y="",v=!1,x=0,b=g.length;g[0].type==="separator"&&(p+="top ",x=1),g[g.length-1].type==="separator"&&(p+="bottom ",b-=1);for(var T=x;T0?"left ":"",p+=S[S.length-1].length>0?"right ":"";for(var L=1;L-1?"alignat":"align",a=e.envName==="split",s=Bf(e.parser,{cols:i,addJot:!0,autoTag:a?void 0:KD(e.envName),emptySingleRow:!0,colSeparationType:n,maxNumCols:a?2:void 0,leqno:e.parser.settings.leqno},"display"),l,u=0,h={type:"ordgroup",mode:e.mode,body:[]};if(r[0]&&r[0].type==="ordgroup"){for(var f="",d=0;d0&&m&&(v=1),i[g]={type:"align",align:y,pregap:v,postgap:0}}return s.colSeparationType=m?"align":"alignat",s},"alignedHandler");nu({type:"array",names:["array","darray"],props:{numArgs:1},handler(t,e){var r=U4(e[0]),i=r?[e[0]]:Gr(e[0],"ordgroup").body,n=i.map(function(s){var l=UD(s),u=l.text;if("lcr".indexOf(u)!==-1)return{type:"align",align:u};if(u==="|")return{type:"separator",separator:"|"};if(u===":")return{type:"separator",separator:":"};throw new wt("Unknown column alignment: "+u,s)}),a={cols:n,hskipBeforeAndAfter:!0,maxNumCols:n.length};return Bf(t.parser,a,QD(t.envName))},htmlBuilder:au,mathmlBuilder:su});nu({type:"array",names:["matrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix","matrix*","pmatrix*","bmatrix*","Bmatrix*","vmatrix*","Vmatrix*"],props:{numArgs:0},handler(t){var e={matrix:null,pmatrix:["(",")"],bmatrix:["[","]"],Bmatrix:["\\{","\\}"],vmatrix:["|","|"],Vmatrix:["\\Vert","\\Vert"]}[t.envName.replace("*","")],r="c",i={hskipBeforeAndAfter:!1,cols:[{type:"align",align:r}]};if(t.envName.charAt(t.envName.length-1)==="*"){var n=t.parser;if(n.consumeSpaces(),n.fetch().text==="["){if(n.consume(),n.consumeSpaces(),r=n.fetch().text,"lcr".indexOf(r)===-1)throw new wt("Expected l or c or r",n.nextToken);n.consume(),n.consumeSpaces(),n.expect("]"),n.consume(),i.cols=[{type:"align",align:r}]}}var a=Bf(t.parser,i,QD(t.envName)),s=Math.max(0,...a.body.map(l=>l.length));return a.cols=new Array(s).fill({type:"align",align:r}),e?{type:"leftright",mode:t.mode,body:[a],left:e[0],right:e[1],rightColor:void 0}:a},htmlBuilder:au,mathmlBuilder:su});nu({type:"array",names:["smallmatrix"],props:{numArgs:0},handler(t){var e={arraystretch:.5},r=Bf(t.parser,e,"script");return r.colSeparationType="small",r},htmlBuilder:au,mathmlBuilder:su});nu({type:"array",names:["subarray"],props:{numArgs:1},handler(t,e){var r=U4(e[0]),i=r?[e[0]]:Gr(e[0],"ordgroup").body,n=i.map(function(s){var l=UD(s),u=l.text;if("lc".indexOf(u)!==-1)return{type:"align",align:u};throw new wt("Unknown column alignment: "+u,s)});if(n.length>1)throw new wt("{subarray} can contain only one column");var a={cols:n,hskipBeforeAndAfter:!1,arraystretch:.5};if(a=Bf(t.parser,a,"script"),a.body.length>0&&a.body[0].length>1)throw new wt("{subarray} can contain only one column");return a},htmlBuilder:au,mathmlBuilder:su});nu({type:"array",names:["cases","dcases","rcases","drcases"],props:{numArgs:0},handler(t){var e={arraystretch:1.2,cols:[{type:"align",align:"l",pregap:0,postgap:1},{type:"align",align:"l",pregap:0,postgap:0}]},r=Bf(t.parser,e,QD(t.envName));return{type:"leftright",mode:t.mode,body:[r],left:t.envName.indexOf("r")>-1?".":"\\{",right:t.envName.indexOf("r")>-1?"\\}":".",rightColor:void 0}},htmlBuilder:au,mathmlBuilder:su});nu({type:"array",names:["align","align*","aligned","split"],props:{numArgs:0},handler:gK,htmlBuilder:au,mathmlBuilder:su});nu({type:"array",names:["gathered","gather","gather*"],props:{numArgs:0},handler(t){["gather","gather*"].includes(t.envName)&&j4(t);var e={cols:[{type:"align",align:"c"}],addJot:!0,colSeparationType:"gather",autoTag:KD(t.envName),emptySingleRow:!0,leqno:t.parser.settings.leqno};return Bf(t.parser,e,"display")},htmlBuilder:au,mathmlBuilder:su});nu({type:"array",names:["alignat","alignat*","alignedat"],props:{numArgs:1},handler:gK,htmlBuilder:au,mathmlBuilder:su});nu({type:"array",names:["equation","equation*"],props:{numArgs:0},handler(t){j4(t);var e={autoTag:KD(t.envName),emptySingleRow:!0,singleRow:!0,maxNumCols:1,leqno:t.parser.settings.leqno};return Bf(t.parser,e,"display")},htmlBuilder:au,mathmlBuilder:su});nu({type:"array",names:["CD"],props:{numArgs:0},handler(t){return j4(t),kLe(t.parser)},htmlBuilder:au,mathmlBuilder:su});he("\\nonumber","\\gdef\\@eqnsw{0}");he("\\notag","\\nonumber");Bt({type:"text",names:["\\hline","\\hdashline"],props:{numArgs:0,allowedInText:!0,allowedInMath:!0},handler(t,e){throw new wt(t.funcName+" valid only within array environment")}});bX=pK;Bt({type:"environment",names:["\\begin","\\end"],props:{numArgs:1,argTypes:["text"]},handler(t,e){var{parser:r,funcName:i}=t,n=e[0];if(n.type!=="ordgroup")throw new wt("Invalid environment name",n);for(var a="",s=0;s{var r=t.font,i=e.withFont(r);return ii(t.body,i)},"htmlBuilder$5"),vK=o((t,e)=>{var r=t.font,i=e.withFont(r);return $i(t.body,i)},"mathmlBuilder$4"),TX={"\\Bbb":"\\mathbb","\\bold":"\\mathbf","\\frak":"\\mathfrak","\\bm":"\\boldsymbol"};Bt({type:"font",names:["\\mathrm","\\mathit","\\mathbf","\\mathnormal","\\mathsfit","\\mathbb","\\mathcal","\\mathfrak","\\mathscr","\\mathsf","\\mathtt","\\Bbb","\\bold","\\frak"],props:{numArgs:1,allowedInArgument:!0},handler:o((t,e)=>{var{parser:r,funcName:i}=t,n=z4(e[0]),a=i;return a in TX&&(a=TX[a]),{type:"font",mode:r.mode,font:a.slice(1),body:n}},"handler"),htmlBuilder:yK,mathmlBuilder:vK});Bt({type:"mclass",names:["\\boldsymbol","\\bm"],props:{numArgs:1},handler:o((t,e)=>{var{parser:r}=t,i=e[0],n=ui.isCharacterBox(i);return{type:"mclass",mode:r.mode,mclass:H4(i),body:[{type:"font",mode:r.mode,font:"boldsymbol",body:i}],isCharacterBox:n}},"handler")});Bt({type:"font",names:["\\rm","\\sf","\\tt","\\bf","\\it","\\cal"],props:{numArgs:0,allowedInText:!0},handler:o((t,e)=>{var{parser:r,funcName:i,breakOnTokenText:n}=t,{mode:a}=r,s=r.parseExpression(!0,n),l="math"+i.slice(1);return{type:"font",mode:a,font:l,body:{type:"ordgroup",mode:r.mode,body:s}}},"handler"),htmlBuilder:yK,mathmlBuilder:vK});xK=o((t,e)=>{var r=e;return t==="display"?r=r.id>=gr.SCRIPT.id?r.text():gr.DISPLAY:t==="text"&&r.size===gr.DISPLAY.size?r=gr.TEXT:t==="script"?r=gr.SCRIPT:t==="scriptscript"&&(r=gr.SCRIPTSCRIPT),r},"adjustStyle"),ZD=o((t,e)=>{var r=xK(t.size,e.style),i=r.fracNum(),n=r.fracDen(),a;a=e.havingStyle(i);var s=ii(t.numer,a,e);if(t.continued){var l=8.5/e.fontMetrics().ptPerEm,u=3.5/e.fontMetrics().ptPerEm;s.height=s.height0?g=3*p:g=7*p,y=e.fontMetrics().denom1):(d>0?(m=e.fontMetrics().num2,g=p):(m=e.fontMetrics().num3,g=3*p),y=e.fontMetrics().denom2);var v;if(f){var b=e.fontMetrics().axisHeight;m-s.depth-(b+.5*d){var r=new Ct.MathNode("mfrac",[$i(t.numer,e),$i(t.denom,e)]);if(!t.hasBarLine)r.setAttribute("linethickness","0px");else if(t.barSize){var i=wn(t.barSize,e);r.setAttribute("linethickness",Rt(i))}var n=xK(t.size,e.style);if(n.size!==e.style.size){r=new Ct.MathNode("mstyle",[r]);var a=n.size===gr.DISPLAY.size?"true":"false";r.setAttribute("displaystyle",a),r.setAttribute("scriptlevel","0")}if(t.leftDelim!=null||t.rightDelim!=null){var s=[];if(t.leftDelim!=null){var l=new Ct.MathNode("mo",[new Ct.TextNode(t.leftDelim.replace("\\",""))]);l.setAttribute("fence","true"),s.push(l)}if(s.push(r),t.rightDelim!=null){var u=new Ct.MathNode("mo",[new Ct.TextNode(t.rightDelim.replace("\\",""))]);u.setAttribute("fence","true"),s.push(u)}return qD(s)}return r},"mathmlBuilder$3");Bt({type:"genfrac",names:["\\dfrac","\\frac","\\tfrac","\\dbinom","\\binom","\\tbinom","\\\\atopfrac","\\\\bracefrac","\\\\brackfrac"],props:{numArgs:2,allowedInArgument:!0},handler:o((t,e)=>{var{parser:r,funcName:i}=t,n=e[0],a=e[1],s,l=null,u=null,h="auto";switch(i){case"\\dfrac":case"\\frac":case"\\tfrac":s=!0;break;case"\\\\atopfrac":s=!1;break;case"\\dbinom":case"\\binom":case"\\tbinom":s=!1,l="(",u=")";break;case"\\\\bracefrac":s=!1,l="\\{",u="\\}";break;case"\\\\brackfrac":s=!1,l="[",u="]";break;default:throw new Error("Unrecognized genfrac command")}switch(i){case"\\dfrac":case"\\dbinom":h="display";break;case"\\tfrac":case"\\tbinom":h="text";break}return{type:"genfrac",mode:r.mode,continued:!1,numer:n,denom:a,hasBarLine:s,leftDelim:l,rightDelim:u,size:h,barSize:null}},"handler"),htmlBuilder:ZD,mathmlBuilder:JD});Bt({type:"genfrac",names:["\\cfrac"],props:{numArgs:2},handler:o((t,e)=>{var{parser:r,funcName:i}=t,n=e[0],a=e[1];return{type:"genfrac",mode:r.mode,continued:!0,numer:n,denom:a,hasBarLine:!0,leftDelim:null,rightDelim:null,size:"display",barSize:null}},"handler")});Bt({type:"infix",names:["\\over","\\choose","\\atop","\\brace","\\brack"],props:{numArgs:0,infix:!0},handler(t){var{parser:e,funcName:r,token:i}=t,n;switch(r){case"\\over":n="\\frac";break;case"\\choose":n="\\binom";break;case"\\atop":n="\\\\atopfrac";break;case"\\brace":n="\\\\bracefrac";break;case"\\brack":n="\\\\brackfrac";break;default:throw new Error("Unrecognized infix genfrac command")}return{type:"infix",mode:e.mode,replaceWith:n,token:i}}});kX=["display","text","script","scriptscript"],CX=o(function(e){var r=null;return e.length>0&&(r=e,r=r==="."?null:r),r},"delimFromValue");Bt({type:"genfrac",names:["\\genfrac"],props:{numArgs:6,allowedInArgument:!0,argTypes:["math","math","size","text","math","math"]},handler(t,e){var{parser:r}=t,i=e[4],n=e[5],a=z4(e[0]),s=a.type==="atom"&&a.family==="open"?CX(a.text):null,l=z4(e[1]),u=l.type==="atom"&&l.family==="close"?CX(l.text):null,h=Gr(e[2],"size"),f,d=null;h.isBlank?f=!0:(d=h.value,f=d.number>0);var p="auto",m=e[3];if(m.type==="ordgroup"){if(m.body.length>0){var g=Gr(m.body[0],"textord");p=kX[Number(g.text)]}}else m=Gr(m,"textord"),p=kX[Number(m.text)];return{type:"genfrac",mode:r.mode,numer:i,denom:n,continued:!1,hasBarLine:f,barSize:d,leftDelim:s,rightDelim:u,size:p}},htmlBuilder:ZD,mathmlBuilder:JD});Bt({type:"infix",names:["\\above"],props:{numArgs:1,argTypes:["size"],infix:!0},handler(t,e){var{parser:r,funcName:i,token:n}=t;return{type:"infix",mode:r.mode,replaceWith:"\\\\abovefrac",size:Gr(e[0],"size").value,token:n}}});Bt({type:"genfrac",names:["\\\\abovefrac"],props:{numArgs:3,argTypes:["math","size","math"]},handler:o((t,e)=>{var{parser:r,funcName:i}=t,n=e[0],a=mDe(Gr(e[1],"infix").size),s=e[2],l=a.number>0;return{type:"genfrac",mode:r.mode,numer:n,denom:s,continued:!1,hasBarLine:l,barSize:a,leftDelim:null,rightDelim:null,size:"auto"}},"handler"),htmlBuilder:ZD,mathmlBuilder:JD});bK=o((t,e)=>{var r=e.style,i,n;t.type==="supsub"?(i=t.sup?ii(t.sup,e.havingStyle(r.sup()),e):ii(t.sub,e.havingStyle(r.sub()),e),n=Gr(t.base,"horizBrace")):n=Gr(t,"horizBrace");var a=ii(n.base,e.havingBaseStyle(gr.DISPLAY)),s=kh.svgSpan(n,e),l;if(n.isOver?(l=je.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:a},{type:"kern",size:.1},{type:"elem",elem:s}]},e),l.children[0].children[0].children[1].classes.push("svg-align")):(l=je.makeVList({positionType:"bottom",positionData:a.depth+.1+s.height,children:[{type:"elem",elem:s},{type:"kern",size:.1},{type:"elem",elem:a}]},e),l.children[0].children[0].children[0].classes.push("svg-align")),i){var u=je.makeSpan(["mord",n.isOver?"mover":"munder"],[l],e);n.isOver?l=je.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:u},{type:"kern",size:.2},{type:"elem",elem:i}]},e):l=je.makeVList({positionType:"bottom",positionData:u.depth+.2+i.height+i.depth,children:[{type:"elem",elem:i},{type:"kern",size:.2},{type:"elem",elem:u}]},e)}return je.makeSpan(["mord",n.isOver?"mover":"munder"],[l],e)},"htmlBuilder$3"),BLe=o((t,e)=>{var r=kh.mathMLnode(t.label);return new Ct.MathNode(t.isOver?"mover":"munder",[$i(t.base,e),r])},"mathmlBuilder$2");Bt({type:"horizBrace",names:["\\overbrace","\\underbrace"],props:{numArgs:1},handler(t,e){var{parser:r,funcName:i}=t;return{type:"horizBrace",mode:r.mode,label:i,isOver:/^\\over/.test(i),base:e[0]}},htmlBuilder:bK,mathmlBuilder:BLe});Bt({type:"href",names:["\\href"],props:{numArgs:2,argTypes:["url","original"],allowedInText:!0},handler:o((t,e)=>{var{parser:r}=t,i=e[1],n=Gr(e[0],"url").url;return r.settings.isTrusted({command:"\\href",url:n})?{type:"href",mode:r.mode,href:n,body:$n(i)}:r.formatUnsupportedCmd("\\href")},"handler"),htmlBuilder:o((t,e)=>{var r=ca(t.body,e,!1);return je.makeAnchor(t.href,[],r,e)},"htmlBuilder"),mathmlBuilder:o((t,e)=>{var r=Pf(t.body,e);return r instanceof Ms||(r=new Ms("mrow",[r])),r.setAttribute("href",t.href),r},"mathmlBuilder")});Bt({type:"href",names:["\\url"],props:{numArgs:1,argTypes:["url"],allowedInText:!0},handler:o((t,e)=>{var{parser:r}=t,i=Gr(e[0],"url").url;if(!r.settings.isTrusted({command:"\\url",url:i}))return r.formatUnsupportedCmd("\\url");for(var n=[],a=0;a{var{parser:r,funcName:i,token:n}=t,a=Gr(e[0],"raw").string,s=e[1];r.settings.strict&&r.settings.reportNonstrict("htmlExtension","HTML extension is disabled on strict mode");var l,u={};switch(i){case"\\htmlClass":u.class=a,l={command:"\\htmlClass",class:a};break;case"\\htmlId":u.id=a,l={command:"\\htmlId",id:a};break;case"\\htmlStyle":u.style=a,l={command:"\\htmlStyle",style:a};break;case"\\htmlData":{for(var h=a.split(","),f=0;f{var r=ca(t.body,e,!1),i=["enclosing"];t.attributes.class&&i.push(...t.attributes.class.trim().split(/\s+/));var n=je.makeSpan(i,r,e);for(var a in t.attributes)a!=="class"&&t.attributes.hasOwnProperty(a)&&n.setAttribute(a,t.attributes[a]);return n},"htmlBuilder"),mathmlBuilder:o((t,e)=>Pf(t.body,e),"mathmlBuilder")});Bt({type:"htmlmathml",names:["\\html@mathml"],props:{numArgs:2,allowedInText:!0},handler:o((t,e)=>{var{parser:r}=t;return{type:"htmlmathml",mode:r.mode,html:$n(e[0]),mathml:$n(e[1])}},"handler"),htmlBuilder:o((t,e)=>{var r=ca(t.html,e,!1);return je.makeFragment(r)},"htmlBuilder"),mathmlBuilder:o((t,e)=>Pf(t.mathml,e),"mathmlBuilder")});wD=o(function(e){if(/^[-+]? *(\d+(\.\d*)?|\.\d+)$/.test(e))return{number:+e,unit:"bp"};var r=/([-+]?) *(\d+(?:\.\d*)?|\.\d+) *([a-z]{2})/.exec(e);if(!r)throw new wt("Invalid size: '"+e+"' in \\includegraphics");var i={number:+(r[1]+r[2]),unit:r[3]};if(!$X(i))throw new wt("Invalid unit: '"+i.unit+"' in \\includegraphics.");return i},"sizeData");Bt({type:"includegraphics",names:["\\includegraphics"],props:{numArgs:1,numOptionalArgs:1,argTypes:["raw","url"],allowedInText:!1},handler:o((t,e,r)=>{var{parser:i}=t,n={number:0,unit:"em"},a={number:.9,unit:"em"},s={number:0,unit:"em"},l="";if(r[0])for(var u=Gr(r[0],"raw").string,h=u.split(","),f=0;f{var r=wn(t.height,e),i=0;t.totalheight.number>0&&(i=wn(t.totalheight,e)-r);var n=0;t.width.number>0&&(n=wn(t.width,e));var a={height:Rt(r+i)};n>0&&(a.width=Rt(n)),i>0&&(a.verticalAlign=Rt(-i));var s=new LD(t.src,t.alt,a);return s.height=r,s.depth=i,s},"htmlBuilder"),mathmlBuilder:o((t,e)=>{var r=new Ct.MathNode("mglyph",[]);r.setAttribute("alt",t.alt);var i=wn(t.height,e),n=0;if(t.totalheight.number>0&&(n=wn(t.totalheight,e)-i,r.setAttribute("valign",Rt(-n))),r.setAttribute("height",Rt(i+n)),t.width.number>0){var a=wn(t.width,e);r.setAttribute("width",Rt(a))}return r.setAttribute("src",t.src),r},"mathmlBuilder")});Bt({type:"kern",names:["\\kern","\\mkern","\\hskip","\\mskip"],props:{numArgs:1,argTypes:["size"],primitive:!0,allowedInText:!0},handler(t,e){var{parser:r,funcName:i}=t,n=Gr(e[0],"size");if(r.settings.strict){var a=i[1]==="m",s=n.value.unit==="mu";a?(s||r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+i+" supports only mu units, "+("not "+n.value.unit+" units")),r.mode!=="math"&&r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+i+" works only in math mode")):s&&r.settings.reportNonstrict("mathVsTextUnits","LaTeX's "+i+" doesn't support mu units")}return{type:"kern",mode:r.mode,dimension:n.value}},htmlBuilder(t,e){return je.makeGlue(t.dimension,e)},mathmlBuilder(t,e){var r=wn(t.dimension,e);return new Ct.SpaceNode(r)}});Bt({type:"lap",names:["\\mathllap","\\mathrlap","\\mathclap"],props:{numArgs:1,allowedInText:!0},handler:o((t,e)=>{var{parser:r,funcName:i}=t,n=e[0];return{type:"lap",mode:r.mode,alignment:i.slice(5),body:n}},"handler"),htmlBuilder:o((t,e)=>{var r;t.alignment==="clap"?(r=je.makeSpan([],[ii(t.body,e)]),r=je.makeSpan(["inner"],[r],e)):r=je.makeSpan(["inner"],[ii(t.body,e)]);var i=je.makeSpan(["fix"],[]),n=je.makeSpan([t.alignment],[r,i],e),a=je.makeSpan(["strut"]);return a.style.height=Rt(n.height+n.depth),n.depth&&(a.style.verticalAlign=Rt(-n.depth)),n.children.unshift(a),n=je.makeSpan(["thinbox"],[n],e),je.makeSpan(["mord","vbox"],[n],e)},"htmlBuilder"),mathmlBuilder:o((t,e)=>{var r=new Ct.MathNode("mpadded",[$i(t.body,e)]);if(t.alignment!=="rlap"){var i=t.alignment==="llap"?"-1":"-0.5";r.setAttribute("lspace",i+"width")}return r.setAttribute("width","0px"),r},"mathmlBuilder")});Bt({type:"styling",names:["\\(","$"],props:{numArgs:0,allowedInText:!0,allowedInMath:!1},handler(t,e){var{funcName:r,parser:i}=t,n=i.mode;i.switchMode("math");var a=r==="\\("?"\\)":"$",s=i.parseExpression(!1,a);return i.expect(a),i.switchMode(n),{type:"styling",mode:i.mode,style:"text",body:s}}});Bt({type:"text",names:["\\)","\\]"],props:{numArgs:0,allowedInText:!0,allowedInMath:!1},handler(t,e){throw new wt("Mismatched "+t.funcName)}});wX=o((t,e)=>{switch(e.style.size){case gr.DISPLAY.size:return t.display;case gr.TEXT.size:return t.text;case gr.SCRIPT.size:return t.script;case gr.SCRIPTSCRIPT.size:return t.scriptscript;default:return t.text}},"chooseMathStyle");Bt({type:"mathchoice",names:["\\mathchoice"],props:{numArgs:4,primitive:!0},handler:o((t,e)=>{var{parser:r}=t;return{type:"mathchoice",mode:r.mode,display:$n(e[0]),text:$n(e[1]),script:$n(e[2]),scriptscript:$n(e[3])}},"handler"),htmlBuilder:o((t,e)=>{var r=wX(t,e),i=ca(r,e,!1);return je.makeFragment(i)},"htmlBuilder"),mathmlBuilder:o((t,e)=>{var r=wX(t,e);return Pf(r,e)},"mathmlBuilder")});TK=o((t,e,r,i,n,a,s)=>{t=je.makeSpan([],[t]);var l=r&&ui.isCharacterBox(r),u,h;if(e){var f=ii(e,i.havingStyle(n.sup()),i);h={elem:f,kern:Math.max(i.fontMetrics().bigOpSpacing1,i.fontMetrics().bigOpSpacing3-f.depth)}}if(r){var d=ii(r,i.havingStyle(n.sub()),i);u={elem:d,kern:Math.max(i.fontMetrics().bigOpSpacing2,i.fontMetrics().bigOpSpacing4-d.height)}}var p;if(h&&u){var m=i.fontMetrics().bigOpSpacing5+u.elem.height+u.elem.depth+u.kern+t.depth+s;p=je.makeVList({positionType:"bottom",positionData:m,children:[{type:"kern",size:i.fontMetrics().bigOpSpacing5},{type:"elem",elem:u.elem,marginLeft:Rt(-a)},{type:"kern",size:u.kern},{type:"elem",elem:t},{type:"kern",size:h.kern},{type:"elem",elem:h.elem,marginLeft:Rt(a)},{type:"kern",size:i.fontMetrics().bigOpSpacing5}]},i)}else if(u){var g=t.height-s;p=je.makeVList({positionType:"top",positionData:g,children:[{type:"kern",size:i.fontMetrics().bigOpSpacing5},{type:"elem",elem:u.elem,marginLeft:Rt(-a)},{type:"kern",size:u.kern},{type:"elem",elem:t}]},i)}else if(h){var y=t.depth+s;p=je.makeVList({positionType:"bottom",positionData:y,children:[{type:"elem",elem:t},{type:"kern",size:h.kern},{type:"elem",elem:h.elem,marginLeft:Rt(a)},{type:"kern",size:i.fontMetrics().bigOpSpacing5}]},i)}else return t;var v=[p];if(u&&a!==0&&!l){var x=je.makeSpan(["mspace"],[],i);x.style.marginRight=Rt(a),v.unshift(x)}return je.makeSpan(["mop","op-limits"],v,i)},"assembleSupSub"),kK=["\\smallint"],Lg=o((t,e)=>{var r,i,n=!1,a;t.type==="supsub"?(r=t.sup,i=t.sub,a=Gr(t.base,"op"),n=!0):a=Gr(t,"op");var s=e.style,l=!1;s.size===gr.DISPLAY.size&&a.symbol&&!kK.includes(a.name)&&(l=!0);var u;if(a.symbol){var h=l?"Size2-Regular":"Size1-Regular",f="";if((a.name==="\\oiint"||a.name==="\\oiiint")&&(f=a.name.slice(1),a.name=f==="oiint"?"\\iint":"\\iiint"),u=je.makeSymbol(a.name,h,"math",e,["mop","op-symbol",l?"large-op":"small-op"]),f.length>0){var d=u.italic,p=je.staticSvg(f+"Size"+(l?"2":"1"),e);u=je.makeVList({positionType:"individualShift",children:[{type:"elem",elem:u,shift:0},{type:"elem",elem:p,shift:l?.08:0}]},e),a.name="\\"+f,u.classes.unshift("mop"),u.italic=d}}else if(a.body){var m=ca(a.body,e,!0);m.length===1&&m[0]instanceof uo?(u=m[0],u.classes[0]="mop"):u=je.makeSpan(["mop"],m,e)}else{for(var g=[],y=1;y{var r;if(t.symbol)r=new Ms("mo",[wl(t.name,t.mode)]),kK.includes(t.name)&&r.setAttribute("largeop","false");else if(t.body)r=new Ms("mo",ho(t.body,e));else{r=new Ms("mi",[new Cl(t.name.slice(1))]);var i=new Ms("mo",[wl("\u2061","text")]);t.parentIsSupSub?r=new Ms("mrow",[r,i]):r=KX([r,i])}return r},"mathmlBuilder$1"),FLe={"\u220F":"\\prod","\u2210":"\\coprod","\u2211":"\\sum","\u22C0":"\\bigwedge","\u22C1":"\\bigvee","\u22C2":"\\bigcap","\u22C3":"\\bigcup","\u2A00":"\\bigodot","\u2A01":"\\bigoplus","\u2A02":"\\bigotimes","\u2A04":"\\biguplus","\u2A06":"\\bigsqcup"};Bt({type:"op",names:["\\coprod","\\bigvee","\\bigwedge","\\biguplus","\\bigcap","\\bigcup","\\intop","\\prod","\\sum","\\bigotimes","\\bigoplus","\\bigodot","\\bigsqcup","\\smallint","\u220F","\u2210","\u2211","\u22C0","\u22C1","\u22C2","\u22C3","\u2A00","\u2A01","\u2A02","\u2A04","\u2A06"],props:{numArgs:0},handler:o((t,e)=>{var{parser:r,funcName:i}=t,n=i;return n.length===1&&(n=FLe[n]),{type:"op",mode:r.mode,limits:!0,parentIsSupSub:!1,symbol:!0,name:n}},"handler"),htmlBuilder:Lg,mathmlBuilder:Qx});Bt({type:"op",names:["\\mathop"],props:{numArgs:1,primitive:!0},handler:o((t,e)=>{var{parser:r}=t,i=e[0];return{type:"op",mode:r.mode,limits:!1,parentIsSupSub:!1,symbol:!1,body:$n(i)}},"handler"),htmlBuilder:Lg,mathmlBuilder:Qx});$Le={"\u222B":"\\int","\u222C":"\\iint","\u222D":"\\iiint","\u222E":"\\oint","\u222F":"\\oiint","\u2230":"\\oiiint"};Bt({type:"op",names:["\\arcsin","\\arccos","\\arctan","\\arctg","\\arcctg","\\arg","\\ch","\\cos","\\cosec","\\cosh","\\cot","\\cotg","\\coth","\\csc","\\ctg","\\cth","\\deg","\\dim","\\exp","\\hom","\\ker","\\lg","\\ln","\\log","\\sec","\\sin","\\sinh","\\sh","\\tan","\\tanh","\\tg","\\th"],props:{numArgs:0},handler(t){var{parser:e,funcName:r}=t;return{type:"op",mode:e.mode,limits:!1,parentIsSupSub:!1,symbol:!1,name:r}},htmlBuilder:Lg,mathmlBuilder:Qx});Bt({type:"op",names:["\\det","\\gcd","\\inf","\\lim","\\max","\\min","\\Pr","\\sup"],props:{numArgs:0},handler(t){var{parser:e,funcName:r}=t;return{type:"op",mode:e.mode,limits:!0,parentIsSupSub:!1,symbol:!1,name:r}},htmlBuilder:Lg,mathmlBuilder:Qx});Bt({type:"op",names:["\\int","\\iint","\\iiint","\\oint","\\oiint","\\oiiint","\u222B","\u222C","\u222D","\u222E","\u222F","\u2230"],props:{numArgs:0},handler(t){var{parser:e,funcName:r}=t,i=r;return i.length===1&&(i=$Le[i]),{type:"op",mode:e.mode,limits:!1,parentIsSupSub:!1,symbol:!0,name:i}},htmlBuilder:Lg,mathmlBuilder:Qx});CK=o((t,e)=>{var r,i,n=!1,a;t.type==="supsub"?(r=t.sup,i=t.sub,a=Gr(t.base,"operatorname"),n=!0):a=Gr(t,"operatorname");var s;if(a.body.length>0){for(var l=a.body.map(d=>{var p=d.text;return typeof p=="string"?{type:"textord",mode:d.mode,text:p}:d}),u=ca(l,e.withFont("mathrm"),!0),h=0;h{for(var r=ho(t.body,e.withFont("mathrm")),i=!0,n=0;nf.toText()).join("");r=[new Ct.TextNode(l)]}var u=new Ct.MathNode("mi",r);u.setAttribute("mathvariant","normal");var h=new Ct.MathNode("mo",[wl("\u2061","text")]);return t.parentIsSupSub?new Ct.MathNode("mrow",[u,h]):Ct.newDocumentFragment([u,h])},"mathmlBuilder");Bt({type:"operatorname",names:["\\operatorname@","\\operatornamewithlimits"],props:{numArgs:1},handler:o((t,e)=>{var{parser:r,funcName:i}=t,n=e[0];return{type:"operatorname",mode:r.mode,body:$n(n),alwaysHandleSupSub:i==="\\operatornamewithlimits",limits:!1,parentIsSupSub:!1}},"handler"),htmlBuilder:CK,mathmlBuilder:zLe});he("\\operatorname","\\@ifstar\\operatornamewithlimits\\operatorname@");Up({type:"ordgroup",htmlBuilder(t,e){return t.semisimple?je.makeFragment(ca(t.body,e,!1)):je.makeSpan(["mord"],ca(t.body,e,!0),e)},mathmlBuilder(t,e){return Pf(t.body,e,!0)}});Bt({type:"overline",names:["\\overline"],props:{numArgs:1},handler(t,e){var{parser:r}=t,i=e[0];return{type:"overline",mode:r.mode,body:i}},htmlBuilder(t,e){var r=ii(t.body,e.havingCrampedStyle()),i=je.makeLineSpan("overline-line",e),n=e.fontMetrics().defaultRuleThickness,a=je.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:r},{type:"kern",size:3*n},{type:"elem",elem:i},{type:"kern",size:n}]},e);return je.makeSpan(["mord","overline"],[a],e)},mathmlBuilder(t,e){var r=new Ct.MathNode("mo",[new Ct.TextNode("\u203E")]);r.setAttribute("stretchy","true");var i=new Ct.MathNode("mover",[$i(t.body,e),r]);return i.setAttribute("accent","true"),i}});Bt({type:"phantom",names:["\\phantom"],props:{numArgs:1,allowedInText:!0},handler:o((t,e)=>{var{parser:r}=t,i=e[0];return{type:"phantom",mode:r.mode,body:$n(i)}},"handler"),htmlBuilder:o((t,e)=>{var r=ca(t.body,e.withPhantom(),!1);return je.makeFragment(r)},"htmlBuilder"),mathmlBuilder:o((t,e)=>{var r=ho(t.body,e);return new Ct.MathNode("mphantom",r)},"mathmlBuilder")});Bt({type:"hphantom",names:["\\hphantom"],props:{numArgs:1,allowedInText:!0},handler:o((t,e)=>{var{parser:r}=t,i=e[0];return{type:"hphantom",mode:r.mode,body:i}},"handler"),htmlBuilder:o((t,e)=>{var r=je.makeSpan([],[ii(t.body,e.withPhantom())]);if(r.height=0,r.depth=0,r.children)for(var i=0;i{var r=ho($n(t.body),e),i=new Ct.MathNode("mphantom",r),n=new Ct.MathNode("mpadded",[i]);return n.setAttribute("height","0px"),n.setAttribute("depth","0px"),n},"mathmlBuilder")});Bt({type:"vphantom",names:["\\vphantom"],props:{numArgs:1,allowedInText:!0},handler:o((t,e)=>{var{parser:r}=t,i=e[0];return{type:"vphantom",mode:r.mode,body:i}},"handler"),htmlBuilder:o((t,e)=>{var r=je.makeSpan(["inner"],[ii(t.body,e.withPhantom())]),i=je.makeSpan(["fix"],[]);return je.makeSpan(["mord","rlap"],[r,i],e)},"htmlBuilder"),mathmlBuilder:o((t,e)=>{var r=ho($n(t.body),e),i=new Ct.MathNode("mphantom",r),n=new Ct.MathNode("mpadded",[i]);return n.setAttribute("width","0px"),n},"mathmlBuilder")});Bt({type:"raisebox",names:["\\raisebox"],props:{numArgs:2,argTypes:["size","hbox"],allowedInText:!0},handler(t,e){var{parser:r}=t,i=Gr(e[0],"size").value,n=e[1];return{type:"raisebox",mode:r.mode,dy:i,body:n}},htmlBuilder(t,e){var r=ii(t.body,e),i=wn(t.dy,e);return je.makeVList({positionType:"shift",positionData:-i,children:[{type:"elem",elem:r}]},e)},mathmlBuilder(t,e){var r=new Ct.MathNode("mpadded",[$i(t.body,e)]),i=t.dy.number+t.dy.unit;return r.setAttribute("voffset",i),r}});Bt({type:"internal",names:["\\relax"],props:{numArgs:0,allowedInText:!0,allowedInArgument:!0},handler(t){var{parser:e}=t;return{type:"internal",mode:e.mode}}});Bt({type:"rule",names:["\\rule"],props:{numArgs:2,numOptionalArgs:1,allowedInText:!0,allowedInMath:!0,argTypes:["size","size","size"]},handler(t,e,r){var{parser:i}=t,n=r[0],a=Gr(e[0],"size"),s=Gr(e[1],"size");return{type:"rule",mode:i.mode,shift:n&&Gr(n,"size").value,width:a.value,height:s.value}},htmlBuilder(t,e){var r=je.makeSpan(["mord","rule"],[],e),i=wn(t.width,e),n=wn(t.height,e),a=t.shift?wn(t.shift,e):0;return r.style.borderRightWidth=Rt(i),r.style.borderTopWidth=Rt(n),r.style.bottom=Rt(a),r.width=i,r.height=n+a,r.depth=-a,r.maxFontSize=n*1.125*e.sizeMultiplier,r},mathmlBuilder(t,e){var r=wn(t.width,e),i=wn(t.height,e),n=t.shift?wn(t.shift,e):0,a=e.color&&e.getColor()||"black",s=new Ct.MathNode("mspace");s.setAttribute("mathbackground",a),s.setAttribute("width",Rt(r)),s.setAttribute("height",Rt(i));var l=new Ct.MathNode("mpadded",[s]);return n>=0?l.setAttribute("height",Rt(n)):(l.setAttribute("height",Rt(n)),l.setAttribute("depth",Rt(-n))),l.setAttribute("voffset",Rt(n)),l}});o(wK,"sizingGroup");EX=["\\tiny","\\sixptsize","\\scriptsize","\\footnotesize","\\small","\\normalsize","\\large","\\Large","\\LARGE","\\huge","\\Huge"],GLe=o((t,e)=>{var r=e.havingSize(t.size);return wK(t.body,r,e)},"htmlBuilder");Bt({type:"sizing",names:EX,props:{numArgs:0,allowedInText:!0},handler:o((t,e)=>{var{breakOnTokenText:r,funcName:i,parser:n}=t,a=n.parseExpression(!1,r);return{type:"sizing",mode:n.mode,size:EX.indexOf(i)+1,body:a}},"handler"),htmlBuilder:GLe,mathmlBuilder:o((t,e)=>{var r=e.havingSize(t.size),i=ho(t.body,r),n=new Ct.MathNode("mstyle",i);return n.setAttribute("mathsize",Rt(r.sizeMultiplier)),n},"mathmlBuilder")});Bt({type:"smash",names:["\\smash"],props:{numArgs:1,numOptionalArgs:1,allowedInText:!0},handler:o((t,e,r)=>{var{parser:i}=t,n=!1,a=!1,s=r[0]&&Gr(r[0],"ordgroup");if(s)for(var l="",u=0;u{var r=je.makeSpan([],[ii(t.body,e)]);if(!t.smashHeight&&!t.smashDepth)return r;if(t.smashHeight&&(r.height=0,r.children))for(var i=0;i{var r=new Ct.MathNode("mpadded",[$i(t.body,e)]);return t.smashHeight&&r.setAttribute("height","0px"),t.smashDepth&&r.setAttribute("depth","0px"),r},"mathmlBuilder")});Bt({type:"sqrt",names:["\\sqrt"],props:{numArgs:1,numOptionalArgs:1},handler(t,e,r){var{parser:i}=t,n=r[0],a=e[0];return{type:"sqrt",mode:i.mode,body:a,index:n}},htmlBuilder(t,e){var r=ii(t.body,e.havingCrampedStyle());r.height===0&&(r.height=e.fontMetrics().xHeight),r=je.wrapFragment(r,e);var i=e.fontMetrics(),n=i.defaultRuleThickness,a=n;e.style.idr.height+r.depth+s&&(s=(s+d-r.height-r.depth)/2);var p=u.height-r.height-s-h;r.style.paddingLeft=Rt(f);var m=je.makeVList({positionType:"firstBaseline",children:[{type:"elem",elem:r,wrapperClasses:["svg-align"]},{type:"kern",size:-(r.height+p)},{type:"elem",elem:u},{type:"kern",size:h}]},e);if(t.index){var g=e.havingStyle(gr.SCRIPTSCRIPT),y=ii(t.index,g,e),v=.6*(m.height-m.depth),x=je.makeVList({positionType:"shift",positionData:-v,children:[{type:"elem",elem:y}]},e),b=je.makeSpan(["root"],[x]);return je.makeSpan(["mord","sqrt"],[b,m],e)}else return je.makeSpan(["mord","sqrt"],[m],e)},mathmlBuilder(t,e){var{body:r,index:i}=t;return i?new Ct.MathNode("mroot",[$i(r,e),$i(i,e)]):new Ct.MathNode("msqrt",[$i(r,e)])}});SX={display:gr.DISPLAY,text:gr.TEXT,script:gr.SCRIPT,scriptscript:gr.SCRIPTSCRIPT};Bt({type:"styling",names:["\\displaystyle","\\textstyle","\\scriptstyle","\\scriptscriptstyle"],props:{numArgs:0,allowedInText:!0,primitive:!0},handler(t,e){var{breakOnTokenText:r,funcName:i,parser:n}=t,a=n.parseExpression(!0,r),s=i.slice(1,i.length-5);return{type:"styling",mode:n.mode,style:s,body:a}},htmlBuilder(t,e){var r=SX[t.style],i=e.havingStyle(r).withFont("");return wK(t.body,i,e)},mathmlBuilder(t,e){var r=SX[t.style],i=e.havingStyle(r),n=ho(t.body,i),a=new Ct.MathNode("mstyle",n),s={display:["0","true"],text:["0","false"],script:["1","false"],scriptscript:["2","false"]},l=s[t.style];return a.setAttribute("scriptlevel",l[0]),a.setAttribute("displaystyle",l[1]),a}});VLe=o(function(e,r){var i=e.base;if(i)if(i.type==="op"){var n=i.limits&&(r.style.size===gr.DISPLAY.size||i.alwaysHandleSupSub);return n?Lg:null}else if(i.type==="operatorname"){var a=i.alwaysHandleSupSub&&(r.style.size===gr.DISPLAY.size||i.limits);return a?CK:null}else{if(i.type==="accent")return ui.isCharacterBox(i.base)?HD:null;if(i.type==="horizBrace"){var s=!e.sub;return s===i.isOver?bK:null}else return null}else return null},"htmlBuilderDelegate");Up({type:"supsub",htmlBuilder(t,e){var r=VLe(t,e);if(r)return r(t,e);var{base:i,sup:n,sub:a}=t,s=ii(i,e),l,u,h=e.fontMetrics(),f=0,d=0,p=i&&ui.isCharacterBox(i);if(n){var m=e.havingStyle(e.style.sup());l=ii(n,m,e),p||(f=s.height-m.fontMetrics().supDrop*m.sizeMultiplier/e.sizeMultiplier)}if(a){var g=e.havingStyle(e.style.sub());u=ii(a,g,e),p||(d=s.depth+g.fontMetrics().subDrop*g.sizeMultiplier/e.sizeMultiplier)}var y;e.style===gr.DISPLAY?y=h.sup1:e.style.cramped?y=h.sup3:y=h.sup2;var v=e.sizeMultiplier,x=Rt(.5/h.ptPerEm/v),b=null;if(u){var T=t.base&&t.base.type==="op"&&t.base.name&&(t.base.name==="\\oiint"||t.base.name==="\\oiiint");(s instanceof uo||T)&&(b=Rt(-s.italic))}var w;if(l&&u){f=Math.max(f,y,l.depth+.25*h.xHeight),d=Math.max(d,h.sub2);var k=h.defaultRuleThickness,C=4*k;if(f-l.depth-(u.height-d)0&&(f+=E,d-=E)}var S=[{type:"elem",elem:u,shift:d,marginRight:x,marginLeft:b},{type:"elem",elem:l,shift:-f,marginRight:x}];w=je.makeVList({positionType:"individualShift",children:S},e)}else if(u){d=Math.max(d,h.sub1,u.height-.8*h.xHeight);var L=[{type:"elem",elem:u,marginLeft:b,marginRight:x}];w=je.makeVList({positionType:"shift",positionData:d,children:L},e)}else if(l)f=Math.max(f,y,l.depth+.25*h.xHeight),w=je.makeVList({positionType:"shift",positionData:-f,children:[{type:"elem",elem:l,marginRight:x}]},e);else throw new Error("supsub must have either sup or sub.");var M=ND(s,"right")||"mord";return je.makeSpan([M],[s,je.makeSpan(["msupsub"],[w])],e)},mathmlBuilder(t,e){var r=!1,i,n;t.base&&t.base.type==="horizBrace"&&(n=!!t.sup,n===t.base.isOver&&(r=!0,i=t.base.isOver)),t.base&&(t.base.type==="op"||t.base.type==="operatorname")&&(t.base.parentIsSupSub=!0);var a=[$i(t.base,e)];t.sub&&a.push($i(t.sub,e)),t.sup&&a.push($i(t.sup,e));var s;if(r)s=i?"mover":"munder";else if(t.sub)if(t.sup){var h=t.base;h&&h.type==="op"&&h.limits&&e.style===gr.DISPLAY||h&&h.type==="operatorname"&&h.alwaysHandleSupSub&&(e.style===gr.DISPLAY||h.limits)?s="munderover":s="msubsup"}else{var u=t.base;u&&u.type==="op"&&u.limits&&(e.style===gr.DISPLAY||u.alwaysHandleSupSub)||u&&u.type==="operatorname"&&u.alwaysHandleSupSub&&(u.limits||e.style===gr.DISPLAY)?s="munder":s="msub"}else{var l=t.base;l&&l.type==="op"&&l.limits&&(e.style===gr.DISPLAY||l.alwaysHandleSupSub)||l&&l.type==="operatorname"&&l.alwaysHandleSupSub&&(l.limits||e.style===gr.DISPLAY)?s="mover":s="msup"}return new Ct.MathNode(s,a)}});Up({type:"atom",htmlBuilder(t,e){return je.mathsym(t.text,t.mode,e,["m"+t.family])},mathmlBuilder(t,e){var r=new Ct.MathNode("mo",[wl(t.text,t.mode)]);if(t.family==="bin"){var i=WD(t,e);i==="bold-italic"&&r.setAttribute("mathvariant",i)}else t.family==="punct"?r.setAttribute("separator","true"):(t.family==="open"||t.family==="close")&&r.setAttribute("stretchy","false");return r}});EK={mi:"italic",mn:"normal",mtext:"normal"};Up({type:"mathord",htmlBuilder(t,e){return je.makeOrd(t,e,"mathord")},mathmlBuilder(t,e){var r=new Ct.MathNode("mi",[wl(t.text,t.mode,e)]),i=WD(t,e)||"italic";return i!==EK[r.type]&&r.setAttribute("mathvariant",i),r}});Up({type:"textord",htmlBuilder(t,e){return je.makeOrd(t,e,"textord")},mathmlBuilder(t,e){var r=wl(t.text,t.mode,e),i=WD(t,e)||"normal",n;return t.mode==="text"?n=new Ct.MathNode("mtext",[r]):/[0-9]/.test(t.text)?n=new Ct.MathNode("mn",[r]):t.text==="\\prime"?n=new Ct.MathNode("mo",[r]):n=new Ct.MathNode("mi",[r]),i!==EK[n.type]&&n.setAttribute("mathvariant",i),n}});ED={"\\nobreak":"nobreak","\\allowbreak":"allowbreak"},SD={" ":{},"\\ ":{},"~":{className:"nobreak"},"\\space":{},"\\nobreakspace":{className:"nobreak"}};Up({type:"spacing",htmlBuilder(t,e){if(SD.hasOwnProperty(t.text)){var r=SD[t.text].className||"";if(t.mode==="text"){var i=je.makeOrd(t,e,"textord");return i.classes.push(r),i}else return je.makeSpan(["mspace",r],[je.mathsym(t.text,t.mode,e)],e)}else{if(ED.hasOwnProperty(t.text))return je.makeSpan(["mspace",ED[t.text]],[],e);throw new wt('Unknown type of space "'+t.text+'"')}},mathmlBuilder(t,e){var r;if(SD.hasOwnProperty(t.text))r=new Ct.MathNode("mtext",[new Ct.TextNode("\xA0")]);else{if(ED.hasOwnProperty(t.text))return new Ct.MathNode("mspace");throw new wt('Unknown type of space "'+t.text+'"')}return r}});AX=o(()=>{var t=new Ct.MathNode("mtd",[]);return t.setAttribute("width","50%"),t},"pad");Up({type:"tag",mathmlBuilder(t,e){var r=new Ct.MathNode("mtable",[new Ct.MathNode("mtr",[AX(),new Ct.MathNode("mtd",[Pf(t.body,e)]),AX(),new Ct.MathNode("mtd",[Pf(t.tag,e)])])]);return r.setAttribute("width","100%"),r}});_X={"\\text":void 0,"\\textrm":"textrm","\\textsf":"textsf","\\texttt":"texttt","\\textnormal":"textrm"},DX={"\\textbf":"textbf","\\textmd":"textmd"},qLe={"\\textit":"textit","\\textup":"textup"},LX=o((t,e)=>{var r=t.font;if(r){if(_X[r])return e.withTextFontFamily(_X[r]);if(DX[r])return e.withTextFontWeight(DX[r]);if(r==="\\emph")return e.fontShape==="textit"?e.withTextFontShape("textup"):e.withTextFontShape("textit")}else return e;return e.withTextFontShape(qLe[r])},"optionsWithFont");Bt({type:"text",names:["\\text","\\textrm","\\textsf","\\texttt","\\textnormal","\\textbf","\\textmd","\\textit","\\textup","\\emph"],props:{numArgs:1,argTypes:["text"],allowedInArgument:!0,allowedInText:!0},handler(t,e){var{parser:r,funcName:i}=t,n=e[0];return{type:"text",mode:r.mode,body:$n(n),font:i}},htmlBuilder(t,e){var r=LX(t,e),i=ca(t.body,r,!0);return je.makeSpan(["mord","text"],i,r)},mathmlBuilder(t,e){var r=LX(t,e);return Pf(t.body,r)}});Bt({type:"underline",names:["\\underline"],props:{numArgs:1,allowedInText:!0},handler(t,e){var{parser:r}=t;return{type:"underline",mode:r.mode,body:e[0]}},htmlBuilder(t,e){var r=ii(t.body,e),i=je.makeLineSpan("underline-line",e),n=e.fontMetrics().defaultRuleThickness,a=je.makeVList({positionType:"top",positionData:r.height,children:[{type:"kern",size:n},{type:"elem",elem:i},{type:"kern",size:3*n},{type:"elem",elem:r}]},e);return je.makeSpan(["mord","underline"],[a],e)},mathmlBuilder(t,e){var r=new Ct.MathNode("mo",[new Ct.TextNode("\u203E")]);r.setAttribute("stretchy","true");var i=new Ct.MathNode("munder",[$i(t.body,e),r]);return i.setAttribute("accentunder","true"),i}});Bt({type:"vcenter",names:["\\vcenter"],props:{numArgs:1,argTypes:["original"],allowedInText:!1},handler(t,e){var{parser:r}=t;return{type:"vcenter",mode:r.mode,body:e[0]}},htmlBuilder(t,e){var r=ii(t.body,e),i=e.fontMetrics().axisHeight,n=.5*(r.height-i-(r.depth+i));return je.makeVList({positionType:"shift",positionData:n,children:[{type:"elem",elem:r}]},e)},mathmlBuilder(t,e){return new Ct.MathNode("mpadded",[$i(t.body,e)],["vcenter"])}});Bt({type:"verb",names:["\\verb"],props:{numArgs:0,allowedInText:!0},handler(t,e,r){throw new wt("\\verb ended by end of line instead of matching delimiter")},htmlBuilder(t,e){for(var r=RX(t),i=[],n=e.havingStyle(e.style.text()),a=0;at.body.replace(/ /g,t.star?"\u2423":"\xA0"),"makeVerb"),Mf=jX,SK=`[ \r + ]`,WLe="\\\\[a-zA-Z@]+",ULe="\\\\[^\uD800-\uDFFF]",HLe="("+WLe+")"+SK+"*",YLe=`\\\\( +|[ \r ]+ +?)[ \r ]*`,BD="[\u0300-\u036F]",jLe=new RegExp(BD+"+$"),XLe="("+SK+"+)|"+(YLe+"|")+"([!-\\[\\]-\u2027\u202A-\uD7FF\uF900-\uFFFF]"+(BD+"*")+"|[\uD800-\uDBFF][\uDC00-\uDFFF]"+(BD+"*")+"|\\\\verb\\*([^]).*?\\4|\\\\verb([^*a-zA-Z]).*?\\5"+("|"+HLe)+("|"+ULe+")"),G4=class{static{o(this,"Lexer")}constructor(e,r){this.input=void 0,this.settings=void 0,this.tokenRegex=void 0,this.catcodes=void 0,this.input=e,this.settings=r,this.tokenRegex=new RegExp(XLe,"g"),this.catcodes={"%":14,"~":13}}setCatcode(e,r){this.catcodes[e]=r}lex(){var e=this.input,r=this.tokenRegex.lastIndex;if(r===e.length)return new Ho("EOF",new co(this,r,r));var i=this.tokenRegex.exec(e);if(i===null||i.index!==r)throw new wt("Unexpected character: '"+e[r]+"'",new Ho(e[r],new co(this,r,r+1)));var n=i[6]||i[3]||(i[2]?"\\ ":" ");if(this.catcodes[n]===14){var a=e.indexOf(` +`,this.tokenRegex.lastIndex);return a===-1?(this.tokenRegex.lastIndex=e.length,this.settings.reportNonstrict("commentAtEnd","% comment has no terminating newline; LaTeX would fail because of commenting the end of math mode (e.g. $)")):this.tokenRegex.lastIndex=a+1,this.lex()}return new Ho(n,new co(this,r,this.tokenRegex.lastIndex))}},FD=class{static{o(this,"Namespace")}constructor(e,r){e===void 0&&(e={}),r===void 0&&(r={}),this.current=void 0,this.builtins=void 0,this.undefStack=void 0,this.current=r,this.builtins=e,this.undefStack=[]}beginGroup(){this.undefStack.push({})}endGroup(){if(this.undefStack.length===0)throw new wt("Unbalanced namespace destruction: attempt to pop global namespace; please report this as a bug");var e=this.undefStack.pop();for(var r in e)e.hasOwnProperty(r)&&(e[r]==null?delete this.current[r]:this.current[r]=e[r])}endGroups(){for(;this.undefStack.length>0;)this.endGroup()}has(e){return this.current.hasOwnProperty(e)||this.builtins.hasOwnProperty(e)}get(e){return this.current.hasOwnProperty(e)?this.current[e]:this.builtins[e]}set(e,r,i){if(i===void 0&&(i=!1),i){for(var n=0;n0&&(this.undefStack[this.undefStack.length-1][e]=r)}else{var a=this.undefStack[this.undefStack.length-1];a&&!a.hasOwnProperty(e)&&(a[e]=this.current[e])}r==null?delete this.current[e]:this.current[e]=r}},KLe=mK;he("\\noexpand",function(t){var e=t.popToken();return t.isExpandable(e.text)&&(e.noexpand=!0,e.treatAsRelax=!0),{tokens:[e],numArgs:0}});he("\\expandafter",function(t){var e=t.popToken();return t.expandOnce(!0),{tokens:[e],numArgs:0}});he("\\@firstoftwo",function(t){var e=t.consumeArgs(2);return{tokens:e[0],numArgs:0}});he("\\@secondoftwo",function(t){var e=t.consumeArgs(2);return{tokens:e[1],numArgs:0}});he("\\@ifnextchar",function(t){var e=t.consumeArgs(3);t.consumeSpaces();var r=t.future();return e[0].length===1&&e[0][0].text===r.text?{tokens:e[1],numArgs:0}:{tokens:e[2],numArgs:0}});he("\\@ifstar","\\@ifnextchar *{\\@firstoftwo{#1}}");he("\\TextOrMath",function(t){var e=t.consumeArgs(2);return t.mode==="text"?{tokens:e[0],numArgs:0}:{tokens:e[1],numArgs:0}});NX={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,a:10,A:10,b:11,B:11,c:12,C:12,d:13,D:13,e:14,E:14,f:15,F:15};he("\\char",function(t){var e=t.popToken(),r,i="";if(e.text==="'")r=8,e=t.popToken();else if(e.text==='"')r=16,e=t.popToken();else if(e.text==="`")if(e=t.popToken(),e.text[0]==="\\")i=e.text.charCodeAt(1);else{if(e.text==="EOF")throw new wt("\\char` missing argument");i=e.text.charCodeAt(0)}else r=10;if(r){if(i=NX[e.text],i==null||i>=r)throw new wt("Invalid base-"+r+" digit "+e.text);for(var n;(n=NX[t.future().text])!=null&&n{var n=t.consumeArg().tokens;if(n.length!==1)throw new wt("\\newcommand's first argument must be a macro name");var a=n[0].text,s=t.isDefined(a);if(s&&!e)throw new wt("\\newcommand{"+a+"} attempting to redefine "+(a+"; use \\renewcommand"));if(!s&&!r)throw new wt("\\renewcommand{"+a+"} when command "+a+" does not yet exist; use \\newcommand");var l=0;if(n=t.consumeArg().tokens,n.length===1&&n[0].text==="["){for(var u="",h=t.expandNextToken();h.text!=="]"&&h.text!=="EOF";)u+=h.text,h=t.expandNextToken();if(!u.match(/^\s*[0-9]+\s*$/))throw new wt("Invalid number of arguments: "+u);l=parseInt(u),n=t.consumeArg().tokens}return s&&i||t.macros.set(a,{tokens:n,numArgs:l}),""},"newcommand");he("\\newcommand",t=>eL(t,!1,!0,!1));he("\\renewcommand",t=>eL(t,!0,!1,!1));he("\\providecommand",t=>eL(t,!0,!0,!0));he("\\message",t=>{var e=t.consumeArgs(1)[0];return console.log(e.reverse().map(r=>r.text).join("")),""});he("\\errmessage",t=>{var e=t.consumeArgs(1)[0];return console.error(e.reverse().map(r=>r.text).join("")),""});he("\\show",t=>{var e=t.popToken(),r=e.text;return console.log(e,t.macros.get(r),Mf[r],ji.math[r],ji.text[r]),""});he("\\bgroup","{");he("\\egroup","}");he("~","\\nobreakspace");he("\\lq","`");he("\\rq","'");he("\\aa","\\r a");he("\\AA","\\r A");he("\\textcopyright","\\html@mathml{\\textcircled{c}}{\\char`\xA9}");he("\\copyright","\\TextOrMath{\\textcopyright}{\\text{\\textcopyright}}");he("\\textregistered","\\html@mathml{\\textcircled{\\scriptsize R}}{\\char`\xAE}");he("\u212C","\\mathscr{B}");he("\u2130","\\mathscr{E}");he("\u2131","\\mathscr{F}");he("\u210B","\\mathscr{H}");he("\u2110","\\mathscr{I}");he("\u2112","\\mathscr{L}");he("\u2133","\\mathscr{M}");he("\u211B","\\mathscr{R}");he("\u212D","\\mathfrak{C}");he("\u210C","\\mathfrak{H}");he("\u2128","\\mathfrak{Z}");he("\\Bbbk","\\Bbb{k}");he("\xB7","\\cdotp");he("\\llap","\\mathllap{\\textrm{#1}}");he("\\rlap","\\mathrlap{\\textrm{#1}}");he("\\clap","\\mathclap{\\textrm{#1}}");he("\\mathstrut","\\vphantom{(}");he("\\underbar","\\underline{\\text{#1}}");he("\\not",'\\html@mathml{\\mathrel{\\mathrlap\\@not}}{\\char"338}');he("\\neq","\\html@mathml{\\mathrel{\\not=}}{\\mathrel{\\char`\u2260}}");he("\\ne","\\neq");he("\u2260","\\neq");he("\\notin","\\html@mathml{\\mathrel{{\\in}\\mathllap{/\\mskip1mu}}}{\\mathrel{\\char`\u2209}}");he("\u2209","\\notin");he("\u2258","\\html@mathml{\\mathrel{=\\kern{-1em}\\raisebox{0.4em}{$\\scriptsize\\frown$}}}{\\mathrel{\\char`\u2258}}");he("\u2259","\\html@mathml{\\stackrel{\\tiny\\wedge}{=}}{\\mathrel{\\char`\u2258}}");he("\u225A","\\html@mathml{\\stackrel{\\tiny\\vee}{=}}{\\mathrel{\\char`\u225A}}");he("\u225B","\\html@mathml{\\stackrel{\\scriptsize\\star}{=}}{\\mathrel{\\char`\u225B}}");he("\u225D","\\html@mathml{\\stackrel{\\tiny\\mathrm{def}}{=}}{\\mathrel{\\char`\u225D}}");he("\u225E","\\html@mathml{\\stackrel{\\tiny\\mathrm{m}}{=}}{\\mathrel{\\char`\u225E}}");he("\u225F","\\html@mathml{\\stackrel{\\tiny?}{=}}{\\mathrel{\\char`\u225F}}");he("\u27C2","\\perp");he("\u203C","\\mathclose{!\\mkern-0.8mu!}");he("\u220C","\\notni");he("\u231C","\\ulcorner");he("\u231D","\\urcorner");he("\u231E","\\llcorner");he("\u231F","\\lrcorner");he("\xA9","\\copyright");he("\xAE","\\textregistered");he("\uFE0F","\\textregistered");he("\\ulcorner",'\\html@mathml{\\@ulcorner}{\\mathop{\\char"231c}}');he("\\urcorner",'\\html@mathml{\\@urcorner}{\\mathop{\\char"231d}}');he("\\llcorner",'\\html@mathml{\\@llcorner}{\\mathop{\\char"231e}}');he("\\lrcorner",'\\html@mathml{\\@lrcorner}{\\mathop{\\char"231f}}');he("\\vdots","{\\varvdots\\rule{0pt}{15pt}}");he("\u22EE","\\vdots");he("\\varGamma","\\mathit{\\Gamma}");he("\\varDelta","\\mathit{\\Delta}");he("\\varTheta","\\mathit{\\Theta}");he("\\varLambda","\\mathit{\\Lambda}");he("\\varXi","\\mathit{\\Xi}");he("\\varPi","\\mathit{\\Pi}");he("\\varSigma","\\mathit{\\Sigma}");he("\\varUpsilon","\\mathit{\\Upsilon}");he("\\varPhi","\\mathit{\\Phi}");he("\\varPsi","\\mathit{\\Psi}");he("\\varOmega","\\mathit{\\Omega}");he("\\substack","\\begin{subarray}{c}#1\\end{subarray}");he("\\colon","\\nobreak\\mskip2mu\\mathpunct{}\\mathchoice{\\mkern-3mu}{\\mkern-3mu}{}{}{:}\\mskip6mu\\relax");he("\\boxed","\\fbox{$\\displaystyle{#1}$}");he("\\iff","\\DOTSB\\;\\Longleftrightarrow\\;");he("\\implies","\\DOTSB\\;\\Longrightarrow\\;");he("\\impliedby","\\DOTSB\\;\\Longleftarrow\\;");he("\\dddot","{\\overset{\\raisebox{-0.1ex}{\\normalsize ...}}{#1}}");he("\\ddddot","{\\overset{\\raisebox{-0.1ex}{\\normalsize ....}}{#1}}");IX={",":"\\dotsc","\\not":"\\dotsb","+":"\\dotsb","=":"\\dotsb","<":"\\dotsb",">":"\\dotsb","-":"\\dotsb","*":"\\dotsb",":":"\\dotsb","\\DOTSB":"\\dotsb","\\coprod":"\\dotsb","\\bigvee":"\\dotsb","\\bigwedge":"\\dotsb","\\biguplus":"\\dotsb","\\bigcap":"\\dotsb","\\bigcup":"\\dotsb","\\prod":"\\dotsb","\\sum":"\\dotsb","\\bigotimes":"\\dotsb","\\bigoplus":"\\dotsb","\\bigodot":"\\dotsb","\\bigsqcup":"\\dotsb","\\And":"\\dotsb","\\longrightarrow":"\\dotsb","\\Longrightarrow":"\\dotsb","\\longleftarrow":"\\dotsb","\\Longleftarrow":"\\dotsb","\\longleftrightarrow":"\\dotsb","\\Longleftrightarrow":"\\dotsb","\\mapsto":"\\dotsb","\\longmapsto":"\\dotsb","\\hookrightarrow":"\\dotsb","\\doteq":"\\dotsb","\\mathbin":"\\dotsb","\\mathrel":"\\dotsb","\\relbar":"\\dotsb","\\Relbar":"\\dotsb","\\xrightarrow":"\\dotsb","\\xleftarrow":"\\dotsb","\\DOTSI":"\\dotsi","\\int":"\\dotsi","\\oint":"\\dotsi","\\iint":"\\dotsi","\\iiint":"\\dotsi","\\iiiint":"\\dotsi","\\idotsint":"\\dotsi","\\DOTSX":"\\dotsx"};he("\\dots",function(t){var e="\\dotso",r=t.expandAfterFuture().text;return r in IX?e=IX[r]:(r.slice(0,4)==="\\not"||r in ji.math&&["bin","rel"].includes(ji.math[r].group))&&(e="\\dotsb"),e});tL={")":!0,"]":!0,"\\rbrack":!0,"\\}":!0,"\\rbrace":!0,"\\rangle":!0,"\\rceil":!0,"\\rfloor":!0,"\\rgroup":!0,"\\rmoustache":!0,"\\right":!0,"\\bigr":!0,"\\biggr":!0,"\\Bigr":!0,"\\Biggr":!0,$:!0,";":!0,".":!0,",":!0};he("\\dotso",function(t){var e=t.future().text;return e in tL?"\\ldots\\,":"\\ldots"});he("\\dotsc",function(t){var e=t.future().text;return e in tL&&e!==","?"\\ldots\\,":"\\ldots"});he("\\cdots",function(t){var e=t.future().text;return e in tL?"\\@cdots\\,":"\\@cdots"});he("\\dotsb","\\cdots");he("\\dotsm","\\cdots");he("\\dotsi","\\!\\cdots");he("\\dotsx","\\ldots\\,");he("\\DOTSI","\\relax");he("\\DOTSB","\\relax");he("\\DOTSX","\\relax");he("\\tmspace","\\TextOrMath{\\kern#1#3}{\\mskip#1#2}\\relax");he("\\,","\\tmspace+{3mu}{.1667em}");he("\\thinspace","\\,");he("\\>","\\mskip{4mu}");he("\\:","\\tmspace+{4mu}{.2222em}");he("\\medspace","\\:");he("\\;","\\tmspace+{5mu}{.2777em}");he("\\thickspace","\\;");he("\\!","\\tmspace-{3mu}{.1667em}");he("\\negthinspace","\\!");he("\\negmedspace","\\tmspace-{4mu}{.2222em}");he("\\negthickspace","\\tmspace-{5mu}{.277em}");he("\\enspace","\\kern.5em ");he("\\enskip","\\hskip.5em\\relax");he("\\quad","\\hskip1em\\relax");he("\\qquad","\\hskip2em\\relax");he("\\tag","\\@ifstar\\tag@literal\\tag@paren");he("\\tag@paren","\\tag@literal{({#1})}");he("\\tag@literal",t=>{if(t.macros.get("\\df@tag"))throw new wt("Multiple \\tag");return"\\gdef\\df@tag{\\text{#1}}"});he("\\bmod","\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}\\mathbin{\\rm mod}\\mathchoice{\\mskip1mu}{\\mskip1mu}{\\mskip5mu}{\\mskip5mu}");he("\\pod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern8mu}{\\mkern8mu}{\\mkern8mu}(#1)");he("\\pmod","\\pod{{\\rm mod}\\mkern6mu#1}");he("\\mod","\\allowbreak\\mathchoice{\\mkern18mu}{\\mkern12mu}{\\mkern12mu}{\\mkern12mu}{\\rm mod}\\,\\,#1");he("\\newline","\\\\\\relax");he("\\TeX","\\textrm{\\html@mathml{T\\kern-.1667em\\raisebox{-.5ex}{E}\\kern-.125emX}{TeX}}");AK=Rt(ru["Main-Regular"][84][1]-.7*ru["Main-Regular"][65][1]);he("\\LaTeX","\\textrm{\\html@mathml{"+("L\\kern-.36em\\raisebox{"+AK+"}{\\scriptstyle A}")+"\\kern-.15em\\TeX}{LaTeX}}");he("\\KaTeX","\\textrm{\\html@mathml{"+("K\\kern-.17em\\raisebox{"+AK+"}{\\scriptstyle A}")+"\\kern-.15em\\TeX}{KaTeX}}");he("\\hspace","\\@ifstar\\@hspacer\\@hspace");he("\\@hspace","\\hskip #1\\relax");he("\\@hspacer","\\rule{0pt}{0pt}\\hskip #1\\relax");he("\\ordinarycolon",":");he("\\vcentcolon","\\mathrel{\\mathop\\ordinarycolon}");he("\\dblcolon",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-.9mu}\\vcentcolon}}{\\mathop{\\char"2237}}');he("\\coloneqq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2254}}');he("\\Coloneqq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}=}}{\\mathop{\\char"2237\\char"3d}}');he("\\coloneq",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"3a\\char"2212}}');he("\\Coloneq",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\mathrel{-}}}{\\mathop{\\char"2237\\char"2212}}');he("\\eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2255}}');he("\\Eqqcolon",'\\html@mathml{\\mathrel{=\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"3d\\char"2237}}');he("\\eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\vcentcolon}}{\\mathop{\\char"2239}}');he("\\Eqcolon",'\\html@mathml{\\mathrel{\\mathrel{-}\\mathrel{\\mkern-1.2mu}\\dblcolon}}{\\mathop{\\char"2212\\char"2237}}');he("\\colonapprox",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"3a\\char"2248}}');he("\\Colonapprox",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\approx}}{\\mathop{\\char"2237\\char"2248}}');he("\\colonsim",'\\html@mathml{\\mathrel{\\vcentcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"3a\\char"223c}}');he("\\Colonsim",'\\html@mathml{\\mathrel{\\dblcolon\\mathrel{\\mkern-1.2mu}\\sim}}{\\mathop{\\char"2237\\char"223c}}');he("\u2237","\\dblcolon");he("\u2239","\\eqcolon");he("\u2254","\\coloneqq");he("\u2255","\\eqqcolon");he("\u2A74","\\Coloneqq");he("\\ratio","\\vcentcolon");he("\\coloncolon","\\dblcolon");he("\\colonequals","\\coloneqq");he("\\coloncolonequals","\\Coloneqq");he("\\equalscolon","\\eqqcolon");he("\\equalscoloncolon","\\Eqqcolon");he("\\colonminus","\\coloneq");he("\\coloncolonminus","\\Coloneq");he("\\minuscolon","\\eqcolon");he("\\minuscoloncolon","\\Eqcolon");he("\\coloncolonapprox","\\Colonapprox");he("\\coloncolonsim","\\Colonsim");he("\\simcolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\vcentcolon}");he("\\simcoloncolon","\\mathrel{\\sim\\mathrel{\\mkern-1.2mu}\\dblcolon}");he("\\approxcolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\vcentcolon}");he("\\approxcoloncolon","\\mathrel{\\approx\\mathrel{\\mkern-1.2mu}\\dblcolon}");he("\\notni","\\html@mathml{\\not\\ni}{\\mathrel{\\char`\u220C}}");he("\\limsup","\\DOTSB\\operatorname*{lim\\,sup}");he("\\liminf","\\DOTSB\\operatorname*{lim\\,inf}");he("\\injlim","\\DOTSB\\operatorname*{inj\\,lim}");he("\\projlim","\\DOTSB\\operatorname*{proj\\,lim}");he("\\varlimsup","\\DOTSB\\operatorname*{\\overline{lim}}");he("\\varliminf","\\DOTSB\\operatorname*{\\underline{lim}}");he("\\varinjlim","\\DOTSB\\operatorname*{\\underrightarrow{lim}}");he("\\varprojlim","\\DOTSB\\operatorname*{\\underleftarrow{lim}}");he("\\gvertneqq","\\html@mathml{\\@gvertneqq}{\u2269}");he("\\lvertneqq","\\html@mathml{\\@lvertneqq}{\u2268}");he("\\ngeqq","\\html@mathml{\\@ngeqq}{\u2271}");he("\\ngeqslant","\\html@mathml{\\@ngeqslant}{\u2271}");he("\\nleqq","\\html@mathml{\\@nleqq}{\u2270}");he("\\nleqslant","\\html@mathml{\\@nleqslant}{\u2270}");he("\\nshortmid","\\html@mathml{\\@nshortmid}{\u2224}");he("\\nshortparallel","\\html@mathml{\\@nshortparallel}{\u2226}");he("\\nsubseteqq","\\html@mathml{\\@nsubseteqq}{\u2288}");he("\\nsupseteqq","\\html@mathml{\\@nsupseteqq}{\u2289}");he("\\varsubsetneq","\\html@mathml{\\@varsubsetneq}{\u228A}");he("\\varsubsetneqq","\\html@mathml{\\@varsubsetneqq}{\u2ACB}");he("\\varsupsetneq","\\html@mathml{\\@varsupsetneq}{\u228B}");he("\\varsupsetneqq","\\html@mathml{\\@varsupsetneqq}{\u2ACC}");he("\\imath","\\html@mathml{\\@imath}{\u0131}");he("\\jmath","\\html@mathml{\\@jmath}{\u0237}");he("\\llbracket","\\html@mathml{\\mathopen{[\\mkern-3.2mu[}}{\\mathopen{\\char`\u27E6}}");he("\\rrbracket","\\html@mathml{\\mathclose{]\\mkern-3.2mu]}}{\\mathclose{\\char`\u27E7}}");he("\u27E6","\\llbracket");he("\u27E7","\\rrbracket");he("\\lBrace","\\html@mathml{\\mathopen{\\{\\mkern-3.2mu[}}{\\mathopen{\\char`\u2983}}");he("\\rBrace","\\html@mathml{\\mathclose{]\\mkern-3.2mu\\}}}{\\mathclose{\\char`\u2984}}");he("\u2983","\\lBrace");he("\u2984","\\rBrace");he("\\minuso","\\mathbin{\\html@mathml{{\\mathrlap{\\mathchoice{\\kern{0.145em}}{\\kern{0.145em}}{\\kern{0.1015em}}{\\kern{0.0725em}}\\circ}{-}}}{\\char`\u29B5}}");he("\u29B5","\\minuso");he("\\darr","\\downarrow");he("\\dArr","\\Downarrow");he("\\Darr","\\Downarrow");he("\\lang","\\langle");he("\\rang","\\rangle");he("\\uarr","\\uparrow");he("\\uArr","\\Uparrow");he("\\Uarr","\\Uparrow");he("\\N","\\mathbb{N}");he("\\R","\\mathbb{R}");he("\\Z","\\mathbb{Z}");he("\\alef","\\aleph");he("\\alefsym","\\aleph");he("\\Alpha","\\mathrm{A}");he("\\Beta","\\mathrm{B}");he("\\bull","\\bullet");he("\\Chi","\\mathrm{X}");he("\\clubs","\\clubsuit");he("\\cnums","\\mathbb{C}");he("\\Complex","\\mathbb{C}");he("\\Dagger","\\ddagger");he("\\diamonds","\\diamondsuit");he("\\empty","\\emptyset");he("\\Epsilon","\\mathrm{E}");he("\\Eta","\\mathrm{H}");he("\\exist","\\exists");he("\\harr","\\leftrightarrow");he("\\hArr","\\Leftrightarrow");he("\\Harr","\\Leftrightarrow");he("\\hearts","\\heartsuit");he("\\image","\\Im");he("\\infin","\\infty");he("\\Iota","\\mathrm{I}");he("\\isin","\\in");he("\\Kappa","\\mathrm{K}");he("\\larr","\\leftarrow");he("\\lArr","\\Leftarrow");he("\\Larr","\\Leftarrow");he("\\lrarr","\\leftrightarrow");he("\\lrArr","\\Leftrightarrow");he("\\Lrarr","\\Leftrightarrow");he("\\Mu","\\mathrm{M}");he("\\natnums","\\mathbb{N}");he("\\Nu","\\mathrm{N}");he("\\Omicron","\\mathrm{O}");he("\\plusmn","\\pm");he("\\rarr","\\rightarrow");he("\\rArr","\\Rightarrow");he("\\Rarr","\\Rightarrow");he("\\real","\\Re");he("\\reals","\\mathbb{R}");he("\\Reals","\\mathbb{R}");he("\\Rho","\\mathrm{P}");he("\\sdot","\\cdot");he("\\sect","\\S");he("\\spades","\\spadesuit");he("\\sub","\\subset");he("\\sube","\\subseteq");he("\\supe","\\supseteq");he("\\Tau","\\mathrm{T}");he("\\thetasym","\\vartheta");he("\\weierp","\\wp");he("\\Zeta","\\mathrm{Z}");he("\\argmin","\\DOTSB\\operatorname*{arg\\,min}");he("\\argmax","\\DOTSB\\operatorname*{arg\\,max}");he("\\plim","\\DOTSB\\mathop{\\operatorname{plim}}\\limits");he("\\bra","\\mathinner{\\langle{#1}|}");he("\\ket","\\mathinner{|{#1}\\rangle}");he("\\braket","\\mathinner{\\langle{#1}\\rangle}");he("\\Bra","\\left\\langle#1\\right|");he("\\Ket","\\left|#1\\right\\rangle");_K=o(t=>e=>{var r=e.consumeArg().tokens,i=e.consumeArg().tokens,n=e.consumeArg().tokens,a=e.consumeArg().tokens,s=e.macros.get("|"),l=e.macros.get("\\|");e.macros.beginGroup();var u=o(d=>p=>{t&&(p.macros.set("|",s),n.length&&p.macros.set("\\|",l));var m=d;if(!d&&n.length){var g=p.future();g.text==="|"&&(p.popToken(),m=!0)}return{tokens:m?n:i,numArgs:0}},"midMacro");e.macros.set("|",u(!1)),n.length&&e.macros.set("\\|",u(!0));var h=e.consumeArg().tokens,f=e.expandTokens([...a,...h,...r]);return e.macros.endGroup(),{tokens:f.reverse(),numArgs:0}},"braketHelper");he("\\bra@ket",_K(!1));he("\\bra@set",_K(!0));he("\\Braket","\\bra@ket{\\left\\langle}{\\,\\middle\\vert\\,}{\\,\\middle\\vert\\,}{\\right\\rangle}");he("\\Set","\\bra@set{\\left\\{\\:}{\\;\\middle\\vert\\;}{\\;\\middle\\Vert\\;}{\\:\\right\\}}");he("\\set","\\bra@set{\\{\\,}{\\mid}{}{\\,\\}}");he("\\angln","{\\angl n}");he("\\blue","\\textcolor{##6495ed}{#1}");he("\\orange","\\textcolor{##ffa500}{#1}");he("\\pink","\\textcolor{##ff00af}{#1}");he("\\red","\\textcolor{##df0030}{#1}");he("\\green","\\textcolor{##28ae7b}{#1}");he("\\gray","\\textcolor{gray}{#1}");he("\\purple","\\textcolor{##9d38bd}{#1}");he("\\blueA","\\textcolor{##ccfaff}{#1}");he("\\blueB","\\textcolor{##80f6ff}{#1}");he("\\blueC","\\textcolor{##63d9ea}{#1}");he("\\blueD","\\textcolor{##11accd}{#1}");he("\\blueE","\\textcolor{##0c7f99}{#1}");he("\\tealA","\\textcolor{##94fff5}{#1}");he("\\tealB","\\textcolor{##26edd5}{#1}");he("\\tealC","\\textcolor{##01d1c1}{#1}");he("\\tealD","\\textcolor{##01a995}{#1}");he("\\tealE","\\textcolor{##208170}{#1}");he("\\greenA","\\textcolor{##b6ffb0}{#1}");he("\\greenB","\\textcolor{##8af281}{#1}");he("\\greenC","\\textcolor{##74cf70}{#1}");he("\\greenD","\\textcolor{##1fab54}{#1}");he("\\greenE","\\textcolor{##0d923f}{#1}");he("\\goldA","\\textcolor{##ffd0a9}{#1}");he("\\goldB","\\textcolor{##ffbb71}{#1}");he("\\goldC","\\textcolor{##ff9c39}{#1}");he("\\goldD","\\textcolor{##e07d10}{#1}");he("\\goldE","\\textcolor{##a75a05}{#1}");he("\\redA","\\textcolor{##fca9a9}{#1}");he("\\redB","\\textcolor{##ff8482}{#1}");he("\\redC","\\textcolor{##f9685d}{#1}");he("\\redD","\\textcolor{##e84d39}{#1}");he("\\redE","\\textcolor{##bc2612}{#1}");he("\\maroonA","\\textcolor{##ffbde0}{#1}");he("\\maroonB","\\textcolor{##ff92c6}{#1}");he("\\maroonC","\\textcolor{##ed5fa6}{#1}");he("\\maroonD","\\textcolor{##ca337c}{#1}");he("\\maroonE","\\textcolor{##9e034e}{#1}");he("\\purpleA","\\textcolor{##ddd7ff}{#1}");he("\\purpleB","\\textcolor{##c6b9fc}{#1}");he("\\purpleC","\\textcolor{##aa87ff}{#1}");he("\\purpleD","\\textcolor{##7854ab}{#1}");he("\\purpleE","\\textcolor{##543b78}{#1}");he("\\mintA","\\textcolor{##f5f9e8}{#1}");he("\\mintB","\\textcolor{##edf2df}{#1}");he("\\mintC","\\textcolor{##e0e5cc}{#1}");he("\\grayA","\\textcolor{##f6f7f7}{#1}");he("\\grayB","\\textcolor{##f0f1f2}{#1}");he("\\grayC","\\textcolor{##e3e5e6}{#1}");he("\\grayD","\\textcolor{##d6d8da}{#1}");he("\\grayE","\\textcolor{##babec2}{#1}");he("\\grayF","\\textcolor{##888d93}{#1}");he("\\grayG","\\textcolor{##626569}{#1}");he("\\grayH","\\textcolor{##3b3e40}{#1}");he("\\grayI","\\textcolor{##21242c}{#1}");he("\\kaBlue","\\textcolor{##314453}{#1}");he("\\kaGreen","\\textcolor{##71B307}{#1}");DK={"^":!0,_:!0,"\\limits":!0,"\\nolimits":!0},$D=class{static{o(this,"MacroExpander")}constructor(e,r,i){this.settings=void 0,this.expansionCount=void 0,this.lexer=void 0,this.macros=void 0,this.stack=void 0,this.mode=void 0,this.settings=r,this.expansionCount=0,this.feed(e),this.macros=new FD(KLe,r.macros),this.mode=i,this.stack=[]}feed(e){this.lexer=new G4(e,this.settings)}switchMode(e){this.mode=e}beginGroup(){this.macros.beginGroup()}endGroup(){this.macros.endGroup()}endGroups(){this.macros.endGroups()}future(){return this.stack.length===0&&this.pushToken(this.lexer.lex()),this.stack[this.stack.length-1]}popToken(){return this.future(),this.stack.pop()}pushToken(e){this.stack.push(e)}pushTokens(e){this.stack.push(...e)}scanArgument(e){var r,i,n;if(e){if(this.consumeSpaces(),this.future().text!=="[")return null;r=this.popToken(),{tokens:n,end:i}=this.consumeArg(["]"])}else({tokens:n,start:r,end:i}=this.consumeArg());return this.pushToken(new Ho("EOF",i.loc)),this.pushTokens(n),new Ho("",co.range(r,i))}consumeSpaces(){for(;;){var e=this.future();if(e.text===" ")this.stack.pop();else break}}consumeArg(e){var r=[],i=e&&e.length>0;i||this.consumeSpaces();var n=this.future(),a,s=0,l=0;do{if(a=this.popToken(),r.push(a),a.text==="{")++s;else if(a.text==="}"){if(--s,s===-1)throw new wt("Extra }",a)}else if(a.text==="EOF")throw new wt("Unexpected end of input in a macro argument, expected '"+(e&&i?e[l]:"}")+"'",a);if(e&&i)if((s===0||s===1&&e[l]==="{")&&a.text===e[l]){if(++l,l===e.length){r.splice(-l,l);break}}else l=0}while(s!==0||i);return n.text==="{"&&r[r.length-1].text==="}"&&(r.pop(),r.shift()),r.reverse(),{tokens:r,start:n,end:a}}consumeArgs(e,r){if(r){if(r.length!==e+1)throw new wt("The length of delimiters doesn't match the number of args!");for(var i=r[0],n=0;nthis.settings.maxExpand)throw new wt("Too many expansions: infinite loop or need to increase maxExpand setting")}expandOnce(e){var r=this.popToken(),i=r.text,n=r.noexpand?null:this._getExpansion(i);if(n==null||e&&n.unexpandable){if(e&&n==null&&i[0]==="\\"&&!this.isDefined(i))throw new wt("Undefined control sequence: "+i);return this.pushToken(r),!1}this.countExpansion(1);var a=n.tokens,s=this.consumeArgs(n.numArgs,n.delimiters);if(n.numArgs){a=a.slice();for(var l=a.length-1;l>=0;--l){var u=a[l];if(u.text==="#"){if(l===0)throw new wt("Incomplete placeholder at end of macro body",u);if(u=a[--l],u.text==="#")a.splice(l+1,1);else if(/^[1-9]$/.test(u.text))a.splice(l,2,...s[+u.text-1]);else throw new wt("Not a valid argument number",u)}}}return this.pushTokens(a),a.length}expandAfterFuture(){return this.expandOnce(),this.future()}expandNextToken(){for(;;)if(this.expandOnce()===!1){var e=this.stack.pop();return e.treatAsRelax&&(e.text="\\relax"),e}throw new Error}expandMacro(e){return this.macros.has(e)?this.expandTokens([new Ho(e)]):void 0}expandTokens(e){var r=[],i=this.stack.length;for(this.pushTokens(e);this.stack.length>i;)if(this.expandOnce(!0)===!1){var n=this.stack.pop();n.treatAsRelax&&(n.noexpand=!1,n.treatAsRelax=!1),r.push(n)}return this.countExpansion(r.length),r}expandMacroAsText(e){var r=this.expandMacro(e);return r&&r.map(i=>i.text).join("")}_getExpansion(e){var r=this.macros.get(e);if(r==null)return r;if(e.length===1){var i=this.lexer.catcodes[e];if(i!=null&&i!==13)return}var n=typeof r=="function"?r(this):r;if(typeof n=="string"){var a=0;if(n.indexOf("#")!==-1)for(var s=n.replace(/##/g,"");s.indexOf("#"+(a+1))!==-1;)++a;for(var l=new G4(n,this.settings),u=[],h=l.lex();h.text!=="EOF";)u.push(h),h=l.lex();u.reverse();var f={tokens:u,numArgs:a};return f}return n}isDefined(e){return this.macros.has(e)||Mf.hasOwnProperty(e)||ji.math.hasOwnProperty(e)||ji.text.hasOwnProperty(e)||DK.hasOwnProperty(e)}isExpandable(e){var r=this.macros.get(e);return r!=null?typeof r=="string"||typeof r=="function"||!r.unexpandable:Mf.hasOwnProperty(e)&&!Mf[e].primitive}},MX=/^[₊₋₌₍₎₀₁₂₃₄₅₆₇₈₉ₐₑₕᵢⱼₖₗₘₙₒₚᵣₛₜᵤᵥₓᵦᵧᵨᵩᵪ]/,I4=Object.freeze({"\u208A":"+","\u208B":"-","\u208C":"=","\u208D":"(","\u208E":")","\u2080":"0","\u2081":"1","\u2082":"2","\u2083":"3","\u2084":"4","\u2085":"5","\u2086":"6","\u2087":"7","\u2088":"8","\u2089":"9","\u2090":"a","\u2091":"e","\u2095":"h","\u1D62":"i","\u2C7C":"j","\u2096":"k","\u2097":"l","\u2098":"m","\u2099":"n","\u2092":"o","\u209A":"p","\u1D63":"r","\u209B":"s","\u209C":"t","\u1D64":"u","\u1D65":"v","\u2093":"x","\u1D66":"\u03B2","\u1D67":"\u03B3","\u1D68":"\u03C1","\u1D69":"\u03D5","\u1D6A":"\u03C7","\u207A":"+","\u207B":"-","\u207C":"=","\u207D":"(","\u207E":")","\u2070":"0","\xB9":"1","\xB2":"2","\xB3":"3","\u2074":"4","\u2075":"5","\u2076":"6","\u2077":"7","\u2078":"8","\u2079":"9","\u1D2C":"A","\u1D2E":"B","\u1D30":"D","\u1D31":"E","\u1D33":"G","\u1D34":"H","\u1D35":"I","\u1D36":"J","\u1D37":"K","\u1D38":"L","\u1D39":"M","\u1D3A":"N","\u1D3C":"O","\u1D3E":"P","\u1D3F":"R","\u1D40":"T","\u1D41":"U","\u2C7D":"V","\u1D42":"W","\u1D43":"a","\u1D47":"b","\u1D9C":"c","\u1D48":"d","\u1D49":"e","\u1DA0":"f","\u1D4D":"g",\u02B0:"h","\u2071":"i",\u02B2:"j","\u1D4F":"k",\u02E1:"l","\u1D50":"m",\u207F:"n","\u1D52":"o","\u1D56":"p",\u02B3:"r",\u02E2:"s","\u1D57":"t","\u1D58":"u","\u1D5B":"v",\u02B7:"w",\u02E3:"x",\u02B8:"y","\u1DBB":"z","\u1D5D":"\u03B2","\u1D5E":"\u03B3","\u1D5F":"\u03B4","\u1D60":"\u03D5","\u1D61":"\u03C7","\u1DBF":"\u03B8"}),AD={"\u0301":{text:"\\'",math:"\\acute"},"\u0300":{text:"\\`",math:"\\grave"},"\u0308":{text:'\\"',math:"\\ddot"},"\u0303":{text:"\\~",math:"\\tilde"},"\u0304":{text:"\\=",math:"\\bar"},"\u0306":{text:"\\u",math:"\\breve"},"\u030C":{text:"\\v",math:"\\check"},"\u0302":{text:"\\^",math:"\\hat"},"\u0307":{text:"\\.",math:"\\dot"},"\u030A":{text:"\\r",math:"\\mathring"},"\u030B":{text:"\\H"},"\u0327":{text:"\\c"}},OX={\u00E1:"a\u0301",\u00E0:"a\u0300",\u00E4:"a\u0308",\u01DF:"a\u0308\u0304",\u00E3:"a\u0303",\u0101:"a\u0304",\u0103:"a\u0306",\u1EAF:"a\u0306\u0301",\u1EB1:"a\u0306\u0300",\u1EB5:"a\u0306\u0303",\u01CE:"a\u030C",\u00E2:"a\u0302",\u1EA5:"a\u0302\u0301",\u1EA7:"a\u0302\u0300",\u1EAB:"a\u0302\u0303",\u0227:"a\u0307",\u01E1:"a\u0307\u0304",\u00E5:"a\u030A",\u01FB:"a\u030A\u0301",\u1E03:"b\u0307",\u0107:"c\u0301",\u1E09:"c\u0327\u0301",\u010D:"c\u030C",\u0109:"c\u0302",\u010B:"c\u0307",\u00E7:"c\u0327",\u010F:"d\u030C",\u1E0B:"d\u0307",\u1E11:"d\u0327",\u00E9:"e\u0301",\u00E8:"e\u0300",\u00EB:"e\u0308",\u1EBD:"e\u0303",\u0113:"e\u0304",\u1E17:"e\u0304\u0301",\u1E15:"e\u0304\u0300",\u0115:"e\u0306",\u1E1D:"e\u0327\u0306",\u011B:"e\u030C",\u00EA:"e\u0302",\u1EBF:"e\u0302\u0301",\u1EC1:"e\u0302\u0300",\u1EC5:"e\u0302\u0303",\u0117:"e\u0307",\u0229:"e\u0327",\u1E1F:"f\u0307",\u01F5:"g\u0301",\u1E21:"g\u0304",\u011F:"g\u0306",\u01E7:"g\u030C",\u011D:"g\u0302",\u0121:"g\u0307",\u0123:"g\u0327",\u1E27:"h\u0308",\u021F:"h\u030C",\u0125:"h\u0302",\u1E23:"h\u0307",\u1E29:"h\u0327",\u00ED:"i\u0301",\u00EC:"i\u0300",\u00EF:"i\u0308",\u1E2F:"i\u0308\u0301",\u0129:"i\u0303",\u012B:"i\u0304",\u012D:"i\u0306",\u01D0:"i\u030C",\u00EE:"i\u0302",\u01F0:"j\u030C",\u0135:"j\u0302",\u1E31:"k\u0301",\u01E9:"k\u030C",\u0137:"k\u0327",\u013A:"l\u0301",\u013E:"l\u030C",\u013C:"l\u0327",\u1E3F:"m\u0301",\u1E41:"m\u0307",\u0144:"n\u0301",\u01F9:"n\u0300",\u00F1:"n\u0303",\u0148:"n\u030C",\u1E45:"n\u0307",\u0146:"n\u0327",\u00F3:"o\u0301",\u00F2:"o\u0300",\u00F6:"o\u0308",\u022B:"o\u0308\u0304",\u00F5:"o\u0303",\u1E4D:"o\u0303\u0301",\u1E4F:"o\u0303\u0308",\u022D:"o\u0303\u0304",\u014D:"o\u0304",\u1E53:"o\u0304\u0301",\u1E51:"o\u0304\u0300",\u014F:"o\u0306",\u01D2:"o\u030C",\u00F4:"o\u0302",\u1ED1:"o\u0302\u0301",\u1ED3:"o\u0302\u0300",\u1ED7:"o\u0302\u0303",\u022F:"o\u0307",\u0231:"o\u0307\u0304",\u0151:"o\u030B",\u1E55:"p\u0301",\u1E57:"p\u0307",\u0155:"r\u0301",\u0159:"r\u030C",\u1E59:"r\u0307",\u0157:"r\u0327",\u015B:"s\u0301",\u1E65:"s\u0301\u0307",\u0161:"s\u030C",\u1E67:"s\u030C\u0307",\u015D:"s\u0302",\u1E61:"s\u0307",\u015F:"s\u0327",\u1E97:"t\u0308",\u0165:"t\u030C",\u1E6B:"t\u0307",\u0163:"t\u0327",\u00FA:"u\u0301",\u00F9:"u\u0300",\u00FC:"u\u0308",\u01D8:"u\u0308\u0301",\u01DC:"u\u0308\u0300",\u01D6:"u\u0308\u0304",\u01DA:"u\u0308\u030C",\u0169:"u\u0303",\u1E79:"u\u0303\u0301",\u016B:"u\u0304",\u1E7B:"u\u0304\u0308",\u016D:"u\u0306",\u01D4:"u\u030C",\u00FB:"u\u0302",\u016F:"u\u030A",\u0171:"u\u030B",\u1E7D:"v\u0303",\u1E83:"w\u0301",\u1E81:"w\u0300",\u1E85:"w\u0308",\u0175:"w\u0302",\u1E87:"w\u0307",\u1E98:"w\u030A",\u1E8D:"x\u0308",\u1E8B:"x\u0307",\u00FD:"y\u0301",\u1EF3:"y\u0300",\u00FF:"y\u0308",\u1EF9:"y\u0303",\u0233:"y\u0304",\u0177:"y\u0302",\u1E8F:"y\u0307",\u1E99:"y\u030A",\u017A:"z\u0301",\u017E:"z\u030C",\u1E91:"z\u0302",\u017C:"z\u0307",\u00C1:"A\u0301",\u00C0:"A\u0300",\u00C4:"A\u0308",\u01DE:"A\u0308\u0304",\u00C3:"A\u0303",\u0100:"A\u0304",\u0102:"A\u0306",\u1EAE:"A\u0306\u0301",\u1EB0:"A\u0306\u0300",\u1EB4:"A\u0306\u0303",\u01CD:"A\u030C",\u00C2:"A\u0302",\u1EA4:"A\u0302\u0301",\u1EA6:"A\u0302\u0300",\u1EAA:"A\u0302\u0303",\u0226:"A\u0307",\u01E0:"A\u0307\u0304",\u00C5:"A\u030A",\u01FA:"A\u030A\u0301",\u1E02:"B\u0307",\u0106:"C\u0301",\u1E08:"C\u0327\u0301",\u010C:"C\u030C",\u0108:"C\u0302",\u010A:"C\u0307",\u00C7:"C\u0327",\u010E:"D\u030C",\u1E0A:"D\u0307",\u1E10:"D\u0327",\u00C9:"E\u0301",\u00C8:"E\u0300",\u00CB:"E\u0308",\u1EBC:"E\u0303",\u0112:"E\u0304",\u1E16:"E\u0304\u0301",\u1E14:"E\u0304\u0300",\u0114:"E\u0306",\u1E1C:"E\u0327\u0306",\u011A:"E\u030C",\u00CA:"E\u0302",\u1EBE:"E\u0302\u0301",\u1EC0:"E\u0302\u0300",\u1EC4:"E\u0302\u0303",\u0116:"E\u0307",\u0228:"E\u0327",\u1E1E:"F\u0307",\u01F4:"G\u0301",\u1E20:"G\u0304",\u011E:"G\u0306",\u01E6:"G\u030C",\u011C:"G\u0302",\u0120:"G\u0307",\u0122:"G\u0327",\u1E26:"H\u0308",\u021E:"H\u030C",\u0124:"H\u0302",\u1E22:"H\u0307",\u1E28:"H\u0327",\u00CD:"I\u0301",\u00CC:"I\u0300",\u00CF:"I\u0308",\u1E2E:"I\u0308\u0301",\u0128:"I\u0303",\u012A:"I\u0304",\u012C:"I\u0306",\u01CF:"I\u030C",\u00CE:"I\u0302",\u0130:"I\u0307",\u0134:"J\u0302",\u1E30:"K\u0301",\u01E8:"K\u030C",\u0136:"K\u0327",\u0139:"L\u0301",\u013D:"L\u030C",\u013B:"L\u0327",\u1E3E:"M\u0301",\u1E40:"M\u0307",\u0143:"N\u0301",\u01F8:"N\u0300",\u00D1:"N\u0303",\u0147:"N\u030C",\u1E44:"N\u0307",\u0145:"N\u0327",\u00D3:"O\u0301",\u00D2:"O\u0300",\u00D6:"O\u0308",\u022A:"O\u0308\u0304",\u00D5:"O\u0303",\u1E4C:"O\u0303\u0301",\u1E4E:"O\u0303\u0308",\u022C:"O\u0303\u0304",\u014C:"O\u0304",\u1E52:"O\u0304\u0301",\u1E50:"O\u0304\u0300",\u014E:"O\u0306",\u01D1:"O\u030C",\u00D4:"O\u0302",\u1ED0:"O\u0302\u0301",\u1ED2:"O\u0302\u0300",\u1ED6:"O\u0302\u0303",\u022E:"O\u0307",\u0230:"O\u0307\u0304",\u0150:"O\u030B",\u1E54:"P\u0301",\u1E56:"P\u0307",\u0154:"R\u0301",\u0158:"R\u030C",\u1E58:"R\u0307",\u0156:"R\u0327",\u015A:"S\u0301",\u1E64:"S\u0301\u0307",\u0160:"S\u030C",\u1E66:"S\u030C\u0307",\u015C:"S\u0302",\u1E60:"S\u0307",\u015E:"S\u0327",\u0164:"T\u030C",\u1E6A:"T\u0307",\u0162:"T\u0327",\u00DA:"U\u0301",\u00D9:"U\u0300",\u00DC:"U\u0308",\u01D7:"U\u0308\u0301",\u01DB:"U\u0308\u0300",\u01D5:"U\u0308\u0304",\u01D9:"U\u0308\u030C",\u0168:"U\u0303",\u1E78:"U\u0303\u0301",\u016A:"U\u0304",\u1E7A:"U\u0304\u0308",\u016C:"U\u0306",\u01D3:"U\u030C",\u00DB:"U\u0302",\u016E:"U\u030A",\u0170:"U\u030B",\u1E7C:"V\u0303",\u1E82:"W\u0301",\u1E80:"W\u0300",\u1E84:"W\u0308",\u0174:"W\u0302",\u1E86:"W\u0307",\u1E8C:"X\u0308",\u1E8A:"X\u0307",\u00DD:"Y\u0301",\u1EF2:"Y\u0300",\u0178:"Y\u0308",\u1EF8:"Y\u0303",\u0232:"Y\u0304",\u0176:"Y\u0302",\u1E8E:"Y\u0307",\u0179:"Z\u0301",\u017D:"Z\u030C",\u1E90:"Z\u0302",\u017B:"Z\u0307",\u03AC:"\u03B1\u0301",\u1F70:"\u03B1\u0300",\u1FB1:"\u03B1\u0304",\u1FB0:"\u03B1\u0306",\u03AD:"\u03B5\u0301",\u1F72:"\u03B5\u0300",\u03AE:"\u03B7\u0301",\u1F74:"\u03B7\u0300",\u03AF:"\u03B9\u0301",\u1F76:"\u03B9\u0300",\u03CA:"\u03B9\u0308",\u0390:"\u03B9\u0308\u0301",\u1FD2:"\u03B9\u0308\u0300",\u1FD1:"\u03B9\u0304",\u1FD0:"\u03B9\u0306",\u03CC:"\u03BF\u0301",\u1F78:"\u03BF\u0300",\u03CD:"\u03C5\u0301",\u1F7A:"\u03C5\u0300",\u03CB:"\u03C5\u0308",\u03B0:"\u03C5\u0308\u0301",\u1FE2:"\u03C5\u0308\u0300",\u1FE1:"\u03C5\u0304",\u1FE0:"\u03C5\u0306",\u03CE:"\u03C9\u0301",\u1F7C:"\u03C9\u0300",\u038E:"\u03A5\u0301",\u1FEA:"\u03A5\u0300",\u03AB:"\u03A5\u0308",\u1FE9:"\u03A5\u0304",\u1FE8:"\u03A5\u0306",\u038F:"\u03A9\u0301",\u1FFA:"\u03A9\u0300"},V4=class t{static{o(this,"Parser")}constructor(e,r){this.mode=void 0,this.gullet=void 0,this.settings=void 0,this.leftrightDepth=void 0,this.nextToken=void 0,this.mode="math",this.gullet=new $D(e,r,this.mode),this.settings=r,this.leftrightDepth=0}expect(e,r){if(r===void 0&&(r=!0),this.fetch().text!==e)throw new wt("Expected '"+e+"', got '"+this.fetch().text+"'",this.fetch());r&&this.consume()}consume(){this.nextToken=null}fetch(){return this.nextToken==null&&(this.nextToken=this.gullet.expandNextToken()),this.nextToken}switchMode(e){this.mode=e,this.gullet.switchMode(e)}parse(){this.settings.globalGroup||this.gullet.beginGroup(),this.settings.colorIsTextColor&&this.gullet.macros.set("\\color","\\textcolor");try{var e=this.parseExpression(!1);return this.expect("EOF"),this.settings.globalGroup||this.gullet.endGroup(),e}finally{this.gullet.endGroups()}}subparse(e){var r=this.nextToken;this.consume(),this.gullet.pushToken(new Ho("}")),this.gullet.pushTokens(e);var i=this.parseExpression(!1);return this.expect("}"),this.nextToken=r,i}parseExpression(e,r){for(var i=[];;){this.mode==="math"&&this.consumeSpaces();var n=this.fetch();if(t.endOfExpression.indexOf(n.text)!==-1||r&&n.text===r||e&&Mf[n.text]&&Mf[n.text].infix)break;var a=this.parseAtom(r);if(a){if(a.type==="internal")continue}else break;i.push(a)}return this.mode==="text"&&this.formLigatures(i),this.handleInfixNodes(i)}handleInfixNodes(e){for(var r=-1,i,n=0;n=0&&this.settings.reportNonstrict("unicodeTextInMathMode",'Latin-1/Unicode text character "'+r[0]+'" used in math mode',e);var l=ji[this.mode][r].group,u=co.range(e),h;if(GDe.hasOwnProperty(l)){var f=l;h={type:"atom",mode:this.mode,family:f,loc:u,text:r}}else h={type:l,mode:this.mode,loc:u,text:r};s=h}else if(r.charCodeAt(0)>=128)this.settings.strict&&(BX(r.charCodeAt(0))?this.mode==="math"&&this.settings.reportNonstrict("unicodeTextInMathMode",'Unicode text character "'+r[0]+'" used in math mode',e):this.settings.reportNonstrict("unknownSymbol",'Unrecognized Unicode character "'+r[0]+'"'+(" ("+r.charCodeAt(0)+")"),e)),s={type:"textord",mode:"text",loc:co.range(e),text:r};else return null;if(this.consume(),a)for(var d=0;d{e.tagName==="A"&&e.hasAttribute("target")&&e.setAttribute(t,e.getAttribute("target")??"")}),Tl.addHook("afterSanitizeAttributes",e=>{e.tagName==="A"&&e.hasAttribute(t)&&(e.setAttribute("target",e.getAttribute(t)??""),e.removeAttribute(t),e.getAttribute("target")==="_blank"&&e.setAttribute("rel","noopener"))})}var Hp,ZLe,JLe,zK,FK,Tr,tRe,rRe,iRe,nRe,GK,Yp,aRe,sRe,ou,nL,oRe,lRe,$K,K4,sn,jp,cRe,Rg,lt,Vr=P(()=>{"use strict";zx();Sr();Hp=//gi,ZLe=o(t=>t?GK(t).replace(/\\n/g,"#br#").split("#br#"):[""],"getRows"),JLe=(()=>{let t=!1;return()=>{t||(eRe(),t=!0)}})();o(eRe,"setupDompurifyHooks");zK=o(t=>(JLe(),Tl.sanitize(t)),"removeScript"),FK=o((t,e)=>{if(Or(e)){let r=e.securityLevel;r==="antiscript"||r==="strict"||r==="sandbox"?t=zK(t):r!=="loose"&&(t=GK(t),t=t.replace(//g,">"),t=t.replace(/=/g,"="),t=nRe(t))}return t},"sanitizeMore"),Tr=o((t,e)=>t&&(e.dompurifyConfig?t=Tl.sanitize(FK(t,e),e.dompurifyConfig).toString():t=Tl.sanitize(FK(t,e),{FORBID_TAGS:["style"]}).toString(),t),"sanitizeText"),tRe=o((t,e)=>typeof t=="string"?Tr(t,e):t.flat().map(r=>Tr(r,e)),"sanitizeTextOrArray"),rRe=o(t=>Hp.test(t),"hasBreaks"),iRe=o(t=>t.split(Hp),"splitBreaks"),nRe=o(t=>t.replace(/#br#/g,"
"),"placeholderToBreak"),GK=o(t=>t.replace(Hp,"#br#"),"breakToPlaceholder"),Yp=o(t=>{let e="";return t&&(e=window.location.protocol+"//"+window.location.host+window.location.pathname+window.location.search,e=CSS.escape(e)),e},"getUrl"),aRe=o(function(...t){let e=t.filter(r=>!isNaN(r));return Math.max(...e)},"getMax"),sRe=o(function(...t){let e=t.filter(r=>!isNaN(r));return Math.min(...e)},"getMin"),ou=o(function(t){let e=t.split(/(,)/),r=[];for(let i=0;i0&&i+1Math.max(0,t.split(e).length-1),"countOccurrence"),oRe=o((t,e)=>{let r=nL(t,"~"),i=nL(e,"~");return r===1&&i===1},"shouldCombineSets"),lRe=o(t=>{let e=nL(t,"~"),r=!1;if(e<=1)return t;e%2!==0&&t.startsWith("~")&&(t=t.substring(1),r=!0);let i=[...t],n=i.indexOf("~"),a=i.lastIndexOf("~");for(;n!==-1&&a!==-1&&n!==a;)i[n]="<",i[a]=">",n=i.indexOf("~"),a=i.lastIndexOf("~");return r&&i.unshift("~"),i.join("")},"processSet"),$K=o(()=>window.MathMLElement!==void 0,"isMathMLSupported"),K4=/\$\$(.*)\$\$/g,sn=o(t=>(t.match(K4)?.length??0)>0,"hasKatex"),jp=o(async(t,e)=>{let r=document.createElement("div");r.innerHTML=await Rg(t,e),r.id="katex-temp",r.style.visibility="hidden",r.style.position="absolute",r.style.top="0",document.querySelector("body")?.insertAdjacentElement("beforeend",r);let n={width:r.clientWidth,height:r.clientHeight};return r.remove(),n},"calculateMathMLDimensions"),cRe=o(async(t,e)=>{if(!sn(t))return t;if(!($K()||e.legacyMathML||e.forceLegacyMathML))return t.replace(K4,"MathML is unsupported in this environment.");{let{default:r}=await Promise.resolve().then(()=>(BK(),PK)),i=e.forceLegacyMathML||!$K()&&e.legacyMathML?"htmlAndMathml":"mathml";return t.split(Hp).map(n=>sn(n)?`
${n}
`:`
${n}
`).join("").replace(K4,(n,a)=>r.renderToString(a,{throwOnError:!0,displayMode:!0,output:i}).replace(/\n/g," ").replace(//g,""))}return t.replace(K4,"Katex is not supported in @mermaid-js/tiny. Please use the full mermaid library.")},"renderKatexUnsanitized"),Rg=o(async(t,e)=>Tr(await cRe(t,e),e),"renderKatexSanitized"),lt={getRows:ZLe,sanitizeText:Tr,sanitizeTextOrArray:tRe,hasBreaks:rRe,splitBreaks:iRe,lineBreakRegex:Hp,removeScript:zK,getUrl:Yp,evaluate:ls,getMax:aRe,getMin:sRe}});var sL,aL,VK,Q4,qK,WK,fo,lu=P(()=>{"use strict";FY();Sr();Vr();bt();sL={body:'?',height:80,width:80},aL=new Map,VK=new Map,Q4=o(t=>{for(let e of t){if(!e.name)throw new Error('Invalid icon loader. Must have a "name" property with non-empty string value.');if(Q.debug("Registering icon pack:",e.name),"loader"in e)VK.set(e.name,e.loader);else if("icons"in e)aL.set(e.name,e.icons);else throw Q.error("Invalid icon loader:",e),new Error('Invalid icon loader. Must have either "icons" or "loader" property.')}},"registerIconPacks"),qK=o(async(t,e)=>{let r=D8(t,!0,e!==void 0);if(!r)throw new Error(`Invalid icon name: ${t}`);let i=r.prefix||e;if(!i)throw new Error(`Icon name must contain a prefix: ${t}`);let n=aL.get(i);if(!n){let s=VK.get(i);if(!s)throw new Error(`Icon set not found: ${r.prefix}`);try{n={...await s(),prefix:i},aL.set(i,n)}catch(l){throw Q.error(l),new Error(`Failed to load icon set: ${r.prefix}`)}}let a=R8(n,r.name);if(!a)throw new Error(`Icon not found: ${t}`);return a},"getRegisteredIconData"),WK=o(async t=>{try{return await qK(t),!0}catch{return!1}},"isIconAvailable"),fo=o(async(t,e,r)=>{let i;try{i=await qK(t,e?.fallbackPrefix)}catch(s){Q.error(s),i=sL}let n=I8(i,e),a=O8(M8(n.body),{...n.attributes,...r});return Tr(a,Lt())},"getIconSVG")});function Z4(t){for(var e=[],r=1;r{"use strict";o(Z4,"dedent")});var J4,Xp,UK,ew=P(()=>{"use strict";J4=/^-{3}\s*[\n\r](.*?)[\n\r]-{3}\s*[\n\r]+/s,Xp=/%{2}{\s*(?:(\w+)\s*:|(\w+))\s*(?:(\w+)|((?:(?!}%{2}).|\r?\n)*))?\s*(?:}%{2})?/gi,UK=/\s*%%.*\n/gm});var Ng,lL=P(()=>{"use strict";Ng=class extends Error{static{o(this,"UnknownDiagramError")}constructor(e){super(e),this.name="UnknownDiagramError"}}});var wh,Ig,Zx,cL,HK,Kp=P(()=>{"use strict";bt();ew();lL();wh={},Ig=o(function(t,e){t=t.replace(J4,"").replace(Xp,"").replace(UK,` +`);for(let[r,{detector:i}]of Object.entries(wh))if(i(t,e))return r;throw new Ng(`No diagram type detected matching given configuration for text: ${t}`)},"detectType"),Zx=o((...t)=>{for(let{id:e,detector:r,loader:i}of t)cL(e,r,i)},"registerLazyLoadedDiagrams"),cL=o((t,e,r)=>{wh[t]&&Q.warn(`Detector with key ${t} already exists. Overwriting.`),wh[t]={detector:e,loader:r},Q.debug(`Detector with key ${t} added${r?" with loader":""}`)},"addDetector"),HK=o(t=>wh[t].loader,"getDiagramLoader")});var Jx,YK,uL=P(()=>{"use strict";Jx=(function(){var t=o(function(Ce,Fe,Ue,qe){for(Ue=Ue||{},qe=Ce.length;qe--;Ue[Ce[qe]]=Fe);return Ue},"o"),e=[1,24],r=[1,25],i=[1,26],n=[1,27],a=[1,28],s=[1,63],l=[1,64],u=[1,65],h=[1,66],f=[1,67],d=[1,68],p=[1,69],m=[1,29],g=[1,30],y=[1,31],v=[1,32],x=[1,33],b=[1,34],T=[1,35],w=[1,36],k=[1,37],C=[1,38],E=[1,39],S=[1,40],L=[1,41],M=[1,42],I=[1,43],A=[1,44],_=[1,45],D=[1,46],N=[1,47],R=[1,48],B=[1,50],O=[1,51],$=[1,52],z=[1,53],F=[1,54],V=[1,55],H=[1,56],X=[1,57],W=[1,58],Z=[1,59],Y=[1,60],ae=[14,42],J=[14,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],ee=[12,14,34,36,37,38,39,40,41,42,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],re=[1,82],te=[1,83],be=[1,84],de=[1,85],Ee=[12,14,42],Ne=[12,14,33,42],we=[12,14,33,42,76,77,79,80],Te=[12,33],De=[34,36,37,38,39,40,41,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74],$e={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,mermaidDoc:4,direction:5,direction_tb:6,direction_bt:7,direction_rl:8,direction_lr:9,graphConfig:10,C4_CONTEXT:11,NEWLINE:12,statements:13,EOF:14,C4_CONTAINER:15,C4_COMPONENT:16,C4_DYNAMIC:17,C4_DEPLOYMENT:18,otherStatements:19,diagramStatements:20,otherStatement:21,title:22,accDescription:23,acc_title:24,acc_title_value:25,acc_descr:26,acc_descr_value:27,acc_descr_multiline_value:28,boundaryStatement:29,boundaryStartStatement:30,boundaryStopStatement:31,boundaryStart:32,LBRACE:33,ENTERPRISE_BOUNDARY:34,attributes:35,SYSTEM_BOUNDARY:36,BOUNDARY:37,CONTAINER_BOUNDARY:38,NODE:39,NODE_L:40,NODE_R:41,RBRACE:42,diagramStatement:43,PERSON:44,PERSON_EXT:45,SYSTEM:46,SYSTEM_DB:47,SYSTEM_QUEUE:48,SYSTEM_EXT:49,SYSTEM_EXT_DB:50,SYSTEM_EXT_QUEUE:51,CONTAINER:52,CONTAINER_DB:53,CONTAINER_QUEUE:54,CONTAINER_EXT:55,CONTAINER_EXT_DB:56,CONTAINER_EXT_QUEUE:57,COMPONENT:58,COMPONENT_DB:59,COMPONENT_QUEUE:60,COMPONENT_EXT:61,COMPONENT_EXT_DB:62,COMPONENT_EXT_QUEUE:63,REL:64,BIREL:65,REL_U:66,REL_D:67,REL_L:68,REL_R:69,REL_B:70,REL_INDEX:71,UPDATE_EL_STYLE:72,UPDATE_REL_STYLE:73,UPDATE_LAYOUT_CONFIG:74,attribute:75,STR:76,STR_KEY:77,STR_VALUE:78,ATTRIBUTE:79,ATTRIBUTE_EMPTY:80,$accept:0,$end:1},terminals_:{2:"error",6:"direction_tb",7:"direction_bt",8:"direction_rl",9:"direction_lr",11:"C4_CONTEXT",12:"NEWLINE",14:"EOF",15:"C4_CONTAINER",16:"C4_COMPONENT",17:"C4_DYNAMIC",18:"C4_DEPLOYMENT",22:"title",23:"accDescription",24:"acc_title",25:"acc_title_value",26:"acc_descr",27:"acc_descr_value",28:"acc_descr_multiline_value",33:"LBRACE",34:"ENTERPRISE_BOUNDARY",36:"SYSTEM_BOUNDARY",37:"BOUNDARY",38:"CONTAINER_BOUNDARY",39:"NODE",40:"NODE_L",41:"NODE_R",42:"RBRACE",44:"PERSON",45:"PERSON_EXT",46:"SYSTEM",47:"SYSTEM_DB",48:"SYSTEM_QUEUE",49:"SYSTEM_EXT",50:"SYSTEM_EXT_DB",51:"SYSTEM_EXT_QUEUE",52:"CONTAINER",53:"CONTAINER_DB",54:"CONTAINER_QUEUE",55:"CONTAINER_EXT",56:"CONTAINER_EXT_DB",57:"CONTAINER_EXT_QUEUE",58:"COMPONENT",59:"COMPONENT_DB",60:"COMPONENT_QUEUE",61:"COMPONENT_EXT",62:"COMPONENT_EXT_DB",63:"COMPONENT_EXT_QUEUE",64:"REL",65:"BIREL",66:"REL_U",67:"REL_D",68:"REL_L",69:"REL_R",70:"REL_B",71:"REL_INDEX",72:"UPDATE_EL_STYLE",73:"UPDATE_REL_STYLE",74:"UPDATE_LAYOUT_CONFIG",76:"STR",77:"STR_KEY",78:"STR_VALUE",79:"ATTRIBUTE",80:"ATTRIBUTE_EMPTY"},productions_:[0,[3,1],[3,1],[5,1],[5,1],[5,1],[5,1],[4,1],[10,4],[10,4],[10,4],[10,4],[10,4],[13,1],[13,1],[13,2],[19,1],[19,2],[19,3],[21,1],[21,1],[21,2],[21,2],[21,1],[29,3],[30,3],[30,3],[30,4],[32,2],[32,2],[32,2],[32,2],[32,2],[32,2],[32,2],[31,1],[20,1],[20,2],[20,3],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,1],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[43,2],[35,1],[35,2],[75,1],[75,2],[75,1],[75,1]],performAction:o(function(Fe,Ue,qe,Me,He,K,oe){var U=K.length-1;switch(He){case 3:Me.setDirection("TB");break;case 4:Me.setDirection("BT");break;case 5:Me.setDirection("RL");break;case 6:Me.setDirection("LR");break;case 8:case 9:case 10:case 11:case 12:Me.setC4Type(K[U-3]);break;case 19:Me.setTitle(K[U].substring(6)),this.$=K[U].substring(6);break;case 20:Me.setAccDescription(K[U].substring(15)),this.$=K[U].substring(15);break;case 21:this.$=K[U].trim(),Me.setTitle(this.$);break;case 22:case 23:this.$=K[U].trim(),Me.setAccDescription(this.$);break;case 28:K[U].splice(2,0,"ENTERPRISE"),Me.addPersonOrSystemBoundary(...K[U]),this.$=K[U];break;case 29:K[U].splice(2,0,"SYSTEM"),Me.addPersonOrSystemBoundary(...K[U]),this.$=K[U];break;case 30:Me.addPersonOrSystemBoundary(...K[U]),this.$=K[U];break;case 31:K[U].splice(2,0,"CONTAINER"),Me.addContainerBoundary(...K[U]),this.$=K[U];break;case 32:Me.addDeploymentNode("node",...K[U]),this.$=K[U];break;case 33:Me.addDeploymentNode("nodeL",...K[U]),this.$=K[U];break;case 34:Me.addDeploymentNode("nodeR",...K[U]),this.$=K[U];break;case 35:Me.popBoundaryParseStack();break;case 39:Me.addPersonOrSystem("person",...K[U]),this.$=K[U];break;case 40:Me.addPersonOrSystem("external_person",...K[U]),this.$=K[U];break;case 41:Me.addPersonOrSystem("system",...K[U]),this.$=K[U];break;case 42:Me.addPersonOrSystem("system_db",...K[U]),this.$=K[U];break;case 43:Me.addPersonOrSystem("system_queue",...K[U]),this.$=K[U];break;case 44:Me.addPersonOrSystem("external_system",...K[U]),this.$=K[U];break;case 45:Me.addPersonOrSystem("external_system_db",...K[U]),this.$=K[U];break;case 46:Me.addPersonOrSystem("external_system_queue",...K[U]),this.$=K[U];break;case 47:Me.addContainer("container",...K[U]),this.$=K[U];break;case 48:Me.addContainer("container_db",...K[U]),this.$=K[U];break;case 49:Me.addContainer("container_queue",...K[U]),this.$=K[U];break;case 50:Me.addContainer("external_container",...K[U]),this.$=K[U];break;case 51:Me.addContainer("external_container_db",...K[U]),this.$=K[U];break;case 52:Me.addContainer("external_container_queue",...K[U]),this.$=K[U];break;case 53:Me.addComponent("component",...K[U]),this.$=K[U];break;case 54:Me.addComponent("component_db",...K[U]),this.$=K[U];break;case 55:Me.addComponent("component_queue",...K[U]),this.$=K[U];break;case 56:Me.addComponent("external_component",...K[U]),this.$=K[U];break;case 57:Me.addComponent("external_component_db",...K[U]),this.$=K[U];break;case 58:Me.addComponent("external_component_queue",...K[U]),this.$=K[U];break;case 60:Me.addRel("rel",...K[U]),this.$=K[U];break;case 61:Me.addRel("birel",...K[U]),this.$=K[U];break;case 62:Me.addRel("rel_u",...K[U]),this.$=K[U];break;case 63:Me.addRel("rel_d",...K[U]),this.$=K[U];break;case 64:Me.addRel("rel_l",...K[U]),this.$=K[U];break;case 65:Me.addRel("rel_r",...K[U]),this.$=K[U];break;case 66:Me.addRel("rel_b",...K[U]),this.$=K[U];break;case 67:K[U].splice(0,1),Me.addRel("rel",...K[U]),this.$=K[U];break;case 68:Me.updateElStyle("update_el_style",...K[U]),this.$=K[U];break;case 69:Me.updateRelStyle("update_rel_style",...K[U]),this.$=K[U];break;case 70:Me.updateLayoutConfig("update_layout_config",...K[U]),this.$=K[U];break;case 71:this.$=[K[U]];break;case 72:K[U].unshift(K[U-1]),this.$=K[U];break;case 73:case 75:this.$=K[U].trim();break;case 74:let ue={};ue[K[U-1].trim()]=K[U].trim(),this.$=ue;break;case 76:this.$="";break}},"anonymous"),table:[{3:1,4:2,5:3,6:[1,5],7:[1,6],8:[1,7],9:[1,8],10:4,11:[1,9],15:[1,10],16:[1,11],17:[1,12],18:[1,13]},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,7]},{1:[2,3]},{1:[2,4]},{1:[2,5]},{1:[2,6]},{12:[1,14]},{12:[1,15]},{12:[1,16]},{12:[1,17]},{12:[1,18]},{13:19,19:20,20:21,21:22,22:e,23:r,24:i,26:n,28:a,29:49,30:61,32:62,34:s,36:l,37:u,38:h,39:f,40:d,41:p,43:23,44:m,45:g,46:y,47:v,48:x,49:b,50:T,51:w,52:k,53:C,54:E,55:S,56:L,57:M,58:I,59:A,60:_,61:D,62:N,63:R,64:B,65:O,66:$,67:z,68:F,69:V,70:H,71:X,72:W,73:Z,74:Y},{13:70,19:20,20:21,21:22,22:e,23:r,24:i,26:n,28:a,29:49,30:61,32:62,34:s,36:l,37:u,38:h,39:f,40:d,41:p,43:23,44:m,45:g,46:y,47:v,48:x,49:b,50:T,51:w,52:k,53:C,54:E,55:S,56:L,57:M,58:I,59:A,60:_,61:D,62:N,63:R,64:B,65:O,66:$,67:z,68:F,69:V,70:H,71:X,72:W,73:Z,74:Y},{13:71,19:20,20:21,21:22,22:e,23:r,24:i,26:n,28:a,29:49,30:61,32:62,34:s,36:l,37:u,38:h,39:f,40:d,41:p,43:23,44:m,45:g,46:y,47:v,48:x,49:b,50:T,51:w,52:k,53:C,54:E,55:S,56:L,57:M,58:I,59:A,60:_,61:D,62:N,63:R,64:B,65:O,66:$,67:z,68:F,69:V,70:H,71:X,72:W,73:Z,74:Y},{13:72,19:20,20:21,21:22,22:e,23:r,24:i,26:n,28:a,29:49,30:61,32:62,34:s,36:l,37:u,38:h,39:f,40:d,41:p,43:23,44:m,45:g,46:y,47:v,48:x,49:b,50:T,51:w,52:k,53:C,54:E,55:S,56:L,57:M,58:I,59:A,60:_,61:D,62:N,63:R,64:B,65:O,66:$,67:z,68:F,69:V,70:H,71:X,72:W,73:Z,74:Y},{13:73,19:20,20:21,21:22,22:e,23:r,24:i,26:n,28:a,29:49,30:61,32:62,34:s,36:l,37:u,38:h,39:f,40:d,41:p,43:23,44:m,45:g,46:y,47:v,48:x,49:b,50:T,51:w,52:k,53:C,54:E,55:S,56:L,57:M,58:I,59:A,60:_,61:D,62:N,63:R,64:B,65:O,66:$,67:z,68:F,69:V,70:H,71:X,72:W,73:Z,74:Y},{14:[1,74]},t(ae,[2,13],{43:23,29:49,30:61,32:62,20:75,34:s,36:l,37:u,38:h,39:f,40:d,41:p,44:m,45:g,46:y,47:v,48:x,49:b,50:T,51:w,52:k,53:C,54:E,55:S,56:L,57:M,58:I,59:A,60:_,61:D,62:N,63:R,64:B,65:O,66:$,67:z,68:F,69:V,70:H,71:X,72:W,73:Z,74:Y}),t(ae,[2,14]),t(J,[2,16],{12:[1,76]}),t(ae,[2,36],{12:[1,77]}),t(ee,[2,19]),t(ee,[2,20]),{25:[1,78]},{27:[1,79]},t(ee,[2,23]),{35:80,75:81,76:re,77:te,79:be,80:de},{35:86,75:81,76:re,77:te,79:be,80:de},{35:87,75:81,76:re,77:te,79:be,80:de},{35:88,75:81,76:re,77:te,79:be,80:de},{35:89,75:81,76:re,77:te,79:be,80:de},{35:90,75:81,76:re,77:te,79:be,80:de},{35:91,75:81,76:re,77:te,79:be,80:de},{35:92,75:81,76:re,77:te,79:be,80:de},{35:93,75:81,76:re,77:te,79:be,80:de},{35:94,75:81,76:re,77:te,79:be,80:de},{35:95,75:81,76:re,77:te,79:be,80:de},{35:96,75:81,76:re,77:te,79:be,80:de},{35:97,75:81,76:re,77:te,79:be,80:de},{35:98,75:81,76:re,77:te,79:be,80:de},{35:99,75:81,76:re,77:te,79:be,80:de},{35:100,75:81,76:re,77:te,79:be,80:de},{35:101,75:81,76:re,77:te,79:be,80:de},{35:102,75:81,76:re,77:te,79:be,80:de},{35:103,75:81,76:re,77:te,79:be,80:de},{35:104,75:81,76:re,77:te,79:be,80:de},t(Ee,[2,59]),{35:105,75:81,76:re,77:te,79:be,80:de},{35:106,75:81,76:re,77:te,79:be,80:de},{35:107,75:81,76:re,77:te,79:be,80:de},{35:108,75:81,76:re,77:te,79:be,80:de},{35:109,75:81,76:re,77:te,79:be,80:de},{35:110,75:81,76:re,77:te,79:be,80:de},{35:111,75:81,76:re,77:te,79:be,80:de},{35:112,75:81,76:re,77:te,79:be,80:de},{35:113,75:81,76:re,77:te,79:be,80:de},{35:114,75:81,76:re,77:te,79:be,80:de},{35:115,75:81,76:re,77:te,79:be,80:de},{20:116,29:49,30:61,32:62,34:s,36:l,37:u,38:h,39:f,40:d,41:p,43:23,44:m,45:g,46:y,47:v,48:x,49:b,50:T,51:w,52:k,53:C,54:E,55:S,56:L,57:M,58:I,59:A,60:_,61:D,62:N,63:R,64:B,65:O,66:$,67:z,68:F,69:V,70:H,71:X,72:W,73:Z,74:Y},{12:[1,118],33:[1,117]},{35:119,75:81,76:re,77:te,79:be,80:de},{35:120,75:81,76:re,77:te,79:be,80:de},{35:121,75:81,76:re,77:te,79:be,80:de},{35:122,75:81,76:re,77:te,79:be,80:de},{35:123,75:81,76:re,77:te,79:be,80:de},{35:124,75:81,76:re,77:te,79:be,80:de},{35:125,75:81,76:re,77:te,79:be,80:de},{14:[1,126]},{14:[1,127]},{14:[1,128]},{14:[1,129]},{1:[2,8]},t(ae,[2,15]),t(J,[2,17],{21:22,19:130,22:e,23:r,24:i,26:n,28:a}),t(ae,[2,37],{19:20,20:21,21:22,43:23,29:49,30:61,32:62,13:131,22:e,23:r,24:i,26:n,28:a,34:s,36:l,37:u,38:h,39:f,40:d,41:p,44:m,45:g,46:y,47:v,48:x,49:b,50:T,51:w,52:k,53:C,54:E,55:S,56:L,57:M,58:I,59:A,60:_,61:D,62:N,63:R,64:B,65:O,66:$,67:z,68:F,69:V,70:H,71:X,72:W,73:Z,74:Y}),t(ee,[2,21]),t(ee,[2,22]),t(Ee,[2,39]),t(Ne,[2,71],{75:81,35:132,76:re,77:te,79:be,80:de}),t(we,[2,73]),{78:[1,133]},t(we,[2,75]),t(we,[2,76]),t(Ee,[2,40]),t(Ee,[2,41]),t(Ee,[2,42]),t(Ee,[2,43]),t(Ee,[2,44]),t(Ee,[2,45]),t(Ee,[2,46]),t(Ee,[2,47]),t(Ee,[2,48]),t(Ee,[2,49]),t(Ee,[2,50]),t(Ee,[2,51]),t(Ee,[2,52]),t(Ee,[2,53]),t(Ee,[2,54]),t(Ee,[2,55]),t(Ee,[2,56]),t(Ee,[2,57]),t(Ee,[2,58]),t(Ee,[2,60]),t(Ee,[2,61]),t(Ee,[2,62]),t(Ee,[2,63]),t(Ee,[2,64]),t(Ee,[2,65]),t(Ee,[2,66]),t(Ee,[2,67]),t(Ee,[2,68]),t(Ee,[2,69]),t(Ee,[2,70]),{31:134,42:[1,135]},{12:[1,136]},{33:[1,137]},t(Te,[2,28]),t(Te,[2,29]),t(Te,[2,30]),t(Te,[2,31]),t(Te,[2,32]),t(Te,[2,33]),t(Te,[2,34]),{1:[2,9]},{1:[2,10]},{1:[2,11]},{1:[2,12]},t(J,[2,18]),t(ae,[2,38]),t(Ne,[2,72]),t(we,[2,74]),t(Ee,[2,24]),t(Ee,[2,35]),t(De,[2,25]),t(De,[2,26],{12:[1,138]}),t(De,[2,27])],defaultActions:{2:[2,1],3:[2,2],4:[2,7],5:[2,3],6:[2,4],7:[2,5],8:[2,6],74:[2,8],126:[2,9],127:[2,10],128:[2,11],129:[2,12]},parseError:o(function(Fe,Ue){if(Ue.recoverable)this.trace(Fe);else{var qe=new Error(Fe);throw qe.hash=Ue,qe}},"parseError"),parse:o(function(Fe){var Ue=this,qe=[0],Me=[],He=[null],K=[],oe=this.table,U="",ue=0,G=0,se=0,le=2,ke=1,me=K.slice.call(arguments,1),ye=Object.create(this.lexer),Re={yy:{}};for(var ve in this.yy)Object.prototype.hasOwnProperty.call(this.yy,ve)&&(Re.yy[ve]=this.yy[ve]);ye.setInput(Fe,Re.yy),Re.yy.lexer=ye,Re.yy.parser=this,typeof ye.yylloc>"u"&&(ye.yylloc={});var Oe=ye.yylloc;K.push(Oe);var We=ye.options&&ye.options.ranges;typeof Re.yy.parseError=="function"?this.parseError=Re.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function Be(yt){qe.length=qe.length-2*yt,He.length=He.length-yt,K.length=K.length-yt}o(Be,"popStack");function Qe(){var yt;return yt=Me.pop()||ye.lex()||ke,typeof yt!="number"&&(yt instanceof Array&&(Me=yt,yt=Me.pop()),yt=Ue.symbols_[yt]||yt),yt}o(Qe,"lex");for(var ce,it,fe,ut,Nt,Pt,St={},It,ot,ct,Dt;;){if(fe=qe[qe.length-1],this.defaultActions[fe]?ut=this.defaultActions[fe]:((ce===null||typeof ce>"u")&&(ce=Qe()),ut=oe[fe]&&oe[fe][ce]),typeof ut>"u"||!ut.length||!ut[0]){var kt="";Dt=[];for(It in oe[fe])this.terminals_[It]&&It>le&&Dt.push("'"+this.terminals_[It]+"'");ye.showPosition?kt="Parse error on line "+(ue+1)+`: +`+ye.showPosition()+` +Expecting `+Dt.join(", ")+", got '"+(this.terminals_[ce]||ce)+"'":kt="Parse error on line "+(ue+1)+": Unexpected "+(ce==ke?"end of input":"'"+(this.terminals_[ce]||ce)+"'"),this.parseError(kt,{text:ye.match,token:this.terminals_[ce]||ce,line:ye.yylineno,loc:Oe,expected:Dt})}if(ut[0]instanceof Array&&ut.length>1)throw new Error("Parse Error: multiple actions possible at state: "+fe+", token: "+ce);switch(ut[0]){case 1:qe.push(ce),He.push(ye.yytext),K.push(ye.yylloc),qe.push(ut[1]),ce=null,it?(ce=it,it=null):(G=ye.yyleng,U=ye.yytext,ue=ye.yylineno,Oe=ye.yylloc,se>0&&se--);break;case 2:if(ot=this.productions_[ut[1]][1],St.$=He[He.length-ot],St._$={first_line:K[K.length-(ot||1)].first_line,last_line:K[K.length-1].last_line,first_column:K[K.length-(ot||1)].first_column,last_column:K[K.length-1].last_column},We&&(St._$.range=[K[K.length-(ot||1)].range[0],K[K.length-1].range[1]]),Pt=this.performAction.apply(St,[U,G,ue,Re.yy,ut[1],He,K].concat(me)),typeof Pt<"u")return Pt;ot&&(qe=qe.slice(0,-1*ot*2),He=He.slice(0,-1*ot),K=K.slice(0,-1*ot)),qe.push(this.productions_[ut[1]][0]),He.push(St.$),K.push(St._$),ct=oe[qe[qe.length-2]][qe[qe.length-1]],qe.push(ct);break;case 3:return!0}}return!0},"parse")},pe=(function(){var Ce={EOF:1,parseError:o(function(Ue,qe){if(this.yy.parser)this.yy.parser.parseError(Ue,qe);else throw new Error(Ue)},"parseError"),setInput:o(function(Fe,Ue){return this.yy=Ue||this.yy||{},this._input=Fe,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var Fe=this._input[0];this.yytext+=Fe,this.yyleng++,this.offset++,this.match+=Fe,this.matched+=Fe;var Ue=Fe.match(/(?:\r\n?|\n).*/g);return Ue?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),Fe},"input"),unput:o(function(Fe){var Ue=Fe.length,qe=Fe.split(/(?:\r\n?|\n)/g);this._input=Fe+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-Ue),this.offset-=Ue;var Me=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),qe.length-1&&(this.yylineno-=qe.length-1);var He=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:qe?(qe.length===Me.length?this.yylloc.first_column:0)+Me[Me.length-qe.length].length-qe[0].length:this.yylloc.first_column-Ue},this.options.ranges&&(this.yylloc.range=[He[0],He[0]+this.yyleng-Ue]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(Fe){this.unput(this.match.slice(Fe))},"less"),pastInput:o(function(){var Fe=this.matched.substr(0,this.matched.length-this.match.length);return(Fe.length>20?"...":"")+Fe.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var Fe=this.match;return Fe.length<20&&(Fe+=this._input.substr(0,20-Fe.length)),(Fe.substr(0,20)+(Fe.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var Fe=this.pastInput(),Ue=new Array(Fe.length+1).join("-");return Fe+this.upcomingInput()+` +`+Ue+"^"},"showPosition"),test_match:o(function(Fe,Ue){var qe,Me,He;if(this.options.backtrack_lexer&&(He={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(He.yylloc.range=this.yylloc.range.slice(0))),Me=Fe[0].match(/(?:\r\n?|\n).*/g),Me&&(this.yylineno+=Me.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:Me?Me[Me.length-1].length-Me[Me.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+Fe[0].length},this.yytext+=Fe[0],this.match+=Fe[0],this.matches=Fe,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(Fe[0].length),this.matched+=Fe[0],qe=this.performAction.call(this,this.yy,this,Ue,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),qe)return qe;if(this._backtrack){for(var K in He)this[K]=He[K];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var Fe,Ue,qe,Me;this._more||(this.yytext="",this.match="");for(var He=this._currentRules(),K=0;KUe[0].length)){if(Ue=qe,Me=K,this.options.backtrack_lexer){if(Fe=this.test_match(qe,He[K]),Fe!==!1)return Fe;if(this._backtrack){Ue=!1;continue}else return!1}else if(!this.options.flex)break}return Ue?(Fe=this.test_match(Ue,He[Me]),Fe!==!1?Fe:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var Ue=this.next();return Ue||this.lex()},"lex"),begin:o(function(Ue){this.conditionStack.push(Ue)},"begin"),popState:o(function(){var Ue=this.conditionStack.length-1;return Ue>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(Ue){return Ue=this.conditionStack.length-1-Math.abs(Ue||0),Ue>=0?this.conditionStack[Ue]:"INITIAL"},"topState"),pushState:o(function(Ue){this.begin(Ue)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{},performAction:o(function(Ue,qe,Me,He){var K=He;switch(Me){case 0:return 6;case 1:return 7;case 2:return 8;case 3:return 9;case 4:return 22;case 5:return 23;case 6:return this.begin("acc_title"),24;break;case 7:return this.popState(),"acc_title_value";break;case 8:return this.begin("acc_descr"),26;break;case 9:return this.popState(),"acc_descr_value";break;case 10:this.begin("acc_descr_multiline");break;case 11:this.popState();break;case 12:return"acc_descr_multiline_value";case 13:break;case 14:c;break;case 15:return 12;case 16:break;case 17:return 11;case 18:return 15;case 19:return 16;case 20:return 17;case 21:return 18;case 22:return this.begin("person_ext"),45;break;case 23:return this.begin("person"),44;break;case 24:return this.begin("system_ext_queue"),51;break;case 25:return this.begin("system_ext_db"),50;break;case 26:return this.begin("system_ext"),49;break;case 27:return this.begin("system_queue"),48;break;case 28:return this.begin("system_db"),47;break;case 29:return this.begin("system"),46;break;case 30:return this.begin("boundary"),37;break;case 31:return this.begin("enterprise_boundary"),34;break;case 32:return this.begin("system_boundary"),36;break;case 33:return this.begin("container_ext_queue"),57;break;case 34:return this.begin("container_ext_db"),56;break;case 35:return this.begin("container_ext"),55;break;case 36:return this.begin("container_queue"),54;break;case 37:return this.begin("container_db"),53;break;case 38:return this.begin("container"),52;break;case 39:return this.begin("container_boundary"),38;break;case 40:return this.begin("component_ext_queue"),63;break;case 41:return this.begin("component_ext_db"),62;break;case 42:return this.begin("component_ext"),61;break;case 43:return this.begin("component_queue"),60;break;case 44:return this.begin("component_db"),59;break;case 45:return this.begin("component"),58;break;case 46:return this.begin("node"),39;break;case 47:return this.begin("node"),39;break;case 48:return this.begin("node_l"),40;break;case 49:return this.begin("node_r"),41;break;case 50:return this.begin("rel"),64;break;case 51:return this.begin("birel"),65;break;case 52:return this.begin("rel_u"),66;break;case 53:return this.begin("rel_u"),66;break;case 54:return this.begin("rel_d"),67;break;case 55:return this.begin("rel_d"),67;break;case 56:return this.begin("rel_l"),68;break;case 57:return this.begin("rel_l"),68;break;case 58:return this.begin("rel_r"),69;break;case 59:return this.begin("rel_r"),69;break;case 60:return this.begin("rel_b"),70;break;case 61:return this.begin("rel_index"),71;break;case 62:return this.begin("update_el_style"),72;break;case 63:return this.begin("update_rel_style"),73;break;case 64:return this.begin("update_layout_config"),74;break;case 65:return"EOF_IN_STRUCT";case 66:return this.begin("attribute"),"ATTRIBUTE_EMPTY";break;case 67:this.begin("attribute");break;case 68:this.popState(),this.popState();break;case 69:return 80;case 70:break;case 71:return 80;case 72:this.begin("string");break;case 73:this.popState();break;case 74:return"STR";case 75:this.begin("string_kv");break;case 76:return this.begin("string_kv_key"),"STR_KEY";break;case 77:this.popState(),this.begin("string_kv_value");break;case 78:return"STR_VALUE";case 79:this.popState(),this.popState();break;case 80:return"STR";case 81:return"LBRACE";case 82:return"RBRACE";case 83:return"SPACE";case 84:return"EOL";case 85:return 14}},"anonymous"),rules:[/^(?:.*direction\s+TB[^\n]*)/,/^(?:.*direction\s+BT[^\n]*)/,/^(?:.*direction\s+RL[^\n]*)/,/^(?:.*direction\s+LR[^\n]*)/,/^(?:title\s[^#\n;]+)/,/^(?:accDescription\s[^#\n;]+)/,/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:%%(?!\{)*[^\n]*(\r?\n?)+)/,/^(?:%%[^\n]*(\r?\n)*)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:C4Context\b)/,/^(?:C4Container\b)/,/^(?:C4Component\b)/,/^(?:C4Dynamic\b)/,/^(?:C4Deployment\b)/,/^(?:Person_Ext\b)/,/^(?:Person\b)/,/^(?:SystemQueue_Ext\b)/,/^(?:SystemDb_Ext\b)/,/^(?:System_Ext\b)/,/^(?:SystemQueue\b)/,/^(?:SystemDb\b)/,/^(?:System\b)/,/^(?:Boundary\b)/,/^(?:Enterprise_Boundary\b)/,/^(?:System_Boundary\b)/,/^(?:ContainerQueue_Ext\b)/,/^(?:ContainerDb_Ext\b)/,/^(?:Container_Ext\b)/,/^(?:ContainerQueue\b)/,/^(?:ContainerDb\b)/,/^(?:Container\b)/,/^(?:Container_Boundary\b)/,/^(?:ComponentQueue_Ext\b)/,/^(?:ComponentDb_Ext\b)/,/^(?:Component_Ext\b)/,/^(?:ComponentQueue\b)/,/^(?:ComponentDb\b)/,/^(?:Component\b)/,/^(?:Deployment_Node\b)/,/^(?:Node\b)/,/^(?:Node_L\b)/,/^(?:Node_R\b)/,/^(?:Rel\b)/,/^(?:BiRel\b)/,/^(?:Rel_Up\b)/,/^(?:Rel_U\b)/,/^(?:Rel_Down\b)/,/^(?:Rel_D\b)/,/^(?:Rel_Left\b)/,/^(?:Rel_L\b)/,/^(?:Rel_Right\b)/,/^(?:Rel_R\b)/,/^(?:Rel_Back\b)/,/^(?:RelIndex\b)/,/^(?:UpdateElementStyle\b)/,/^(?:UpdateRelStyle\b)/,/^(?:UpdateLayoutConfig\b)/,/^(?:$)/,/^(?:[(][ ]*[,])/,/^(?:[(])/,/^(?:[)])/,/^(?:,,)/,/^(?:,)/,/^(?:[ ]*["]["])/,/^(?:[ ]*["])/,/^(?:["])/,/^(?:[^"]*)/,/^(?:[ ]*[\$])/,/^(?:[^=]*)/,/^(?:[=][ ]*["])/,/^(?:[^"]+)/,/^(?:["])/,/^(?:[^,]+)/,/^(?:\{)/,/^(?:\})/,/^(?:[\s]+)/,/^(?:[\n\r]+)/,/^(?:$)/],conditions:{acc_descr_multiline:{rules:[11,12],inclusive:!1},acc_descr:{rules:[9],inclusive:!1},acc_title:{rules:[7],inclusive:!1},string_kv_value:{rules:[78,79],inclusive:!1},string_kv_key:{rules:[77],inclusive:!1},string_kv:{rules:[76],inclusive:!1},string:{rules:[73,74],inclusive:!1},attribute:{rules:[68,69,70,71,72,75,80],inclusive:!1},update_layout_config:{rules:[65,66,67,68],inclusive:!1},update_rel_style:{rules:[65,66,67,68],inclusive:!1},update_el_style:{rules:[65,66,67,68],inclusive:!1},rel_b:{rules:[65,66,67,68],inclusive:!1},rel_r:{rules:[65,66,67,68],inclusive:!1},rel_l:{rules:[65,66,67,68],inclusive:!1},rel_d:{rules:[65,66,67,68],inclusive:!1},rel_u:{rules:[65,66,67,68],inclusive:!1},rel_bi:{rules:[],inclusive:!1},rel:{rules:[65,66,67,68],inclusive:!1},node_r:{rules:[65,66,67,68],inclusive:!1},node_l:{rules:[65,66,67,68],inclusive:!1},node:{rules:[65,66,67,68],inclusive:!1},index:{rules:[],inclusive:!1},rel_index:{rules:[65,66,67,68],inclusive:!1},component_ext_queue:{rules:[65,66,67,68],inclusive:!1},component_ext_db:{rules:[65,66,67,68],inclusive:!1},component_ext:{rules:[65,66,67,68],inclusive:!1},component_queue:{rules:[65,66,67,68],inclusive:!1},component_db:{rules:[65,66,67,68],inclusive:!1},component:{rules:[65,66,67,68],inclusive:!1},container_boundary:{rules:[65,66,67,68],inclusive:!1},container_ext_queue:{rules:[65,66,67,68],inclusive:!1},container_ext_db:{rules:[65,66,67,68],inclusive:!1},container_ext:{rules:[65,66,67,68],inclusive:!1},container_queue:{rules:[65,66,67,68],inclusive:!1},container_db:{rules:[65,66,67,68],inclusive:!1},container:{rules:[65,66,67,68],inclusive:!1},birel:{rules:[65,66,67,68],inclusive:!1},system_boundary:{rules:[65,66,67,68],inclusive:!1},enterprise_boundary:{rules:[65,66,67,68],inclusive:!1},boundary:{rules:[65,66,67,68],inclusive:!1},system_ext_queue:{rules:[65,66,67,68],inclusive:!1},system_ext_db:{rules:[65,66,67,68],inclusive:!1},system_ext:{rules:[65,66,67,68],inclusive:!1},system_queue:{rules:[65,66,67,68],inclusive:!1},system_db:{rules:[65,66,67,68],inclusive:!1},system:{rules:[65,66,67,68],inclusive:!1},person_ext:{rules:[65,66,67,68],inclusive:!1},person:{rules:[65,66,67,68],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,8,10,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,81,82,83,84,85],inclusive:!0}}};return Ce})();$e.lexer=pe;function Je(){this.yy={}}return o(Je,"Parser"),Je.prototype=$e,$e.Parser=Je,new Je})();Jx.parser=Jx;YK=Jx});var uRe,hRe,Hr,El,Xi=P(()=>{"use strict";bt();uRe=o(function(t,e){for(let r of e)t.attr(r[0],r[1])},"d3Attrs"),hRe=o(function(t,e,r){let i=new Map;return r?(i.set("width","100%"),i.set("style",`max-width: ${e}px;`)):(i.set("height",t),i.set("width",e)),i},"calculateSvgSizeAttrs"),Hr=o(function(t,e,r,i){let n=hRe(e,r,i);uRe(t,n)},"configureSvgSize"),El=o(function(t,e,r,i){let n=e.node().getBBox(),a=n.width,s=n.height;Q.info(`SVG bounds: ${a}x${s}`,n);let l=0,u=0;Q.info(`Graph bounds: ${l}x${u}`,t),l=a+r*2,u=s+r*2,Q.info(`Calculated bounds: ${l}x${u}`),Hr(e,u,l,i);let h=`${n.x-r} ${n.y-r} ${n.width+2*r} ${n.height+2*r}`;e.attr("viewBox",h)},"setupGraphViewbox")});var tw,fRe,jK,XK,hL=P(()=>{"use strict";bt();tw={},fRe=o((t,e,r,i)=>{let n="";return t in tw&&tw[t]?n=tw[t]({...r,svgId:i}):Q.warn(`No theme found for ${t}`),` & { + font-family: ${r.fontFamily}; + font-size: ${r.fontSize}; + fill: ${r.textColor} + } + @keyframes edge-animation-frame { + from { + stroke-dashoffset: 0; + } + } + @keyframes dash { + to { + stroke-dashoffset: 0; + } + } + & .edge-animation-slow { + stroke-dasharray: 9,5 !important; + stroke-dashoffset: 900; + animation: dash 50s linear infinite; + stroke-linecap: round; + } + & .edge-animation-fast { + stroke-dasharray: 9,5 !important; + stroke-dashoffset: 900; + animation: dash 20s linear infinite; + stroke-linecap: round; + } + /* Classes common for multiple diagrams */ + + & .error-icon { + fill: ${r.errorBkgColor}; + } + & .error-text { + fill: ${r.errorTextColor}; + stroke: ${r.errorTextColor}; + } + + & .edge-thickness-normal { + stroke-width: ${r.strokeWidth??1}px; + } + & .edge-thickness-thick { + stroke-width: 3.5px + } + & .edge-pattern-solid { + stroke-dasharray: 0; + } + & .edge-thickness-invisible { + stroke-width: 0; + fill: none; + } + & .edge-pattern-dashed{ + stroke-dasharray: 3; + } + .edge-pattern-dotted { + stroke-dasharray: 2; + } + + & .marker { + fill: ${r.lineColor}; + stroke: ${r.lineColor}; + } + & .marker.cross { + stroke: ${r.lineColor}; + } + + & svg { + font-family: ${r.fontFamily}; + font-size: ${r.fontSize}; + } + & p { + margin: 0 + } + + ${n} + .node .neo-node { + stroke: ${r.nodeBorder}; + } + + [data-look="neo"].node rect, [data-look="neo"].cluster rect, [data-look="neo"].node polygon { + stroke: ${r.useGradient?"url("+i+"-gradient)":r.nodeBorder}; + filter: ${r.dropShadow?r.dropShadow.replace("url(#drop-shadow)",`url(${i}-drop-shadow)`):"none"}; + } + + + [data-look="neo"].node path { + stroke: ${r.useGradient?"url("+i+"-gradient)":r.nodeBorder}; + stroke-width: ${r.strokeWidth??1}px; + } + + [data-look="neo"].node .outer-path { + filter: ${r.dropShadow?r.dropShadow.replace("url(#drop-shadow)",`url(${i}-drop-shadow)`):"none"}; + } + + [data-look="neo"].node .neo-line path { + stroke: ${r.nodeBorder}; + filter: none; + } + + [data-look="neo"].node circle{ + stroke: ${r.useGradient?"url("+i+"-gradient)":r.nodeBorder}; + filter: ${r.dropShadow?r.dropShadow.replace("url(#drop-shadow)",`url(${i}-drop-shadow)`):"none"}; + } + + [data-look="neo"].node circle .state-start{ + fill: #000000; + } + + [data-look="neo"].icon-shape .icon { + fill: ${r.useGradient?"url("+i+"-gradient)":r.nodeBorder}; + filter: ${r.dropShadow?r.dropShadow.replace("url(#drop-shadow)",`url(${i}-drop-shadow)`):"none"}; + } + + [data-look="neo"].icon-shape .icon-neo path { + stroke: ${r.useGradient?"url("+i+"-gradient)":r.nodeBorder}; + filter: ${r.dropShadow?r.dropShadow.replace("url(#drop-shadow)",`url(${i}-drop-shadow)`):"none"}; + } + + ${e} +`},"getStyles"),jK=o((t,e)=>{e!==void 0&&(tw[t]=e)},"addStylesForDiagram"),XK=fRe});var e2={};ur(e2,{clear:()=>wr,getAccDescription:()=>Rr,getAccTitle:()=>Dr,getDiagramTitle:()=>Nr,setAccDescription:()=>Lr,setAccTitle:()=>Ar,setDiagramTitle:()=>Mr});var fL,dL,pL,mL,wr,Ar,Dr,Lr,Rr,Mr,Nr,Ki=P(()=>{"use strict";Vr();Sr();fL="",dL="",pL="",mL=o(t=>Tr(t,Lt()),"sanitizeText"),wr=o(()=>{fL="",pL="",dL=""},"clear"),Ar=o(t=>{fL=mL(t).replace(/^\s+/g,"")},"setAccTitle"),Dr=o(()=>fL,"getAccTitle"),Lr=o(t=>{pL=mL(t).replace(/\n\s+/g,` +`)},"setAccDescription"),Rr=o(()=>pL,"getAccDescription"),Mr=o(t=>{dL=mL(t)},"setDiagramTitle"),Nr=o(()=>dL,"getDiagramTitle")});var KK,dRe,ge,t2,iw,r2,yL,pRe,rw,Qp,i2,gL,Ut=P(()=>{"use strict";Kp();bt();Sr();Vr();Xi();hL();Ki();KK=Q,dRe=_x,ge=Lt,t2=x4,iw=Nf,r2=o(t=>Tr(t,ge()),"sanitizeText"),yL=El,pRe=o(()=>e2,"getCommonDb"),rw={},Qp=o((t,e,r)=>{rw[t]&&KK.warn(`Diagram with id ${t} already registered. Overwriting.`),rw[t]=e,r&&cL(t,r),jK(t,e.styles),e.injectUtils?.(KK,dRe,ge,r2,yL,pRe(),()=>{})},"registerDiagram"),i2=o(t=>{if(t in rw)return rw[t];throw new gL(t)},"getDiagram"),gL=class extends Error{static{o(this,"DiagramNotFoundError")}constructor(e){super(`Diagram ${e} not found.`)}}});var fc,Ff,Bs,hc,cu,n2,vL,xL,nw,aw,QK,mRe,gRe,yRe,vRe,xRe,bRe,TRe,kRe,CRe,wRe,ERe,SRe,ARe,_Re,DRe,LRe,RRe,ZK,NRe,IRe,JK,MRe,ORe,PRe,BRe,$f,FRe,$Re,zRe,GRe,VRe,a2,bL=P(()=>{"use strict";Ut();Vr();Ki();fc=[],Ff=[""],Bs="global",hc="",cu=[{alias:"global",label:{text:"global"},type:{text:"global"},tags:null,link:null,parentBoundary:""}],n2=[],vL="",xL=!1,nw=4,aw=2,mRe=o(function(){return QK},"getC4Type"),gRe=o(function(t){QK=Tr(t,ge())},"setC4Type"),yRe=o(function(t,e,r,i,n,a,s,l,u){if(t==null||e===void 0||e===null||r===void 0||r===null||i===void 0||i===null)return;let h={},f=n2.find(d=>d.from===e&&d.to===r);if(f?h=f:n2.push(h),h.type=t,h.from=e,h.to=r,h.label={text:i},n==null)h.techn={text:""};else if(typeof n=="object"){let[d,p]=Object.entries(n)[0];h[d]={text:p}}else h.techn={text:n};if(a==null)h.descr={text:""};else if(typeof a=="object"){let[d,p]=Object.entries(a)[0];h[d]={text:p}}else h.descr={text:a};if(typeof s=="object"){let[d,p]=Object.entries(s)[0];h[d]=p}else h.sprite=s;if(typeof l=="object"){let[d,p]=Object.entries(l)[0];h[d]=p}else h.tags=l;if(typeof u=="object"){let[d,p]=Object.entries(u)[0];h[d]=p}else h.link=u;h.wrap=$f()},"addRel"),vRe=o(function(t,e,r,i,n,a,s){if(e===null||r===null)return;let l={},u=fc.find(h=>h.alias===e);if(u&&e===u.alias?l=u:(l.alias=e,fc.push(l)),r==null?l.label={text:""}:l.label={text:r},i==null)l.descr={text:""};else if(typeof i=="object"){let[h,f]=Object.entries(i)[0];l[h]={text:f}}else l.descr={text:i};if(typeof n=="object"){let[h,f]=Object.entries(n)[0];l[h]=f}else l.sprite=n;if(typeof a=="object"){let[h,f]=Object.entries(a)[0];l[h]=f}else l.tags=a;if(typeof s=="object"){let[h,f]=Object.entries(s)[0];l[h]=f}else l.link=s;l.typeC4Shape={text:t},l.parentBoundary=Bs,l.wrap=$f()},"addPersonOrSystem"),xRe=o(function(t,e,r,i,n,a,s,l){if(e===null||r===null)return;let u={},h=fc.find(f=>f.alias===e);if(h&&e===h.alias?u=h:(u.alias=e,fc.push(u)),r==null?u.label={text:""}:u.label={text:r},i==null)u.techn={text:""};else if(typeof i=="object"){let[f,d]=Object.entries(i)[0];u[f]={text:d}}else u.techn={text:i};if(n==null)u.descr={text:""};else if(typeof n=="object"){let[f,d]=Object.entries(n)[0];u[f]={text:d}}else u.descr={text:n};if(typeof a=="object"){let[f,d]=Object.entries(a)[0];u[f]=d}else u.sprite=a;if(typeof s=="object"){let[f,d]=Object.entries(s)[0];u[f]=d}else u.tags=s;if(typeof l=="object"){let[f,d]=Object.entries(l)[0];u[f]=d}else u.link=l;u.wrap=$f(),u.typeC4Shape={text:t},u.parentBoundary=Bs},"addContainer"),bRe=o(function(t,e,r,i,n,a,s,l){if(e===null||r===null)return;let u={},h=fc.find(f=>f.alias===e);if(h&&e===h.alias?u=h:(u.alias=e,fc.push(u)),r==null?u.label={text:""}:u.label={text:r},i==null)u.techn={text:""};else if(typeof i=="object"){let[f,d]=Object.entries(i)[0];u[f]={text:d}}else u.techn={text:i};if(n==null)u.descr={text:""};else if(typeof n=="object"){let[f,d]=Object.entries(n)[0];u[f]={text:d}}else u.descr={text:n};if(typeof a=="object"){let[f,d]=Object.entries(a)[0];u[f]=d}else u.sprite=a;if(typeof s=="object"){let[f,d]=Object.entries(s)[0];u[f]=d}else u.tags=s;if(typeof l=="object"){let[f,d]=Object.entries(l)[0];u[f]=d}else u.link=l;u.wrap=$f(),u.typeC4Shape={text:t},u.parentBoundary=Bs},"addComponent"),TRe=o(function(t,e,r,i,n){if(t===null||e===null)return;let a={},s=cu.find(l=>l.alias===t);if(s&&t===s.alias?a=s:(a.alias=t,cu.push(a)),e==null?a.label={text:""}:a.label={text:e},r==null)a.type={text:"system"};else if(typeof r=="object"){let[l,u]=Object.entries(r)[0];a[l]={text:u}}else a.type={text:r};if(typeof i=="object"){let[l,u]=Object.entries(i)[0];a[l]=u}else a.tags=i;if(typeof n=="object"){let[l,u]=Object.entries(n)[0];a[l]=u}else a.link=n;a.parentBoundary=Bs,a.wrap=$f(),hc=Bs,Bs=t,Ff.push(hc)},"addPersonOrSystemBoundary"),kRe=o(function(t,e,r,i,n){if(t===null||e===null)return;let a={},s=cu.find(l=>l.alias===t);if(s&&t===s.alias?a=s:(a.alias=t,cu.push(a)),e==null?a.label={text:""}:a.label={text:e},r==null)a.type={text:"container"};else if(typeof r=="object"){let[l,u]=Object.entries(r)[0];a[l]={text:u}}else a.type={text:r};if(typeof i=="object"){let[l,u]=Object.entries(i)[0];a[l]=u}else a.tags=i;if(typeof n=="object"){let[l,u]=Object.entries(n)[0];a[l]=u}else a.link=n;a.parentBoundary=Bs,a.wrap=$f(),hc=Bs,Bs=t,Ff.push(hc)},"addContainerBoundary"),CRe=o(function(t,e,r,i,n,a,s,l){if(e===null||r===null)return;let u={},h=cu.find(f=>f.alias===e);if(h&&e===h.alias?u=h:(u.alias=e,cu.push(u)),r==null?u.label={text:""}:u.label={text:r},i==null)u.type={text:"node"};else if(typeof i=="object"){let[f,d]=Object.entries(i)[0];u[f]={text:d}}else u.type={text:i};if(n==null)u.descr={text:""};else if(typeof n=="object"){let[f,d]=Object.entries(n)[0];u[f]={text:d}}else u.descr={text:n};if(typeof s=="object"){let[f,d]=Object.entries(s)[0];u[f]=d}else u.tags=s;if(typeof l=="object"){let[f,d]=Object.entries(l)[0];u[f]=d}else u.link=l;u.nodeType=t,u.parentBoundary=Bs,u.wrap=$f(),hc=Bs,Bs=e,Ff.push(hc)},"addDeploymentNode"),wRe=o(function(){Bs=hc,Ff.pop(),hc=Ff.pop(),Ff.push(hc)},"popBoundaryParseStack"),ERe=o(function(t,e,r,i,n,a,s,l,u,h,f){let d=fc.find(p=>p.alias===e);if(!(d===void 0&&(d=cu.find(p=>p.alias===e),d===void 0))){if(r!=null)if(typeof r=="object"){let[p,m]=Object.entries(r)[0];d[p]=m}else d.bgColor=r;if(i!=null)if(typeof i=="object"){let[p,m]=Object.entries(i)[0];d[p]=m}else d.fontColor=i;if(n!=null)if(typeof n=="object"){let[p,m]=Object.entries(n)[0];d[p]=m}else d.borderColor=n;if(a!=null)if(typeof a=="object"){let[p,m]=Object.entries(a)[0];d[p]=m}else d.shadowing=a;if(s!=null)if(typeof s=="object"){let[p,m]=Object.entries(s)[0];d[p]=m}else d.shape=s;if(l!=null)if(typeof l=="object"){let[p,m]=Object.entries(l)[0];d[p]=m}else d.sprite=l;if(u!=null)if(typeof u=="object"){let[p,m]=Object.entries(u)[0];d[p]=m}else d.techn=u;if(h!=null)if(typeof h=="object"){let[p,m]=Object.entries(h)[0];d[p]=m}else d.legendText=h;if(f!=null)if(typeof f=="object"){let[p,m]=Object.entries(f)[0];d[p]=m}else d.legendSprite=f}},"updateElStyle"),SRe=o(function(t,e,r,i,n,a,s){let l=n2.find(u=>u.from===e&&u.to===r);if(l!==void 0){if(i!=null)if(typeof i=="object"){let[u,h]=Object.entries(i)[0];l[u]=h}else l.textColor=i;if(n!=null)if(typeof n=="object"){let[u,h]=Object.entries(n)[0];l[u]=h}else l.lineColor=n;if(a!=null)if(typeof a=="object"){let[u,h]=Object.entries(a)[0];l[u]=parseInt(h)}else l.offsetX=parseInt(a);if(s!=null)if(typeof s=="object"){let[u,h]=Object.entries(s)[0];l[u]=parseInt(h)}else l.offsetY=parseInt(s)}},"updateRelStyle"),ARe=o(function(t,e,r){let i=nw,n=aw;if(typeof e=="object"){let a=Object.values(e)[0];i=parseInt(a)}else i=parseInt(e);if(typeof r=="object"){let a=Object.values(r)[0];n=parseInt(a)}else n=parseInt(r);i>=1&&(nw=i),n>=1&&(aw=n)},"updateLayoutConfig"),_Re=o(function(){return nw},"getC4ShapeInRow"),DRe=o(function(){return aw},"getC4BoundaryInRow"),LRe=o(function(){return Bs},"getCurrentBoundaryParse"),RRe=o(function(){return hc},"getParentBoundaryParse"),ZK=o(function(t){return t==null?fc:fc.filter(e=>e.parentBoundary===t)},"getC4ShapeArray"),NRe=o(function(t){return fc.find(e=>e.alias===t)},"getC4Shape"),IRe=o(function(t){return Object.keys(ZK(t))},"getC4ShapeKeys"),JK=o(function(t){return t==null?cu:cu.filter(e=>e.parentBoundary===t)},"getBoundaries"),MRe=JK,ORe=o(function(){return n2},"getRels"),PRe=o(function(){return vL},"getTitle"),BRe=o(function(t){xL=t},"setWrap"),$f=o(function(){return xL},"autoWrap"),FRe=o(function(){fc=[],cu=[{alias:"global",label:{text:"global"},type:{text:"global"},tags:null,link:null,parentBoundary:""}],hc="",Bs="global",Ff=[""],n2=[],Ff=[""],vL="",xL=!1,nw=4,aw=2},"clear"),$Re={SOLID:0,DOTTED:1,NOTE:2,SOLID_CROSS:3,DOTTED_CROSS:4,SOLID_OPEN:5,DOTTED_OPEN:6,LOOP_START:10,LOOP_END:11,ALT_START:12,ALT_ELSE:13,ALT_END:14,OPT_START:15,OPT_END:16,ACTIVE_START:17,ACTIVE_END:18,PAR_START:19,PAR_AND:20,PAR_END:21,RECT_START:22,RECT_END:23,SOLID_POINT:24,DOTTED_POINT:25},zRe={FILLED:0,OPEN:1},GRe={LEFTOF:0,RIGHTOF:1,OVER:2},VRe=o(function(t){vL=Tr(t,ge())},"setTitle"),a2={addPersonOrSystem:vRe,addPersonOrSystemBoundary:TRe,addContainer:xRe,addContainerBoundary:kRe,addComponent:bRe,addDeploymentNode:CRe,popBoundaryParseStack:wRe,addRel:yRe,updateElStyle:ERe,updateRelStyle:SRe,updateLayoutConfig:ARe,autoWrap:$f,setWrap:BRe,getC4ShapeArray:ZK,getC4Shape:NRe,getC4ShapeKeys:IRe,getBoundaries:JK,getBoundarys:MRe,getCurrentBoundaryParse:LRe,getParentBoundaryParse:RRe,getRels:ORe,getTitle:PRe,getC4Type:mRe,getC4ShapeInRow:_Re,getC4BoundaryInRow:DRe,setAccTitle:Ar,getAccTitle:Dr,getAccDescription:Rr,setAccDescription:Lr,getConfig:o(()=>ge().c4,"getConfig"),clear:FRe,LINETYPE:$Re,ARROWTYPE:zRe,PLACEMENT:GRe,setTitle:VRe,setC4Type:gRe}});function Zp(t,e){return t==null||e==null?NaN:te?1:t>=e?0:NaN}var TL=P(()=>{"use strict";o(Zp,"ascending")});function kL(t,e){return t==null||e==null?NaN:et?1:e>=t?0:NaN}var eQ=P(()=>{"use strict";o(kL,"descending")});function Jp(t){let e,r,i;t.length!==2?(e=Zp,r=o((l,u)=>Zp(t(l),u),"compare2"),i=o((l,u)=>t(l)-u,"delta")):(e=t===Zp||t===kL?t:qRe,r=t,i=t);function n(l,u,h=0,f=l.length){if(h>>1;r(l[d],u)<0?h=d+1:f=d}while(h>>1;r(l[d],u)<=0?h=d+1:f=d}while(hh&&i(l[d-1],u)>-i(l[d],u)?d-1:d}return o(s,"center"),{left:n,center:s,right:a}}function qRe(){return 0}var CL=P(()=>{"use strict";TL();eQ();o(Jp,"bisector");o(qRe,"zero")});function wL(t){return t===null?NaN:+t}var tQ=P(()=>{"use strict";o(wL,"number")});var rQ,iQ,WRe,URe,EL,nQ=P(()=>{"use strict";TL();CL();tQ();rQ=Jp(Zp),iQ=rQ.right,WRe=rQ.left,URe=Jp(wL).center,EL=iQ});function aQ({_intern:t,_key:e},r){let i=e(r);return t.has(i)?t.get(i):r}function HRe({_intern:t,_key:e},r){let i=e(r);return t.has(i)?t.get(i):(t.set(i,r),r)}function YRe({_intern:t,_key:e},r){let i=e(r);return t.has(i)&&(r=t.get(i),t.delete(i)),r}function jRe(t){return t!==null&&typeof t=="object"?t.valueOf():t}var Mg,sQ=P(()=>{"use strict";Mg=class extends Map{static{o(this,"InternMap")}constructor(e,r=jRe){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),e!=null)for(let[i,n]of e)this.set(i,n)}get(e){return super.get(aQ(this,e))}has(e){return super.has(aQ(this,e))}set(e,r){return super.set(HRe(this,e),r)}delete(e){return super.delete(YRe(this,e))}};o(aQ,"intern_get");o(HRe,"intern_set");o(YRe,"intern_delete");o(jRe,"keyof")});function sw(t,e,r){let i=(e-t)/Math.max(0,r),n=Math.floor(Math.log10(i)),a=i/Math.pow(10,n),s=a>=XRe?10:a>=KRe?5:a>=QRe?2:1,l,u,h;return n<0?(h=Math.pow(10,-n)/s,l=Math.round(t*h),u=Math.round(e*h),l/he&&--u,h=-h):(h=Math.pow(10,n)*s,l=Math.round(t/h),u=Math.round(e/h),l*he&&--u),u0))return[];if(t===e)return[t];let i=e=n))return[];let l=a-n+1,u=new Array(l);if(i)if(s<0)for(let h=0;h{"use strict";XRe=Math.sqrt(50),KRe=Math.sqrt(10),QRe=Math.sqrt(2);o(sw,"tickSpec");o(ow,"ticks");o(s2,"tickIncrement");o(Og,"tickStep")});function lw(t,e){let r;if(e===void 0)for(let i of t)i!=null&&(r=i)&&(r=i);else{let i=-1;for(let n of t)(n=e(n,++i,t))!=null&&(r=n)&&(r=n)}return r}var lQ=P(()=>{"use strict";o(lw,"max")});function cw(t,e){let r;if(e===void 0)for(let i of t)i!=null&&(r>i||r===void 0&&i>=i)&&(r=i);else{let i=-1;for(let n of t)(n=e(n,++i,t))!=null&&(r>n||r===void 0&&n>=n)&&(r=n)}return r}var cQ=P(()=>{"use strict";o(cw,"min")});function uw(t,e,r){t=+t,e=+e,r=(n=arguments.length)<2?(e=t,t=0,1):n<3?1:+r;for(var i=-1,n=Math.max(0,Math.ceil((e-t)/r))|0,a=new Array(n);++i{"use strict";o(uw,"range")});var zf=P(()=>{"use strict";nQ();CL();lQ();cQ();uQ();oQ();sQ()});function SL(t){return t}var hQ=P(()=>{"use strict";o(SL,"default")});function ZRe(t){return"translate("+t+",0)"}function JRe(t){return"translate(0,"+t+")"}function e9e(t){return e=>+t(e)}function t9e(t,e){return e=Math.max(0,t.bandwidth()-e*2)/2,t.round()&&(e=Math.round(e)),r=>+t(r)+e}function r9e(){return!this.__axis}function dQ(t,e){var r=[],i=null,n=null,a=6,s=6,l=3,u=typeof window<"u"&&window.devicePixelRatio>1?0:.5,h=t===fw||t===hw?-1:1,f=t===hw||t===AL?"x":"y",d=t===fw||t===_L?ZRe:JRe;function p(m){var g=i??(e.ticks?e.ticks.apply(e,r):e.domain()),y=n??(e.tickFormat?e.tickFormat.apply(e,r):SL),v=Math.max(a,0)+l,x=e.range(),b=+x[0]+u,T=+x[x.length-1]+u,w=(e.bandwidth?t9e:e9e)(e.copy(),u),k=m.selection?m.selection():m,C=k.selectAll(".domain").data([null]),E=k.selectAll(".tick").data(g,e).order(),S=E.exit(),L=E.enter().append("g").attr("class","tick"),M=E.select("line"),I=E.select("text");C=C.merge(C.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),E=E.merge(L),M=M.merge(L.append("line").attr("stroke","currentColor").attr(f+"2",h*a)),I=I.merge(L.append("text").attr("fill","currentColor").attr(f,h*v).attr("dy",t===fw?"0em":t===_L?"0.71em":"0.32em")),m!==k&&(C=C.transition(m),E=E.transition(m),M=M.transition(m),I=I.transition(m),S=S.transition(m).attr("opacity",fQ).attr("transform",function(A){return isFinite(A=w(A))?d(A+u):this.getAttribute("transform")}),L.attr("opacity",fQ).attr("transform",function(A){var _=this.parentNode.__axis;return d((_&&isFinite(_=_(A))?_:w(A))+u)})),S.remove(),C.attr("d",t===hw||t===AL?s?"M"+h*s+","+b+"H"+u+"V"+T+"H"+h*s:"M"+u+","+b+"V"+T:s?"M"+b+","+h*s+"V"+u+"H"+T+"V"+h*s:"M"+b+","+u+"H"+T),E.attr("opacity",1).attr("transform",function(A){return d(w(A)+u)}),M.attr(f+"2",h*a),I.attr(f,h*v).text(y),k.filter(r9e).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",t===AL?"start":t===hw?"end":"middle"),k.each(function(){this.__axis=w})}return o(p,"axis"),p.scale=function(m){return arguments.length?(e=m,p):e},p.ticks=function(){return r=Array.from(arguments),p},p.tickArguments=function(m){return arguments.length?(r=m==null?[]:Array.from(m),p):r.slice()},p.tickValues=function(m){return arguments.length?(i=m==null?null:Array.from(m),p):i&&i.slice()},p.tickFormat=function(m){return arguments.length?(n=m,p):n},p.tickSize=function(m){return arguments.length?(a=s=+m,p):a},p.tickSizeInner=function(m){return arguments.length?(a=+m,p):a},p.tickSizeOuter=function(m){return arguments.length?(s=+m,p):s},p.tickPadding=function(m){return arguments.length?(l=+m,p):l},p.offset=function(m){return arguments.length?(u=+m,p):u},p}function DL(t){return dQ(fw,t)}function LL(t){return dQ(_L,t)}var fw,AL,_L,hw,fQ,pQ=P(()=>{"use strict";hQ();fw=1,AL=2,_L=3,hw=4,fQ=1e-6;o(ZRe,"translateX");o(JRe,"translateY");o(e9e,"number");o(t9e,"center");o(r9e,"entering");o(dQ,"axis");o(DL,"axisTop");o(LL,"axisBottom")});var mQ=P(()=>{"use strict";pQ()});function yQ(){for(var t=0,e=arguments.length,r={},i;t=0&&(i=r.slice(n+1),r=r.slice(0,n)),r&&!e.hasOwnProperty(r))throw new Error("unknown type: "+r);return{type:r,name:i}})}function a9e(t,e){for(var r=0,i=t.length,n;r{"use strict";i9e={value:o(()=>{},"value")};o(yQ,"dispatch");o(dw,"Dispatch");o(n9e,"parseTypenames");dw.prototype=yQ.prototype={constructor:dw,on:o(function(t,e){var r=this._,i=n9e(t+"",r),n,a=-1,s=i.length;if(arguments.length<2){for(;++a0)for(var r=new Array(n),i=0,n,a;i{"use strict";vQ()});var pw,IL,ML=P(()=>{"use strict";pw="http://www.w3.org/1999/xhtml",IL={svg:"http://www.w3.org/2000/svg",xhtml:pw,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"}});function uu(t){var e=t+="",r=e.indexOf(":");return r>=0&&(e=t.slice(0,r))!=="xmlns"&&(t=t.slice(r+1)),IL.hasOwnProperty(e)?{space:IL[e],local:t}:t}var mw=P(()=>{"use strict";ML();o(uu,"default")});function s9e(t){return function(){var e=this.ownerDocument,r=this.namespaceURI;return r===pw&&e.documentElement.namespaceURI===pw?e.createElement(t):e.createElementNS(r,t)}}function o9e(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function o2(t){var e=uu(t);return(e.local?o9e:s9e)(e)}var OL=P(()=>{"use strict";mw();ML();o(s9e,"creatorInherit");o(o9e,"creatorFixed");o(o2,"default")});function l9e(){}function Gf(t){return t==null?l9e:function(){return this.querySelector(t)}}var gw=P(()=>{"use strict";o(l9e,"none");o(Gf,"default")});function PL(t){typeof t!="function"&&(t=Gf(t));for(var e=this._groups,r=e.length,i=new Array(r),n=0;n{"use strict";dc();gw();o(PL,"default")});function BL(t){return t==null?[]:Array.isArray(t)?t:Array.from(t)}var bQ=P(()=>{"use strict";o(BL,"array")});function c9e(){return[]}function Pg(t){return t==null?c9e:function(){return this.querySelectorAll(t)}}var FL=P(()=>{"use strict";o(c9e,"empty");o(Pg,"default")});function u9e(t){return function(){return BL(t.apply(this,arguments))}}function $L(t){typeof t=="function"?t=u9e(t):t=Pg(t);for(var e=this._groups,r=e.length,i=[],n=[],a=0;a{"use strict";dc();bQ();FL();o(u9e,"arrayAll");o($L,"default")});function Bg(t){return function(){return this.matches(t)}}function yw(t){return function(e){return e.matches(t)}}var l2=P(()=>{"use strict";o(Bg,"default");o(yw,"childMatcher")});function f9e(t){return function(){return h9e.call(this.children,t)}}function d9e(){return this.firstElementChild}function zL(t){return this.select(t==null?d9e:f9e(typeof t=="function"?t:yw(t)))}var h9e,kQ=P(()=>{"use strict";l2();h9e=Array.prototype.find;o(f9e,"childFind");o(d9e,"childFirst");o(zL,"default")});function m9e(){return Array.from(this.children)}function g9e(t){return function(){return p9e.call(this.children,t)}}function GL(t){return this.selectAll(t==null?m9e:g9e(typeof t=="function"?t:yw(t)))}var p9e,CQ=P(()=>{"use strict";l2();p9e=Array.prototype.filter;o(m9e,"children");o(g9e,"childrenFilter");o(GL,"default")});function VL(t){typeof t!="function"&&(t=Bg(t));for(var e=this._groups,r=e.length,i=new Array(r),n=0;n{"use strict";dc();l2();o(VL,"default")});function c2(t){return new Array(t.length)}var qL=P(()=>{"use strict";o(c2,"default")});function WL(){return new Nn(this._enter||this._groups.map(c2),this._parents)}function u2(t,e){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=e}var UL=P(()=>{"use strict";qL();dc();o(WL,"default");o(u2,"EnterNode");u2.prototype={constructor:u2,appendChild:o(function(t){return this._parent.insertBefore(t,this._next)},"appendChild"),insertBefore:o(function(t,e){return this._parent.insertBefore(t,e)},"insertBefore"),querySelector:o(function(t){return this._parent.querySelector(t)},"querySelector"),querySelectorAll:o(function(t){return this._parent.querySelectorAll(t)},"querySelectorAll")}});function HL(t){return function(){return t}}var EQ=P(()=>{"use strict";o(HL,"default")});function y9e(t,e,r,i,n,a){for(var s=0,l,u=e.length,h=a.length;s=T&&(T=b+1);!(k=v[T])&&++T{"use strict";dc();UL();EQ();o(y9e,"bindIndex");o(v9e,"bindKey");o(x9e,"datum");o(YL,"default");o(b9e,"arraylike")});function jL(){return new Nn(this._exit||this._groups.map(c2),this._parents)}var AQ=P(()=>{"use strict";qL();dc();o(jL,"default")});function XL(t,e,r){var i=this.enter(),n=this,a=this.exit();return typeof t=="function"?(i=t(i),i&&(i=i.selection())):i=i.append(t+""),e!=null&&(n=e(n),n&&(n=n.selection())),r==null?a.remove():r(a),i&&n?i.merge(n).order():n}var _Q=P(()=>{"use strict";o(XL,"default")});function KL(t){for(var e=t.selection?t.selection():t,r=this._groups,i=e._groups,n=r.length,a=i.length,s=Math.min(n,a),l=new Array(n),u=0;u{"use strict";dc();o(KL,"default")});function QL(){for(var t=this._groups,e=-1,r=t.length;++e=0;)(s=i[n])&&(a&&s.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(s,a),a=s);return this}var LQ=P(()=>{"use strict";o(QL,"default")});function ZL(t){t||(t=T9e);function e(d,p){return d&&p?t(d.__data__,p.__data__):!d-!p}o(e,"compareNode");for(var r=this._groups,i=r.length,n=new Array(i),a=0;ae?1:t>=e?0:NaN}var RQ=P(()=>{"use strict";dc();o(ZL,"default");o(T9e,"ascending")});function JL(){var t=arguments[0];return arguments[0]=this,t.apply(null,arguments),this}var NQ=P(()=>{"use strict";o(JL,"default")});function eR(){return Array.from(this)}var IQ=P(()=>{"use strict";o(eR,"default")});function tR(){for(var t=this._groups,e=0,r=t.length;e{"use strict";o(tR,"default")});function rR(){let t=0;for(let e of this)++t;return t}var OQ=P(()=>{"use strict";o(rR,"default")});function iR(){return!this.node()}var PQ=P(()=>{"use strict";o(iR,"default")});function nR(t){for(var e=this._groups,r=0,i=e.length;r{"use strict";o(nR,"default")});function k9e(t){return function(){this.removeAttribute(t)}}function C9e(t){return function(){this.removeAttributeNS(t.space,t.local)}}function w9e(t,e){return function(){this.setAttribute(t,e)}}function E9e(t,e){return function(){this.setAttributeNS(t.space,t.local,e)}}function S9e(t,e){return function(){var r=e.apply(this,arguments);r==null?this.removeAttribute(t):this.setAttribute(t,r)}}function A9e(t,e){return function(){var r=e.apply(this,arguments);r==null?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,r)}}function aR(t,e){var r=uu(t);if(arguments.length<2){var i=this.node();return r.local?i.getAttributeNS(r.space,r.local):i.getAttribute(r)}return this.each((e==null?r.local?C9e:k9e:typeof e=="function"?r.local?A9e:S9e:r.local?E9e:w9e)(r,e))}var FQ=P(()=>{"use strict";mw();o(k9e,"attrRemove");o(C9e,"attrRemoveNS");o(w9e,"attrConstant");o(E9e,"attrConstantNS");o(S9e,"attrFunction");o(A9e,"attrFunctionNS");o(aR,"default")});function h2(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}var sR=P(()=>{"use strict";o(h2,"default")});function _9e(t){return function(){this.style.removeProperty(t)}}function D9e(t,e,r){return function(){this.style.setProperty(t,e,r)}}function L9e(t,e,r){return function(){var i=e.apply(this,arguments);i==null?this.style.removeProperty(t):this.style.setProperty(t,i,r)}}function oR(t,e,r){return arguments.length>1?this.each((e==null?_9e:typeof e=="function"?L9e:D9e)(t,e,r??"")):Vf(this.node(),t)}function Vf(t,e){return t.style.getPropertyValue(e)||h2(t).getComputedStyle(t,null).getPropertyValue(e)}var lR=P(()=>{"use strict";sR();o(_9e,"styleRemove");o(D9e,"styleConstant");o(L9e,"styleFunction");o(oR,"default");o(Vf,"styleValue")});function R9e(t){return function(){delete this[t]}}function N9e(t,e){return function(){this[t]=e}}function I9e(t,e){return function(){var r=e.apply(this,arguments);r==null?delete this[t]:this[t]=r}}function cR(t,e){return arguments.length>1?this.each((e==null?R9e:typeof e=="function"?I9e:N9e)(t,e)):this.node()[t]}var $Q=P(()=>{"use strict";o(R9e,"propertyRemove");o(N9e,"propertyConstant");o(I9e,"propertyFunction");o(cR,"default")});function zQ(t){return t.trim().split(/^|\s+/)}function uR(t){return t.classList||new GQ(t)}function GQ(t){this._node=t,this._names=zQ(t.getAttribute("class")||"")}function VQ(t,e){for(var r=uR(t),i=-1,n=e.length;++i{"use strict";o(zQ,"classArray");o(uR,"classList");o(GQ,"ClassList");GQ.prototype={add:o(function(t){var e=this._names.indexOf(t);e<0&&(this._names.push(t),this._node.setAttribute("class",this._names.join(" ")))},"add"),remove:o(function(t){var e=this._names.indexOf(t);e>=0&&(this._names.splice(e,1),this._node.setAttribute("class",this._names.join(" ")))},"remove"),contains:o(function(t){return this._names.indexOf(t)>=0},"contains")};o(VQ,"classedAdd");o(qQ,"classedRemove");o(M9e,"classedTrue");o(O9e,"classedFalse");o(P9e,"classedFunction");o(hR,"default")});function B9e(){this.textContent=""}function F9e(t){return function(){this.textContent=t}}function $9e(t){return function(){var e=t.apply(this,arguments);this.textContent=e??""}}function fR(t){return arguments.length?this.each(t==null?B9e:(typeof t=="function"?$9e:F9e)(t)):this.node().textContent}var UQ=P(()=>{"use strict";o(B9e,"textRemove");o(F9e,"textConstant");o($9e,"textFunction");o(fR,"default")});function z9e(){this.innerHTML=""}function G9e(t){return function(){this.innerHTML=t}}function V9e(t){return function(){var e=t.apply(this,arguments);this.innerHTML=e??""}}function dR(t){return arguments.length?this.each(t==null?z9e:(typeof t=="function"?V9e:G9e)(t)):this.node().innerHTML}var HQ=P(()=>{"use strict";o(z9e,"htmlRemove");o(G9e,"htmlConstant");o(V9e,"htmlFunction");o(dR,"default")});function q9e(){this.nextSibling&&this.parentNode.appendChild(this)}function pR(){return this.each(q9e)}var YQ=P(()=>{"use strict";o(q9e,"raise");o(pR,"default")});function W9e(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function mR(){return this.each(W9e)}var jQ=P(()=>{"use strict";o(W9e,"lower");o(mR,"default")});function gR(t){var e=typeof t=="function"?t:o2(t);return this.select(function(){return this.appendChild(e.apply(this,arguments))})}var XQ=P(()=>{"use strict";OL();o(gR,"default")});function U9e(){return null}function yR(t,e){var r=typeof t=="function"?t:o2(t),i=e==null?U9e:typeof e=="function"?e:Gf(e);return this.select(function(){return this.insertBefore(r.apply(this,arguments),i.apply(this,arguments)||null)})}var KQ=P(()=>{"use strict";OL();gw();o(U9e,"constantNull");o(yR,"default")});function H9e(){var t=this.parentNode;t&&t.removeChild(this)}function vR(){return this.each(H9e)}var QQ=P(()=>{"use strict";o(H9e,"remove");o(vR,"default")});function Y9e(){var t=this.cloneNode(!1),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}function j9e(){var t=this.cloneNode(!0),e=this.parentNode;return e?e.insertBefore(t,this.nextSibling):t}function xR(t){return this.select(t?j9e:Y9e)}var ZQ=P(()=>{"use strict";o(Y9e,"selection_cloneShallow");o(j9e,"selection_cloneDeep");o(xR,"default")});function bR(t){return arguments.length?this.property("__data__",t):this.node().__data__}var JQ=P(()=>{"use strict";o(bR,"default")});function X9e(t){return function(e){t.call(this,e,this.__data__)}}function K9e(t){return t.trim().split(/^|\s+/).map(function(e){var r="",i=e.indexOf(".");return i>=0&&(r=e.slice(i+1),e=e.slice(0,i)),{type:e,name:r}})}function Q9e(t){return function(){var e=this.__on;if(e){for(var r=0,i=-1,n=e.length,a;r{"use strict";o(X9e,"contextListener");o(K9e,"parseTypenames");o(Q9e,"onRemove");o(Z9e,"onAdd");o(TR,"default")});function tZ(t,e,r){var i=h2(t),n=i.CustomEvent;typeof n=="function"?n=new n(e,r):(n=i.document.createEvent("Event"),r?(n.initEvent(e,r.bubbles,r.cancelable),n.detail=r.detail):n.initEvent(e,!1,!1)),t.dispatchEvent(n)}function J9e(t,e){return function(){return tZ(this,t,e)}}function eNe(t,e){return function(){return tZ(this,t,e.apply(this,arguments))}}function kR(t,e){return this.each((typeof e=="function"?eNe:J9e)(t,e))}var rZ=P(()=>{"use strict";sR();o(tZ,"dispatchEvent");o(J9e,"dispatchConstant");o(eNe,"dispatchFunction");o(kR,"default")});function*CR(){for(var t=this._groups,e=0,r=t.length;e{"use strict";o(CR,"default")});function Nn(t,e){this._groups=t,this._parents=e}function nZ(){return new Nn([[document.documentElement]],wR)}function tNe(){return this}var wR,Eh,dc=P(()=>{"use strict";xQ();TQ();kQ();CQ();wQ();SQ();UL();AQ();_Q();DQ();LQ();RQ();NQ();IQ();MQ();OQ();PQ();BQ();FQ();lR();$Q();WQ();UQ();HQ();YQ();jQ();XQ();KQ();QQ();ZQ();JQ();eZ();rZ();iZ();wR=[null];o(Nn,"Selection");o(nZ,"selection");o(tNe,"selection_selection");Nn.prototype=nZ.prototype={constructor:Nn,select:PL,selectAll:$L,selectChild:zL,selectChildren:GL,filter:VL,data:YL,enter:WL,exit:jL,join:XL,merge:KL,selection:tNe,order:QL,sort:ZL,call:JL,nodes:eR,node:tR,size:rR,empty:iR,each:nR,attr:aR,style:oR,property:cR,classed:hR,text:fR,html:dR,raise:pR,lower:mR,append:gR,insert:yR,remove:vR,clone:xR,datum:bR,on:TR,dispatch:kR,[Symbol.iterator]:CR};Eh=nZ});function Ze(t){return typeof t=="string"?new Nn([[document.querySelector(t)]],[document.documentElement]):new Nn([[t]],wR)}var aZ=P(()=>{"use strict";dc();o(Ze,"default")});var pc=P(()=>{"use strict";l2();mw();aZ();dc();gw();FL();lR()});var sZ=P(()=>{"use strict"});function qf(t,e,r){t.prototype=e.prototype=r,r.constructor=t}function Fg(t,e){var r=Object.create(t.prototype);for(var i in e)r[i]=e[i];return r}var ER=P(()=>{"use strict";o(qf,"default");o(Fg,"extend")});function Wf(){}function lZ(){return this.rgb().formatHex()}function cNe(){return this.rgb().formatHex8()}function uNe(){return mZ(this).formatHsl()}function cZ(){return this.rgb().formatRgb()}function gc(t){var e,r;return t=(t+"").trim().toLowerCase(),(e=rNe.exec(t))?(r=e[1].length,e=parseInt(e[1],16),r===6?uZ(e):r===3?new Ua(e>>8&15|e>>4&240,e>>4&15|e&240,(e&15)<<4|e&15,1):r===8?vw(e>>24&255,e>>16&255,e>>8&255,(e&255)/255):r===4?vw(e>>12&15|e>>8&240,e>>8&15|e>>4&240,e>>4&15|e&240,((e&15)<<4|e&15)/255):null):(e=iNe.exec(t))?new Ua(e[1],e[2],e[3],1):(e=nNe.exec(t))?new Ua(e[1]*255/100,e[2]*255/100,e[3]*255/100,1):(e=aNe.exec(t))?vw(e[1],e[2],e[3],e[4]):(e=sNe.exec(t))?vw(e[1]*255/100,e[2]*255/100,e[3]*255/100,e[4]):(e=oNe.exec(t))?dZ(e[1],e[2]/100,e[3]/100,1):(e=lNe.exec(t))?dZ(e[1],e[2]/100,e[3]/100,e[4]):oZ.hasOwnProperty(t)?uZ(oZ[t]):t==="transparent"?new Ua(NaN,NaN,NaN,0):null}function uZ(t){return new Ua(t>>16&255,t>>8&255,t&255,1)}function vw(t,e,r,i){return i<=0&&(t=e=r=NaN),new Ua(t,e,r,i)}function AR(t){return t instanceof Wf||(t=gc(t)),t?(t=t.rgb(),new Ua(t.r,t.g,t.b,t.opacity)):new Ua}function zg(t,e,r,i){return arguments.length===1?AR(t):new Ua(t,e,r,i??1)}function Ua(t,e,r,i){this.r=+t,this.g=+e,this.b=+r,this.opacity=+i}function hZ(){return`#${e0(this.r)}${e0(this.g)}${e0(this.b)}`}function hNe(){return`#${e0(this.r)}${e0(this.g)}${e0(this.b)}${e0((isNaN(this.opacity)?1:this.opacity)*255)}`}function fZ(){let t=Tw(this.opacity);return`${t===1?"rgb(":"rgba("}${t0(this.r)}, ${t0(this.g)}, ${t0(this.b)}${t===1?")":`, ${t})`}`}function Tw(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function t0(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function e0(t){return t=t0(t),(t<16?"0":"")+t.toString(16)}function dZ(t,e,r,i){return i<=0?t=e=r=NaN:r<=0||r>=1?t=e=NaN:e<=0&&(t=NaN),new mc(t,e,r,i)}function mZ(t){if(t instanceof mc)return new mc(t.h,t.s,t.l,t.opacity);if(t instanceof Wf||(t=gc(t)),!t)return new mc;if(t instanceof mc)return t;t=t.rgb();var e=t.r/255,r=t.g/255,i=t.b/255,n=Math.min(e,r,i),a=Math.max(e,r,i),s=NaN,l=a-n,u=(a+n)/2;return l?(e===a?s=(r-i)/l+(r0&&u<1?0:s,new mc(s,l,u,t.opacity)}function gZ(t,e,r,i){return arguments.length===1?mZ(t):new mc(t,e,r,i??1)}function mc(t,e,r,i){this.h=+t,this.s=+e,this.l=+r,this.opacity=+i}function pZ(t){return t=(t||0)%360,t<0?t+360:t}function xw(t){return Math.max(0,Math.min(1,t||0))}function SR(t,e,r){return(t<60?e+(r-e)*t/60:t<180?r:t<240?e+(r-e)*(240-t)/60:e)*255}var f2,bw,$g,d2,hu,rNe,iNe,nNe,aNe,sNe,oNe,lNe,oZ,_R=P(()=>{"use strict";ER();o(Wf,"Color");f2=.7,bw=1/f2,$g="\\s*([+-]?\\d+)\\s*",d2="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",hu="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",rNe=/^#([0-9a-f]{3,8})$/,iNe=new RegExp(`^rgb\\(${$g},${$g},${$g}\\)$`),nNe=new RegExp(`^rgb\\(${hu},${hu},${hu}\\)$`),aNe=new RegExp(`^rgba\\(${$g},${$g},${$g},${d2}\\)$`),sNe=new RegExp(`^rgba\\(${hu},${hu},${hu},${d2}\\)$`),oNe=new RegExp(`^hsl\\(${d2},${hu},${hu}\\)$`),lNe=new RegExp(`^hsla\\(${d2},${hu},${hu},${d2}\\)$`),oZ={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};qf(Wf,gc,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:lZ,formatHex:lZ,formatHex8:cNe,formatHsl:uNe,formatRgb:cZ,toString:cZ});o(lZ,"color_formatHex");o(cNe,"color_formatHex8");o(uNe,"color_formatHsl");o(cZ,"color_formatRgb");o(gc,"color");o(uZ,"rgbn");o(vw,"rgba");o(AR,"rgbConvert");o(zg,"rgb");o(Ua,"Rgb");qf(Ua,zg,Fg(Wf,{brighter(t){return t=t==null?bw:Math.pow(bw,t),new Ua(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=t==null?f2:Math.pow(f2,t),new Ua(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new Ua(t0(this.r),t0(this.g),t0(this.b),Tw(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:hZ,formatHex:hZ,formatHex8:hNe,formatRgb:fZ,toString:fZ}));o(hZ,"rgb_formatHex");o(hNe,"rgb_formatHex8");o(fZ,"rgb_formatRgb");o(Tw,"clampa");o(t0,"clampi");o(e0,"hex");o(dZ,"hsla");o(mZ,"hslConvert");o(gZ,"hsl");o(mc,"Hsl");qf(mc,gZ,Fg(Wf,{brighter(t){return t=t==null?bw:Math.pow(bw,t),new mc(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=t==null?f2:Math.pow(f2,t),new mc(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+(this.h<0)*360,e=isNaN(t)||isNaN(this.s)?0:this.s,r=this.l,i=r+(r<.5?r:1-r)*e,n=2*r-i;return new Ua(SR(t>=240?t-240:t+120,n,i),SR(t,n,i),SR(t<120?t+240:t-120,n,i),this.opacity)},clamp(){return new mc(pZ(this.h),xw(this.s),xw(this.l),Tw(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let t=Tw(this.opacity);return`${t===1?"hsl(":"hsla("}${pZ(this.h)}, ${xw(this.s)*100}%, ${xw(this.l)*100}%${t===1?")":`, ${t})`}`}}));o(pZ,"clamph");o(xw,"clampt");o(SR,"hsl2rgb")});var yZ,vZ,xZ=P(()=>{"use strict";yZ=Math.PI/180,vZ=180/Math.PI});function EZ(t){if(t instanceof fu)return new fu(t.l,t.a,t.b,t.opacity);if(t instanceof Sh)return SZ(t);t instanceof Ua||(t=AR(t));var e=NR(t.r),r=NR(t.g),i=NR(t.b),n=DR((.2225045*e+.7168786*r+.0606169*i)/TZ),a,s;return e===r&&r===i?a=s=n:(a=DR((.4360747*e+.3850649*r+.1430804*i)/bZ),s=DR((.0139322*e+.0971045*r+.7141733*i)/kZ)),new fu(116*n-16,500*(a-n),200*(n-s),t.opacity)}function IR(t,e,r,i){return arguments.length===1?EZ(t):new fu(t,e,r,i??1)}function fu(t,e,r,i){this.l=+t,this.a=+e,this.b=+r,this.opacity=+i}function DR(t){return t>fNe?Math.pow(t,1/3):t/wZ+CZ}function LR(t){return t>Gg?t*t*t:wZ*(t-CZ)}function RR(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function NR(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function dNe(t){if(t instanceof Sh)return new Sh(t.h,t.c,t.l,t.opacity);if(t instanceof fu||(t=EZ(t)),t.a===0&&t.b===0)return new Sh(NaN,0{"use strict";ER();_R();xZ();kw=18,bZ=.96422,TZ=1,kZ=.82521,CZ=4/29,Gg=6/29,wZ=3*Gg*Gg,fNe=Gg*Gg*Gg;o(EZ,"labConvert");o(IR,"lab");o(fu,"Lab");qf(fu,IR,Fg(Wf,{brighter(t){return new fu(this.l+kw*(t??1),this.a,this.b,this.opacity)},darker(t){return new fu(this.l-kw*(t??1),this.a,this.b,this.opacity)},rgb(){var t=(this.l+16)/116,e=isNaN(this.a)?t:t+this.a/500,r=isNaN(this.b)?t:t-this.b/200;return e=bZ*LR(e),t=TZ*LR(t),r=kZ*LR(r),new Ua(RR(3.1338561*e-1.6168667*t-.4906146*r),RR(-.9787684*e+1.9161415*t+.033454*r),RR(.0719453*e-.2289914*t+1.4052427*r),this.opacity)}}));o(DR,"xyz2lab");o(LR,"lab2xyz");o(RR,"lrgb2rgb");o(NR,"rgb2lrgb");o(dNe,"hclConvert");o(p2,"hcl");o(Sh,"Hcl");o(SZ,"hcl2lab");qf(Sh,p2,Fg(Wf,{brighter(t){return new Sh(this.h,this.c,this.l+kw*(t??1),this.opacity)},darker(t){return new Sh(this.h,this.c,this.l-kw*(t??1),this.opacity)},rgb(){return SZ(this).rgb()}}))});var Vg=P(()=>{"use strict";_R();AZ()});function MR(t,e,r,i,n){var a=t*t,s=a*t;return((1-3*t+3*a-s)*e+(4-6*a+3*s)*r+(1+3*t+3*a-3*s)*i+s*n)/6}function OR(t){var e=t.length-1;return function(r){var i=r<=0?r=0:r>=1?(r=1,e-1):Math.floor(r*e),n=t[i],a=t[i+1],s=i>0?t[i-1]:2*n-a,l=i{"use strict";o(MR,"basis");o(OR,"default")});function BR(t){var e=t.length;return function(r){var i=Math.floor(((r%=1)<0?++r:r)*e),n=t[(i+e-1)%e],a=t[i%e],s=t[(i+1)%e],l=t[(i+2)%e];return MR((r-i/e)*e,n,a,s,l)}}var _Z=P(()=>{"use strict";PR();o(BR,"default")});var qg,FR=P(()=>{"use strict";qg=o(t=>()=>t,"default")});function DZ(t,e){return function(r){return t+r*e}}function pNe(t,e,r){return t=Math.pow(t,r),e=Math.pow(e,r)-t,r=1/r,function(i){return Math.pow(t+i*e,r)}}function LZ(t,e){var r=e-t;return r?DZ(t,r>180||r<-180?r-360*Math.round(r/360):r):qg(isNaN(t)?e:t)}function RZ(t){return(t=+t)==1?Ah:function(e,r){return r-e?pNe(e,r,t):qg(isNaN(e)?r:e)}}function Ah(t,e){var r=e-t;return r?DZ(t,r):qg(isNaN(t)?e:t)}var $R=P(()=>{"use strict";FR();o(DZ,"linear");o(pNe,"exponential");o(LZ,"hue");o(RZ,"gamma");o(Ah,"nogamma")});function NZ(t){return function(e){var r=e.length,i=new Array(r),n=new Array(r),a=new Array(r),s,l;for(s=0;s{"use strict";Vg();PR();_Z();$R();r0=o((function t(e){var r=RZ(e);function i(n,a){var s=r((n=zg(n)).r,(a=zg(a)).r),l=r(n.g,a.g),u=r(n.b,a.b),h=Ah(n.opacity,a.opacity);return function(f){return n.r=s(f),n.g=l(f),n.b=u(f),n.opacity=h(f),n+""}}return o(i,"rgb"),i.gamma=t,i}),"rgbGamma")(1);o(NZ,"rgbSpline");mNe=NZ(OR),gNe=NZ(BR)});function GR(t,e){e||(e=[]);var r=t?Math.min(e.length,t.length):0,i=e.slice(),n;return function(a){for(n=0;n{"use strict";o(GR,"default");o(IZ,"isNumberArray")});function OZ(t,e){var r=e?e.length:0,i=t?Math.min(r,t.length):0,n=new Array(i),a=new Array(r),s;for(s=0;s{"use strict";Cw();o(OZ,"genericArray")});function VR(t,e){var r=new Date;return t=+t,e=+e,function(i){return r.setTime(t*(1-i)+e*i),r}}var BZ=P(()=>{"use strict";o(VR,"default")});function Ea(t,e){return t=+t,e=+e,function(r){return t*(1-r)+e*r}}var m2=P(()=>{"use strict";o(Ea,"default")});function qR(t,e){var r={},i={},n;(t===null||typeof t!="object")&&(t={}),(e===null||typeof e!="object")&&(e={});for(n in e)n in t?r[n]=Uf(t[n],e[n]):i[n]=e[n];return function(a){for(n in r)i[n]=r[n](a);return i}}var FZ=P(()=>{"use strict";Cw();o(qR,"default")});function yNe(t){return function(){return t}}function vNe(t){return function(e){return t(e)+""}}function Wg(t,e){var r=UR.lastIndex=WR.lastIndex=0,i,n,a,s=-1,l=[],u=[];for(t=t+"",e=e+"";(i=UR.exec(t))&&(n=WR.exec(e));)(a=n.index)>r&&(a=e.slice(r,a),l[s]?l[s]+=a:l[++s]=a),(i=i[0])===(n=n[0])?l[s]?l[s]+=n:l[++s]=n:(l[++s]=null,u.push({i:s,x:Ea(i,n)})),r=WR.lastIndex;return r{"use strict";m2();UR=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,WR=new RegExp(UR.source,"g");o(yNe,"zero");o(vNe,"one");o(Wg,"default")});function Uf(t,e){var r=typeof e,i;return e==null||r==="boolean"?qg(e):(r==="number"?Ea:r==="string"?(i=gc(e))?(e=i,r0):Wg:e instanceof gc?r0:e instanceof Date?VR:IZ(e)?GR:Array.isArray(e)?OZ:typeof e.valueOf!="function"&&typeof e.toString!="function"||isNaN(e)?qR:Ea)(t,e)}var Cw=P(()=>{"use strict";Vg();zR();PZ();BZ();m2();FZ();HR();FR();MZ();o(Uf,"default")});function ww(t,e){return t=+t,e=+e,function(r){return Math.round(t*(1-r)+e*r)}}var $Z=P(()=>{"use strict";o(ww,"default")});function Sw(t,e,r,i,n,a){var s,l,u;return(s=Math.sqrt(t*t+e*e))&&(t/=s,e/=s),(u=t*r+e*i)&&(r-=t*u,i-=e*u),(l=Math.sqrt(r*r+i*i))&&(r/=l,i/=l,u/=l),t*i{"use strict";zZ=180/Math.PI,Ew={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};o(Sw,"default")});function VZ(t){let e=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(t+"");return e.isIdentity?Ew:Sw(e.a,e.b,e.c,e.d,e.e,e.f)}function qZ(t){return t==null?Ew:(Aw||(Aw=document.createElementNS("http://www.w3.org/2000/svg","g")),Aw.setAttribute("transform",t),(t=Aw.transform.baseVal.consolidate())?(t=t.matrix,Sw(t.a,t.b,t.c,t.d,t.e,t.f)):Ew)}var Aw,WZ=P(()=>{"use strict";GZ();o(VZ,"parseCss");o(qZ,"parseSvg")});function UZ(t,e,r,i){function n(h){return h.length?h.pop()+" ":""}o(n,"pop");function a(h,f,d,p,m,g){if(h!==d||f!==p){var y=m.push("translate(",null,e,null,r);g.push({i:y-4,x:Ea(h,d)},{i:y-2,x:Ea(f,p)})}else(d||p)&&m.push("translate("+d+e+p+r)}o(a,"translate");function s(h,f,d,p){h!==f?(h-f>180?f+=360:f-h>180&&(h+=360),p.push({i:d.push(n(d)+"rotate(",null,i)-2,x:Ea(h,f)})):f&&d.push(n(d)+"rotate("+f+i)}o(s,"rotate");function l(h,f,d,p){h!==f?p.push({i:d.push(n(d)+"skewX(",null,i)-2,x:Ea(h,f)}):f&&d.push(n(d)+"skewX("+f+i)}o(l,"skewX");function u(h,f,d,p,m,g){if(h!==d||f!==p){var y=m.push(n(m)+"scale(",null,",",null,")");g.push({i:y-4,x:Ea(h,d)},{i:y-2,x:Ea(f,p)})}else(d!==1||p!==1)&&m.push(n(m)+"scale("+d+","+p+")")}return o(u,"scale"),function(h,f){var d=[],p=[];return h=t(h),f=t(f),a(h.translateX,h.translateY,f.translateX,f.translateY,d,p),s(h.rotate,f.rotate,d,p),l(h.skewX,f.skewX,d,p),u(h.scaleX,h.scaleY,f.scaleX,f.scaleY,d,p),h=f=null,function(m){for(var g=-1,y=p.length,v;++g{"use strict";m2();WZ();o(UZ,"interpolateTransform");YR=UZ(VZ,"px, ","px)","deg)"),jR=UZ(qZ,", ",")",")")});function YZ(t){return function(e,r){var i=t((e=p2(e)).h,(r=p2(r)).h),n=Ah(e.c,r.c),a=Ah(e.l,r.l),s=Ah(e.opacity,r.opacity);return function(l){return e.h=i(l),e.c=n(l),e.l=a(l),e.opacity=s(l),e+""}}}var XR,xNe,jZ=P(()=>{"use strict";Vg();$R();o(YZ,"hcl");XR=YZ(LZ),xNe=YZ(Ah)});var Ug=P(()=>{"use strict";Cw();m2();$Z();HR();HZ();zR();jZ()});function T2(){return i0||(QZ(bNe),i0=x2.now()+Lw)}function bNe(){i0=0}function b2(){this._call=this._time=this._next=null}function Rw(t,e,r){var i=new b2;return i.restart(t,e,r),i}function ZZ(){T2(),++Hg;for(var t=_w,e;t;)(e=i0-t._time)>=0&&t._call.call(void 0,e),t=t._next;--Hg}function XZ(){i0=(Dw=x2.now())+Lw,Hg=y2=0;try{ZZ()}finally{Hg=0,kNe(),i0=0}}function TNe(){var t=x2.now(),e=t-Dw;e>KZ&&(Lw-=e,Dw=t)}function kNe(){for(var t,e=_w,r,i=1/0;e;)e._call?(i>e._time&&(i=e._time),t=e,e=e._next):(r=e._next,e._next=null,e=t?t._next=r:_w=r);v2=t,KR(i)}function KR(t){if(!Hg){y2&&(y2=clearTimeout(y2));var e=t-i0;e>24?(t<1/0&&(y2=setTimeout(XZ,t-x2.now()-Lw)),g2&&(g2=clearInterval(g2))):(g2||(Dw=x2.now(),g2=setInterval(TNe,KZ)),Hg=1,QZ(XZ))}}var Hg,y2,g2,KZ,_w,v2,Dw,i0,Lw,x2,QZ,QR=P(()=>{"use strict";Hg=0,y2=0,g2=0,KZ=1e3,Dw=0,i0=0,Lw=0,x2=typeof performance=="object"&&performance.now?performance:Date,QZ=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(t){setTimeout(t,17)};o(T2,"now");o(bNe,"clearNow");o(b2,"Timer");b2.prototype=Rw.prototype={constructor:b2,restart:o(function(t,e,r){if(typeof t!="function")throw new TypeError("callback is not a function");r=(r==null?T2():+r)+(e==null?0:+e),!this._next&&v2!==this&&(v2?v2._next=this:_w=this,v2=this),this._call=t,this._time=r,KR()},"restart"),stop:o(function(){this._call&&(this._call=null,this._time=1/0,KR())},"stop")};o(Rw,"timer");o(ZZ,"timerFlush");o(XZ,"wake");o(TNe,"poke");o(kNe,"nap");o(KR,"sleep")});function k2(t,e,r){var i=new b2;return e=e==null?0:+e,i.restart(n=>{i.stop(),t(n+e)},e,r),i}var JZ=P(()=>{"use strict";QR();o(k2,"default")});var Nw=P(()=>{"use strict";QR();JZ()});function _h(t,e,r,i,n,a){var s=t.__transition;if(!s)t.__transition={};else if(r in s)return;ENe(t,r,{name:e,index:i,group:n,on:CNe,tween:wNe,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:rJ})}function w2(t,e){var r=ua(t,e);if(r.state>rJ)throw new Error("too late; already scheduled");return r}function Ha(t,e){var r=ua(t,e);if(r.state>Iw)throw new Error("too late; already running");return r}function ua(t,e){var r=t.__transition;if(!r||!(r=r[e]))throw new Error("transition not found");return r}function ENe(t,e,r){var i=t.__transition,n;i[e]=r,r.timer=Rw(a,0,r.time);function a(h){r.state=eJ,r.timer.restart(s,r.delay,r.time),r.delay<=h&&s(h-r.delay)}o(a,"schedule");function s(h){var f,d,p,m;if(r.state!==eJ)return u();for(f in i)if(m=i[f],m.name===r.name){if(m.state===Iw)return k2(s);m.state===tJ?(m.state=C2,m.timer.stop(),m.on.call("interrupt",t,t.__data__,m.index,m.group),delete i[f]):+f{"use strict";NL();Nw();CNe=RL("start","end","cancel","interrupt"),wNe=[],rJ=0,eJ=1,Mw=2,Iw=3,tJ=4,Ow=5,C2=6;o(_h,"default");o(w2,"init");o(Ha,"set");o(ua,"get");o(ENe,"create")});function E2(t,e){var r=t.__transition,i,n,a=!0,s;if(r){e=e==null?null:e+"";for(s in r){if((i=r[s]).name!==e){a=!1;continue}n=i.state>Mw&&i.state{"use strict";po();o(E2,"default")});function ZR(t){return this.each(function(){E2(this,t)})}var nJ=P(()=>{"use strict";iJ();o(ZR,"default")});function SNe(t,e){var r,i;return function(){var n=Ha(this,t),a=n.tween;if(a!==r){i=r=a;for(var s=0,l=i.length;s{"use strict";po();o(SNe,"tweenRemove");o(ANe,"tweenFunction");o(JR,"default");o(Yg,"tweenValue")});function A2(t,e){var r;return(typeof e=="number"?Ea:e instanceof gc?r0:(r=gc(e))?(e=r,r0):Wg)(t,e)}var e9=P(()=>{"use strict";Vg();Ug();o(A2,"default")});function _Ne(t){return function(){this.removeAttribute(t)}}function DNe(t){return function(){this.removeAttributeNS(t.space,t.local)}}function LNe(t,e,r){var i,n=r+"",a;return function(){var s=this.getAttribute(t);return s===n?null:s===i?a:a=e(i=s,r)}}function RNe(t,e,r){var i,n=r+"",a;return function(){var s=this.getAttributeNS(t.space,t.local);return s===n?null:s===i?a:a=e(i=s,r)}}function NNe(t,e,r){var i,n,a;return function(){var s,l=r(this),u;return l==null?void this.removeAttribute(t):(s=this.getAttribute(t),u=l+"",s===u?null:s===i&&u===n?a:(n=u,a=e(i=s,l)))}}function INe(t,e,r){var i,n,a;return function(){var s,l=r(this),u;return l==null?void this.removeAttributeNS(t.space,t.local):(s=this.getAttributeNS(t.space,t.local),u=l+"",s===u?null:s===i&&u===n?a:(n=u,a=e(i=s,l)))}}function t9(t,e){var r=uu(t),i=r==="transform"?jR:A2;return this.attrTween(t,typeof e=="function"?(r.local?INe:NNe)(r,i,Yg(this,"attr."+t,e)):e==null?(r.local?DNe:_Ne)(r):(r.local?RNe:LNe)(r,i,e))}var aJ=P(()=>{"use strict";Ug();pc();S2();e9();o(_Ne,"attrRemove");o(DNe,"attrRemoveNS");o(LNe,"attrConstant");o(RNe,"attrConstantNS");o(NNe,"attrFunction");o(INe,"attrFunctionNS");o(t9,"default")});function MNe(t,e){return function(r){this.setAttribute(t,e.call(this,r))}}function ONe(t,e){return function(r){this.setAttributeNS(t.space,t.local,e.call(this,r))}}function PNe(t,e){var r,i;function n(){var a=e.apply(this,arguments);return a!==i&&(r=(i=a)&&ONe(t,a)),r}return o(n,"tween"),n._value=e,n}function BNe(t,e){var r,i;function n(){var a=e.apply(this,arguments);return a!==i&&(r=(i=a)&&MNe(t,a)),r}return o(n,"tween"),n._value=e,n}function r9(t,e){var r="attr."+t;if(arguments.length<2)return(r=this.tween(r))&&r._value;if(e==null)return this.tween(r,null);if(typeof e!="function")throw new Error;var i=uu(t);return this.tween(r,(i.local?PNe:BNe)(i,e))}var sJ=P(()=>{"use strict";pc();o(MNe,"attrInterpolate");o(ONe,"attrInterpolateNS");o(PNe,"attrTweenNS");o(BNe,"attrTween");o(r9,"default")});function FNe(t,e){return function(){w2(this,t).delay=+e.apply(this,arguments)}}function $Ne(t,e){return e=+e,function(){w2(this,t).delay=e}}function i9(t){var e=this._id;return arguments.length?this.each((typeof t=="function"?FNe:$Ne)(e,t)):ua(this.node(),e).delay}var oJ=P(()=>{"use strict";po();o(FNe,"delayFunction");o($Ne,"delayConstant");o(i9,"default")});function zNe(t,e){return function(){Ha(this,t).duration=+e.apply(this,arguments)}}function GNe(t,e){return e=+e,function(){Ha(this,t).duration=e}}function n9(t){var e=this._id;return arguments.length?this.each((typeof t=="function"?zNe:GNe)(e,t)):ua(this.node(),e).duration}var lJ=P(()=>{"use strict";po();o(zNe,"durationFunction");o(GNe,"durationConstant");o(n9,"default")});function VNe(t,e){if(typeof e!="function")throw new Error;return function(){Ha(this,t).ease=e}}function a9(t){var e=this._id;return arguments.length?this.each(VNe(e,t)):ua(this.node(),e).ease}var cJ=P(()=>{"use strict";po();o(VNe,"easeConstant");o(a9,"default")});function qNe(t,e){return function(){var r=e.apply(this,arguments);if(typeof r!="function")throw new Error;Ha(this,t).ease=r}}function s9(t){if(typeof t!="function")throw new Error;return this.each(qNe(this._id,t))}var uJ=P(()=>{"use strict";po();o(qNe,"easeVarying");o(s9,"default")});function o9(t){typeof t!="function"&&(t=Bg(t));for(var e=this._groups,r=e.length,i=new Array(r),n=0;n{"use strict";pc();n0();o(o9,"default")});function l9(t){if(t._id!==this._id)throw new Error;for(var e=this._groups,r=t._groups,i=e.length,n=r.length,a=Math.min(i,n),s=new Array(i),l=0;l{"use strict";n0();o(l9,"default")});function WNe(t){return(t+"").trim().split(/^|\s+/).every(function(e){var r=e.indexOf(".");return r>=0&&(e=e.slice(0,r)),!e||e==="start"})}function UNe(t,e,r){var i,n,a=WNe(e)?w2:Ha;return function(){var s=a(this,t),l=s.on;l!==i&&(n=(i=l).copy()).on(e,r),s.on=n}}function c9(t,e){var r=this._id;return arguments.length<2?ua(this.node(),r).on.on(t):this.each(UNe(r,t,e))}var dJ=P(()=>{"use strict";po();o(WNe,"start");o(UNe,"onFunction");o(c9,"default")});function HNe(t){return function(){var e=this.parentNode;for(var r in this.__transition)if(+r!==t)return;e&&e.removeChild(this)}}function u9(){return this.on("end.remove",HNe(this._id))}var pJ=P(()=>{"use strict";o(HNe,"removeFunction");o(u9,"default")});function h9(t){var e=this._name,r=this._id;typeof t!="function"&&(t=Gf(t));for(var i=this._groups,n=i.length,a=new Array(n),s=0;s{"use strict";pc();n0();po();o(h9,"default")});function f9(t){var e=this._name,r=this._id;typeof t!="function"&&(t=Pg(t));for(var i=this._groups,n=i.length,a=[],s=[],l=0;l{"use strict";pc();n0();po();o(f9,"default")});function d9(){return new YNe(this._groups,this._parents)}var YNe,yJ=P(()=>{"use strict";pc();YNe=Eh.prototype.constructor;o(d9,"default")});function jNe(t,e){var r,i,n;return function(){var a=Vf(this,t),s=(this.style.removeProperty(t),Vf(this,t));return a===s?null:a===r&&s===i?n:n=e(r=a,i=s)}}function vJ(t){return function(){this.style.removeProperty(t)}}function XNe(t,e,r){var i,n=r+"",a;return function(){var s=Vf(this,t);return s===n?null:s===i?a:a=e(i=s,r)}}function KNe(t,e,r){var i,n,a;return function(){var s=Vf(this,t),l=r(this),u=l+"";return l==null&&(u=l=(this.style.removeProperty(t),Vf(this,t))),s===u?null:s===i&&u===n?a:(n=u,a=e(i=s,l))}}function QNe(t,e){var r,i,n,a="style."+e,s="end."+a,l;return function(){var u=Ha(this,t),h=u.on,f=u.value[a]==null?l||(l=vJ(e)):void 0;(h!==r||n!==f)&&(i=(r=h).copy()).on(s,n=f),u.on=i}}function p9(t,e,r){var i=(t+="")=="transform"?YR:A2;return e==null?this.styleTween(t,jNe(t,i)).on("end.style."+t,vJ(t)):typeof e=="function"?this.styleTween(t,KNe(t,i,Yg(this,"style."+t,e))).each(QNe(this._id,t)):this.styleTween(t,XNe(t,i,e),r).on("end.style."+t,null)}var xJ=P(()=>{"use strict";Ug();pc();po();S2();e9();o(jNe,"styleNull");o(vJ,"styleRemove");o(XNe,"styleConstant");o(KNe,"styleFunction");o(QNe,"styleMaybeRemove");o(p9,"default")});function ZNe(t,e,r){return function(i){this.style.setProperty(t,e.call(this,i),r)}}function JNe(t,e,r){var i,n;function a(){var s=e.apply(this,arguments);return s!==n&&(i=(n=s)&&ZNe(t,s,r)),i}return o(a,"tween"),a._value=e,a}function m9(t,e,r){var i="style."+(t+="");if(arguments.length<2)return(i=this.tween(i))&&i._value;if(e==null)return this.tween(i,null);if(typeof e!="function")throw new Error;return this.tween(i,JNe(t,e,r??""))}var bJ=P(()=>{"use strict";o(ZNe,"styleInterpolate");o(JNe,"styleTween");o(m9,"default")});function eIe(t){return function(){this.textContent=t}}function tIe(t){return function(){var e=t(this);this.textContent=e??""}}function g9(t){return this.tween("text",typeof t=="function"?tIe(Yg(this,"text",t)):eIe(t==null?"":t+""))}var TJ=P(()=>{"use strict";S2();o(eIe,"textConstant");o(tIe,"textFunction");o(g9,"default")});function rIe(t){return function(e){this.textContent=t.call(this,e)}}function iIe(t){var e,r;function i(){var n=t.apply(this,arguments);return n!==r&&(e=(r=n)&&rIe(n)),e}return o(i,"tween"),i._value=t,i}function y9(t){var e="text";if(arguments.length<1)return(e=this.tween(e))&&e._value;if(t==null)return this.tween(e,null);if(typeof t!="function")throw new Error;return this.tween(e,iIe(t))}var kJ=P(()=>{"use strict";o(rIe,"textInterpolate");o(iIe,"textTween");o(y9,"default")});function v9(){for(var t=this._name,e=this._id,r=Pw(),i=this._groups,n=i.length,a=0;a{"use strict";n0();po();o(v9,"default")});function x9(){var t,e,r=this,i=r._id,n=r.size();return new Promise(function(a,s){var l={value:s},u={value:o(function(){--n===0&&a()},"value")};r.each(function(){var h=Ha(this,i),f=h.on;f!==t&&(e=(t=f).copy(),e._.cancel.push(l),e._.interrupt.push(l),e._.end.push(u)),h.on=e}),n===0&&a()})}var wJ=P(()=>{"use strict";po();o(x9,"default")});function Fs(t,e,r,i){this._groups=t,this._parents=e,this._name=r,this._id=i}function EJ(t){return Eh().transition(t)}function Pw(){return++nIe}var nIe,Dh,n0=P(()=>{"use strict";pc();aJ();sJ();oJ();lJ();cJ();uJ();hJ();fJ();dJ();pJ();mJ();gJ();yJ();xJ();bJ();TJ();kJ();CJ();S2();wJ();nIe=0;o(Fs,"Transition");o(EJ,"transition");o(Pw,"newId");Dh=Eh.prototype;Fs.prototype=EJ.prototype={constructor:Fs,select:h9,selectAll:f9,selectChild:Dh.selectChild,selectChildren:Dh.selectChildren,filter:o9,merge:l9,selection:d9,transition:v9,call:Dh.call,nodes:Dh.nodes,node:Dh.node,size:Dh.size,empty:Dh.empty,each:Dh.each,on:c9,attr:t9,attrTween:r9,style:p9,styleTween:m9,text:g9,textTween:y9,remove:u9,tween:JR,delay:i9,duration:n9,ease:a9,easeVarying:s9,end:x9,[Symbol.iterator]:Dh[Symbol.iterator]}});function Bw(t){return((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2}var SJ=P(()=>{"use strict";o(Bw,"cubicInOut")});var b9=P(()=>{"use strict";SJ()});function sIe(t,e){for(var r;!(r=t.__transition)||!(r=r[e]);)if(!(t=t.parentNode))throw new Error(`transition ${e} not found`);return r}function T9(t){var e,r;t instanceof Fs?(e=t._id,t=t._name):(e=Pw(),(r=aIe).time=T2(),t=t==null?null:t+"");for(var i=this._groups,n=i.length,a=0;a{"use strict";n0();po();b9();Nw();aIe={time:null,delay:0,duration:250,ease:Bw};o(sIe,"inherit");o(T9,"default")});var _J=P(()=>{"use strict";pc();nJ();AJ();Eh.prototype.interrupt=ZR;Eh.prototype.transition=T9});var Fw=P(()=>{"use strict";_J()});var DJ=P(()=>{"use strict"});var LJ=P(()=>{"use strict"});var RJ=P(()=>{"use strict"});function NJ(t){return[+t[0],+t[1]]}function oIe(t){return[NJ(t[0]),NJ(t[1])]}function k9(t){return{type:t}}var O6t,P6t,B6t,F6t,$6t,z6t,IJ=P(()=>{"use strict";Fw();DJ();LJ();RJ();({abs:O6t,max:P6t,min:B6t}=Math);o(NJ,"number1");o(oIe,"number2");F6t={name:"x",handles:["w","e"].map(k9),input:o(function(t,e){return t==null?null:[[+t[0],e[0][1]],[+t[1],e[1][1]]]},"input"),output:o(function(t){return t&&[t[0][0],t[1][0]]},"output")},$6t={name:"y",handles:["n","s"].map(k9),input:o(function(t,e){return t==null?null:[[e[0][0],+t[0]],[e[1][0],+t[1]]]},"input"),output:o(function(t){return t&&[t[0][1],t[1][1]]},"output")},z6t={name:"xy",handles:["n","w","e","s","nw","ne","sw","se"].map(k9),input:o(function(t){return t==null?null:oIe(t)},"input"),output:o(function(t){return t},"output")};o(k9,"type")});var MJ=P(()=>{"use strict";IJ()});function OJ(t){this._+=t[0];for(let e=1,r=t.length;e=0))throw new Error(`invalid digits: ${t}`);if(e>15)return OJ;let r=10**e;return function(i){this._+=i[0];for(let n=1,a=i.length;n{"use strict";C9=Math.PI,w9=2*C9,a0=1e-6,lIe=w9-a0;o(OJ,"append");o(cIe,"appendRound");s0=class{static{o(this,"Path")}constructor(e){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=e==null?OJ:cIe(e)}moveTo(e,r){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+r}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`)}lineTo(e,r){this._append`L${this._x1=+e},${this._y1=+r}`}quadraticCurveTo(e,r,i,n){this._append`Q${+e},${+r},${this._x1=+i},${this._y1=+n}`}bezierCurveTo(e,r,i,n,a,s){this._append`C${+e},${+r},${+i},${+n},${this._x1=+a},${this._y1=+s}`}arcTo(e,r,i,n,a){if(e=+e,r=+r,i=+i,n=+n,a=+a,a<0)throw new Error(`negative radius: ${a}`);let s=this._x1,l=this._y1,u=i-e,h=n-r,f=s-e,d=l-r,p=f*f+d*d;if(this._x1===null)this._append`M${this._x1=e},${this._y1=r}`;else if(p>a0)if(!(Math.abs(d*u-h*f)>a0)||!a)this._append`L${this._x1=e},${this._y1=r}`;else{let m=i-s,g=n-l,y=u*u+h*h,v=m*m+g*g,x=Math.sqrt(y),b=Math.sqrt(p),T=a*Math.tan((C9-Math.acos((y+p-v)/(2*x*b)))/2),w=T/b,k=T/x;Math.abs(w-1)>a0&&this._append`L${e+w*f},${r+w*d}`,this._append`A${a},${a},0,0,${+(d*m>f*g)},${this._x1=e+k*u},${this._y1=r+k*h}`}}arc(e,r,i,n,a,s){if(e=+e,r=+r,i=+i,s=!!s,i<0)throw new Error(`negative radius: ${i}`);let l=i*Math.cos(n),u=i*Math.sin(n),h=e+l,f=r+u,d=1^s,p=s?n-a:a-n;this._x1===null?this._append`M${h},${f}`:(Math.abs(this._x1-h)>a0||Math.abs(this._y1-f)>a0)&&this._append`L${h},${f}`,i&&(p<0&&(p=p%w9+w9),p>lIe?this._append`A${i},${i},0,1,${d},${e-l},${r-u}A${i},${i},0,1,${d},${this._x1=h},${this._y1=f}`:p>a0&&this._append`A${i},${i},0,${+(p>=C9)},${d},${this._x1=e+i*Math.cos(a)},${this._y1=r+i*Math.sin(a)}`)}rect(e,r,i,n){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+r}h${i=+i}v${+n}h${-i}Z`}toString(){return this._}};o(PJ,"path");PJ.prototype=s0.prototype});var E9=P(()=>{"use strict";BJ()});var FJ=P(()=>{"use strict"});var $J=P(()=>{"use strict"});var zJ=P(()=>{"use strict"});var GJ=P(()=>{"use strict"});var VJ=P(()=>{"use strict"});var qJ=P(()=>{"use strict"});var WJ=P(()=>{"use strict"});function S9(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)}function o0(t,e){if((r=(t=e?t.toExponential(e-1):t.toExponential()).indexOf("e"))<0)return null;var r,i=t.slice(0,r);return[i.length>1?i[0]+i.slice(2):i,+t.slice(r+1)]}var _2=P(()=>{"use strict";o(S9,"default");o(o0,"formatDecimalParts")});function yc(t){return t=o0(Math.abs(t)),t?t[1]:NaN}var D2=P(()=>{"use strict";_2();o(yc,"default")});function A9(t,e){return function(r,i){for(var n=r.length,a=[],s=0,l=t[0],u=0;n>0&&l>0&&(u+l+1>i&&(l=Math.max(1,i-u)),a.push(r.substring(n-=l,n+l)),!((u+=l+1)>i));)l=t[s=(s+1)%t.length];return a.reverse().join(e)}}var UJ=P(()=>{"use strict";o(A9,"default")});function _9(t){return function(e){return e.replace(/[0-9]/g,function(r){return t[+r]})}}var HJ=P(()=>{"use strict";o(_9,"default")});function Hf(t){if(!(e=uIe.exec(t)))throw new Error("invalid format: "+t);var e;return new $w({fill:e[1],align:e[2],sign:e[3],symbol:e[4],zero:e[5],width:e[6],comma:e[7],precision:e[8]&&e[8].slice(1),trim:e[9],type:e[10]})}function $w(t){this.fill=t.fill===void 0?" ":t.fill+"",this.align=t.align===void 0?">":t.align+"",this.sign=t.sign===void 0?"-":t.sign+"",this.symbol=t.symbol===void 0?"":t.symbol+"",this.zero=!!t.zero,this.width=t.width===void 0?void 0:+t.width,this.comma=!!t.comma,this.precision=t.precision===void 0?void 0:+t.precision,this.trim=!!t.trim,this.type=t.type===void 0?"":t.type+""}var uIe,D9=P(()=>{"use strict";uIe=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;o(Hf,"formatSpecifier");Hf.prototype=$w.prototype;o($w,"FormatSpecifier");$w.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type}});function L9(t){e:for(var e=t.length,r=1,i=-1,n;r0&&(i=0);break}return i>0?t.slice(0,i)+t.slice(n+1):t}var YJ=P(()=>{"use strict";o(L9,"default")});function N9(t,e){var r=o0(t,e);if(!r)return t+"";var i=r[0],n=r[1],a=n-(R9=Math.max(-8,Math.min(8,Math.floor(n/3)))*3)+1,s=i.length;return a===s?i:a>s?i+new Array(a-s+1).join("0"):a>0?i.slice(0,a)+"."+i.slice(a):"0."+new Array(1-a).join("0")+o0(t,Math.max(0,e+a-1))[0]}var R9,I9=P(()=>{"use strict";_2();o(N9,"default")});function zw(t,e){var r=o0(t,e);if(!r)return t+"";var i=r[0],n=r[1];return n<0?"0."+new Array(-n).join("0")+i:i.length>n+1?i.slice(0,n+1)+"."+i.slice(n+1):i+new Array(n-i.length+2).join("0")}var jJ=P(()=>{"use strict";_2();o(zw,"default")});var M9,XJ=P(()=>{"use strict";_2();I9();jJ();M9={"%":o((t,e)=>(t*100).toFixed(e),"%"),b:o(t=>Math.round(t).toString(2),"b"),c:o(t=>t+"","c"),d:S9,e:o((t,e)=>t.toExponential(e),"e"),f:o((t,e)=>t.toFixed(e),"f"),g:o((t,e)=>t.toPrecision(e),"g"),o:o(t=>Math.round(t).toString(8),"o"),p:o((t,e)=>zw(t*100,e),"p"),r:zw,s:N9,X:o(t=>Math.round(t).toString(16).toUpperCase(),"X"),x:o(t=>Math.round(t).toString(16),"x")}});function Gw(t){return t}var KJ=P(()=>{"use strict";o(Gw,"default")});function O9(t){var e=t.grouping===void 0||t.thousands===void 0?Gw:A9(QJ.call(t.grouping,Number),t.thousands+""),r=t.currency===void 0?"":t.currency[0]+"",i=t.currency===void 0?"":t.currency[1]+"",n=t.decimal===void 0?".":t.decimal+"",a=t.numerals===void 0?Gw:_9(QJ.call(t.numerals,String)),s=t.percent===void 0?"%":t.percent+"",l=t.minus===void 0?"\u2212":t.minus+"",u=t.nan===void 0?"NaN":t.nan+"";function h(d){d=Hf(d);var p=d.fill,m=d.align,g=d.sign,y=d.symbol,v=d.zero,x=d.width,b=d.comma,T=d.precision,w=d.trim,k=d.type;k==="n"?(b=!0,k="g"):M9[k]||(T===void 0&&(T=12),w=!0,k="g"),(v||p==="0"&&m==="=")&&(v=!0,p="0",m="=");var C=y==="$"?r:y==="#"&&/[boxX]/.test(k)?"0"+k.toLowerCase():"",E=y==="$"?i:/[%p]/.test(k)?s:"",S=M9[k],L=/[defgprs%]/.test(k);T=T===void 0?6:/[gprs]/.test(k)?Math.max(1,Math.min(21,T)):Math.max(0,Math.min(20,T));function M(I){var A=C,_=E,D,N,R;if(k==="c")_=S(I)+_,I="";else{I=+I;var B=I<0||1/I<0;if(I=isNaN(I)?u:S(Math.abs(I),T),w&&(I=L9(I)),B&&+I==0&&g!=="+"&&(B=!1),A=(B?g==="("?g:l:g==="-"||g==="("?"":g)+A,_=(k==="s"?ZJ[8+R9/3]:"")+_+(B&&g==="("?")":""),L){for(D=-1,N=I.length;++DR||R>57){_=(R===46?n+I.slice(D+1):I.slice(D))+_,I=I.slice(0,D);break}}}b&&!v&&(I=e(I,1/0));var O=A.length+I.length+_.length,$=O>1)+A+I+_+$.slice(O);break;default:I=$+A+I+_;break}return a(I)}return o(M,"format"),M.toString=function(){return d+""},M}o(h,"newFormat");function f(d,p){var m=h((d=Hf(d),d.type="f",d)),g=Math.max(-8,Math.min(8,Math.floor(yc(p)/3)))*3,y=Math.pow(10,-g),v=ZJ[8+g/3];return function(x){return m(y*x)+v}}return o(f,"formatPrefix"),{format:h,formatPrefix:f}}var QJ,ZJ,JJ=P(()=>{"use strict";D2();UJ();HJ();D9();YJ();XJ();I9();KJ();QJ=Array.prototype.map,ZJ=["y","z","a","f","p","n","\xB5","m","","k","M","G","T","P","E","Z","Y"];o(O9,"default")});function P9(t){return Vw=O9(t),du=Vw.format,qw=Vw.formatPrefix,Vw}var Vw,du,qw,eee=P(()=>{"use strict";JJ();P9({thousands:",",grouping:[3],currency:["$",""]});o(P9,"defaultLocale")});function Ww(t){return Math.max(0,-yc(Math.abs(t)))}var tee=P(()=>{"use strict";D2();o(Ww,"default")});function Uw(t,e){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(yc(e)/3)))*3-yc(Math.abs(t)))}var ree=P(()=>{"use strict";D2();o(Uw,"default")});function Hw(t,e){return t=Math.abs(t),e=Math.abs(e)-t,Math.max(0,yc(e)-yc(t))+1}var iee=P(()=>{"use strict";D2();o(Hw,"default")});var B9=P(()=>{"use strict";eee();D9();tee();ree();iee()});var nee=P(()=>{"use strict"});function hIe(t){var e=0,r=t.children,i=r&&r.length;if(!i)e=1;else for(;--i>=0;)e+=r[i].value;t.value=e}function F9(){return this.eachAfter(hIe)}var aee=P(()=>{"use strict";o(hIe,"count");o(F9,"default")});function $9(t,e){let r=-1;for(let i of this)t.call(e,i,++r,this);return this}var see=P(()=>{"use strict";o($9,"default")});function z9(t,e){for(var r=this,i=[r],n,a,s=-1;r=i.pop();)if(t.call(e,r,++s,this),n=r.children)for(a=n.length-1;a>=0;--a)i.push(n[a]);return this}var oee=P(()=>{"use strict";o(z9,"default")});function G9(t,e){for(var r=this,i=[r],n=[],a,s,l,u=-1;r=i.pop();)if(n.push(r),a=r.children)for(s=0,l=a.length;s{"use strict";o(G9,"default")});function V9(t,e){let r=-1;for(let i of this)if(t.call(e,i,++r,this))return i}var cee=P(()=>{"use strict";o(V9,"default")});function q9(t){return this.eachAfter(function(e){for(var r=+t(e.data)||0,i=e.children,n=i&&i.length;--n>=0;)r+=i[n].value;e.value=r})}var uee=P(()=>{"use strict";o(q9,"default")});function W9(t){return this.eachBefore(function(e){e.children&&e.children.sort(t)})}var hee=P(()=>{"use strict";o(W9,"default")});function U9(t){for(var e=this,r=fIe(e,t),i=[e];e!==r;)e=e.parent,i.push(e);for(var n=i.length;t!==r;)i.splice(n,0,t),t=t.parent;return i}function fIe(t,e){if(t===e)return t;var r=t.ancestors(),i=e.ancestors(),n=null;for(t=r.pop(),e=i.pop();t===e;)n=t,t=r.pop(),e=i.pop();return n}var fee=P(()=>{"use strict";o(U9,"default");o(fIe,"leastCommonAncestor")});function H9(){for(var t=this,e=[t];t=t.parent;)e.push(t);return e}var dee=P(()=>{"use strict";o(H9,"default")});function Y9(){return Array.from(this)}var pee=P(()=>{"use strict";o(Y9,"default")});function j9(){var t=[];return this.eachBefore(function(e){e.children||t.push(e)}),t}var mee=P(()=>{"use strict";o(j9,"default")});function X9(){var t=this,e=[];return t.each(function(r){r!==t&&e.push({source:r.parent,target:r})}),e}var gee=P(()=>{"use strict";o(X9,"default")});function*K9(){var t=this,e,r=[t],i,n,a;do for(e=r.reverse(),r=[];t=e.pop();)if(yield t,i=t.children)for(n=0,a=i.length;n{"use strict";o(K9,"default")});function jg(t,e){t instanceof Map?(t=[void 0,t],e===void 0&&(e=mIe)):e===void 0&&(e=pIe);for(var r=new L2(t),i,n=[r],a,s,l,u;i=n.pop();)if((s=e(i.data))&&(u=(s=Array.from(s)).length))for(i.children=s,l=u-1;l>=0;--l)n.push(a=s[l]=new L2(s[l])),a.parent=i,a.depth=i.depth+1;return r.eachBefore(yIe)}function dIe(){return jg(this).eachBefore(gIe)}function pIe(t){return t.children}function mIe(t){return Array.isArray(t)?t[1]:null}function gIe(t){t.data.value!==void 0&&(t.value=t.data.value),t.data=t.data.data}function yIe(t){var e=0;do t.height=e;while((t=t.parent)&&t.height<++e)}function L2(t){this.data=t,this.depth=this.height=0,this.parent=null}var vee=P(()=>{"use strict";aee();see();oee();lee();cee();uee();hee();fee();dee();pee();mee();gee();yee();o(jg,"hierarchy");o(dIe,"node_copy");o(pIe,"objectChildren");o(mIe,"mapChildren");o(gIe,"copyData");o(yIe,"computeHeight");o(L2,"Node");L2.prototype=jg.prototype={constructor:L2,count:F9,each:$9,eachAfter:G9,eachBefore:z9,find:V9,sum:q9,sort:W9,path:U9,ancestors:H9,descendants:Y9,leaves:j9,links:X9,copy:dIe,[Symbol.iterator]:K9}});function xee(t){if(typeof t!="function")throw new Error;return t}var bee=P(()=>{"use strict";o(xee,"required")});function Xg(){return 0}function l0(t){return function(){return t}}var Tee=P(()=>{"use strict";o(Xg,"constantZero");o(l0,"default")});function Q9(t){t.x0=Math.round(t.x0),t.y0=Math.round(t.y0),t.x1=Math.round(t.x1),t.y1=Math.round(t.y1)}var kee=P(()=>{"use strict";o(Q9,"default")});function Z9(t,e,r,i,n){for(var a=t.children,s,l=-1,u=a.length,h=t.value&&(i-e)/t.value;++l{"use strict";o(Z9,"default")});function J9(t,e,r,i,n){for(var a=t.children,s,l=-1,u=a.length,h=t.value&&(n-r)/t.value;++l{"use strict";o(J9,"default")});function xIe(t,e,r,i,n,a){for(var s=[],l=e.children,u,h,f=0,d=0,p=l.length,m,g,y=e.value,v,x,b,T,w,k,C;fb&&(b=h),C=v*v*k,T=Math.max(b/C,C/x),T>w){v-=h;break}w=T}s.push(u={value:v,dice:m{"use strict";Cee();wee();vIe=(1+Math.sqrt(5))/2;o(xIe,"squarifyRatio");Eee=o((function t(e){function r(i,n,a,s,l){xIe(e,i,n,a,s,l)}return o(r,"squarify"),r.ratio=function(i){return t((i=+i)>1?i:1)},r}),"custom")(vIe)});function Yw(){var t=Eee,e=!1,r=1,i=1,n=[0],a=Xg,s=Xg,l=Xg,u=Xg,h=Xg;function f(p){return p.x0=p.y0=0,p.x1=r,p.y1=i,p.eachBefore(d),n=[0],e&&p.eachBefore(Q9),p}o(f,"treemap");function d(p){var m=n[p.depth],g=p.x0+m,y=p.y0+m,v=p.x1-m,x=p.y1-m;v{"use strict";kee();See();bee();Tee();o(Yw,"default")});var _ee=P(()=>{"use strict";vee();Aee()});var Dee=P(()=>{"use strict"});var Lee=P(()=>{"use strict"});function Yf(t,e){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(e).domain(t);break}return this}var R2=P(()=>{"use strict";o(Yf,"initRange")});function jo(){var t=new Mg,e=[],r=[],i=eN;function n(a){let s=t.get(a);if(s===void 0){if(i!==eN)return i;t.set(a,s=e.push(a)-1)}return r[s%r.length]}return o(n,"scale"),n.domain=function(a){if(!arguments.length)return e.slice();e=[],t=new Mg;for(let s of a)t.has(s)||t.set(s,e.push(s)-1);return n},n.range=function(a){return arguments.length?(r=Array.from(a),n):r.slice()},n.unknown=function(a){return arguments.length?(i=a,n):i},n.copy=function(){return jo(e,r).unknown(i)},Yf.apply(n,arguments),n}var eN,tN=P(()=>{"use strict";zf();R2();eN=Symbol("implicit");o(jo,"ordinal")});function Kg(){var t=jo().unknown(void 0),e=t.domain,r=t.range,i=0,n=1,a,s,l=!1,u=0,h=0,f=.5;delete t.unknown;function d(){var p=e().length,m=n{"use strict";zf();R2();tN();o(Kg,"band")});function rN(t){return function(){return t}}var Nee=P(()=>{"use strict";o(rN,"constants")});function iN(t){return+t}var Iee=P(()=>{"use strict";o(iN,"number")});function Qg(t){return t}function nN(t,e){return(e-=t=+t)?function(r){return(r-t)/e}:rN(isNaN(e)?NaN:.5)}function bIe(t,e){var r;return t>e&&(r=t,t=e,e=r),function(i){return Math.max(t,Math.min(e,i))}}function TIe(t,e,r){var i=t[0],n=t[1],a=e[0],s=e[1];return n2?kIe:TIe,u=h=null,d}o(f,"rescale");function d(p){return p==null||isNaN(p=+p)?a:(u||(u=l(t.map(i),e,r)))(i(s(p)))}return o(d,"scale"),d.invert=function(p){return s(n((h||(h=l(e,t.map(i),Ea)))(p)))},d.domain=function(p){return arguments.length?(t=Array.from(p,iN),f()):t.slice()},d.range=function(p){return arguments.length?(e=Array.from(p),f()):e.slice()},d.rangeRound=function(p){return e=Array.from(p),r=ww,f()},d.clamp=function(p){return arguments.length?(s=p?!0:Qg,f()):s!==Qg},d.interpolate=function(p){return arguments.length?(r=p,f()):r},d.unknown=function(p){return arguments.length?(a=p,d):a},function(p,m){return i=p,n=m,f()}}function N2(){return CIe()(Qg,Qg)}var Mee,aN=P(()=>{"use strict";zf();Ug();Nee();Iee();Mee=[0,1];o(Qg,"identity");o(nN,"normalize");o(bIe,"clamper");o(TIe,"bimap");o(kIe,"polymap");o(jw,"copy");o(CIe,"transformer");o(N2,"continuous")});function sN(t,e,r,i){var n=Og(t,e,r),a;switch(i=Hf(i??",f"),i.type){case"s":{var s=Math.max(Math.abs(t),Math.abs(e));return i.precision==null&&!isNaN(a=Uw(n,s))&&(i.precision=a),qw(i,s)}case"":case"e":case"g":case"p":case"r":{i.precision==null&&!isNaN(a=Hw(n,Math.max(Math.abs(t),Math.abs(e))))&&(i.precision=a-(i.type==="e"));break}case"f":case"%":{i.precision==null&&!isNaN(a=Ww(n))&&(i.precision=a-(i.type==="%")*2);break}}return du(i)}var Oee=P(()=>{"use strict";zf();B9();o(sN,"tickFormat")});function wIe(t){var e=t.domain;return t.ticks=function(r){var i=e();return ow(i[0],i[i.length-1],r??10)},t.tickFormat=function(r,i){var n=e();return sN(n[0],n[n.length-1],r??10,i)},t.nice=function(r){r==null&&(r=10);var i=e(),n=0,a=i.length-1,s=i[n],l=i[a],u,h,f=10;for(l0;){if(h=s2(s,l,r),h===u)return i[n]=s,i[a]=l,e(i);if(h>0)s=Math.floor(s/h)*h,l=Math.ceil(l/h)*h;else if(h<0)s=Math.ceil(s*h)/h,l=Math.floor(l*h)/h;else break;u=h}return t},t}function vc(){var t=N2();return t.copy=function(){return jw(t,vc())},Yf.apply(t,arguments),wIe(t)}var Pee=P(()=>{"use strict";zf();aN();R2();Oee();o(wIe,"linearish");o(vc,"linear")});function oN(t,e){t=t.slice();var r=0,i=t.length-1,n=t[r],a=t[i],s;return a{"use strict";o(oN,"nice")});function zi(t,e,r,i){function n(a){return t(a=arguments.length===0?new Date:new Date(+a)),a}return o(n,"interval"),n.floor=a=>(t(a=new Date(+a)),a),n.ceil=a=>(t(a=new Date(a-1)),e(a,1),t(a),a),n.round=a=>{let s=n(a),l=n.ceil(a);return a-s(e(a=new Date(+a),s==null?1:Math.floor(s)),a),n.range=(a,s,l)=>{let u=[];if(a=n.ceil(a),l=l==null?1:Math.floor(l),!(a0))return u;let h;do u.push(h=new Date(+a)),e(a,l),t(a);while(hzi(s=>{if(s>=s)for(;t(s),!a(s);)s.setTime(s-1)},(s,l)=>{if(s>=s)if(l<0)for(;++l<=0;)for(;e(s,-1),!a(s););else for(;--l>=0;)for(;e(s,1),!a(s););}),r&&(n.count=(a,s)=>(lN.setTime(+a),cN.setTime(+s),t(lN),t(cN),Math.floor(r(lN,cN))),n.every=a=>(a=Math.floor(a),!isFinite(a)||!(a>0)?null:a>1?n.filter(i?s=>i(s)%a===0:s=>n.count(0,s)%a===0):n)),n}var lN,cN,Lh=P(()=>{"use strict";lN=new Date,cN=new Date;o(zi,"timeInterval")});var pu,Fee,uN=P(()=>{"use strict";Lh();pu=zi(()=>{},(t,e)=>{t.setTime(+t+e)},(t,e)=>e-t);pu.every=t=>(t=Math.floor(t),!isFinite(t)||!(t>0)?null:t>1?zi(e=>{e.setTime(Math.floor(e/t)*t)},(e,r)=>{e.setTime(+e+r*t)},(e,r)=>(r-e)/t):pu);Fee=pu.range});var Xo,$ee,hN=P(()=>{"use strict";Lh();Xo=zi(t=>{t.setTime(t-t.getMilliseconds())},(t,e)=>{t.setTime(+t+e*1e3)},(t,e)=>(e-t)/1e3,t=>t.getUTCSeconds()),$ee=Xo.range});var Rh,EIe,Xw,SIe,fN=P(()=>{"use strict";Lh();Rh=zi(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*1e3)},(t,e)=>{t.setTime(+t+e*6e4)},(t,e)=>(e-t)/6e4,t=>t.getMinutes()),EIe=Rh.range,Xw=zi(t=>{t.setUTCSeconds(0,0)},(t,e)=>{t.setTime(+t+e*6e4)},(t,e)=>(e-t)/6e4,t=>t.getUTCMinutes()),SIe=Xw.range});var Nh,AIe,Kw,_Ie,dN=P(()=>{"use strict";Lh();Nh=zi(t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*1e3-t.getMinutes()*6e4)},(t,e)=>{t.setTime(+t+e*36e5)},(t,e)=>(e-t)/36e5,t=>t.getHours()),AIe=Nh.range,Kw=zi(t=>{t.setUTCMinutes(0,0,0)},(t,e)=>{t.setTime(+t+e*36e5)},(t,e)=>(e-t)/36e5,t=>t.getUTCHours()),_Ie=Kw.range});var Sl,DIe,M2,LIe,Qw,RIe,pN=P(()=>{"use strict";Lh();Sl=zi(t=>t.setHours(0,0,0,0),(t,e)=>t.setDate(t.getDate()+e),(t,e)=>(e-t-(e.getTimezoneOffset()-t.getTimezoneOffset())*6e4)/864e5,t=>t.getDate()-1),DIe=Sl.range,M2=zi(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/864e5,t=>t.getUTCDate()-1),LIe=M2.range,Qw=zi(t=>{t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCDate(t.getUTCDate()+e)},(t,e)=>(e-t)/864e5,t=>Math.floor(t/864e5)),RIe=Qw.range});function h0(t){return zi(e=>{e.setDate(e.getDate()-(e.getDay()+7-t)%7),e.setHours(0,0,0,0)},(e,r)=>{e.setDate(e.getDate()+r*7)},(e,r)=>(r-e-(r.getTimezoneOffset()-e.getTimezoneOffset())*6e4)/6048e5)}function f0(t){return zi(e=>{e.setUTCDate(e.getUTCDate()-(e.getUTCDay()+7-t)%7),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCDate(e.getUTCDate()+r*7)},(e,r)=>(r-e)/6048e5)}var xc,jf,Zw,Jw,gu,e3,t3,Gee,NIe,IIe,MIe,OIe,PIe,BIe,d0,Zg,Vee,qee,Xf,Wee,Uee,Hee,FIe,$Ie,zIe,GIe,VIe,qIe,mN=P(()=>{"use strict";Lh();o(h0,"timeWeekday");xc=h0(0),jf=h0(1),Zw=h0(2),Jw=h0(3),gu=h0(4),e3=h0(5),t3=h0(6),Gee=xc.range,NIe=jf.range,IIe=Zw.range,MIe=Jw.range,OIe=gu.range,PIe=e3.range,BIe=t3.range;o(f0,"utcWeekday");d0=f0(0),Zg=f0(1),Vee=f0(2),qee=f0(3),Xf=f0(4),Wee=f0(5),Uee=f0(6),Hee=d0.range,FIe=Zg.range,$Ie=Vee.range,zIe=qee.range,GIe=Xf.range,VIe=Wee.range,qIe=Uee.range});var Ih,WIe,r3,UIe,gN=P(()=>{"use strict";Lh();Ih=zi(t=>{t.setDate(1),t.setHours(0,0,0,0)},(t,e)=>{t.setMonth(t.getMonth()+e)},(t,e)=>e.getMonth()-t.getMonth()+(e.getFullYear()-t.getFullYear())*12,t=>t.getMonth()),WIe=Ih.range,r3=zi(t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCMonth(t.getUTCMonth()+e)},(t,e)=>e.getUTCMonth()-t.getUTCMonth()+(e.getUTCFullYear()-t.getUTCFullYear())*12,t=>t.getUTCMonth()),UIe=r3.range});var Ko,HIe,bc,YIe,yN=P(()=>{"use strict";Lh();Ko=zi(t=>{t.setMonth(0,1),t.setHours(0,0,0,0)},(t,e)=>{t.setFullYear(t.getFullYear()+e)},(t,e)=>e.getFullYear()-t.getFullYear(),t=>t.getFullYear());Ko.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:zi(e=>{e.setFullYear(Math.floor(e.getFullYear()/t)*t),e.setMonth(0,1),e.setHours(0,0,0,0)},(e,r)=>{e.setFullYear(e.getFullYear()+r*t)});HIe=Ko.range,bc=zi(t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,e)=>{t.setUTCFullYear(t.getUTCFullYear()+e)},(t,e)=>e.getUTCFullYear()-t.getUTCFullYear(),t=>t.getUTCFullYear());bc.every=t=>!isFinite(t=Math.floor(t))||!(t>0)?null:zi(e=>{e.setUTCFullYear(Math.floor(e.getUTCFullYear()/t)*t),e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,r)=>{e.setUTCFullYear(e.getUTCFullYear()+r*t)});YIe=bc.range});function jee(t,e,r,i,n,a){let s=[[Xo,1,1e3],[Xo,5,5*1e3],[Xo,15,15*1e3],[Xo,30,30*1e3],[a,1,6e4],[a,5,5*6e4],[a,15,15*6e4],[a,30,30*6e4],[n,1,36e5],[n,3,3*36e5],[n,6,6*36e5],[n,12,12*36e5],[i,1,864e5],[i,2,2*864e5],[r,1,6048e5],[e,1,2592e6],[e,3,3*2592e6],[t,1,31536e6]];function l(h,f,d){let p=fv).right(s,p);if(m===s.length)return t.every(Og(h/31536e6,f/31536e6,d));if(m===0)return pu.every(Math.max(Og(h,f,d),1));let[g,y]=s[p/s[m-1][2]{"use strict";zf();uN();hN();fN();dN();pN();mN();gN();yN();o(jee,"ticker");[XIe,KIe]=jee(bc,r3,d0,Qw,Kw,Xw),[vN,xN]=jee(Ko,Ih,xc,Sl,Nh,Rh)});var i3=P(()=>{"use strict";uN();hN();fN();dN();pN();mN();gN();yN();Xee()});function bN(t){if(0<=t.y&&t.y<100){var e=new Date(-1,t.m,t.d,t.H,t.M,t.S,t.L);return e.setFullYear(t.y),e}return new Date(t.y,t.m,t.d,t.H,t.M,t.S,t.L)}function TN(t){if(0<=t.y&&t.y<100){var e=new Date(Date.UTC(-1,t.m,t.d,t.H,t.M,t.S,t.L));return e.setUTCFullYear(t.y),e}return new Date(Date.UTC(t.y,t.m,t.d,t.H,t.M,t.S,t.L))}function O2(t,e,r){return{y:t,m:e,d:r,H:0,M:0,S:0,L:0}}function kN(t){var e=t.dateTime,r=t.date,i=t.time,n=t.periods,a=t.days,s=t.shortDays,l=t.months,u=t.shortMonths,h=P2(n),f=B2(n),d=P2(a),p=B2(a),m=P2(s),g=B2(s),y=P2(l),v=B2(l),x=P2(u),b=B2(u),T={a:B,A:O,b:$,B:z,c:null,d:tte,e:tte,f:xMe,g:DMe,G:RMe,H:gMe,I:yMe,j:vMe,L:ste,m:bMe,M:TMe,p:F,q:V,Q:nte,s:ate,S:kMe,u:CMe,U:wMe,V:EMe,w:SMe,W:AMe,x:null,X:null,y:_Me,Y:LMe,Z:NMe,"%":ite},w={a:H,A:X,b:W,B:Z,c:null,d:rte,e:rte,f:PMe,g:HMe,G:jMe,H:IMe,I:MMe,j:OMe,L:lte,m:BMe,M:FMe,p:Y,q:ae,Q:nte,s:ate,S:$Me,u:zMe,U:GMe,V:VMe,w:qMe,W:WMe,x:null,X:null,y:UMe,Y:YMe,Z:XMe,"%":ite},k={a:M,A:I,b:A,B:_,c:D,d:Jee,e:Jee,f:fMe,g:Zee,G:Qee,H:ete,I:ete,j:lMe,L:hMe,m:oMe,M:cMe,p:L,q:sMe,Q:pMe,s:mMe,S:uMe,u:tMe,U:rMe,V:iMe,w:eMe,W:nMe,x:N,X:R,y:Zee,Y:Qee,Z:aMe,"%":dMe};T.x=C(r,T),T.X=C(i,T),T.c=C(e,T),w.x=C(r,w),w.X=C(i,w),w.c=C(e,w);function C(J,ee){return function(re){var te=[],be=-1,de=0,Ee=J.length,Ne,we,Te;for(re instanceof Date||(re=new Date(+re));++be53)return null;"w"in te||(te.w=1),"Z"in te?(de=TN(O2(te.y,0,1)),Ee=de.getUTCDay(),de=Ee>4||Ee===0?Zg.ceil(de):Zg(de),de=M2.offset(de,(te.V-1)*7),te.y=de.getUTCFullYear(),te.m=de.getUTCMonth(),te.d=de.getUTCDate()+(te.w+6)%7):(de=bN(O2(te.y,0,1)),Ee=de.getDay(),de=Ee>4||Ee===0?jf.ceil(de):jf(de),de=Sl.offset(de,(te.V-1)*7),te.y=de.getFullYear(),te.m=de.getMonth(),te.d=de.getDate()+(te.w+6)%7)}else("W"in te||"U"in te)&&("w"in te||(te.w="u"in te?te.u%7:"W"in te?1:0),Ee="Z"in te?TN(O2(te.y,0,1)).getUTCDay():bN(O2(te.y,0,1)).getDay(),te.m=0,te.d="W"in te?(te.w+6)%7+te.W*7-(Ee+5)%7:te.w+te.U*7-(Ee+6)%7);return"Z"in te?(te.H+=te.Z/100|0,te.M+=te.Z%100,TN(te)):bN(te)}}o(E,"newParse");function S(J,ee,re,te){for(var be=0,de=ee.length,Ee=re.length,Ne,we;be=Ee)return-1;if(Ne=ee.charCodeAt(be++),Ne===37){if(Ne=ee.charAt(be++),we=k[Ne in Kee?ee.charAt(be++):Ne],!we||(te=we(J,re,te))<0)return-1}else if(Ne!=re.charCodeAt(te++))return-1}return te}o(S,"parseSpecifier");function L(J,ee,re){var te=h.exec(ee.slice(re));return te?(J.p=f.get(te[0].toLowerCase()),re+te[0].length):-1}o(L,"parsePeriod");function M(J,ee,re){var te=m.exec(ee.slice(re));return te?(J.w=g.get(te[0].toLowerCase()),re+te[0].length):-1}o(M,"parseShortWeekday");function I(J,ee,re){var te=d.exec(ee.slice(re));return te?(J.w=p.get(te[0].toLowerCase()),re+te[0].length):-1}o(I,"parseWeekday");function A(J,ee,re){var te=x.exec(ee.slice(re));return te?(J.m=b.get(te[0].toLowerCase()),re+te[0].length):-1}o(A,"parseShortMonth");function _(J,ee,re){var te=y.exec(ee.slice(re));return te?(J.m=v.get(te[0].toLowerCase()),re+te[0].length):-1}o(_,"parseMonth");function D(J,ee,re){return S(J,e,ee,re)}o(D,"parseLocaleDateTime");function N(J,ee,re){return S(J,r,ee,re)}o(N,"parseLocaleDate");function R(J,ee,re){return S(J,i,ee,re)}o(R,"parseLocaleTime");function B(J){return s[J.getDay()]}o(B,"formatShortWeekday");function O(J){return a[J.getDay()]}o(O,"formatWeekday");function $(J){return u[J.getMonth()]}o($,"formatShortMonth");function z(J){return l[J.getMonth()]}o(z,"formatMonth");function F(J){return n[+(J.getHours()>=12)]}o(F,"formatPeriod");function V(J){return 1+~~(J.getMonth()/3)}o(V,"formatQuarter");function H(J){return s[J.getUTCDay()]}o(H,"formatUTCShortWeekday");function X(J){return a[J.getUTCDay()]}o(X,"formatUTCWeekday");function W(J){return u[J.getUTCMonth()]}o(W,"formatUTCShortMonth");function Z(J){return l[J.getUTCMonth()]}o(Z,"formatUTCMonth");function Y(J){return n[+(J.getUTCHours()>=12)]}o(Y,"formatUTCPeriod");function ae(J){return 1+~~(J.getUTCMonth()/3)}return o(ae,"formatUTCQuarter"),{format:o(function(J){var ee=C(J+="",T);return ee.toString=function(){return J},ee},"format"),parse:o(function(J){var ee=E(J+="",!1);return ee.toString=function(){return J},ee},"parse"),utcFormat:o(function(J){var ee=C(J+="",w);return ee.toString=function(){return J},ee},"utcFormat"),utcParse:o(function(J){var ee=E(J+="",!0);return ee.toString=function(){return J},ee},"utcParse")}}function hi(t,e,r){var i=t<0?"-":"",n=(i?-t:t)+"",a=n.length;return i+(a[e.toLowerCase(),r]))}function eMe(t,e,r){var i=Sa.exec(e.slice(r,r+1));return i?(t.w=+i[0],r+i[0].length):-1}function tMe(t,e,r){var i=Sa.exec(e.slice(r,r+1));return i?(t.u=+i[0],r+i[0].length):-1}function rMe(t,e,r){var i=Sa.exec(e.slice(r,r+2));return i?(t.U=+i[0],r+i[0].length):-1}function iMe(t,e,r){var i=Sa.exec(e.slice(r,r+2));return i?(t.V=+i[0],r+i[0].length):-1}function nMe(t,e,r){var i=Sa.exec(e.slice(r,r+2));return i?(t.W=+i[0],r+i[0].length):-1}function Qee(t,e,r){var i=Sa.exec(e.slice(r,r+4));return i?(t.y=+i[0],r+i[0].length):-1}function Zee(t,e,r){var i=Sa.exec(e.slice(r,r+2));return i?(t.y=+i[0]+(+i[0]>68?1900:2e3),r+i[0].length):-1}function aMe(t,e,r){var i=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(e.slice(r,r+6));return i?(t.Z=i[1]?0:-(i[2]+(i[3]||"00")),r+i[0].length):-1}function sMe(t,e,r){var i=Sa.exec(e.slice(r,r+1));return i?(t.q=i[0]*3-3,r+i[0].length):-1}function oMe(t,e,r){var i=Sa.exec(e.slice(r,r+2));return i?(t.m=i[0]-1,r+i[0].length):-1}function Jee(t,e,r){var i=Sa.exec(e.slice(r,r+2));return i?(t.d=+i[0],r+i[0].length):-1}function lMe(t,e,r){var i=Sa.exec(e.slice(r,r+3));return i?(t.m=0,t.d=+i[0],r+i[0].length):-1}function ete(t,e,r){var i=Sa.exec(e.slice(r,r+2));return i?(t.H=+i[0],r+i[0].length):-1}function cMe(t,e,r){var i=Sa.exec(e.slice(r,r+2));return i?(t.M=+i[0],r+i[0].length):-1}function uMe(t,e,r){var i=Sa.exec(e.slice(r,r+2));return i?(t.S=+i[0],r+i[0].length):-1}function hMe(t,e,r){var i=Sa.exec(e.slice(r,r+3));return i?(t.L=+i[0],r+i[0].length):-1}function fMe(t,e,r){var i=Sa.exec(e.slice(r,r+6));return i?(t.L=Math.floor(i[0]/1e3),r+i[0].length):-1}function dMe(t,e,r){var i=QIe.exec(e.slice(r,r+1));return i?r+i[0].length:-1}function pMe(t,e,r){var i=Sa.exec(e.slice(r));return i?(t.Q=+i[0],r+i[0].length):-1}function mMe(t,e,r){var i=Sa.exec(e.slice(r));return i?(t.s=+i[0],r+i[0].length):-1}function tte(t,e){return hi(t.getDate(),e,2)}function gMe(t,e){return hi(t.getHours(),e,2)}function yMe(t,e){return hi(t.getHours()%12||12,e,2)}function vMe(t,e){return hi(1+Sl.count(Ko(t),t),e,3)}function ste(t,e){return hi(t.getMilliseconds(),e,3)}function xMe(t,e){return ste(t,e)+"000"}function bMe(t,e){return hi(t.getMonth()+1,e,2)}function TMe(t,e){return hi(t.getMinutes(),e,2)}function kMe(t,e){return hi(t.getSeconds(),e,2)}function CMe(t){var e=t.getDay();return e===0?7:e}function wMe(t,e){return hi(xc.count(Ko(t)-1,t),e,2)}function ote(t){var e=t.getDay();return e>=4||e===0?gu(t):gu.ceil(t)}function EMe(t,e){return t=ote(t),hi(gu.count(Ko(t),t)+(Ko(t).getDay()===4),e,2)}function SMe(t){return t.getDay()}function AMe(t,e){return hi(jf.count(Ko(t)-1,t),e,2)}function _Me(t,e){return hi(t.getFullYear()%100,e,2)}function DMe(t,e){return t=ote(t),hi(t.getFullYear()%100,e,2)}function LMe(t,e){return hi(t.getFullYear()%1e4,e,4)}function RMe(t,e){var r=t.getDay();return t=r>=4||r===0?gu(t):gu.ceil(t),hi(t.getFullYear()%1e4,e,4)}function NMe(t){var e=t.getTimezoneOffset();return(e>0?"-":(e*=-1,"+"))+hi(e/60|0,"0",2)+hi(e%60,"0",2)}function rte(t,e){return hi(t.getUTCDate(),e,2)}function IMe(t,e){return hi(t.getUTCHours(),e,2)}function MMe(t,e){return hi(t.getUTCHours()%12||12,e,2)}function OMe(t,e){return hi(1+M2.count(bc(t),t),e,3)}function lte(t,e){return hi(t.getUTCMilliseconds(),e,3)}function PMe(t,e){return lte(t,e)+"000"}function BMe(t,e){return hi(t.getUTCMonth()+1,e,2)}function FMe(t,e){return hi(t.getUTCMinutes(),e,2)}function $Me(t,e){return hi(t.getUTCSeconds(),e,2)}function zMe(t){var e=t.getUTCDay();return e===0?7:e}function GMe(t,e){return hi(d0.count(bc(t)-1,t),e,2)}function cte(t){var e=t.getUTCDay();return e>=4||e===0?Xf(t):Xf.ceil(t)}function VMe(t,e){return t=cte(t),hi(Xf.count(bc(t),t)+(bc(t).getUTCDay()===4),e,2)}function qMe(t){return t.getUTCDay()}function WMe(t,e){return hi(Zg.count(bc(t)-1,t),e,2)}function UMe(t,e){return hi(t.getUTCFullYear()%100,e,2)}function HMe(t,e){return t=cte(t),hi(t.getUTCFullYear()%100,e,2)}function YMe(t,e){return hi(t.getUTCFullYear()%1e4,e,4)}function jMe(t,e){var r=t.getUTCDay();return t=r>=4||r===0?Xf(t):Xf.ceil(t),hi(t.getUTCFullYear()%1e4,e,4)}function XMe(){return"+0000"}function ite(){return"%"}function nte(t){return+t}function ate(t){return Math.floor(+t/1e3)}var Kee,Sa,QIe,ZIe,ute=P(()=>{"use strict";i3();o(bN,"localDate");o(TN,"utcDate");o(O2,"newDate");o(kN,"formatLocale");Kee={"-":"",_:" ",0:"0"},Sa=/^\s*\d+/,QIe=/^%/,ZIe=/[\\^$*+?|[\]().{}]/g;o(hi,"pad");o(JIe,"requote");o(P2,"formatRe");o(B2,"formatLookup");o(eMe,"parseWeekdayNumberSunday");o(tMe,"parseWeekdayNumberMonday");o(rMe,"parseWeekNumberSunday");o(iMe,"parseWeekNumberISO");o(nMe,"parseWeekNumberMonday");o(Qee,"parseFullYear");o(Zee,"parseYear");o(aMe,"parseZone");o(sMe,"parseQuarter");o(oMe,"parseMonthNumber");o(Jee,"parseDayOfMonth");o(lMe,"parseDayOfYear");o(ete,"parseHour24");o(cMe,"parseMinutes");o(uMe,"parseSeconds");o(hMe,"parseMilliseconds");o(fMe,"parseMicroseconds");o(dMe,"parseLiteralPercent");o(pMe,"parseUnixTimestamp");o(mMe,"parseUnixTimestampSeconds");o(tte,"formatDayOfMonth");o(gMe,"formatHour24");o(yMe,"formatHour12");o(vMe,"formatDayOfYear");o(ste,"formatMilliseconds");o(xMe,"formatMicroseconds");o(bMe,"formatMonthNumber");o(TMe,"formatMinutes");o(kMe,"formatSeconds");o(CMe,"formatWeekdayNumberMonday");o(wMe,"formatWeekNumberSunday");o(ote,"dISO");o(EMe,"formatWeekNumberISO");o(SMe,"formatWeekdayNumberSunday");o(AMe,"formatWeekNumberMonday");o(_Me,"formatYear");o(DMe,"formatYearISO");o(LMe,"formatFullYear");o(RMe,"formatFullYearISO");o(NMe,"formatZone");o(rte,"formatUTCDayOfMonth");o(IMe,"formatUTCHour24");o(MMe,"formatUTCHour12");o(OMe,"formatUTCDayOfYear");o(lte,"formatUTCMilliseconds");o(PMe,"formatUTCMicroseconds");o(BMe,"formatUTCMonthNumber");o(FMe,"formatUTCMinutes");o($Me,"formatUTCSeconds");o(zMe,"formatUTCWeekdayNumberMonday");o(GMe,"formatUTCWeekNumberSunday");o(cte,"UTCdISO");o(VMe,"formatUTCWeekNumberISO");o(qMe,"formatUTCWeekdayNumberSunday");o(WMe,"formatUTCWeekNumberMonday");o(UMe,"formatUTCYear");o(HMe,"formatUTCYearISO");o(YMe,"formatUTCFullYear");o(jMe,"formatUTCFullYearISO");o(XMe,"formatUTCZone");o(ite,"formatLiteralPercent");o(nte,"formatUnixTimestamp");o(ate,"formatUnixTimestampSeconds")});function CN(t){return Jg=kN(t),p0=Jg.format,hte=Jg.parse,fte=Jg.utcFormat,dte=Jg.utcParse,Jg}var Jg,p0,hte,fte,dte,pte=P(()=>{"use strict";ute();CN({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});o(CN,"defaultLocale")});var wN=P(()=>{"use strict";pte()});function KMe(t){return new Date(t)}function QMe(t){return t instanceof Date?+t:+new Date(+t)}function mte(t,e,r,i,n,a,s,l,u,h){var f=N2(),d=f.invert,p=f.domain,m=h(".%L"),g=h(":%S"),y=h("%I:%M"),v=h("%I %p"),x=h("%a %d"),b=h("%b %d"),T=h("%B"),w=h("%Y");function k(C){return(u(C){"use strict";i3();wN();aN();R2();Bee();o(KMe,"date");o(QMe,"number");o(mte,"calendar");o(n3,"time")});var yte=P(()=>{"use strict";Ree();Pee();tN();gte()});function EN(t){for(var e=t.length/6|0,r=new Array(e),i=0;i{"use strict";o(EN,"default")});var SN,xte=P(()=>{"use strict";vte();SN=EN("4e79a7f28e2ce1575976b7b259a14fedc949af7aa1ff9da79c755fbab0ab")});var bte=P(()=>{"use strict";xte()});function on(t){return o(function(){return t},"constant")}var a3=P(()=>{"use strict";o(on,"default")});function kte(t){return t>1?0:t<-1?e1:Math.acos(t)}function _N(t){return t>=1?F2:t<=-1?-F2:Math.asin(t)}var AN,Ya,Kf,Tte,s3,Tc,m0,Aa,e1,F2,t1,o3=P(()=>{"use strict";AN=Math.abs,Ya=Math.atan2,Kf=Math.cos,Tte=Math.max,s3=Math.min,Tc=Math.sin,m0=Math.sqrt,Aa=1e-12,e1=Math.PI,F2=e1/2,t1=2*e1;o(kte,"acos");o(_N,"asin")});function l3(t){let e=3;return t.digits=function(r){if(!arguments.length)return e;if(r==null)e=null;else{let i=Math.floor(r);if(!(i>=0))throw new RangeError(`invalid digits: ${r}`);e=i}return t},()=>new s0(e)}var DN=P(()=>{"use strict";E9();o(l3,"withPath")});function ZMe(t){return t.innerRadius}function JMe(t){return t.outerRadius}function eOe(t){return t.startAngle}function tOe(t){return t.endAngle}function rOe(t){return t&&t.padAngle}function iOe(t,e,r,i,n,a,s,l){var u=r-t,h=i-e,f=s-n,d=l-a,p=d*u-f*h;if(!(p*pD*D+N*N&&(S=M,L=I),{cx:S,cy:L,x01:-f,y01:-d,x11:S*(n/k-1),y11:L*(n/k-1)}}function kc(){var t=ZMe,e=JMe,r=on(0),i=null,n=eOe,a=tOe,s=rOe,l=null,u=l3(h);function h(){var f,d,p=+t.apply(this,arguments),m=+e.apply(this,arguments),g=n.apply(this,arguments)-F2,y=a.apply(this,arguments)-F2,v=AN(y-g),x=y>g;if(l||(l=f=u()),mAa))l.moveTo(0,0);else if(v>t1-Aa)l.moveTo(m*Kf(g),m*Tc(g)),l.arc(0,0,m,g,y,!x),p>Aa&&(l.moveTo(p*Kf(y),p*Tc(y)),l.arc(0,0,p,y,g,x));else{var b=g,T=y,w=g,k=y,C=v,E=v,S=s.apply(this,arguments)/2,L=S>Aa&&(i?+i.apply(this,arguments):m0(p*p+m*m)),M=s3(AN(m-p)/2,+r.apply(this,arguments)),I=M,A=M,_,D;if(L>Aa){var N=_N(L/p*Tc(S)),R=_N(L/m*Tc(S));(C-=N*2)>Aa?(N*=x?1:-1,w+=N,k-=N):(C=0,w=k=(g+y)/2),(E-=R*2)>Aa?(R*=x?1:-1,b+=R,T-=R):(E=0,b=T=(g+y)/2)}var B=m*Kf(b),O=m*Tc(b),$=p*Kf(k),z=p*Tc(k);if(M>Aa){var F=m*Kf(T),V=m*Tc(T),H=p*Kf(w),X=p*Tc(w),W;if(vAa?A>Aa?(_=c3(H,X,B,O,m,A,x),D=c3(F,V,$,z,m,A,x),l.moveTo(_.cx+_.x01,_.cy+_.y01),AAa)||!(C>Aa)?l.lineTo($,z):I>Aa?(_=c3($,z,F,V,p,-I,x),D=c3(B,O,H,X,p,-I,x),l.lineTo(_.cx+_.x01,_.cy+_.y01),I{"use strict";a3();o3();DN();o(ZMe,"arcInnerRadius");o(JMe,"arcOuterRadius");o(eOe,"arcStartAngle");o(tOe,"arcEndAngle");o(rOe,"arcPadAngle");o(iOe,"intersect");o(c3,"cornerTangents");o(kc,"default")});function $2(t){return typeof t=="object"&&"length"in t?t:Array.from(t)}var wDt,LN=P(()=>{"use strict";wDt=Array.prototype.slice;o($2,"default")});function wte(t){this._context=t}function yu(t){return new wte(t)}var RN=P(()=>{"use strict";o(wte,"Linear");wte.prototype={areaStart:o(function(){this._line=0},"areaStart"),areaEnd:o(function(){this._line=NaN},"areaEnd"),lineStart:o(function(){this._point=0},"lineStart"),lineEnd:o(function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},"lineEnd"),point:o(function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:this._context.lineTo(t,e);break}},"point")};o(yu,"default")});function Ete(t){return t[0]}function Ste(t){return t[1]}var Ate=P(()=>{"use strict";o(Ete,"x");o(Ste,"y")});function Cc(t,e){var r=on(!0),i=null,n=yu,a=null,s=l3(l);t=typeof t=="function"?t:t===void 0?Ete:on(t),e=typeof e=="function"?e:e===void 0?Ste:on(e);function l(u){var h,f=(u=$2(u)).length,d,p=!1,m;for(i==null&&(a=n(m=s())),h=0;h<=f;++h)!(h{"use strict";LN();a3();RN();DN();Ate();o(Cc,"default")});function NN(t,e){return et?1:e>=t?0:NaN}var Dte=P(()=>{"use strict";o(NN,"default")});function IN(t){return t}var Lte=P(()=>{"use strict";o(IN,"default")});function u3(){var t=IN,e=NN,r=null,i=on(0),n=on(t1),a=on(0);function s(l){var u,h=(l=$2(l)).length,f,d,p=0,m=new Array(h),g=new Array(h),y=+i.apply(this,arguments),v=Math.min(t1,Math.max(-t1,n.apply(this,arguments)-y)),x,b=Math.min(Math.abs(v)/h,a.apply(this,arguments)),T=b*(v<0?-1:1),w;for(u=0;u0&&(p+=w);for(e!=null?m.sort(function(k,C){return e(g[k],g[C])}):r!=null&&m.sort(function(k,C){return r(l[k],l[C])}),u=0,d=p?(v-h*T)/p:0;u0?w*d:0)+T,g[f]={data:l[f],index:u,value:w,startAngle:y,endAngle:x,padAngle:b};return g}return o(s,"pie"),s.value=function(l){return arguments.length?(t=typeof l=="function"?l:on(+l),s):t},s.sortValues=function(l){return arguments.length?(e=l,r=null,s):e},s.sort=function(l){return arguments.length?(r=l,e=null,s):r},s.startAngle=function(l){return arguments.length?(i=typeof l=="function"?l:on(+l),s):i},s.endAngle=function(l){return arguments.length?(n=typeof l=="function"?l:on(+l),s):n},s.padAngle=function(l){return arguments.length?(a=typeof l=="function"?l:on(+l),s):a},s}var Rte=P(()=>{"use strict";LN();a3();Dte();Lte();o3();o(u3,"default")});function z2(t){return new h3(t,!0)}function G2(t){return new h3(t,!1)}var h3,Nte=P(()=>{"use strict";h3=class{static{o(this,"Bump")}constructor(e,r){this._context=e,this._x=r}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(e,r){switch(e=+e,r=+r,this._point){case 0:{this._point=1,this._line?this._context.lineTo(e,r):this._context.moveTo(e,r);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+e)/2,this._y0,this._x0,r,e,r):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+r)/2,e,this._y0,e,r);break}}this._x0=e,this._y0=r}};o(z2,"bumpX");o(G2,"bumpY")});function Qo(){}var V2=P(()=>{"use strict";o(Qo,"default")});function r1(t,e,r){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+e)/6,(t._y0+4*t._y1+r)/6)}function q2(t){this._context=t}function wc(t){return new q2(t)}var W2=P(()=>{"use strict";o(r1,"point");o(q2,"Basis");q2.prototype={areaStart:o(function(){this._line=0},"areaStart"),areaEnd:o(function(){this._line=NaN},"areaEnd"),lineStart:o(function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},"lineStart"),lineEnd:o(function(){switch(this._point){case 3:r1(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},"lineEnd"),point:o(function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:r1(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e},"point")};o(wc,"default")});function Ite(t){this._context=t}function f3(t){return new Ite(t)}var Mte=P(()=>{"use strict";V2();W2();o(Ite,"BasisClosed");Ite.prototype={areaStart:Qo,areaEnd:Qo,lineStart:o(function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},"lineStart"),lineEnd:o(function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},"lineEnd"),point:o(function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x2=t,this._y2=e;break;case 1:this._point=2,this._x3=t,this._y3=e;break;case 2:this._point=3,this._x4=t,this._y4=e,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+e)/6);break;default:r1(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e},"point")};o(f3,"default")});function Ote(t){this._context=t}function d3(t){return new Ote(t)}var Pte=P(()=>{"use strict";W2();o(Ote,"BasisOpen");Ote.prototype={areaStart:o(function(){this._line=0},"areaStart"),areaEnd:o(function(){this._line=NaN},"areaEnd"),lineStart:o(function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},"lineStart"),lineEnd:o(function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},"lineEnd"),point:o(function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var r=(this._x0+4*this._x1+t)/6,i=(this._y0+4*this._y1+e)/6;this._line?this._context.lineTo(r,i):this._context.moveTo(r,i);break;case 3:this._point=4;default:r1(this,t,e);break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e},"point")};o(d3,"default")});function Bte(t,e){this._basis=new q2(t),this._beta=e}var MN,Fte=P(()=>{"use strict";W2();o(Bte,"Bundle");Bte.prototype={lineStart:o(function(){this._x=[],this._y=[],this._basis.lineStart()},"lineStart"),lineEnd:o(function(){var t=this._x,e=this._y,r=t.length-1;if(r>0)for(var i=t[0],n=e[0],a=t[r]-i,s=e[r]-n,l=-1,u;++l<=r;)u=l/r,this._basis.point(this._beta*t[l]+(1-this._beta)*(i+u*a),this._beta*e[l]+(1-this._beta)*(n+u*s));this._x=this._y=null,this._basis.lineEnd()},"lineEnd"),point:o(function(t,e){this._x.push(+t),this._y.push(+e)},"point")};MN=o((function t(e){function r(i){return e===1?new q2(i):new Bte(i,e)}return o(r,"bundle"),r.beta=function(i){return t(+i)},r}),"custom")(.85)});function i1(t,e,r){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-e),t._y2+t._k*(t._y1-r),t._x2,t._y2)}function p3(t,e){this._context=t,this._k=(1-e)/6}var U2,H2=P(()=>{"use strict";o(i1,"point");o(p3,"Cardinal");p3.prototype={areaStart:o(function(){this._line=0},"areaStart"),areaEnd:o(function(){this._line=NaN},"areaEnd"),lineStart:o(function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},"lineStart"),lineEnd:o(function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:i1(this,this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},"lineEnd"),point:o(function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2,this._x1=t,this._y1=e;break;case 2:this._point=3;default:i1(this,t,e);break}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e},"point")};U2=o((function t(e){function r(i){return new p3(i,e)}return o(r,"cardinal"),r.tension=function(i){return t(+i)},r}),"custom")(0)});function m3(t,e){this._context=t,this._k=(1-e)/6}var ON,PN=P(()=>{"use strict";V2();H2();o(m3,"CardinalClosed");m3.prototype={areaStart:Qo,areaEnd:Qo,lineStart:o(function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},"lineStart"),lineEnd:o(function(){switch(this._point){case 1:{this._context.moveTo(this._x3,this._y3),this._context.closePath();break}case 2:{this._context.lineTo(this._x3,this._y3),this._context.closePath();break}case 3:{this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}}},"lineEnd"),point:o(function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:i1(this,t,e);break}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e},"point")};ON=o((function t(e){function r(i){return new m3(i,e)}return o(r,"cardinal"),r.tension=function(i){return t(+i)},r}),"custom")(0)});function g3(t,e){this._context=t,this._k=(1-e)/6}var BN,FN=P(()=>{"use strict";H2();o(g3,"CardinalOpen");g3.prototype={areaStart:o(function(){this._line=0},"areaStart"),areaEnd:o(function(){this._line=NaN},"areaEnd"),lineStart:o(function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},"lineStart"),lineEnd:o(function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},"lineEnd"),point:o(function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:i1(this,t,e);break}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e},"point")};BN=o((function t(e){function r(i){return new g3(i,e)}return o(r,"cardinal"),r.tension=function(i){return t(+i)},r}),"custom")(0)});function Y2(t,e,r){var i=t._x1,n=t._y1,a=t._x2,s=t._y2;if(t._l01_a>Aa){var l=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,u=3*t._l01_a*(t._l01_a+t._l12_a);i=(i*l-t._x0*t._l12_2a+t._x2*t._l01_2a)/u,n=(n*l-t._y0*t._l12_2a+t._y2*t._l01_2a)/u}if(t._l23_a>Aa){var h=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,f=3*t._l23_a*(t._l23_a+t._l12_a);a=(a*h+t._x1*t._l23_2a-e*t._l12_2a)/f,s=(s*h+t._y1*t._l23_2a-r*t._l12_2a)/f}t._context.bezierCurveTo(i,n,a,s,t._x2,t._y2)}function $te(t,e){this._context=t,this._alpha=e}var j2,y3=P(()=>{"use strict";o3();H2();o(Y2,"point");o($te,"CatmullRom");$te.prototype={areaStart:o(function(){this._line=0},"areaStart"),areaEnd:o(function(){this._line=NaN},"areaEnd"),lineStart:o(function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},"lineStart"),lineEnd:o(function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},"lineEnd"),point:o(function(t,e){if(t=+t,e=+e,this._point){var r=this._x2-t,i=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(r*r+i*i,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3;default:Y2(this,t,e);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e},"point")};j2=o((function t(e){function r(i){return e?new $te(i,e):new p3(i,0)}return o(r,"catmullRom"),r.alpha=function(i){return t(+i)},r}),"custom")(.5)});function zte(t,e){this._context=t,this._alpha=e}var $N,Gte=P(()=>{"use strict";PN();V2();y3();o(zte,"CatmullRomClosed");zte.prototype={areaStart:Qo,areaEnd:Qo,lineStart:o(function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},"lineStart"),lineEnd:o(function(){switch(this._point){case 1:{this._context.moveTo(this._x3,this._y3),this._context.closePath();break}case 2:{this._context.lineTo(this._x3,this._y3),this._context.closePath();break}case 3:{this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5);break}}},"lineEnd"),point:o(function(t,e){if(t=+t,e=+e,this._point){var r=this._x2-t,i=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(r*r+i*i,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=e;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=e);break;case 2:this._point=3,this._x5=t,this._y5=e;break;default:Y2(this,t,e);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e},"point")};$N=o((function t(e){function r(i){return e?new zte(i,e):new m3(i,0)}return o(r,"catmullRom"),r.alpha=function(i){return t(+i)},r}),"custom")(.5)});function Vte(t,e){this._context=t,this._alpha=e}var zN,qte=P(()=>{"use strict";FN();y3();o(Vte,"CatmullRomOpen");Vte.prototype={areaStart:o(function(){this._line=0},"areaStart"),areaEnd:o(function(){this._line=NaN},"areaEnd"),lineStart:o(function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},"lineStart"),lineEnd:o(function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},"lineEnd"),point:o(function(t,e){if(t=+t,e=+e,this._point){var r=this._x2-t,i=this._y2-e;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(r*r+i*i,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:Y2(this,t,e);break}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=e},"point")};zN=o((function t(e){function r(i){return e?new Vte(i,e):new g3(i,0)}return o(r,"catmullRom"),r.alpha=function(i){return t(+i)},r}),"custom")(.5)});function Wte(t){this._context=t}function v3(t){return new Wte(t)}var Ute=P(()=>{"use strict";V2();o(Wte,"LinearClosed");Wte.prototype={areaStart:Qo,areaEnd:Qo,lineStart:o(function(){this._point=0},"lineStart"),lineEnd:o(function(){this._point&&this._context.closePath()},"lineEnd"),point:o(function(t,e){t=+t,e=+e,this._point?this._context.lineTo(t,e):(this._point=1,this._context.moveTo(t,e))},"point")};o(v3,"default")});function Hte(t){return t<0?-1:1}function Yte(t,e,r){var i=t._x1-t._x0,n=e-t._x1,a=(t._y1-t._y0)/(i||n<0&&-0),s=(r-t._y1)/(n||i<0&&-0),l=(a*n+s*i)/(i+n);return(Hte(a)+Hte(s))*Math.min(Math.abs(a),Math.abs(s),.5*Math.abs(l))||0}function jte(t,e){var r=t._x1-t._x0;return r?(3*(t._y1-t._y0)/r-e)/2:e}function GN(t,e,r){var i=t._x0,n=t._y0,a=t._x1,s=t._y1,l=(a-i)/3;t._context.bezierCurveTo(i+l,n+l*e,a-l,s-l*r,a,s)}function x3(t){this._context=t}function Xte(t){this._context=new Kte(t)}function Kte(t){this._context=t}function X2(t){return new x3(t)}function K2(t){return new Xte(t)}var Qte=P(()=>{"use strict";o(Hte,"sign");o(Yte,"slope3");o(jte,"slope2");o(GN,"point");o(x3,"MonotoneX");x3.prototype={areaStart:o(function(){this._line=0},"areaStart"),areaEnd:o(function(){this._line=NaN},"areaEnd"),lineStart:o(function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},"lineStart"),lineEnd:o(function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:GN(this,this._t0,jte(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},"lineEnd"),point:o(function(t,e){var r=NaN;if(t=+t,e=+e,!(t===this._x1&&e===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;break;case 2:this._point=3,GN(this,jte(this,r=Yte(this,t,e)),r);break;default:GN(this,this._t0,r=Yte(this,t,e));break}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=e,this._t0=r}},"point")};o(Xte,"MonotoneY");(Xte.prototype=Object.create(x3.prototype)).point=function(t,e){x3.prototype.point.call(this,e,t)};o(Kte,"ReflectContext");Kte.prototype={moveTo:o(function(t,e){this._context.moveTo(e,t)},"moveTo"),closePath:o(function(){this._context.closePath()},"closePath"),lineTo:o(function(t,e){this._context.lineTo(e,t)},"lineTo"),bezierCurveTo:o(function(t,e,r,i,n,a){this._context.bezierCurveTo(e,t,i,r,a,n)},"bezierCurveTo")};o(X2,"monotoneX");o(K2,"monotoneY")});function Jte(t){this._context=t}function Zte(t){var e,r=t.length-1,i,n=new Array(r),a=new Array(r),s=new Array(r);for(n[0]=0,a[0]=2,s[0]=t[0]+2*t[1],e=1;e=0;--e)n[e]=(s[e]-n[e+1])/a[e];for(a[r-1]=(t[r]+n[r-1])/2,e=0;e{"use strict";o(Jte,"Natural");Jte.prototype={areaStart:o(function(){this._line=0},"areaStart"),areaEnd:o(function(){this._line=NaN},"areaEnd"),lineStart:o(function(){this._x=[],this._y=[]},"lineStart"),lineEnd:o(function(){var t=this._x,e=this._y,r=t.length;if(r)if(this._line?this._context.lineTo(t[0],e[0]):this._context.moveTo(t[0],e[0]),r===2)this._context.lineTo(t[1],e[1]);else for(var i=Zte(t),n=Zte(e),a=0,s=1;s{"use strict";o(b3,"Step");b3.prototype={areaStart:o(function(){this._line=0},"areaStart"),areaEnd:o(function(){this._line=NaN},"areaEnd"),lineStart:o(function(){this._x=this._y=NaN,this._point=0},"lineStart"),lineEnd:o(function(){0=0&&(this._t=1-this._t,this._line=1-this._line)},"lineEnd"),point:o(function(t,e){switch(t=+t,e=+e,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,e):this._context.moveTo(t,e);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,e),this._context.lineTo(t,e);else{var r=this._x*(1-this._t)+t*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,e)}break}}this._x=t,this._y=e},"point")};o(a1,"default");o(Q2,"stepBefore");o(Z2,"stepAfter")});var rre=P(()=>{"use strict";Cte();_te();Rte();Mte();Pte();W2();Nte();Fte();PN();FN();H2();Gte();qte();y3();Ute();RN();Qte();ere();tre()});var ire=P(()=>{"use strict"});var nre=P(()=>{"use strict"});function Qf(t,e,r){this.k=t,this.x=e,this.y=r}function qN(t){for(;!t.__zoom;)if(!(t=t.parentNode))return VN;return t.__zoom}var VN,WN=P(()=>{"use strict";o(Qf,"Transform");Qf.prototype={constructor:Qf,scale:o(function(t){return t===1?this:new Qf(this.k*t,this.x,this.y)},"scale"),translate:o(function(t,e){return t===0&e===0?this:new Qf(this.k,this.x+this.k*t,this.y+this.k*e)},"translate"),apply:o(function(t){return[t[0]*this.k+this.x,t[1]*this.k+this.y]},"apply"),applyX:o(function(t){return t*this.k+this.x},"applyX"),applyY:o(function(t){return t*this.k+this.y},"applyY"),invert:o(function(t){return[(t[0]-this.x)/this.k,(t[1]-this.y)/this.k]},"invert"),invertX:o(function(t){return(t-this.x)/this.k},"invertX"),invertY:o(function(t){return(t-this.y)/this.k},"invertY"),rescaleX:o(function(t){return t.copy().domain(t.range().map(this.invertX,this).map(t.invert,t))},"rescaleX"),rescaleY:o(function(t){return t.copy().domain(t.range().map(this.invertY,this).map(t.invert,t))},"rescaleY"),toString:o(function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"},"toString")};VN=new Qf(1,0,0);qN.prototype=Qf.prototype;o(qN,"transform")});var are=P(()=>{"use strict"});var sre=P(()=>{"use strict";Fw();ire();nre();WN();are()});var ore=P(()=>{"use strict";sre();WN()});var Pr=P(()=>{"use strict";zf();mQ();MJ();FJ();Vg();$J();zJ();NL();sZ();GJ();b9();VJ();WJ();B9();nee();_ee();Ug();E9();Dee();qJ();Lee();yte();bte();pc();rre();i3();wN();Nw();Fw();ore()});var lre=ar(_a=>{"use strict";Object.defineProperty(_a,"__esModule",{value:!0});_a.BLANK_URL=_a.relativeFirstCharacters=_a.whitespaceEscapeCharsRegex=_a.urlSchemeRegex=_a.ctrlCharactersRegex=_a.htmlCtrlEntityRegex=_a.htmlEntitiesRegex=_a.invalidProtocolRegex=void 0;_a.invalidProtocolRegex=/^([^\w]*)(javascript|data|vbscript)/im;_a.htmlEntitiesRegex=/&#(\w+)(^\w|;)?/g;_a.htmlCtrlEntityRegex=/&(newline|tab);/gi;_a.ctrlCharactersRegex=/[\u0000-\u001F\u007F-\u009F\u2000-\u200D\uFEFF]/gim;_a.urlSchemeRegex=/^.+(:|:)/gim;_a.whitespaceEscapeCharsRegex=/(\\|%5[cC])((%(6[eE]|72|74))|[nrt])/g;_a.relativeFirstCharacters=[".","/"];_a.BLANK_URL="about:blank"});var s1=ar(T3=>{"use strict";Object.defineProperty(T3,"__esModule",{value:!0});T3.sanitizeUrl=void 0;var us=lre();function nOe(t){return us.relativeFirstCharacters.indexOf(t[0])>-1}o(nOe,"isRelativeUrlWithoutProtocol");function aOe(t){var e=t.replace(us.ctrlCharactersRegex,"");return e.replace(us.htmlEntitiesRegex,function(r,i){return String.fromCharCode(i)})}o(aOe,"decodeHtmlCharacters");function sOe(t){return URL.canParse(t)}o(sOe,"isValidUrl");function cre(t){try{return decodeURIComponent(t)}catch{return t}}o(cre,"decodeURI");function oOe(t){if(!t)return us.BLANK_URL;var e,r=cre(t.trim());do r=aOe(r).replace(us.htmlCtrlEntityRegex,"").replace(us.ctrlCharactersRegex,"").replace(us.whitespaceEscapeCharsRegex,"").trim(),r=cre(r),e=r.match(us.ctrlCharactersRegex)||r.match(us.htmlEntitiesRegex)||r.match(us.htmlCtrlEntityRegex)||r.match(us.whitespaceEscapeCharsRegex);while(e&&e.length>0);var i=r;if(!i)return us.BLANK_URL;if(nOe(i))return i;var n=i.trimStart(),a=n.match(us.urlSchemeRegex);if(!a)return i;var s=a[0].toLowerCase().trim();if(us.invalidProtocolRegex.test(s))return us.BLANK_URL;var l=n.replace(/\\/g,"/");if(s==="mailto:"||s.includes("://"))return l;if(s==="http:"||s==="https:"){if(!sOe(l))return us.BLANK_URL;var u=new URL(l);return u.protocol=u.protocol.toLowerCase(),u.hostname=u.hostname.toLowerCase(),u.toString()}return l}o(oOe,"sanitizeUrl");T3.sanitizeUrl=oOe});var UN,g0,k3,ure,C3,w3,ja,J2,E3,y0=P(()=>{"use strict";UN=Wa(s1(),1);Pr();Vr();g0=o((t,e)=>{let r=t.append("rect");if(r.attr("x",e.x),r.attr("y",e.y),r.attr("fill",e.fill),r.attr("stroke",e.stroke),r.attr("width",e.width),r.attr("height",e.height),e.name&&r.attr("name",e.name),e.rx&&r.attr("rx",e.rx),e.ry&&r.attr("ry",e.ry),e.attrs!==void 0)for(let i in e.attrs)r.attr(i,e.attrs[i]);return e.class&&r.attr("class",e.class),r},"drawRect"),k3=o((t,e)=>{let r={x:e.startx,y:e.starty,width:e.stopx-e.startx,height:e.stopy-e.starty,fill:e.fill,stroke:e.stroke,class:"rect"};g0(t,r).lower()},"drawBackgroundRect"),ure=o((t,e)=>{let r=e.text.replace(Hp," "),i=t.append("text");i.attr("x",e.x),i.attr("y",e.y),i.attr("class","legend"),i.style("text-anchor",e.anchor),e.class&&i.attr("class",e.class);let n=i.append("tspan");return n.attr("x",e.x+e.textMargin*2),n.text(r),i},"drawText"),C3=o((t,e,r,i)=>{let n=t.append("image");n.attr("x",e),n.attr("y",r);let a=(0,UN.sanitizeUrl)(i);n.attr("xlink:href",a)},"drawImage"),w3=o((t,e,r,i)=>{let n=t.append("use");n.attr("x",e),n.attr("y",r);let a=(0,UN.sanitizeUrl)(i);n.attr("xlink:href",`#${a}`)},"drawEmbeddedImage"),ja=o(()=>({x:0,y:0,width:100,height:100,fill:"#EDF2AE",stroke:"#666",anchor:"start",rx:0,ry:0}),"getNoteRect"),J2=o(()=>({x:0,y:0,width:100,height:100,"text-anchor":"start",style:"#666",textMargin:0,rx:0,ry:0,tspan:!0}),"getTextObj"),E3=o(()=>{let t=Ze(".mermaidTooltip");return t.empty()&&(t=Ze("body").append("div").attr("class","mermaidTooltip").style("opacity",0).style("position","absolute").style("text-align","center").style("max-width","200px").style("padding","2px").style("font-size","12px").style("background","#ffffde").style("border","1px solid #333").style("border-radius","2px").style("pointer-events","none").style("z-index","100")),t},"createTooltip")});var hre,HN,fre,lOe,cOe,uOe,hOe,fOe,dOe,pOe,mOe,gOe,yOe,vOe,Mh,Ec,dre=P(()=>{"use strict";Vr();y0();hre=Wa(s1(),1),HN=o(function(t,e){return g0(t,e)},"drawRect"),fre=o(function(t,e,r,i,n,a){let s=t.append("image");s.attr("width",e),s.attr("height",r),s.attr("x",i),s.attr("y",n);let l=a.startsWith("data:image/png;base64")?a:(0,hre.sanitizeUrl)(a);s.attr("xlink:href",l)},"drawImage"),lOe=o((t,e,r,i)=>{let n=t.append("g"),a=0;for(let s of e){let l=s.textColor?s.textColor:"#444444",u=s.lineColor?s.lineColor:"#444444",h=s.offsetX?parseInt(s.offsetX):0,f=s.offsetY?parseInt(s.offsetY):0,d="";if(a===0){let m=n.append("line");m.attr("x1",s.startPoint.x),m.attr("y1",s.startPoint.y),m.attr("x2",s.endPoint.x),m.attr("y2",s.endPoint.y),m.attr("stroke-width","1"),m.attr("stroke",u),m.style("fill","none"),s.type!=="rel_b"&&m.attr("marker-end","url("+d+"#"+i+"-arrowhead)"),(s.type==="birel"||s.type==="rel_b")&&m.attr("marker-start","url("+d+"#"+i+"-arrowend)"),a=-1}else{let m=n.append("path");m.attr("fill","none").attr("stroke-width","1").attr("stroke",u).attr("d","Mstartx,starty Qcontrolx,controly stopx,stopy ".replaceAll("startx",s.startPoint.x).replaceAll("starty",s.startPoint.y).replaceAll("controlx",s.startPoint.x+(s.endPoint.x-s.startPoint.x)/2-(s.endPoint.x-s.startPoint.x)/4).replaceAll("controly",s.startPoint.y+(s.endPoint.y-s.startPoint.y)/2).replaceAll("stopx",s.endPoint.x).replaceAll("stopy",s.endPoint.y)),s.type!=="rel_b"&&m.attr("marker-end","url("+d+"#"+i+"-arrowhead)"),(s.type==="birel"||s.type==="rel_b")&&m.attr("marker-start","url("+d+"#"+i+"-arrowend)")}let p=r.messageFont();Mh(r)(s.label.text,n,Math.min(s.startPoint.x,s.endPoint.x)+Math.abs(s.endPoint.x-s.startPoint.x)/2+h,Math.min(s.startPoint.y,s.endPoint.y)+Math.abs(s.endPoint.y-s.startPoint.y)/2+f,s.label.width,s.label.height,{fill:l},p),s.techn&&s.techn.text!==""&&(p=r.messageFont(),Mh(r)("["+s.techn.text+"]",n,Math.min(s.startPoint.x,s.endPoint.x)+Math.abs(s.endPoint.x-s.startPoint.x)/2+h,Math.min(s.startPoint.y,s.endPoint.y)+Math.abs(s.endPoint.y-s.startPoint.y)/2+r.messageFontSize+5+f,Math.max(s.label.width,s.techn.width),s.techn.height,{fill:l,"font-style":"italic"},p))}},"drawRels"),cOe=o(function(t,e,r){let i=t.append("g"),n=e.bgColor?e.bgColor:"none",a=e.borderColor?e.borderColor:"#444444",s=e.fontColor?e.fontColor:"black",l={"stroke-width":1,"stroke-dasharray":"7.0,7.0"};e.nodeType&&(l={"stroke-width":1});let u={x:e.x,y:e.y,fill:n,stroke:a,width:e.width,height:e.height,rx:2.5,ry:2.5,attrs:l};HN(i,u);let h=r.boundaryFont();h.fontWeight="bold",h.fontSize=h.fontSize+2,h.fontColor=s,Mh(r)(e.label.text,i,e.x,e.y+e.label.Y,e.width,e.height,{fill:"#444444"},h),e.type&&e.type.text!==""&&(h=r.boundaryFont(),h.fontColor=s,Mh(r)(e.type.text,i,e.x,e.y+e.type.Y,e.width,e.height,{fill:"#444444"},h)),e.descr&&e.descr.text!==""&&(h=r.boundaryFont(),h.fontSize=h.fontSize-2,h.fontColor=s,Mh(r)(e.descr.text,i,e.x,e.y+e.descr.Y,e.width,e.height,{fill:"#444444"},h))},"drawBoundary"),uOe=o(function(t,e,r){let i=e.bgColor?e.bgColor:r[e.typeC4Shape.text+"_bg_color"],n=e.borderColor?e.borderColor:r[e.typeC4Shape.text+"_border_color"],a=e.fontColor?e.fontColor:"#FFFFFF",s="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAACD0lEQVR4Xu2YoU4EMRCGT+4j8Ai8AhaH4QHgAUjQuFMECUgMIUgwJAgMhgQsAYUiJCiQIBBY+EITsjfTdme6V24v4c8vyGbb+ZjOtN0bNcvjQXmkH83WvYBWto6PLm6v7p7uH1/w2fXD+PBycX1Pv2l3IdDm/vn7x+dXQiAubRzoURa7gRZWd0iGRIiJbOnhnfYBQZNJjNbuyY2eJG8fkDE3bbG4ep6MHUAsgYxmE3nVs6VsBWJSGccsOlFPmLIViMzLOB7pCVO2AtHJMohH7Fh6zqitQK7m0rJvAVYgGcEpe//PLdDz65sM4pF9N7ICcXDKIB5Nv6j7tD0NoSdM2QrU9Gg0ewE1LqBhHR3BBdvj2vapnidjHxD/q6vd7Pvhr31AwcY8eXMTXAKECZZJFXuEq27aLgQK5uLMohCenGGuGewOxSjBvYBqeG6B+Nqiblggdjnc+ZXDy+FNFpFzw76O3UBAROuXh6FoiAcf5g9eTvUgzy0nWg6I8cXHRUpg5bOVBCo+KDpFajOf23GgPme7RSQ+lacIENUgJ6gg1k6HjgOlqnLqip4tEuhv0hNEMXUD0clyXE3p6pZA0S2nnvTlXwLJEZWlb7cTQH1+USgTN4VhAenm/wea1OCAOmqo6fE1WCb9WSKBah+rbUWPWAmE2Rvk0ApiB45eOyNAzU8xcTvj8KvkKEoOaIYeHNA3ZuygAvFMUO0AAAAASUVORK5CYII=";switch(e.typeC4Shape.text){case"person":s="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAACD0lEQVR4Xu2YoU4EMRCGT+4j8Ai8AhaH4QHgAUjQuFMECUgMIUgwJAgMhgQsAYUiJCiQIBBY+EITsjfTdme6V24v4c8vyGbb+ZjOtN0bNcvjQXmkH83WvYBWto6PLm6v7p7uH1/w2fXD+PBycX1Pv2l3IdDm/vn7x+dXQiAubRzoURa7gRZWd0iGRIiJbOnhnfYBQZNJjNbuyY2eJG8fkDE3bbG4ep6MHUAsgYxmE3nVs6VsBWJSGccsOlFPmLIViMzLOB7pCVO2AtHJMohH7Fh6zqitQK7m0rJvAVYgGcEpe//PLdDz65sM4pF9N7ICcXDKIB5Nv6j7tD0NoSdM2QrU9Gg0ewE1LqBhHR3BBdvj2vapnidjHxD/q6vd7Pvhr31AwcY8eXMTXAKECZZJFXuEq27aLgQK5uLMohCenGGuGewOxSjBvYBqeG6B+Nqiblggdjnc+ZXDy+FNFpFzw76O3UBAROuXh6FoiAcf5g9eTvUgzy0nWg6I8cXHRUpg5bOVBCo+KDpFajOf23GgPme7RSQ+lacIENUgJ6gg1k6HjgOlqnLqip4tEuhv0hNEMXUD0clyXE3p6pZA0S2nnvTlXwLJEZWlb7cTQH1+USgTN4VhAenm/wea1OCAOmqo6fE1WCb9WSKBah+rbUWPWAmE2Rvk0ApiB45eOyNAzU8xcTvj8KvkKEoOaIYeHNA3ZuygAvFMUO0AAAAASUVORK5CYII=";break;case"external_person":s="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAIAAADYYG7QAAAB6ElEQVR4Xu2YLY+EMBCG9+dWr0aj0Wg0Go1Go0+j8Xdv2uTCvv1gpt0ebHKPuhDaeW4605Z9mJvx4AdXUyTUdd08z+u6flmWZRnHsWkafk9DptAwDPu+f0eAYtu2PEaGWuj5fCIZrBAC2eLBAnRCsEkkxmeaJp7iDJ2QMDdHsLg8SxKFEJaAo8lAXnmuOFIhTMpxxKATebo4UiFknuNo4OniSIXQyRxEA3YsnjGCVEjVXD7yLUAqxBGUyPv/Y4W2beMgGuS7kVQIBycH0fD+oi5pezQETxdHKmQKGk1eQEYldK+jw5GxPfZ9z7Mk0Qnhf1W1m3w//EUn5BDmSZsbR44QQLBEqrBHqOrmSKaQAxdnLArCrxZcM7A7ZKs4ioRq8LFC+NpC3WCBJsvpVw5edm9iEXFuyNfxXAgSwfrFQ1c0iNda8AdejvUgnktOtJQQxmcfFzGglc5WVCj7oDgFqU18boeFSs52CUh8LE8BIVQDT1ABrB0HtgSEYlX5doJnCwv9TXocKCaKbnwhdDKPq4lf3SwU3HLq4V/+WYhHVMa/3b4IlfyikAduCkcBc7mQ3/z/Qq/cTuikhkzB12Ae/mcJC9U+Vo8Ej1gWAtgbeGgFsAMHr50BIWOLCbezvhpBFUdY6EJuJ/QDW0XoMX60zZ0AAAAASUVORK5CYII=";break}let l=t.append("g");l.attr("class","person-man");let u=ja();switch(e.typeC4Shape.text){case"person":case"external_person":case"system":case"external_system":case"container":case"external_container":case"component":case"external_component":u.x=e.x,u.y=e.y,u.fill=i,u.width=e.width,u.height=e.height,u.stroke=n,u.rx=2.5,u.ry=2.5,u.attrs={"stroke-width":.5},HN(l,u);break;case"system_db":case"external_system_db":case"container_db":case"external_container_db":case"component_db":case"external_component_db":l.append("path").attr("fill",i).attr("stroke-width","0.5").attr("stroke",n).attr("d","Mstartx,startyc0,-10 half,-10 half,-10c0,0 half,0 half,10l0,heightc0,10 -half,10 -half,10c0,0 -half,0 -half,-10l0,-height".replaceAll("startx",e.x).replaceAll("starty",e.y).replaceAll("half",e.width/2).replaceAll("height",e.height)),l.append("path").attr("fill","none").attr("stroke-width","0.5").attr("stroke",n).attr("d","Mstartx,startyc0,10 half,10 half,10c0,0 half,0 half,-10".replaceAll("startx",e.x).replaceAll("starty",e.y).replaceAll("half",e.width/2));break;case"system_queue":case"external_system_queue":case"container_queue":case"external_container_queue":case"component_queue":case"external_component_queue":l.append("path").attr("fill",i).attr("stroke-width","0.5").attr("stroke",n).attr("d","Mstartx,startylwidth,0c5,0 5,half 5,halfc0,0 0,half -5,halfl-width,0c-5,0 -5,-half -5,-halfc0,0 0,-half 5,-half".replaceAll("startx",e.x).replaceAll("starty",e.y).replaceAll("width",e.width).replaceAll("half",e.height/2)),l.append("path").attr("fill","none").attr("stroke-width","0.5").attr("stroke",n).attr("d","Mstartx,startyc-5,0 -5,half -5,halfc0,half 5,half 5,half".replaceAll("startx",e.x+e.width).replaceAll("starty",e.y).replaceAll("half",e.height/2));break}let h=vOe(r,e.typeC4Shape.text);switch(l.append("text").attr("fill",a).attr("font-family",h.fontFamily).attr("font-size",h.fontSize-2).attr("font-style","italic").attr("lengthAdjust","spacing").attr("textLength",e.typeC4Shape.width).attr("x",e.x+e.width/2-e.typeC4Shape.width/2).attr("y",e.y+e.typeC4Shape.Y).text("<<"+e.typeC4Shape.text+">>"),e.typeC4Shape.text){case"person":case"external_person":fre(l,48,48,e.x+e.width/2-24,e.y+e.image.Y,s);break}let f=r[e.typeC4Shape.text+"Font"]();return f.fontWeight="bold",f.fontSize=f.fontSize+2,f.fontColor=a,Mh(r)(e.label.text,l,e.x,e.y+e.label.Y,e.width,e.height,{fill:a},f),f=r[e.typeC4Shape.text+"Font"](),f.fontColor=a,e.techn&&e.techn?.text!==""?Mh(r)(e.techn.text,l,e.x,e.y+e.techn.Y,e.width,e.height,{fill:a,"font-style":"italic"},f):e.type&&e.type.text!==""&&Mh(r)(e.type.text,l,e.x,e.y+e.type.Y,e.width,e.height,{fill:a,"font-style":"italic"},f),e.descr&&e.descr.text!==""&&(f=r.personFont(),f.fontColor=a,Mh(r)(e.descr.text,l,e.x,e.y+e.descr.Y,e.width,e.height,{fill:a},f)),e.height},"drawC4Shape"),hOe=o(function(t,e){t.append("defs").append("symbol").attr("id",e+"-database").attr("fill-rule","evenodd").attr("clip-rule","evenodd").append("path").attr("transform","scale(.5)").attr("d","M12.258.001l.256.004.255.005.253.008.251.01.249.012.247.015.246.016.242.019.241.02.239.023.236.024.233.027.231.028.229.031.225.032.223.034.22.036.217.038.214.04.211.041.208.043.205.045.201.046.198.048.194.05.191.051.187.053.183.054.18.056.175.057.172.059.168.06.163.061.16.063.155.064.15.066.074.033.073.033.071.034.07.034.069.035.068.035.067.035.066.035.064.036.064.036.062.036.06.036.06.037.058.037.058.037.055.038.055.038.053.038.052.038.051.039.05.039.048.039.047.039.045.04.044.04.043.04.041.04.04.041.039.041.037.041.036.041.034.041.033.042.032.042.03.042.029.042.027.042.026.043.024.043.023.043.021.043.02.043.018.044.017.043.015.044.013.044.012.044.011.045.009.044.007.045.006.045.004.045.002.045.001.045v17l-.001.045-.002.045-.004.045-.006.045-.007.045-.009.044-.011.045-.012.044-.013.044-.015.044-.017.043-.018.044-.02.043-.021.043-.023.043-.024.043-.026.043-.027.042-.029.042-.03.042-.032.042-.033.042-.034.041-.036.041-.037.041-.039.041-.04.041-.041.04-.043.04-.044.04-.045.04-.047.039-.048.039-.05.039-.051.039-.052.038-.053.038-.055.038-.055.038-.058.037-.058.037-.06.037-.06.036-.062.036-.064.036-.064.036-.066.035-.067.035-.068.035-.069.035-.07.034-.071.034-.073.033-.074.033-.15.066-.155.064-.16.063-.163.061-.168.06-.172.059-.175.057-.18.056-.183.054-.187.053-.191.051-.194.05-.198.048-.201.046-.205.045-.208.043-.211.041-.214.04-.217.038-.22.036-.223.034-.225.032-.229.031-.231.028-.233.027-.236.024-.239.023-.241.02-.242.019-.246.016-.247.015-.249.012-.251.01-.253.008-.255.005-.256.004-.258.001-.258-.001-.256-.004-.255-.005-.253-.008-.251-.01-.249-.012-.247-.015-.245-.016-.243-.019-.241-.02-.238-.023-.236-.024-.234-.027-.231-.028-.228-.031-.226-.032-.223-.034-.22-.036-.217-.038-.214-.04-.211-.041-.208-.043-.204-.045-.201-.046-.198-.048-.195-.05-.19-.051-.187-.053-.184-.054-.179-.056-.176-.057-.172-.059-.167-.06-.164-.061-.159-.063-.155-.064-.151-.066-.074-.033-.072-.033-.072-.034-.07-.034-.069-.035-.068-.035-.067-.035-.066-.035-.064-.036-.063-.036-.062-.036-.061-.036-.06-.037-.058-.037-.057-.037-.056-.038-.055-.038-.053-.038-.052-.038-.051-.039-.049-.039-.049-.039-.046-.039-.046-.04-.044-.04-.043-.04-.041-.04-.04-.041-.039-.041-.037-.041-.036-.041-.034-.041-.033-.042-.032-.042-.03-.042-.029-.042-.027-.042-.026-.043-.024-.043-.023-.043-.021-.043-.02-.043-.018-.044-.017-.043-.015-.044-.013-.044-.012-.044-.011-.045-.009-.044-.007-.045-.006-.045-.004-.045-.002-.045-.001-.045v-17l.001-.045.002-.045.004-.045.006-.045.007-.045.009-.044.011-.045.012-.044.013-.044.015-.044.017-.043.018-.044.02-.043.021-.043.023-.043.024-.043.026-.043.027-.042.029-.042.03-.042.032-.042.033-.042.034-.041.036-.041.037-.041.039-.041.04-.041.041-.04.043-.04.044-.04.046-.04.046-.039.049-.039.049-.039.051-.039.052-.038.053-.038.055-.038.056-.038.057-.037.058-.037.06-.037.061-.036.062-.036.063-.036.064-.036.066-.035.067-.035.068-.035.069-.035.07-.034.072-.034.072-.033.074-.033.151-.066.155-.064.159-.063.164-.061.167-.06.172-.059.176-.057.179-.056.184-.054.187-.053.19-.051.195-.05.198-.048.201-.046.204-.045.208-.043.211-.041.214-.04.217-.038.22-.036.223-.034.226-.032.228-.031.231-.028.234-.027.236-.024.238-.023.241-.02.243-.019.245-.016.247-.015.249-.012.251-.01.253-.008.255-.005.256-.004.258-.001.258.001zm-9.258 20.499v.01l.001.021.003.021.004.022.005.021.006.022.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.023.018.024.019.024.021.024.022.025.023.024.024.025.052.049.056.05.061.051.066.051.07.051.075.051.079.052.084.052.088.052.092.052.097.052.102.051.105.052.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.048.144.049.147.047.152.047.155.047.16.045.163.045.167.043.171.043.176.041.178.041.183.039.187.039.19.037.194.035.197.035.202.033.204.031.209.03.212.029.216.027.219.025.222.024.226.021.23.02.233.018.236.016.24.015.243.012.246.01.249.008.253.005.256.004.259.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.021.224-.024.22-.026.216-.027.212-.028.21-.031.205-.031.202-.034.198-.034.194-.036.191-.037.187-.039.183-.04.179-.04.175-.042.172-.043.168-.044.163-.045.16-.046.155-.046.152-.047.148-.048.143-.049.139-.049.136-.05.131-.05.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.053.083-.051.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.05.023-.024.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.023.01-.022.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.127l-.077.055-.08.053-.083.054-.085.053-.087.052-.09.052-.093.051-.095.05-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.045-.118.044-.12.043-.122.042-.124.042-.126.041-.128.04-.13.04-.132.038-.134.038-.135.037-.138.037-.139.035-.142.035-.143.034-.144.033-.147.032-.148.031-.15.03-.151.03-.153.029-.154.027-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.01-.179.008-.179.008-.181.006-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.006-.179-.008-.179-.008-.178-.01-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.027-.153-.029-.151-.03-.15-.03-.148-.031-.146-.032-.145-.033-.143-.034-.141-.035-.14-.035-.137-.037-.136-.037-.134-.038-.132-.038-.13-.04-.128-.04-.126-.041-.124-.042-.122-.042-.12-.044-.117-.043-.116-.045-.113-.045-.112-.046-.109-.047-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.05-.093-.052-.09-.051-.087-.052-.085-.053-.083-.054-.08-.054-.077-.054v4.127zm0-5.654v.011l.001.021.003.021.004.021.005.022.006.022.007.022.009.022.01.022.011.023.012.023.013.023.015.024.016.023.017.024.018.024.019.024.021.024.022.024.023.025.024.024.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.052.11.051.114.051.119.052.123.05.127.051.131.05.135.049.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.044.171.042.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.022.23.02.233.018.236.016.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.012.241-.015.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.048.139-.05.136-.049.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.051.051-.049.023-.025.023-.024.021-.025.02-.024.019-.024.018-.024.017-.024.015-.023.014-.023.013-.024.012-.022.01-.023.01-.023.008-.022.006-.022.006-.022.004-.021.004-.022.001-.021.001-.021v-4.139l-.077.054-.08.054-.083.054-.085.052-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.044-.118.044-.12.044-.122.042-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.035-.143.033-.144.033-.147.033-.148.031-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.009-.179.009-.179.007-.181.007-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.007-.179-.007-.179-.009-.178-.009-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.031-.146-.033-.145-.033-.143-.033-.141-.035-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.04-.126-.041-.124-.042-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.051-.093-.051-.09-.051-.087-.053-.085-.052-.083-.054-.08-.054-.077-.054v4.139zm0-5.666v.011l.001.02.003.022.004.021.005.022.006.021.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.024.018.023.019.024.021.025.022.024.023.024.024.025.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.051.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.043.171.043.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.021.23.02.233.018.236.017.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.013.241-.014.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.049.139-.049.136-.049.131-.051.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.049.023-.025.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.022.01-.023.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.153l-.077.054-.08.054-.083.053-.085.053-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.048-.105.048-.106.048-.109.046-.111.046-.114.046-.115.044-.118.044-.12.043-.122.043-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.034-.143.034-.144.033-.147.032-.148.032-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.024-.161.024-.162.023-.163.023-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.01-.178.01-.179.009-.179.007-.181.006-.182.006-.182.004-.184.003-.184.001-.185.001-.185-.001-.184-.001-.184-.003-.182-.004-.182-.006-.181-.006-.179-.007-.179-.009-.178-.01-.176-.01-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.023-.162-.023-.161-.024-.159-.024-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.032-.146-.032-.145-.033-.143-.034-.141-.034-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.041-.126-.041-.124-.041-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.048-.105-.048-.102-.048-.1-.05-.097-.049-.095-.051-.093-.051-.09-.052-.087-.052-.085-.053-.083-.053-.08-.054-.077-.054v4.153zm8.74-8.179l-.257.004-.254.005-.25.008-.247.011-.244.012-.241.014-.237.016-.233.018-.231.021-.226.022-.224.023-.22.026-.216.027-.212.028-.21.031-.205.032-.202.033-.198.034-.194.036-.191.038-.187.038-.183.04-.179.041-.175.042-.172.043-.168.043-.163.045-.16.046-.155.046-.152.048-.148.048-.143.048-.139.049-.136.05-.131.05-.126.051-.123.051-.118.051-.114.052-.11.052-.106.052-.101.052-.096.052-.092.052-.088.052-.083.052-.079.052-.074.051-.07.052-.065.051-.06.05-.056.05-.051.05-.023.025-.023.024-.021.024-.02.025-.019.024-.018.024-.017.023-.015.024-.014.023-.013.023-.012.023-.01.023-.01.022-.008.022-.006.023-.006.021-.004.022-.004.021-.001.021-.001.021.001.021.001.021.004.021.004.022.006.021.006.023.008.022.01.022.01.023.012.023.013.023.014.023.015.024.017.023.018.024.019.024.02.025.021.024.023.024.023.025.051.05.056.05.06.05.065.051.07.052.074.051.079.052.083.052.088.052.092.052.096.052.101.052.106.052.11.052.114.052.118.051.123.051.126.051.131.05.136.05.139.049.143.048.148.048.152.048.155.046.16.046.163.045.168.043.172.043.175.042.179.041.183.04.187.038.191.038.194.036.198.034.202.033.205.032.21.031.212.028.216.027.22.026.224.023.226.022.231.021.233.018.237.016.241.014.244.012.247.011.25.008.254.005.257.004.26.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.022.224-.023.22-.026.216-.027.212-.028.21-.031.205-.032.202-.033.198-.034.194-.036.191-.038.187-.038.183-.04.179-.041.175-.042.172-.043.168-.043.163-.045.16-.046.155-.046.152-.048.148-.048.143-.048.139-.049.136-.05.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.05.051-.05.023-.025.023-.024.021-.024.02-.025.019-.024.018-.024.017-.023.015-.024.014-.023.013-.023.012-.023.01-.023.01-.022.008-.022.006-.023.006-.021.004-.022.004-.021.001-.021.001-.021-.001-.021-.001-.021-.004-.021-.004-.022-.006-.021-.006-.023-.008-.022-.01-.022-.01-.023-.012-.023-.013-.023-.014-.023-.015-.024-.017-.023-.018-.024-.019-.024-.02-.025-.021-.024-.023-.024-.023-.025-.051-.05-.056-.05-.06-.05-.065-.051-.07-.052-.074-.051-.079-.052-.083-.052-.088-.052-.092-.052-.096-.052-.101-.052-.106-.052-.11-.052-.114-.052-.118-.051-.123-.051-.126-.051-.131-.05-.136-.05-.139-.049-.143-.048-.148-.048-.152-.048-.155-.046-.16-.046-.163-.045-.168-.043-.172-.043-.175-.042-.179-.041-.183-.04-.187-.038-.191-.038-.194-.036-.198-.034-.202-.033-.205-.032-.21-.031-.212-.028-.216-.027-.22-.026-.224-.023-.226-.022-.231-.021-.233-.018-.237-.016-.241-.014-.244-.012-.247-.011-.25-.008-.254-.005-.257-.004-.26-.001-.26.001z")},"insertDatabaseIcon"),fOe=o(function(t,e){t.append("defs").append("symbol").attr("id",e+"-computer").attr("width","24").attr("height","24").append("path").attr("transform","scale(.5)").attr("d","M2 2v13h20v-13h-20zm18 11h-16v-9h16v9zm-10.228 6l.466-1h3.524l.467 1h-4.457zm14.228 3h-24l2-6h2.104l-1.33 4h18.45l-1.297-4h2.073l2 6zm-5-10h-14v-7h14v7z")},"insertComputerIcon"),dOe=o(function(t,e){t.append("defs").append("symbol").attr("id",e+"-clock").attr("width","24").attr("height","24").append("path").attr("transform","scale(.5)").attr("d","M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm5.848 12.459c.202.038.202.333.001.372-1.907.361-6.045 1.111-6.547 1.111-.719 0-1.301-.582-1.301-1.301 0-.512.77-5.447 1.125-7.445.034-.192.312-.181.343.014l.985 6.238 5.394 1.011z")},"insertClockIcon"),pOe=o(function(t,e){t.append("defs").append("marker").attr("id",e+"-arrowhead").attr("refX",9).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z")},"insertArrowHead"),mOe=o(function(t,e){t.append("defs").append("marker").attr("id",e+"-arrowend").attr("refX",1).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto").append("path").attr("d","M 10 0 L 0 5 L 10 10 z")},"insertArrowEnd"),gOe=o(function(t,e){t.append("defs").append("marker").attr("id",e+"-filled-head").attr("refX",18).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L14,7 L9,1 Z")},"insertArrowFilledHead"),yOe=o(function(t,e){let i=t.append("defs").append("marker").attr("id",e+"-crosshead").attr("markerWidth",15).attr("markerHeight",8).attr("orient","auto").attr("refX",16).attr("refY",4);i.append("path").attr("fill","black").attr("stroke","#000000").style("stroke-dasharray","0, 0").attr("stroke-width","1px").attr("d","M 9,2 V 6 L16,4 Z"),i.append("path").attr("fill","none").attr("stroke","#000000").style("stroke-dasharray","0, 0").attr("stroke-width","1px").attr("d","M 0,1 L 6,7 M 6,1 L 0,7")},"insertArrowCrossHead"),vOe=o((t,e)=>({fontFamily:t[e+"FontFamily"],fontSize:t[e+"FontSize"],fontWeight:t[e+"FontWeight"]}),"getC4ShapeFont"),Mh=(function(){function t(n,a,s,l,u,h,f){let d=a.append("text").attr("x",s+u/2).attr("y",l+h/2+5).style("text-anchor","middle").text(n);i(d,f)}o(t,"byText");function e(n,a,s,l,u,h,f,d){let{fontSize:p,fontFamily:m,fontWeight:g}=d,y=n.split(lt.lineBreakRegex);for(let v=0;v{"use strict";xOe=typeof global=="object"&&global&&global.Object===Object&&global,A3=xOe});var bOe,TOe,In,Al=P(()=>{"use strict";YN();bOe=typeof self=="object"&&self&&self.Object===Object&&self,TOe=A3||bOe||Function("return this")(),In=TOe});var kOe,Da,v0=P(()=>{"use strict";Al();kOe=In.Symbol,Da=kOe});function EOe(t){var e=COe.call(t,eb),r=t[eb];try{t[eb]=void 0;var i=!0}catch{}var n=wOe.call(t);return i&&(e?t[eb]=r:delete t[eb]),n}var pre,COe,wOe,eb,mre,gre=P(()=>{"use strict";v0();pre=Object.prototype,COe=pre.hasOwnProperty,wOe=pre.toString,eb=Da?Da.toStringTag:void 0;o(EOe,"getRawTag");mre=EOe});function _Oe(t){return AOe.call(t)}var SOe,AOe,yre,vre=P(()=>{"use strict";SOe=Object.prototype,AOe=SOe.toString;o(_Oe,"objectToString");yre=_Oe});function ROe(t){return t==null?t===void 0?LOe:DOe:xre&&xre in Object(t)?mre(t):yre(t)}var DOe,LOe,xre,Xa,Oh=P(()=>{"use strict";v0();gre();vre();DOe="[object Null]",LOe="[object Undefined]",xre=Da?Da.toStringTag:void 0;o(ROe,"baseGetTag");Xa=ROe});function NOe(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var Gi,Zo=P(()=>{"use strict";o(NOe,"isObject");Gi=NOe});function BOe(t){if(!Gi(t))return!1;var e=Xa(t);return e==MOe||e==OOe||e==IOe||e==POe}var IOe,MOe,OOe,POe,Qn,tb=P(()=>{"use strict";Oh();Zo();IOe="[object AsyncFunction]",MOe="[object Function]",OOe="[object GeneratorFunction]",POe="[object Proxy]";o(BOe,"isFunction");Qn=BOe});var FOe,_3,bre=P(()=>{"use strict";Al();FOe=In["__core-js_shared__"],_3=FOe});function $Oe(t){return!!Tre&&Tre in t}var Tre,kre,Cre=P(()=>{"use strict";bre();Tre=(function(){var t=/[^.]+$/.exec(_3&&_3.keys&&_3.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})();o($Oe,"isMasked");kre=$Oe});function VOe(t){if(t!=null){try{return GOe.call(t)}catch{}try{return t+""}catch{}}return""}var zOe,GOe,Ph,jN=P(()=>{"use strict";zOe=Function.prototype,GOe=zOe.toString;o(VOe,"toSource");Ph=VOe});function KOe(t){if(!Gi(t)||kre(t))return!1;var e=Qn(t)?XOe:WOe;return e.test(Ph(t))}var qOe,WOe,UOe,HOe,YOe,jOe,XOe,wre,Ere=P(()=>{"use strict";tb();Cre();Zo();jN();qOe=/[\\^$.*+?()[\]{}|]/g,WOe=/^\[object .+?Constructor\]$/,UOe=Function.prototype,HOe=Object.prototype,YOe=UOe.toString,jOe=HOe.hasOwnProperty,XOe=RegExp("^"+YOe.call(jOe).replace(qOe,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");o(KOe,"baseIsNative");wre=KOe});function QOe(t,e){return t?.[e]}var Sre,Are=P(()=>{"use strict";o(QOe,"getValue");Sre=QOe});function ZOe(t,e){var r=Sre(t,e);return wre(r)?r:void 0}var mo,Zf=P(()=>{"use strict";Ere();Are();o(ZOe,"getNative");mo=ZOe});var JOe,Bh,rb=P(()=>{"use strict";Zf();JOe=mo(Object,"create"),Bh=JOe});function ePe(){this.__data__=Bh?Bh(null):{},this.size=0}var _re,Dre=P(()=>{"use strict";rb();o(ePe,"hashClear");_re=ePe});function tPe(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var Lre,Rre=P(()=>{"use strict";o(tPe,"hashDelete");Lre=tPe});function aPe(t){var e=this.__data__;if(Bh){var r=e[t];return r===rPe?void 0:r}return nPe.call(e,t)?e[t]:void 0}var rPe,iPe,nPe,Nre,Ire=P(()=>{"use strict";rb();rPe="__lodash_hash_undefined__",iPe=Object.prototype,nPe=iPe.hasOwnProperty;o(aPe,"hashGet");Nre=aPe});function lPe(t){var e=this.__data__;return Bh?e[t]!==void 0:oPe.call(e,t)}var sPe,oPe,Mre,Ore=P(()=>{"use strict";rb();sPe=Object.prototype,oPe=sPe.hasOwnProperty;o(lPe,"hashHas");Mre=lPe});function uPe(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=Bh&&e===void 0?cPe:e,this}var cPe,Pre,Bre=P(()=>{"use strict";rb();cPe="__lodash_hash_undefined__";o(uPe,"hashSet");Pre=uPe});function o1(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e{"use strict";Dre();Rre();Ire();Ore();Bre();o(o1,"Hash");o1.prototype.clear=_re;o1.prototype.delete=Lre;o1.prototype.get=Nre;o1.prototype.has=Mre;o1.prototype.set=Pre;XN=o1});function hPe(){this.__data__=[],this.size=0}var $re,zre=P(()=>{"use strict";o(hPe,"listCacheClear");$re=hPe});function fPe(t,e){return t===e||t!==t&&e!==e}var _l,x0=P(()=>{"use strict";o(fPe,"eq");_l=fPe});function dPe(t,e){for(var r=t.length;r--;)if(_l(t[r][0],e))return r;return-1}var Jf,ib=P(()=>{"use strict";x0();o(dPe,"assocIndexOf");Jf=dPe});function gPe(t){var e=this.__data__,r=Jf(e,t);if(r<0)return!1;var i=e.length-1;return r==i?e.pop():mPe.call(e,r,1),--this.size,!0}var pPe,mPe,Gre,Vre=P(()=>{"use strict";ib();pPe=Array.prototype,mPe=pPe.splice;o(gPe,"listCacheDelete");Gre=gPe});function yPe(t){var e=this.__data__,r=Jf(e,t);return r<0?void 0:e[r][1]}var qre,Wre=P(()=>{"use strict";ib();o(yPe,"listCacheGet");qre=yPe});function vPe(t){return Jf(this.__data__,t)>-1}var Ure,Hre=P(()=>{"use strict";ib();o(vPe,"listCacheHas");Ure=vPe});function xPe(t,e){var r=this.__data__,i=Jf(r,t);return i<0?(++this.size,r.push([t,e])):r[i][1]=e,this}var Yre,jre=P(()=>{"use strict";ib();o(xPe,"listCacheSet");Yre=xPe});function l1(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e{"use strict";zre();Vre();Wre();Hre();jre();o(l1,"ListCache");l1.prototype.clear=$re;l1.prototype.delete=Gre;l1.prototype.get=qre;l1.prototype.has=Ure;l1.prototype.set=Yre;ed=l1});var bPe,td,D3=P(()=>{"use strict";Zf();Al();bPe=mo(In,"Map"),td=bPe});function TPe(){this.size=0,this.__data__={hash:new XN,map:new(td||ed),string:new XN}}var Xre,Kre=P(()=>{"use strict";Fre();nb();D3();o(TPe,"mapCacheClear");Xre=TPe});function kPe(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}var Qre,Zre=P(()=>{"use strict";o(kPe,"isKeyable");Qre=kPe});function CPe(t,e){var r=t.__data__;return Qre(e)?r[typeof e=="string"?"string":"hash"]:r.map}var rd,ab=P(()=>{"use strict";Zre();o(CPe,"getMapData");rd=CPe});function wPe(t){var e=rd(this,t).delete(t);return this.size-=e?1:0,e}var Jre,eie=P(()=>{"use strict";ab();o(wPe,"mapCacheDelete");Jre=wPe});function EPe(t){return rd(this,t).get(t)}var tie,rie=P(()=>{"use strict";ab();o(EPe,"mapCacheGet");tie=EPe});function SPe(t){return rd(this,t).has(t)}var iie,nie=P(()=>{"use strict";ab();o(SPe,"mapCacheHas");iie=SPe});function APe(t,e){var r=rd(this,t),i=r.size;return r.set(t,e),this.size+=r.size==i?0:1,this}var aie,sie=P(()=>{"use strict";ab();o(APe,"mapCacheSet");aie=APe});function c1(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e{"use strict";Kre();eie();rie();nie();sie();o(c1,"MapCache");c1.prototype.clear=Xre;c1.prototype.delete=Jre;c1.prototype.get=tie;c1.prototype.has=iie;c1.prototype.set=aie;b0=c1});function KN(t,e){if(typeof t!="function"||e!=null&&typeof e!="function")throw new TypeError(_Pe);var r=o(function(){var i=arguments,n=e?e.apply(this,i):i[0],a=r.cache;if(a.has(n))return a.get(n);var s=t.apply(this,i);return r.cache=a.set(n,s)||a,s},"memoized");return r.cache=new(KN.Cache||b0),r}var _Pe,u1,QN=P(()=>{"use strict";L3();_Pe="Expected a function";o(KN,"memoize");KN.Cache=b0;u1=KN});function DPe(){this.__data__=new ed,this.size=0}var oie,lie=P(()=>{"use strict";nb();o(DPe,"stackClear");oie=DPe});function LPe(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}var cie,uie=P(()=>{"use strict";o(LPe,"stackDelete");cie=LPe});function RPe(t){return this.__data__.get(t)}var hie,fie=P(()=>{"use strict";o(RPe,"stackGet");hie=RPe});function NPe(t){return this.__data__.has(t)}var die,pie=P(()=>{"use strict";o(NPe,"stackHas");die=NPe});function MPe(t,e){var r=this.__data__;if(r instanceof ed){var i=r.__data__;if(!td||i.length{"use strict";nb();D3();L3();IPe=200;o(MPe,"stackSet");mie=MPe});function h1(t){var e=this.__data__=new ed(t);this.size=e.size}var vu,sb=P(()=>{"use strict";nb();lie();uie();fie();pie();gie();o(h1,"Stack");h1.prototype.clear=oie;h1.prototype.delete=cie;h1.prototype.get=hie;h1.prototype.has=die;h1.prototype.set=mie;vu=h1});var OPe,f1,ZN=P(()=>{"use strict";Zf();OPe=(function(){try{var t=mo(Object,"defineProperty");return t({},"",{}),t}catch{}})(),f1=OPe});function PPe(t,e,r){e=="__proto__"&&f1?f1(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var xu,d1=P(()=>{"use strict";ZN();o(PPe,"baseAssignValue");xu=PPe});function BPe(t,e,r){(r!==void 0&&!_l(t[e],r)||r===void 0&&!(e in t))&&xu(t,e,r)}var ob,JN=P(()=>{"use strict";d1();x0();o(BPe,"assignMergeValue");ob=BPe});function FPe(t){return function(e,r,i){for(var n=-1,a=Object(e),s=i(e),l=s.length;l--;){var u=s[t?l:++n];if(r(a[u],u,a)===!1)break}return e}}var yie,vie=P(()=>{"use strict";o(FPe,"createBaseFor");yie=FPe});var $Pe,p1,R3=P(()=>{"use strict";vie();$Pe=yie(),p1=$Pe});function GPe(t,e){if(e)return t.slice();var r=t.length,i=Tie?Tie(r):new t.constructor(r);return t.copy(i),i}var kie,xie,zPe,bie,Tie,N3,eI=P(()=>{"use strict";Al();kie=typeof exports=="object"&&exports&&!exports.nodeType&&exports,xie=kie&&typeof module=="object"&&module&&!module.nodeType&&module,zPe=xie&&xie.exports===kie,bie=zPe?In.Buffer:void 0,Tie=bie?bie.allocUnsafe:void 0;o(GPe,"cloneBuffer");N3=GPe});var VPe,m1,tI=P(()=>{"use strict";Al();VPe=In.Uint8Array,m1=VPe});function qPe(t){var e=new t.constructor(t.byteLength);return new m1(e).set(new m1(t)),e}var g1,I3=P(()=>{"use strict";tI();o(qPe,"cloneArrayBuffer");g1=qPe});function WPe(t,e){var r=e?g1(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}var M3,rI=P(()=>{"use strict";I3();o(WPe,"cloneTypedArray");M3=WPe});function UPe(t,e){var r=-1,i=t.length;for(e||(e=Array(i));++r{"use strict";o(UPe,"copyArray");O3=UPe});var Cie,HPe,wie,Eie=P(()=>{"use strict";Zo();Cie=Object.create,HPe=(function(){function t(){}return o(t,"object"),function(e){if(!Gi(e))return{};if(Cie)return Cie(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}})(),wie=HPe});function YPe(t,e){return function(r){return t(e(r))}}var P3,nI=P(()=>{"use strict";o(YPe,"overArg");P3=YPe});var jPe,y1,B3=P(()=>{"use strict";nI();jPe=P3(Object.getPrototypeOf,Object),y1=jPe});function KPe(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||XPe;return t===r}var XPe,bu,v1=P(()=>{"use strict";XPe=Object.prototype;o(KPe,"isPrototype");bu=KPe});function QPe(t){return typeof t.constructor=="function"&&!bu(t)?wie(y1(t)):{}}var F3,aI=P(()=>{"use strict";Eie();B3();v1();o(QPe,"initCloneObject");F3=QPe});function ZPe(t){return t!=null&&typeof t=="object"}var En,Dl=P(()=>{"use strict";o(ZPe,"isObjectLike");En=ZPe});function eBe(t){return En(t)&&Xa(t)==JPe}var JPe,sI,Sie=P(()=>{"use strict";Oh();Dl();JPe="[object Arguments]";o(eBe,"baseIsArguments");sI=eBe});var Aie,tBe,rBe,iBe,Sc,x1=P(()=>{"use strict";Sie();Dl();Aie=Object.prototype,tBe=Aie.hasOwnProperty,rBe=Aie.propertyIsEnumerable,iBe=sI((function(){return arguments})())?sI:function(t){return En(t)&&tBe.call(t,"callee")&&!rBe.call(t,"callee")},Sc=iBe});var nBe,Gt,fn=P(()=>{"use strict";nBe=Array.isArray,Gt=nBe});function sBe(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=aBe}var aBe,b1,$3=P(()=>{"use strict";aBe=9007199254740991;o(sBe,"isLength");b1=sBe});function oBe(t){return t!=null&&b1(t.length)&&!Qn(t)}var Mn,Ll=P(()=>{"use strict";tb();$3();o(oBe,"isArrayLike");Mn=oBe});function lBe(t){return En(t)&&Mn(t)}var T0,z3=P(()=>{"use strict";Ll();Dl();o(lBe,"isArrayLikeObject");T0=lBe});function cBe(){return!1}var _ie,Die=P(()=>{"use strict";o(cBe,"stubFalse");_ie=cBe});var Nie,Lie,uBe,Rie,hBe,fBe,Ac,T1=P(()=>{"use strict";Al();Die();Nie=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Lie=Nie&&typeof module=="object"&&module&&!module.nodeType&&module,uBe=Lie&&Lie.exports===Nie,Rie=uBe?In.Buffer:void 0,hBe=Rie?Rie.isBuffer:void 0,fBe=hBe||_ie,Ac=fBe});function vBe(t){if(!En(t)||Xa(t)!=dBe)return!1;var e=y1(t);if(e===null)return!0;var r=gBe.call(e,"constructor")&&e.constructor;return typeof r=="function"&&r instanceof r&&Iie.call(r)==yBe}var dBe,pBe,mBe,Iie,gBe,yBe,Mie,Oie=P(()=>{"use strict";Oh();B3();Dl();dBe="[object Object]",pBe=Function.prototype,mBe=Object.prototype,Iie=pBe.toString,gBe=mBe.hasOwnProperty,yBe=Iie.call(Object);o(vBe,"isPlainObject");Mie=vBe});function qBe(t){return En(t)&&b1(t.length)&&!!ln[Xa(t)]}var xBe,bBe,TBe,kBe,CBe,wBe,EBe,SBe,ABe,_Be,DBe,LBe,RBe,NBe,IBe,MBe,OBe,PBe,BBe,FBe,$Be,zBe,GBe,VBe,ln,Pie,Bie=P(()=>{"use strict";Oh();$3();Dl();xBe="[object Arguments]",bBe="[object Array]",TBe="[object Boolean]",kBe="[object Date]",CBe="[object Error]",wBe="[object Function]",EBe="[object Map]",SBe="[object Number]",ABe="[object Object]",_Be="[object RegExp]",DBe="[object Set]",LBe="[object String]",RBe="[object WeakMap]",NBe="[object ArrayBuffer]",IBe="[object DataView]",MBe="[object Float32Array]",OBe="[object Float64Array]",PBe="[object Int8Array]",BBe="[object Int16Array]",FBe="[object Int32Array]",$Be="[object Uint8Array]",zBe="[object Uint8ClampedArray]",GBe="[object Uint16Array]",VBe="[object Uint32Array]",ln={};ln[MBe]=ln[OBe]=ln[PBe]=ln[BBe]=ln[FBe]=ln[$Be]=ln[zBe]=ln[GBe]=ln[VBe]=!0;ln[xBe]=ln[bBe]=ln[NBe]=ln[TBe]=ln[IBe]=ln[kBe]=ln[CBe]=ln[wBe]=ln[EBe]=ln[SBe]=ln[ABe]=ln[_Be]=ln[DBe]=ln[LBe]=ln[RBe]=!1;o(qBe,"baseIsTypedArray");Pie=qBe});function WBe(t){return function(e){return t(e)}}var Rl,k0=P(()=>{"use strict";o(WBe,"baseUnary");Rl=WBe});var Fie,lb,UBe,oI,HBe,Nl,cb=P(()=>{"use strict";YN();Fie=typeof exports=="object"&&exports&&!exports.nodeType&&exports,lb=Fie&&typeof module=="object"&&module&&!module.nodeType&&module,UBe=lb&&lb.exports===Fie,oI=UBe&&A3.process,HBe=(function(){try{var t=lb&&lb.require&&lb.require("util").types;return t||oI&&oI.binding&&oI.binding("util")}catch{}})(),Nl=HBe});var $ie,YBe,id,ub=P(()=>{"use strict";Bie();k0();cb();$ie=Nl&&Nl.isTypedArray,YBe=$ie?Rl($ie):Pie,id=YBe});function jBe(t,e){if(!(e==="constructor"&&typeof t[e]=="function")&&e!="__proto__")return t[e]}var hb,lI=P(()=>{"use strict";o(jBe,"safeGet");hb=jBe});function QBe(t,e,r){var i=t[e];(!(KBe.call(t,e)&&_l(i,r))||r===void 0&&!(e in t))&&xu(t,e,r)}var XBe,KBe,Tu,k1=P(()=>{"use strict";d1();x0();XBe=Object.prototype,KBe=XBe.hasOwnProperty;o(QBe,"assignValue");Tu=QBe});function ZBe(t,e,r,i){var n=!r;r||(r={});for(var a=-1,s=e.length;++a{"use strict";k1();d1();o(ZBe,"copyObject");Il=ZBe});function JBe(t,e){for(var r=-1,i=Array(t);++r{"use strict";o(JBe,"baseTimes");zie=JBe});function rFe(t,e){var r=typeof t;return e=e??eFe,!!e&&(r=="number"||r!="symbol"&&tFe.test(t))&&t>-1&&t%1==0&&t{"use strict";eFe=9007199254740991,tFe=/^(?:0|[1-9]\d*)$/;o(rFe,"isIndex");nd=rFe});function aFe(t,e){var r=Gt(t),i=!r&&Sc(t),n=!r&&!i&&Ac(t),a=!r&&!i&&!n&&id(t),s=r||i||n||a,l=s?zie(t.length,String):[],u=l.length;for(var h in t)(e||nFe.call(t,h))&&!(s&&(h=="length"||n&&(h=="offset"||h=="parent")||a&&(h=="buffer"||h=="byteLength"||h=="byteOffset")||nd(h,u)))&&l.push(h);return l}var iFe,nFe,G3,cI=P(()=>{"use strict";Gie();x1();fn();T1();fb();ub();iFe=Object.prototype,nFe=iFe.hasOwnProperty;o(aFe,"arrayLikeKeys");G3=aFe});function sFe(t){var e=[];if(t!=null)for(var r in Object(t))e.push(r);return e}var Vie,qie=P(()=>{"use strict";o(sFe,"nativeKeysIn");Vie=sFe});function cFe(t){if(!Gi(t))return Vie(t);var e=bu(t),r=[];for(var i in t)i=="constructor"&&(e||!lFe.call(t,i))||r.push(i);return r}var oFe,lFe,Wie,Uie=P(()=>{"use strict";Zo();v1();qie();oFe=Object.prototype,lFe=oFe.hasOwnProperty;o(cFe,"baseKeysIn");Wie=cFe});function uFe(t){return Mn(t)?G3(t,!0):Wie(t)}var go,ad=P(()=>{"use strict";cI();Uie();Ll();o(uFe,"keysIn");go=uFe});function hFe(t){return Il(t,go(t))}var Hie,Yie=P(()=>{"use strict";C0();ad();o(hFe,"toPlainObject");Hie=hFe});function fFe(t,e,r,i,n,a,s){var l=hb(t,r),u=hb(e,r),h=s.get(u);if(h){ob(t,r,h);return}var f=a?a(l,u,r+"",t,e,s):void 0,d=f===void 0;if(d){var p=Gt(u),m=!p&&Ac(u),g=!p&&!m&&id(u);f=u,p||m||g?Gt(l)?f=l:T0(l)?f=O3(l):m?(d=!1,f=N3(u,!0)):g?(d=!1,f=M3(u,!0)):f=[]:Mie(u)||Sc(u)?(f=l,Sc(l)?f=Hie(l):(!Gi(l)||Qn(l))&&(f=F3(u))):d=!1}d&&(s.set(u,f),n(f,u,i,a,s),s.delete(u)),ob(t,r,f)}var jie,Xie=P(()=>{"use strict";JN();eI();rI();iI();aI();x1();fn();z3();T1();tb();Zo();Oie();ub();lI();Yie();o(fFe,"baseMergeDeep");jie=fFe});function Kie(t,e,r,i,n){t!==e&&p1(e,function(a,s){if(n||(n=new vu),Gi(a))jie(t,e,s,r,Kie,i,n);else{var l=i?i(hb(t,s),a,s+"",t,e,n):void 0;l===void 0&&(l=a),ob(t,s,l)}},go)}var Qie,Zie=P(()=>{"use strict";sb();JN();R3();Xie();Zo();ad();lI();o(Kie,"baseMerge");Qie=Kie});function dFe(t){return t}var La,Fh=P(()=>{"use strict";o(dFe,"identity");La=dFe});function pFe(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}var Jie,ene=P(()=>{"use strict";o(pFe,"apply");Jie=pFe});function mFe(t,e,r){return e=tne(e===void 0?t.length-1:e,0),function(){for(var i=arguments,n=-1,a=tne(i.length-e,0),s=Array(a);++n{"use strict";ene();tne=Math.max;o(mFe,"overRest");V3=mFe});function gFe(t){return function(){return t}}var yo,hI=P(()=>{"use strict";o(gFe,"constant");yo=gFe});var yFe,rne,ine=P(()=>{"use strict";hI();ZN();Fh();yFe=f1?function(t,e){return f1(t,"toString",{configurable:!0,enumerable:!1,value:yo(e),writable:!0})}:La,rne=yFe});function TFe(t){var e=0,r=0;return function(){var i=bFe(),n=xFe-(i-r);if(r=i,n>0){if(++e>=vFe)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}var vFe,xFe,bFe,nne,ane=P(()=>{"use strict";vFe=800,xFe=16,bFe=Date.now;o(TFe,"shortOut");nne=TFe});var kFe,q3,fI=P(()=>{"use strict";ine();ane();kFe=nne(rne),q3=kFe});function CFe(t,e){return q3(V3(t,e,La),t+"")}var ku,C1=P(()=>{"use strict";Fh();uI();fI();o(CFe,"baseRest");ku=CFe});function wFe(t,e,r){if(!Gi(r))return!1;var i=typeof e;return(i=="number"?Mn(r)&&nd(e,r.length):i=="string"&&e in r)?_l(r[e],t):!1}var Jo,w0=P(()=>{"use strict";x0();Ll();fb();Zo();o(wFe,"isIterateeCall");Jo=wFe});function EFe(t){return ku(function(e,r){var i=-1,n=r.length,a=n>1?r[n-1]:void 0,s=n>2?r[2]:void 0;for(a=t.length>3&&typeof a=="function"?(n--,a):void 0,s&&Jo(r[0],r[1],s)&&(a=n<3?void 0:a,n=1),e=Object(e);++i{"use strict";C1();w0();o(EFe,"createAssigner");W3=EFe});var SFe,sd,pI=P(()=>{"use strict";Zie();dI();SFe=W3(function(t,e,r){Qie(t,e,r)}),sd=SFe});function yI(t,e){if(!t)return e;let r=`curve${t.charAt(0).toUpperCase()+t.slice(1)}`;return AFe[r]??e}function RFe(t,e){let r=t.trim();if(r)return e.securityLevel!=="loose"?(0,lne.sanitizeUrl)(r):r}function hne(t,e){return!t||!e?0:Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function IFe(t){let e,r=0;t.forEach(n=>{r+=hne(n,e),e=n});let i=r/2;return vI(t,i)}function MFe(t){return t.length===1?t[0]:IFe(t)}function PFe(t,e,r){let i=structuredClone(r);Q.info("our points",i),e!=="start_left"&&e!=="start_right"&&i.reverse();let n=25+t,a=vI(i,n),s=10+t*.5,l=Math.atan2(i[0].y-a.y,i[0].x-a.x),u={x:0,y:0};return e==="start_left"?(u.x=Math.sin(l+Math.PI)*s+(i[0].x+a.x)/2,u.y=-Math.cos(l+Math.PI)*s+(i[0].y+a.y)/2):e==="end_right"?(u.x=Math.sin(l-Math.PI)*s+(i[0].x+a.x)/2-5,u.y=-Math.cos(l-Math.PI)*s+(i[0].y+a.y)/2-5):e==="end_left"?(u.x=Math.sin(l)*s+(i[0].x+a.x)/2-5,u.y=-Math.cos(l)*s+(i[0].y+a.y)/2-5):(u.x=Math.sin(l)*s+(i[0].x+a.x)/2,u.y=-Math.cos(l)*s+(i[0].y+a.y)/2),u}function xI(t){let e="",r="";for(let i of t)i!==void 0&&(i.startsWith("color:")||i.startsWith("text-align:")?r=r+i+";":e=e+i+";");return{style:e,labelStyle:r}}function BFe(t){let e="",r="0123456789abcdef",i=r.length;for(let n=0;nMath.round(parseFloat(a)).toString());return n.includes(r.toString())||n.includes(i.toString())}var lne,gI,AFe,_Fe,DFe,cne,une,LFe,NFe,sne,vI,OFe,one,bI,TI,FFe,$Fe,kI,zFe,CI,mI,U3,GFe,VFe,$s,Kt,fne,zs,Cu,er=P(()=>{"use strict";lne=Wa(s1(),1);Pr();Vr();iD();bt();Kp();kg();QN();pI();ew();gI="\u200B",AFe={curveBasis:wc,curveBasisClosed:f3,curveBasisOpen:d3,curveBumpX:z2,curveBumpY:G2,curveBundle:MN,curveCardinalClosed:ON,curveCardinalOpen:BN,curveCardinal:U2,curveCatmullRomClosed:$N,curveCatmullRomOpen:zN,curveCatmullRom:j2,curveLinear:yu,curveLinearClosed:v3,curveMonotoneX:X2,curveMonotoneY:K2,curveNatural:n1,curveStep:a1,curveStepAfter:Z2,curveStepBefore:Q2},_Fe=/\s*(?:(\w+)(?=:):|(\w+))\s*(?:(\w+)|((?:(?!}%{2}).|\r?\n)*))?\s*(?:}%{2})?/gi,DFe=o(function(t,e){let r=cne(t,/(?:init\b)|(?:initialize\b)/),i={};if(Array.isArray(r)){let s=r.map(l=>l.args);Eg(s),i=Yi(i,[...s])}else i=r.args;if(!i)return;let n=Ig(t,e),a="config";return i[a]!==void 0&&(n==="flowchart-v2"&&(n="flowchart"),i[n]=i[a],delete i[a]),i},"detectInit"),cne=o(function(t,e=null){try{let r=new RegExp(`[%]{2}(?![{]${_Fe.source})(?=[}][%]{2}).* +`,"ig");t=t.trim().replace(r,"").replace(/'/gm,'"'),Q.debug(`Detecting diagram directive${e!==null?" type:"+e:""} based on the text:${t}`);let i,n=[];for(;(i=Xp.exec(t))!==null;)if(i.index===Xp.lastIndex&&Xp.lastIndex++,i&&!e||e&&i[1]?.match(e)||e&&i[2]?.match(e)){let a=i[1]?i[1]:i[2],s=i[3]?i[3].trim():i[4]?JSON.parse(i[4].trim()):null;n.push({type:a,args:s})}return n.length===0?{type:t,args:null}:n.length===1?n[0]:n}catch(r){return Q.error(`ERROR: ${r.message} - Unable to parse directive type: '${e}' based on the text: '${t}'`),{type:void 0,args:null}}},"detectDirective"),une=o(function(t){return t.replace(Xp,"")},"removeDirectives"),LFe=o(function(t,e){for(let[r,i]of e.entries())if(i.match(t))return r;return-1},"isSubstringInArray");o(yI,"interpolateToCurve");o(RFe,"formatUrl");NFe=o((t,...e)=>{let r=t.split("."),i=r.length-1,n=r[i],a=window;for(let s=0;s{let r=Math.pow(10,e);return Math.round(t*r)/r},"roundNumber"),vI=o((t,e)=>{let r,i=e;for(let n of t){if(r){let a=hne(n,r);if(a===0)return r;if(a=1)return{x:n.x,y:n.y};if(s>0&&s<1)return{x:sne((1-s)*r.x+s*n.x,5),y:sne((1-s)*r.y+s*n.y,5)}}}r=n}throw new Error("Could not find a suitable point for the given distance")},"calculatePoint"),OFe=o((t,e,r)=>{Q.info(`our points ${JSON.stringify(e)}`),e[0]!==r&&(e=e.reverse());let n=vI(e,25),a=t?10:5,s=Math.atan2(e[0].y-n.y,e[0].x-n.x),l={x:0,y:0};return l.x=Math.sin(s)*a+(e[0].x+n.x)/2,l.y=-Math.cos(s)*a+(e[0].y+n.y)/2,l},"calcCardinalityPosition");o(PFe,"calcTerminalLabelPosition");o(xI,"getStylesFromArray");one=0,bI=o(()=>(one++,"id-"+Math.random().toString(36).substr(2,12)+"-"+one),"generateId");o(BFe,"makeRandomHex");TI=o(t=>BFe(t.length),"random"),FFe=o(function(){return{x:0,y:0,fill:void 0,anchor:"start",style:"#666",width:100,height:100,textMargin:0,rx:0,ry:0,valign:void 0,text:""}},"getTextObj"),$Fe=o(function(t,e){let r=e.text.replace(lt.lineBreakRegex," "),[,i]=$s(e.fontSize),n=t.append("text");n.attr("x",e.x),n.attr("y",e.y),n.style("text-anchor",e.anchor),n.style("font-family",e.fontFamily),n.style("font-size",i),n.style("font-weight",e.fontWeight),n.attr("fill",e.fill),e.class!==void 0&&n.attr("class",e.class);let a=n.append("tspan");return a.attr("x",e.x+e.textMargin*2),a.attr("fill",e.fill),a.text(r),n},"drawSimpleText"),kI=u1((t,e,r)=>{if(!t||(r=Object.assign({fontSize:12,fontWeight:400,fontFamily:"Arial",joinWith:"
"},r),lt.lineBreakRegex.test(t)))return t;let i=t.split(" ").filter(Boolean),n=[],a="";return i.forEach((s,l)=>{let u=Ra(`${s} `,r),h=Ra(a,r);if(u>e){let{hyphenatedStrings:p,remainingWord:m}=zFe(s,e,"-",r);n.push(a,...p),a=m}else h+u>=e?(n.push(a),a=s):a=[a,s].filter(Boolean).join(" ");l+1===i.length&&n.push(a)}),n.filter(s=>s!=="").join(r.joinWith)},(t,e,r)=>`${t}${e}${r.fontSize}${r.fontWeight}${r.fontFamily}${r.joinWith}`),zFe=u1((t,e,r="-",i)=>{i=Object.assign({fontSize:12,fontWeight:400,fontFamily:"Arial",margin:0},i);let n=[...t],a=[],s="";return n.forEach((l,u)=>{let h=`${s}${l}`;if(Ra(h,i)>=e){let d=u+1,p=n.length===d,m=`${h}${r}`;a.push(p?h:m),s=""}else s=h}),{hyphenatedStrings:a,remainingWord:s}},(t,e,r="-",i)=>`${t}${e}${r}${i.fontSize}${i.fontWeight}${i.fontFamily}`);o(H3,"calculateTextHeight");o(Ra,"calculateTextWidth");CI=u1((t,e)=>{let{fontSize:r=12,fontFamily:i="Arial",fontWeight:n=400}=e;if(!t)return{width:0,height:0};let[,a]=$s(r),s=["sans-serif",i],l=t.split(lt.lineBreakRegex),u=[],h=Ze("body");if(!h.remove)return{width:0,height:0,lineHeight:0};let f=h.append("svg");for(let p of s){let m=0,g={width:0,height:0,lineHeight:0};for(let y of l){let v=FFe();v.text=y||gI;let x=$Fe(f,v).style("font-size",a).style("font-weight",n).style("font-family",p),b=(x._groups||x)[0][0].getBBox();if(b.width===0&&b.height===0)throw new Error("svg element not in render tree");g.width=Math.round(Math.max(g.width,b.width)),m=Math.round(b.height),g.height+=m,g.lineHeight=Math.round(Math.max(g.lineHeight,m))}u.push(g)}f.remove();let d=isNaN(u[1].height)||isNaN(u[1].width)||isNaN(u[1].lineHeight)||u[0].height>u[1].height&&u[0].width>u[1].width&&u[0].lineHeight>u[1].lineHeight?0:1;return u[d]},(t,e)=>`${t}${e.fontSize}${e.fontWeight}${e.fontFamily}`),mI=class{constructor(e=!1,r){this.count=0;this.count=r?r.length:0,this.next=e?()=>this.count++:()=>Date.now()}static{o(this,"InitIDGenerator")}},GFe=o(function(t){return U3=U3||document.createElement("div"),t=escape(t).replace(/%26/g,"&").replace(/%23/g,"#").replace(/%3B/g,";"),U3.innerHTML=t,unescape(U3.textContent)},"entityDecode");o(wI,"isDetailedError");VFe=o((t,e,r,i)=>{if(!i)return;let n=t.node()?.getBBox();n&&t.append("text").text(i).attr("text-anchor","middle").attr("x",n.x+n.width/2).attr("y",-r).attr("class",e)},"insertTitle"),$s=o(t=>{if(typeof t=="number")return[t,t+"px"];let e=parseInt(t??"",10);return Number.isNaN(e)?[void 0,void 0]:t===String(e)?[e,t+"px"]:[e,t]},"parseFontSize");o(fi,"cleanAndMerge");Kt={assignWithDepth:Yi,wrapLabel:kI,calculateTextHeight:H3,calculateTextWidth:Ra,calculateTextDimensions:CI,cleanAndMerge:fi,detectInit:DFe,detectDirective:cne,isSubstringInArray:LFe,interpolateToCurve:yI,calcLabelPosition:MFe,calcCardinalityPosition:OFe,calcTerminalLabelPosition:PFe,formatUrl:RFe,getStylesFromArray:xI,generateId:bI,random:TI,runFunc:NFe,entityDecode:GFe,insertTitle:VFe,isLabelCoordinateInPath:qFe,parseFontSize:$s,InitIDGenerator:mI},fne=o(function(t){let e=t;return e=e.replace(/style.*:\S*#.*;/g,function(r){return r.substring(0,r.length-1)}),e=e.replace(/classDef.*:\S*#.*;/g,function(r){return r.substring(0,r.length-1)}),e=e.replace(/#\w+;/g,function(r){let i=r.substring(1,r.length-1);return/^\+?\d+$/.test(i)?"\uFB02\xB0\xB0"+i+"\xB6\xDF":"\uFB02\xB0"+i+"\xB6\xDF"}),e},"encodeEntities"),zs=o(function(t){return t.replace(/fl°°/g,"&#").replace(/fl°/g,"&").replace(/¶ß/g,";")},"decodeEntities"),Cu=o((t,e,{counter:r=0,prefix:i,suffix:n},a)=>a||`${i?`${i}_`:""}${t}_${e}_${r}${n?`_${n}`:""}`,"getEdgeId");o(xi,"handleUndefinedAttr");o(qFe,"isLabelCoordinateInPath")});function _c(t,e,r,i,n){if(!e[t].width)if(r)e[t].text=kI(e[t].text,n,i),e[t].textLines=e[t].text.split(lt.lineBreakRegex).length,e[t].width=n,e[t].height=H3(e[t].text,i);else{let a=e[t].text.split(lt.lineBreakRegex);e[t].textLines=a.length;let s=0;e[t].height=0,e[t].width=0;for(let l of a)e[t].width=Math.max(Ra(l,i),e[t].width),s=H3(l,i),e[t].height=e[t].height+s}}function yne(t,e,r,i,n){let a=new K3(n);a.data.widthLimit=r.data.widthLimit/Math.min(EI,i.length);for(let[s,l]of i.entries()){let u=0;l.image={width:0,height:0,Y:0},l.sprite&&(l.image.width=48,l.image.height=48,l.image.Y=u,u=l.image.Y+l.image.height);let h=l.wrap&&tr.wrap,f=Y3(tr);if(f.fontSize=f.fontSize+2,f.fontWeight="bold",_c("label",l,h,f,a.data.widthLimit),l.label.Y=u+8,u=l.label.Y+l.label.height,l.type&&l.type.text!==""){l.type.text="["+l.type.text+"]";let g=Y3(tr);_c("type",l,h,g,a.data.widthLimit),l.type.Y=u+5,u=l.type.Y+l.type.height}if(l.descr&&l.descr.text!==""){let g=Y3(tr);g.fontSize=g.fontSize-2,_c("descr",l,h,g,a.data.widthLimit),l.descr.Y=u+20,u=l.descr.Y+l.descr.height}if(s==0||s%EI===0){let g=r.data.startx+tr.diagramMarginX,y=r.data.stopy+tr.diagramMarginY+u;a.setData(g,g,y,y)}else{let g=a.data.stopx!==a.data.startx?a.data.stopx+tr.diagramMarginX:a.data.startx,y=a.data.starty;a.setData(g,g,y,y)}a.name=l.alias;let d=n.db.getC4ShapeArray(l.alias),p=n.db.getC4ShapeKeys(l.alias);p.length>0&&gne(a,t,d,p),e=l.alias;let m=n.db.getBoundaries(e);m.length>0&&yne(t,e,a,m,n),l.alias!=="global"&&mne(t,l,a),r.data.stopy=Math.max(a.data.stopy+tr.c4ShapeMargin,r.data.stopy),r.data.stopx=Math.max(a.data.stopx+tr.c4ShapeMargin,r.data.stopx),j3=Math.max(j3,r.data.stopx),X3=Math.max(X3,r.data.stopy)}}var j3,X3,pne,EI,tr,K3,SI,db,Y3,WFe,mne,gne,vo,dne,UFe,HFe,YFe,AI,vne=P(()=>{"use strict";Pr();dre();bt();uL();Vr();bL();Ut();kg();er();Xi();j3=0,X3=0,pne=4,EI=2;Jx.yy=a2;tr={},K3=class{static{o(this,"Bounds")}constructor(e){this.name="",this.data={},this.data.startx=void 0,this.data.stopx=void 0,this.data.starty=void 0,this.data.stopy=void 0,this.data.widthLimit=void 0,this.nextData={},this.nextData.startx=void 0,this.nextData.stopx=void 0,this.nextData.starty=void 0,this.nextData.stopy=void 0,this.nextData.cnt=0,SI(e.db.getConfig())}setData(e,r,i,n){this.nextData.startx=this.data.startx=e,this.nextData.stopx=this.data.stopx=r,this.nextData.starty=this.data.starty=i,this.nextData.stopy=this.data.stopy=n}updateVal(e,r,i,n){e[r]===void 0?e[r]=i:e[r]=n(i,e[r])}insert(e){this.nextData.cnt=this.nextData.cnt+1;let r=this.nextData.startx===this.nextData.stopx?this.nextData.stopx+e.margin:this.nextData.stopx+e.margin*2,i=r+e.width,n=this.nextData.starty+e.margin*2,a=n+e.height;(r>=this.data.widthLimit||i>=this.data.widthLimit||this.nextData.cnt>pne)&&(r=this.nextData.startx+e.margin+tr.nextLinePaddingX,n=this.nextData.stopy+e.margin*2,this.nextData.stopx=i=r+e.width,this.nextData.starty=this.nextData.stopy,this.nextData.stopy=a=n+e.height,this.nextData.cnt=1),e.x=r,e.y=n,this.updateVal(this.data,"startx",r,Math.min),this.updateVal(this.data,"starty",n,Math.min),this.updateVal(this.data,"stopx",i,Math.max),this.updateVal(this.data,"stopy",a,Math.max),this.updateVal(this.nextData,"startx",r,Math.min),this.updateVal(this.nextData,"starty",n,Math.min),this.updateVal(this.nextData,"stopx",i,Math.max),this.updateVal(this.nextData,"stopy",a,Math.max)}init(e){this.name="",this.data={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0,widthLimit:void 0},this.nextData={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0,cnt:0},SI(e.db.getConfig())}bumpLastMargin(e){this.data.stopx+=e,this.data.stopy+=e}},SI=o(function(t){Yi(tr,t),t.fontFamily&&(tr.personFontFamily=tr.systemFontFamily=tr.messageFontFamily=t.fontFamily),t.fontSize&&(tr.personFontSize=tr.systemFontSize=tr.messageFontSize=t.fontSize),t.fontWeight&&(tr.personFontWeight=tr.systemFontWeight=tr.messageFontWeight=t.fontWeight)},"setConf"),db=o((t,e)=>({fontFamily:t[e+"FontFamily"],fontSize:t[e+"FontSize"],fontWeight:t[e+"FontWeight"]}),"c4ShapeFont"),Y3=o(t=>({fontFamily:t.boundaryFontFamily,fontSize:t.boundaryFontSize,fontWeight:t.boundaryFontWeight}),"boundaryFont"),WFe=o(t=>({fontFamily:t.messageFontFamily,fontSize:t.messageFontSize,fontWeight:t.messageFontWeight}),"messageFont");o(_c,"calcC4ShapeTextWH");mne=o(function(t,e,r){e.x=r.data.startx,e.y=r.data.starty,e.width=r.data.stopx-r.data.startx,e.height=r.data.stopy-r.data.starty,e.label.y=tr.c4ShapeMargin-35;let i=e.wrap&&tr.wrap,n=Y3(tr);n.fontSize=n.fontSize+2,n.fontWeight="bold";let a=Ra(e.label.text,n);_c("label",e,i,n,a),Ec.drawBoundary(t,e,tr)},"drawBoundary"),gne=o(function(t,e,r,i){let n=0;for(let a of i){n=0;let s=r[a],l=db(tr,s.typeC4Shape.text);switch(l.fontSize=l.fontSize-2,s.typeC4Shape.width=Ra("\xAB"+s.typeC4Shape.text+"\xBB",l),s.typeC4Shape.height=l.fontSize+2,s.typeC4Shape.Y=tr.c4ShapePadding,n=s.typeC4Shape.Y+s.typeC4Shape.height-4,s.image={width:0,height:0,Y:0},s.typeC4Shape.text){case"person":case"external_person":s.image.width=48,s.image.height=48,s.image.Y=n,n=s.image.Y+s.image.height;break}s.sprite&&(s.image.width=48,s.image.height=48,s.image.Y=n,n=s.image.Y+s.image.height);let u=s.wrap&&tr.wrap,h=tr.width-tr.c4ShapePadding*2,f=db(tr,s.typeC4Shape.text);if(f.fontSize=f.fontSize+2,f.fontWeight="bold",_c("label",s,u,f,h),s.label.Y=n+8,n=s.label.Y+s.label.height,s.type&&s.type.text!==""){s.type.text="["+s.type.text+"]";let m=db(tr,s.typeC4Shape.text);_c("type",s,u,m,h),s.type.Y=n+5,n=s.type.Y+s.type.height}else if(s.techn&&s.techn.text!==""){s.techn.text="["+s.techn.text+"]";let m=db(tr,s.techn.text);_c("techn",s,u,m,h),s.techn.Y=n+5,n=s.techn.Y+s.techn.height}let d=n,p=s.label.width;if(s.descr&&s.descr.text!==""){let m=db(tr,s.typeC4Shape.text);_c("descr",s,u,m,h),s.descr.Y=n+20,n=s.descr.Y+s.descr.height,p=Math.max(s.label.width,s.descr.width),d=n-s.descr.textLines*5}p=p+tr.c4ShapePadding,s.width=Math.max(s.width||tr.width,p,tr.width),s.height=Math.max(s.height||tr.height,d,tr.height),s.margin=s.margin||tr.c4ShapeMargin,t.insert(s),Ec.drawC4Shape(e,s,tr)}t.bumpLastMargin(tr.c4ShapeMargin)},"drawC4ShapeArray"),vo=class{static{o(this,"Point")}constructor(e,r){this.x=e,this.y=r}},dne=o(function(t,e){let r=t.x,i=t.y,n=e.x,a=e.y,s=r+t.width/2,l=i+t.height/2,u=Math.abs(r-n),h=Math.abs(i-a),f=h/u,d=t.height/t.width,p=null;return i==a&&rn?p=new vo(r,l):r==n&&ia&&(p=new vo(s,i)),r>n&&i=f?p=new vo(r,l+f*t.width/2):p=new vo(s-u/h*t.height/2,i+t.height):r=f?p=new vo(r+t.width,l+f*t.width/2):p=new vo(s+u/h*t.height/2,i+t.height):ra?d>=f?p=new vo(r+t.width,l-f*t.width/2):p=new vo(s+t.height/2*u/h,i):r>n&&i>a&&(d>=f?p=new vo(r,l-t.width/2*f):p=new vo(s-t.height/2*u/h,i)),p},"getIntersectPoint"),UFe=o(function(t,e){let r={x:0,y:0};r.x=e.x+e.width/2,r.y=e.y+e.height/2;let i=dne(t,r);r.x=t.x+t.width/2,r.y=t.y+t.height/2;let n=dne(e,r);return{startPoint:i,endPoint:n}},"getIntersectPoints"),HFe=o(function(t,e,r,i,n){let a=0;for(let s of e){a=a+1;let l=s.wrap&&tr.wrap,u=WFe(tr);i.db.getC4Type()==="C4Dynamic"&&(s.label.text=a+": "+s.label.text);let f=Ra(s.label.text,u);_c("label",s,l,u,f),s.techn&&s.techn.text!==""&&(f=Ra(s.techn.text,u),_c("techn",s,l,u,f)),s.descr&&s.descr.text!==""&&(f=Ra(s.descr.text,u),_c("descr",s,l,u,f));let d=r(s.from),p=r(s.to),m=UFe(d,p);s.startPoint=m.startPoint,s.endPoint=m.endPoint}Ec.drawRels(t,e,tr,n)},"drawRels");o(yne,"drawInsideBoundary");YFe=o(function(t,e,r,i){tr=ge().c4;let n=ge().securityLevel,a;n==="sandbox"&&(a=Ze("#i"+e));let s=n==="sandbox"?Ze(a.nodes()[0].contentDocument.body):Ze("body"),l=i.db;i.db.setWrap(tr.wrap),pne=l.getC4ShapeInRow(),EI=l.getC4BoundaryInRow(),Q.debug(`C:${JSON.stringify(tr,null,2)}`);let u=n==="sandbox"?s.select(`[id="${e}"]`):Ze(`[id="${e}"]`);Ec.insertComputerIcon(u,e),Ec.insertDatabaseIcon(u,e),Ec.insertClockIcon(u,e);let h=new K3(i);h.setData(tr.diagramMarginX,tr.diagramMarginX,tr.diagramMarginY,tr.diagramMarginY),h.data.widthLimit=screen.availWidth,j3=tr.diagramMarginX,X3=tr.diagramMarginY;let f=i.db.getTitle(),d=i.db.getBoundaries("");yne(u,"",h,d,i),Ec.insertArrowHead(u,e),Ec.insertArrowEnd(u,e),Ec.insertArrowCrossHead(u,e),Ec.insertArrowFilledHead(u,e),HFe(u,i.db.getRels(),i.db.getC4Shape,i,e),h.data.stopx=j3,h.data.stopy=X3;let p=h.data,g=p.stopy-p.starty+2*tr.diagramMarginY,v=p.stopx-p.startx+2*tr.diagramMarginX;f&&u.append("text").text(f).attr("x",(p.stopx-p.startx)/2-4*tr.diagramMarginX).attr("y",p.starty+tr.diagramMarginY),Hr(u,g,v,tr.useMaxWidth);let x=f?60:0;u.attr("viewBox",p.startx-tr.diagramMarginX+" -"+(tr.diagramMarginY+x)+" "+v+" "+(g+x)),Q.debug("models:",p)},"draw"),AI={drawPersonOrSystemArray:gne,drawBoundary:mne,setConf:SI,draw:YFe}});var jFe,xne,bne=P(()=>{"use strict";jFe=o(t=>`.person { + stroke: ${t.personBorder}; + fill: ${t.personBkg}; + } +`,"getStyles"),xne=jFe});var Tne={};ur(Tne,{diagram:()=>XFe});var XFe,kne=P(()=>{"use strict";uL();bL();vne();bne();XFe={parser:YK,db:a2,renderer:AI,styles:xne,init:o(({c4:t,wrap:e})=>{AI.setConf(t),a2.setWrap(e)},"init")}});function $ne(t){return typeof t>"u"||t===null}function JFe(t){return typeof t=="object"&&t!==null}function e$e(t){return Array.isArray(t)?t:$ne(t)?[]:[t]}function t$e(t,e){var r,i,n,a;if(e)for(a=Object.keys(e),r=0,i=a.length;rl&&(a=" ... ",e=i-l+a.length),r-i>l&&(s=" ...",r=i+l-s.length),{str:a+t.slice(e,r).replace(/\t/g,"\u2192")+s,pos:i-e+a.length}}function DI(t,e){return ha.repeat(" ",e-t.length)+t}function u$e(t,e){if(e=Object.create(e||null),!t.buffer)return null;e.maxLength||(e.maxLength=79),typeof e.indent!="number"&&(e.indent=1),typeof e.linesBefore!="number"&&(e.linesBefore=3),typeof e.linesAfter!="number"&&(e.linesAfter=2);for(var r=/\r?\n|\r|\0/g,i=[0],n=[],a,s=-1;a=r.exec(t.buffer);)n.push(a.index),i.push(a.index+a[0].length),t.position<=a.index&&s<0&&(s=i.length-2);s<0&&(s=i.length-1);var l="",u,h,f=Math.min(t.line+e.linesAfter,n.length).toString().length,d=e.maxLength-(e.indent+f+3);for(u=1;u<=e.linesBefore&&!(s-u<0);u++)h=_I(t.buffer,i[s-u],n[s-u],t.position-(i[s]-i[s-u]),d),l=ha.repeat(" ",e.indent)+DI((t.line-u+1).toString(),f)+" | "+h.str+` +`+l;for(h=_I(t.buffer,i[s],n[s],t.position,d),l+=ha.repeat(" ",e.indent)+DI((t.line+1).toString(),f)+" | "+h.str+` +`,l+=ha.repeat("-",e.indent+f+3+h.pos)+`^ +`,u=1;u<=e.linesAfter&&!(s+u>=n.length);u++)h=_I(t.buffer,i[s+u],n[s+u],t.position-(i[s]-i[s+u]),d),l+=ha.repeat(" ",e.indent)+DI((t.line+u+1).toString(),f)+" | "+h.str+` +`;return l.replace(/\n$/,"")}function p$e(t){var e={};return t!==null&&Object.keys(t).forEach(function(r){t[r].forEach(function(i){e[String(i)]=r})}),e}function m$e(t,e){if(e=e||{},Object.keys(e).forEach(function(r){if(f$e.indexOf(r)===-1)throw new xo('Unknown option "'+r+'" is met in definition of "'+t+'" YAML type.')}),this.options=e,this.tag=t,this.kind=e.kind||null,this.resolve=e.resolve||function(){return!0},this.construct=e.construct||function(r){return r},this.instanceOf=e.instanceOf||null,this.predicate=e.predicate||null,this.represent=e.represent||null,this.representName=e.representName||null,this.defaultStyle=e.defaultStyle||null,this.multi=e.multi||!1,this.styleAliases=p$e(e.styleAliases||null),d$e.indexOf(this.kind)===-1)throw new xo('Unknown kind "'+this.kind+'" is specified for "'+t+'" YAML type.')}function wne(t,e){var r=[];return t[e].forEach(function(i){var n=r.length;r.forEach(function(a,s){a.tag===i.tag&&a.kind===i.kind&&a.multi===i.multi&&(n=s)}),r[n]=i}),r}function g$e(){var t={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}},e,r;function i(n){n.multi?(t.multi[n.kind].push(n),t.multi.fallback.push(n)):t[n.kind][n.tag]=t.fallback[n.tag]=n}for(o(i,"collectType"),e=0,r=arguments.length;e=0&&(e=e.slice(1)),e===".inf"?r===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:e===".nan"?NaN:r*parseFloat(e,10)}function G$e(t,e){var r;if(isNaN(t))switch(e){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===t)switch(e){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===t)switch(e){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(ha.isNegativeZero(t))return"-0.0";return r=t.toString(10),z$e.test(r)?r.replace("e",".e"):r}function V$e(t){return Object.prototype.toString.call(t)==="[object Number]"&&(t%1!==0||ha.isNegativeZero(t))}function U$e(t){return t===null?!1:Vne.exec(t)!==null||qne.exec(t)!==null}function H$e(t){var e,r,i,n,a,s,l,u=0,h=null,f,d,p;if(e=Vne.exec(t),e===null&&(e=qne.exec(t)),e===null)throw new Error("Date resolve error");if(r=+e[1],i=+e[2]-1,n=+e[3],!e[4])return new Date(Date.UTC(r,i,n));if(a=+e[4],s=+e[5],l=+e[6],e[7]){for(u=e[7].slice(0,3);u.length<3;)u+="0";u=+u}return e[9]&&(f=+e[10],d=+(e[11]||0),h=(f*60+d)*6e4,e[9]==="-"&&(h=-h)),p=new Date(Date.UTC(r,i,n,a,s,l,u)),h&&p.setTime(p.getTime()-h),p}function Y$e(t){return t.toISOString()}function X$e(t){return t==="<<"||t===null}function Q$e(t){if(t===null)return!1;var e,r,i=0,n=t.length,a=PI;for(r=0;r64)){if(e<0)return!1;i+=6}return i%8===0}function Z$e(t){var e,r,i=t.replace(/[\r\n=]/g,""),n=i.length,a=PI,s=0,l=[];for(e=0;e>16&255),l.push(s>>8&255),l.push(s&255)),s=s<<6|a.indexOf(i.charAt(e));return r=n%4*6,r===0?(l.push(s>>16&255),l.push(s>>8&255),l.push(s&255)):r===18?(l.push(s>>10&255),l.push(s>>2&255)):r===12&&l.push(s>>4&255),new Uint8Array(l)}function J$e(t){var e="",r=0,i,n,a=t.length,s=PI;for(i=0;i>18&63],e+=s[r>>12&63],e+=s[r>>6&63],e+=s[r&63]),r=(r<<8)+t[i];return n=a%3,n===0?(e+=s[r>>18&63],e+=s[r>>12&63],e+=s[r>>6&63],e+=s[r&63]):n===2?(e+=s[r>>10&63],e+=s[r>>4&63],e+=s[r<<2&63],e+=s[64]):n===1&&(e+=s[r>>2&63],e+=s[r<<4&63],e+=s[64],e+=s[64]),e}function eze(t){return Object.prototype.toString.call(t)==="[object Uint8Array]"}function nze(t){if(t===null)return!0;var e=[],r,i,n,a,s,l=t;for(r=0,i=l.length;r>10)+55296,(t-65536&1023)+56320)}function Xne(t,e,r){e==="__proto__"?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,writable:!0,value:r}):t[e]=r}function Cze(t,e){this.input=t,this.filename=e.filename||null,this.schema=e.schema||Wne,this.onWarning=e.onWarning||null,this.legacy=e.legacy||!1,this.json=e.json||!1,this.listener=e.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=t.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.firstTabInLine=-1,this.documents=[]}function Zne(t,e){var r={name:t.filename,buffer:t.input.slice(0,-1),position:t.position,line:t.line,column:t.position-t.lineStart};return r.snippet=h$e(r),new xo(e,r)}function or(t,e){throw Zne(t,e)}function J3(t,e){t.onWarning&&t.onWarning.call(null,Zne(t,e))}function od(t,e,r,i){var n,a,s,l;if(e1&&(t.result+=ha.repeat(` +`,e-1))}function wze(t,e,r){var i,n,a,s,l,u,h,f,d=t.kind,p=t.result,m;if(m=t.input.charCodeAt(t.position),bo(m)||E1(m)||m===35||m===38||m===42||m===33||m===124||m===62||m===39||m===34||m===37||m===64||m===96||(m===63||m===45)&&(n=t.input.charCodeAt(t.position+1),bo(n)||r&&E1(n)))return!1;for(t.kind="scalar",t.result="",a=s=t.position,l=!1;m!==0;){if(m===58){if(n=t.input.charCodeAt(t.position+1),bo(n)||r&&E1(n))break}else if(m===35){if(i=t.input.charCodeAt(t.position-1),bo(i))break}else{if(t.position===t.lineStart&&r5(t)||r&&E1(m))break;if(wu(m))if(u=t.line,h=t.lineStart,f=t.lineIndent,Zn(t,!1,-1),t.lineIndent>=e){l=!0,m=t.input.charCodeAt(t.position);continue}else{t.position=s,t.line=u,t.lineStart=h,t.lineIndent=f;break}}l&&(od(t,a,s,!1),FI(t,t.line-u),a=s=t.position,l=!1),S0(m)||(s=t.position+1),m=t.input.charCodeAt(++t.position)}return od(t,a,s,!1),t.result?!0:(t.kind=d,t.result=p,!1)}function Eze(t,e){var r,i,n;if(r=t.input.charCodeAt(t.position),r!==39)return!1;for(t.kind="scalar",t.result="",t.position++,i=n=t.position;(r=t.input.charCodeAt(t.position))!==0;)if(r===39)if(od(t,i,t.position,!0),r=t.input.charCodeAt(++t.position),r===39)i=t.position,t.position++,n=t.position;else return!0;else wu(r)?(od(t,i,n,!0),FI(t,Zn(t,!1,e)),i=n=t.position):t.position===t.lineStart&&r5(t)?or(t,"unexpected end of the document within a single quoted scalar"):(t.position++,n=t.position);or(t,"unexpected end of the stream within a single quoted scalar")}function Sze(t,e){var r,i,n,a,s,l;if(l=t.input.charCodeAt(t.position),l!==34)return!1;for(t.kind="scalar",t.result="",t.position++,r=i=t.position;(l=t.input.charCodeAt(t.position))!==0;){if(l===34)return od(t,r,t.position,!0),t.position++,!0;if(l===92){if(od(t,r,t.position,!0),l=t.input.charCodeAt(++t.position),wu(l))Zn(t,!1,e);else if(l<256&&Kne[l])t.result+=Qne[l],t.position++;else if((s=bze(l))>0){for(n=s,a=0;n>0;n--)l=t.input.charCodeAt(++t.position),(s=xze(l))>=0?a=(a<<4)+s:or(t,"expected hexadecimal character");t.result+=kze(a),t.position++}else or(t,"unknown escape sequence");r=i=t.position}else wu(l)?(od(t,r,i,!0),FI(t,Zn(t,!1,e)),r=i=t.position):t.position===t.lineStart&&r5(t)?or(t,"unexpected end of the document within a double quoted scalar"):(t.position++,i=t.position)}or(t,"unexpected end of the stream within a double quoted scalar")}function Aze(t,e){var r=!0,i,n,a,s=t.tag,l,u=t.anchor,h,f,d,p,m,g=Object.create(null),y,v,x,b;if(b=t.input.charCodeAt(t.position),b===91)f=93,m=!1,l=[];else if(b===123)f=125,m=!0,l={};else return!1;for(t.anchor!==null&&(t.anchorMap[t.anchor]=l),b=t.input.charCodeAt(++t.position);b!==0;){if(Zn(t,!0,e),b=t.input.charCodeAt(t.position),b===f)return t.position++,t.tag=s,t.anchor=u,t.kind=m?"mapping":"sequence",t.result=l,!0;r?b===44&&or(t,"expected the node content, but found ','"):or(t,"missed comma between flow collection entries"),v=y=x=null,d=p=!1,b===63&&(h=t.input.charCodeAt(t.position+1),bo(h)&&(d=p=!0,t.position++,Zn(t,!0,e))),i=t.line,n=t.lineStart,a=t.position,A1(t,e,Q3,!1,!0),v=t.tag,y=t.result,Zn(t,!0,e),b=t.input.charCodeAt(t.position),(p||t.line===i)&&b===58&&(d=!0,b=t.input.charCodeAt(++t.position),Zn(t,!0,e),A1(t,e,Q3,!1,!0),x=t.result),m?S1(t,l,g,v,y,x,i,n,a):d?l.push(S1(t,null,g,v,y,x,i,n,a)):l.push(y),Zn(t,!0,e),b=t.input.charCodeAt(t.position),b===44?(r=!0,b=t.input.charCodeAt(++t.position)):r=!1}or(t,"unexpected end of the stream within a flow collection")}function _ze(t,e){var r,i,n=LI,a=!1,s=!1,l=e,u=0,h=!1,f,d;if(d=t.input.charCodeAt(t.position),d===124)i=!1;else if(d===62)i=!0;else return!1;for(t.kind="scalar",t.result="";d!==0;)if(d=t.input.charCodeAt(++t.position),d===43||d===45)LI===n?n=d===43?Ene:mze:or(t,"repeat of a chomping mode identifier");else if((f=Tze(d))>=0)f===0?or(t,"bad explicit indentation width of a block scalar; it cannot be less than one"):s?or(t,"repeat of an indentation width identifier"):(l=e+f-1,s=!0);else break;if(S0(d)){do d=t.input.charCodeAt(++t.position);while(S0(d));if(d===35)do d=t.input.charCodeAt(++t.position);while(!wu(d)&&d!==0)}for(;d!==0;){for(BI(t),t.lineIndent=0,d=t.input.charCodeAt(t.position);(!s||t.lineIndentl&&(l=t.lineIndent),wu(d)){u++;continue}if(t.lineIndente)&&u!==0)or(t,"bad indentation of a sequence entry");else if(t.lineIndente)&&(v&&(s=t.line,l=t.lineStart,u=t.position),A1(t,e,Z3,!0,n)&&(v?g=t.result:y=t.result),v||(S1(t,d,p,m,g,y,s,l,u),m=g=y=null),Zn(t,!0,-1),b=t.input.charCodeAt(t.position)),(t.line===a||t.lineIndent>e)&&b!==0)or(t,"bad indentation of a mapping entry");else if(t.lineIndente?u=1:t.lineIndent===e?u=0:t.lineIndente?u=1:t.lineIndent===e?u=0:t.lineIndent tag; it should be "scalar", not "'+t.kind+'"'),d=0,p=t.implicitTypes.length;d"),t.result!==null&&g.kind!==t.kind&&or(t,"unacceptable node kind for !<"+t.tag+'> tag; it should be "'+g.kind+'", not "'+t.kind+'"'),g.resolve(t.result,t.tag)?(t.result=g.construct(t.result,t.tag),t.anchor!==null&&(t.anchorMap[t.anchor]=t.result)):or(t,"cannot resolve a node with !<"+t.tag+"> explicit tag")}return t.listener!==null&&t.listener("close",t),t.tag!==null||t.anchor!==null||f}function Ize(t){var e=t.position,r,i,n,a=!1,s;for(t.version=null,t.checkLineBreaks=t.legacy,t.tagMap=Object.create(null),t.anchorMap=Object.create(null);(s=t.input.charCodeAt(t.position))!==0&&(Zn(t,!0,-1),s=t.input.charCodeAt(t.position),!(t.lineIndent>0||s!==37));){for(a=!0,s=t.input.charCodeAt(++t.position),r=t.position;s!==0&&!bo(s);)s=t.input.charCodeAt(++t.position);for(i=t.input.slice(r,t.position),n=[],i.length<1&&or(t,"directive name must not be less than one character in length");s!==0;){for(;S0(s);)s=t.input.charCodeAt(++t.position);if(s===35){do s=t.input.charCodeAt(++t.position);while(s!==0&&!wu(s));break}if(wu(s))break;for(r=t.position;s!==0&&!bo(s);)s=t.input.charCodeAt(++t.position);n.push(t.input.slice(r,t.position))}s!==0&&BI(t),ld.call(_ne,i)?_ne[i](t,i,n):J3(t,'unknown document directive "'+i+'"')}if(Zn(t,!0,-1),t.lineIndent===0&&t.input.charCodeAt(t.position)===45&&t.input.charCodeAt(t.position+1)===45&&t.input.charCodeAt(t.position+2)===45?(t.position+=3,Zn(t,!0,-1)):a&&or(t,"directives end mark is expected"),A1(t,t.lineIndent-1,Z3,!1,!0),Zn(t,!0,-1),t.checkLineBreaks&&yze.test(t.input.slice(e,t.position))&&J3(t,"non-ASCII line breaks are interpreted as content"),t.documents.push(t.result),t.position===t.lineStart&&r5(t)){t.input.charCodeAt(t.position)===46&&(t.position+=3,Zn(t,!0,-1));return}if(t.position"u"&&(r=e,e=null);var i=Jne(t,r);if(typeof e!="function")return i;for(var n=0,a=i.length;n=55296&&r<=56319&&e+1=56320&&i<=57343)?(r-55296)*1024+i-56320+65536:r}function lae(t){var e=/^\n* /;return e.test(t)}function cGe(t,e,r,i,n,a,s,l){var u,h=0,f=null,d=!1,p=!1,m=i!==-1,g=-1,y=oGe(pb(t,0))&&lGe(pb(t,t.length-1));if(e||s)for(u=0;u=65536?u+=2:u++){if(h=pb(t,u),!vb(h))return w1;y=y&&Ine(h,f,l),f=h}else{for(u=0;u=65536?u+=2:u++){if(h=pb(t,u),h===gb)d=!0,m&&(p=p||u-g-1>i&&t[g+1]!==" ",g=u);else if(!vb(h))return w1;y=y&&Ine(h,f,l),f=h}p=p||m&&u-g-1>i&&t[g+1]!==" "}return!d&&!p?y&&!s&&!n(t)?cae:a===yb?w1:MI:r>9&&lae(t)?w1:s?a===yb?w1:MI:p?hae:uae}function uGe(t,e,r,i,n){t.dump=(function(){if(e.length===0)return t.quotingType===yb?'""':"''";if(!t.noCompatMode&&(eGe.indexOf(e)!==-1||tGe.test(e)))return t.quotingType===yb?'"'+e+'"':"'"+e+"'";var a=t.indent*Math.max(1,r),s=t.lineWidth===-1?-1:Math.max(Math.min(t.lineWidth,40),t.lineWidth-a),l=i||t.flowLevel>-1&&r>=t.flowLevel;function u(h){return sGe(t,h)}switch(o(u,"testAmbiguity"),cGe(e,l,t.indent,s,u,t.quotingType,t.forceQuotes&&!i,n)){case cae:return e;case MI:return"'"+e.replace(/'/g,"''")+"'";case uae:return"|"+Mne(e,t.indent)+One(Rne(e,a));case hae:return">"+Mne(e,t.indent)+One(Rne(hGe(e,s),a));case w1:return'"'+fGe(e)+'"';default:throw new xo("impossible error: invalid scalar style")}})()}function Mne(t,e){var r=lae(t)?String(e):"",i=t[t.length-1]===` +`,n=i&&(t[t.length-2]===` +`||t===` +`),a=n?"+":i?"":"-";return r+a+` +`}function One(t){return t[t.length-1]===` +`?t.slice(0,-1):t}function hGe(t,e){for(var r=/(\n+)([^\n]*)/g,i=(function(){var h=t.indexOf(` +`);return h=h!==-1?h:t.length,r.lastIndex=h,Pne(t.slice(0,h),e)})(),n=t[0]===` +`||t[0]===" ",a,s;s=r.exec(t);){var l=s[1],u=s[2];a=u[0]===" ",i+=l+(!n&&!a&&u!==""?` +`:"")+Pne(u,e),n=a}return i}function Pne(t,e){if(t===""||t[0]===" ")return t;for(var r=/ [^ ]/g,i,n=0,a,s=0,l=0,u="";i=r.exec(t);)l=i.index,l-n>e&&(a=s>n?s:l,u+=` +`+t.slice(n,a),n=a+1),s=l;return u+=` +`,t.length-n>e&&s>n?u+=t.slice(n,s)+` +`+t.slice(s+1):u+=t.slice(n),u.slice(1)}function fGe(t){for(var e="",r=0,i,n=0;n=65536?n+=2:n++)r=pb(t,n),i=fs[r],!i&&vb(r)?(e+=t[n],r>=65536&&(e+=t[n+1])):e+=i||iGe(r);return e}function dGe(t,e,r){var i="",n=t.tag,a,s,l;for(a=0,s=r.length;a"u"&&$h(t,e,null,!1,!1))&&(i!==""&&(i+=","+(t.condenseFlow?"":" ")),i+=t.dump);t.tag=n,t.dump="["+i+"]"}function Bne(t,e,r,i){var n="",a=t.tag,s,l,u;for(s=0,l=r.length;s"u"&&$h(t,e+1,null,!0,!0,!1,!0))&&((!i||n!=="")&&(n+=II(t,e)),t.dump&&gb===t.dump.charCodeAt(0)?n+="-":n+="- ",n+=t.dump);t.tag=a,t.dump=n||"[]"}function pGe(t,e,r){var i="",n=t.tag,a=Object.keys(r),s,l,u,h,f;for(s=0,l=a.length;s1024&&(f+="? "),f+=t.dump+(t.condenseFlow?'"':"")+":"+(t.condenseFlow?"":" "),$h(t,e,h,!1,!1)&&(f+=t.dump,i+=f));t.tag=n,t.dump="{"+i+"}"}function mGe(t,e,r,i){var n="",a=t.tag,s=Object.keys(r),l,u,h,f,d,p;if(t.sortKeys===!0)s.sort();else if(typeof t.sortKeys=="function")s.sort(t.sortKeys);else if(t.sortKeys)throw new xo("sortKeys must be a boolean or a function");for(l=0,u=s.length;l1024,d&&(t.dump&&gb===t.dump.charCodeAt(0)?p+="?":p+="? "),p+=t.dump,d&&(p+=II(t,e)),$h(t,e+1,f,!0,d)&&(t.dump&&gb===t.dump.charCodeAt(0)?p+=":":p+=": ",p+=t.dump,n+=p));t.tag=a,t.dump=n||"{}"}function Fne(t,e,r){var i,n,a,s,l,u;for(n=r?t.explicitTypes:t.implicitTypes,a=0,s=n.length;a tag resolver accepts not "'+u+'" style');t.dump=i}return!0}return!1}function $h(t,e,r,i,n,a,s){t.tag=null,t.dump=r,Fne(t,r,!1)||Fne(t,r,!0);var l=tae.call(t.dump),u=i,h;i&&(i=t.flowLevel<0||t.flowLevel>e);var f=l==="[object Object]"||l==="[object Array]",d,p;if(f&&(d=t.duplicates.indexOf(r),p=d!==-1),(t.tag!==null&&t.tag!=="?"||p||t.indent!==2&&e>0)&&(n=!1),p&&t.usedDuplicates[d])t.dump="*ref_"+d;else{if(f&&p&&!t.usedDuplicates[d]&&(t.usedDuplicates[d]=!0),l==="[object Object]")i&&Object.keys(t.dump).length!==0?(mGe(t,e,t.dump,n),p&&(t.dump="&ref_"+d+t.dump)):(pGe(t,e,t.dump),p&&(t.dump="&ref_"+d+" "+t.dump));else if(l==="[object Array]")i&&t.dump.length!==0?(t.noArrayIndent&&!s&&e>0?Bne(t,e-1,t.dump,n):Bne(t,e,t.dump,n),p&&(t.dump="&ref_"+d+t.dump)):(dGe(t,e,t.dump),p&&(t.dump="&ref_"+d+" "+t.dump));else if(l==="[object String]")t.tag!=="?"&&uGe(t,t.dump,e,a,u);else{if(l==="[object Undefined]")return!1;if(t.skipInvalid)return!1;throw new xo("unacceptable kind of an object to dump "+l)}t.tag!==null&&t.tag!=="?"&&(h=encodeURI(t.tag[0]==="!"?t.tag.slice(1):t.tag).replace(/!/g,"%21"),t.tag[0]==="!"?h="!"+h:h.slice(0,18)==="tag:yaml.org,2002:"?h="!!"+h.slice(18):h="!<"+h+">",t.dump=h+" "+t.dump)}return!0}function gGe(t,e){var r=[],i=[],n,a;for(OI(t,r,i),n=0,a=i.length;n{"use strict";o($ne,"isNothing");o(JFe,"isObject");o(e$e,"toArray");o(t$e,"extend");o(r$e,"repeat");o(i$e,"isNegativeZero");n$e=$ne,a$e=JFe,s$e=e$e,o$e=r$e,l$e=i$e,c$e=t$e,ha={isNothing:n$e,isObject:a$e,toArray:s$e,repeat:o$e,isNegativeZero:l$e,extend:c$e};o(zne,"formatError");o(mb,"YAMLException$1");mb.prototype=Object.create(Error.prototype);mb.prototype.constructor=mb;mb.prototype.toString=o(function(e){return this.name+": "+zne(this,e)},"toString");xo=mb;o(_I,"getLine");o(DI,"padStart");o(u$e,"makeSnippet");h$e=u$e,f$e=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],d$e=["scalar","sequence","mapping"];o(p$e,"compileStyleAliases");o(m$e,"Type$1");hs=m$e;o(wne,"compileList");o(g$e,"compileMap");o(RI,"Schema$1");RI.prototype.extend=o(function(e){var r=[],i=[];if(e instanceof hs)i.push(e);else if(Array.isArray(e))i=i.concat(e);else if(e&&(Array.isArray(e.implicit)||Array.isArray(e.explicit)))e.implicit&&(r=r.concat(e.implicit)),e.explicit&&(i=i.concat(e.explicit));else throw new xo("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");r.forEach(function(a){if(!(a instanceof hs))throw new xo("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(a.loadKind&&a.loadKind!=="scalar")throw new xo("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(a.multi)throw new xo("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),i.forEach(function(a){if(!(a instanceof hs))throw new xo("Specified list of YAML types (or a single Type object) contains a non-Type object.")});var n=Object.create(RI.prototype);return n.implicit=(this.implicit||[]).concat(r),n.explicit=(this.explicit||[]).concat(i),n.compiledImplicit=wne(n,"implicit"),n.compiledExplicit=wne(n,"explicit"),n.compiledTypeMap=g$e(n.compiledImplicit,n.compiledExplicit),n},"extend");y$e=RI,v$e=new hs("tag:yaml.org,2002:str",{kind:"scalar",construct:o(function(t){return t!==null?t:""},"construct")}),x$e=new hs("tag:yaml.org,2002:seq",{kind:"sequence",construct:o(function(t){return t!==null?t:[]},"construct")}),b$e=new hs("tag:yaml.org,2002:map",{kind:"mapping",construct:o(function(t){return t!==null?t:{}},"construct")}),T$e=new y$e({explicit:[v$e,x$e,b$e]});o(k$e,"resolveYamlNull");o(C$e,"constructYamlNull");o(w$e,"isNull");E$e=new hs("tag:yaml.org,2002:null",{kind:"scalar",resolve:k$e,construct:C$e,predicate:w$e,represent:{canonical:o(function(){return"~"},"canonical"),lowercase:o(function(){return"null"},"lowercase"),uppercase:o(function(){return"NULL"},"uppercase"),camelcase:o(function(){return"Null"},"camelcase"),empty:o(function(){return""},"empty")},defaultStyle:"lowercase"});o(S$e,"resolveYamlBoolean");o(A$e,"constructYamlBoolean");o(_$e,"isBoolean");D$e=new hs("tag:yaml.org,2002:bool",{kind:"scalar",resolve:S$e,construct:A$e,predicate:_$e,represent:{lowercase:o(function(t){return t?"true":"false"},"lowercase"),uppercase:o(function(t){return t?"TRUE":"FALSE"},"uppercase"),camelcase:o(function(t){return t?"True":"False"},"camelcase")},defaultStyle:"lowercase"});o(L$e,"isHexCode");o(R$e,"isOctCode");o(N$e,"isDecCode");o(I$e,"resolveYamlInteger");o(M$e,"constructYamlInteger");o(O$e,"isInteger");P$e=new hs("tag:yaml.org,2002:int",{kind:"scalar",resolve:I$e,construct:M$e,predicate:O$e,represent:{binary:o(function(t){return t>=0?"0b"+t.toString(2):"-0b"+t.toString(2).slice(1)},"binary"),octal:o(function(t){return t>=0?"0o"+t.toString(8):"-0o"+t.toString(8).slice(1)},"octal"),decimal:o(function(t){return t.toString(10)},"decimal"),hexadecimal:o(function(t){return t>=0?"0x"+t.toString(16).toUpperCase():"-0x"+t.toString(16).toUpperCase().slice(1)},"hexadecimal")},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),B$e=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");o(F$e,"resolveYamlFloat");o($$e,"constructYamlFloat");z$e=/^[-+]?[0-9]+e/;o(G$e,"representYamlFloat");o(V$e,"isFloat");q$e=new hs("tag:yaml.org,2002:float",{kind:"scalar",resolve:F$e,construct:$$e,predicate:V$e,represent:G$e,defaultStyle:"lowercase"}),Gne=T$e.extend({implicit:[E$e,D$e,P$e,q$e]}),W$e=Gne,Vne=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),qne=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");o(U$e,"resolveYamlTimestamp");o(H$e,"constructYamlTimestamp");o(Y$e,"representYamlTimestamp");j$e=new hs("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:U$e,construct:H$e,instanceOf:Date,represent:Y$e});o(X$e,"resolveYamlMerge");K$e=new hs("tag:yaml.org,2002:merge",{kind:"scalar",resolve:X$e}),PI=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/= +\r`;o(Q$e,"resolveYamlBinary");o(Z$e,"constructYamlBinary");o(J$e,"representYamlBinary");o(eze,"isBinary");tze=new hs("tag:yaml.org,2002:binary",{kind:"scalar",resolve:Q$e,construct:Z$e,predicate:eze,represent:J$e}),rze=Object.prototype.hasOwnProperty,ize=Object.prototype.toString;o(nze,"resolveYamlOmap");o(aze,"constructYamlOmap");sze=new hs("tag:yaml.org,2002:omap",{kind:"sequence",resolve:nze,construct:aze}),oze=Object.prototype.toString;o(lze,"resolveYamlPairs");o(cze,"constructYamlPairs");uze=new hs("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:lze,construct:cze}),hze=Object.prototype.hasOwnProperty;o(fze,"resolveYamlSet");o(dze,"constructYamlSet");pze=new hs("tag:yaml.org,2002:set",{kind:"mapping",resolve:fze,construct:dze}),Wne=W$e.extend({implicit:[j$e,K$e],explicit:[tze,sze,uze,pze]}),ld=Object.prototype.hasOwnProperty,Q3=1,Une=2,Hne=3,Z3=4,LI=1,mze=2,Ene=3,gze=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,yze=/[\x85\u2028\u2029]/,vze=/[,\[\]\{\}]/,Yne=/^(?:!|!!|![a-z\-]+!)$/i,jne=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;o(Sne,"_class");o(wu,"is_EOL");o(S0,"is_WHITE_SPACE");o(bo,"is_WS_OR_EOL");o(E1,"is_FLOW_INDICATOR");o(xze,"fromHexCode");o(bze,"escapedHexLen");o(Tze,"fromDecimalCode");o(Ane,"simpleEscapeSequence");o(kze,"charFromCodepoint");o(Xne,"setProperty");Kne=new Array(256),Qne=new Array(256);for(E0=0;E0<256;E0++)Kne[E0]=Ane(E0)?1:0,Qne[E0]=Ane(E0);o(Cze,"State$1");o(Zne,"generateError");o(or,"throwError");o(J3,"throwWarning");_ne={YAML:o(function(e,r,i){var n,a,s;e.version!==null&&or(e,"duplication of %YAML directive"),i.length!==1&&or(e,"YAML directive accepts exactly one argument"),n=/^([0-9]+)\.([0-9]+)$/.exec(i[0]),n===null&&or(e,"ill-formed argument of the YAML directive"),a=parseInt(n[1],10),s=parseInt(n[2],10),a!==1&&or(e,"unacceptable YAML version of the document"),e.version=i[0],e.checkLineBreaks=s<2,s!==1&&s!==2&&J3(e,"unsupported YAML version of the document")},"handleYamlDirective"),TAG:o(function(e,r,i){var n,a;i.length!==2&&or(e,"TAG directive accepts exactly two arguments"),n=i[0],a=i[1],Yne.test(n)||or(e,"ill-formed tag handle (first argument) of the TAG directive"),ld.call(e.tagMap,n)&&or(e,'there is a previously declared suffix for "'+n+'" tag handle'),jne.test(a)||or(e,"ill-formed tag prefix (second argument) of the TAG directive");try{a=decodeURIComponent(a)}catch{or(e,"tag prefix is malformed: "+a)}e.tagMap[n]=a},"handleTagDirective")};o(od,"captureSegment");o(Dne,"mergeMappings");o(S1,"storeMappingPair");o(BI,"readLineBreak");o(Zn,"skipSeparationSpace");o(r5,"testDocumentSeparator");o(FI,"writeFoldedLines");o(wze,"readPlainScalar");o(Eze,"readSingleQuotedScalar");o(Sze,"readDoubleQuotedScalar");o(Aze,"readFlowCollection");o(_ze,"readBlockScalar");o(Lne,"readBlockSequence");o(Dze,"readBlockMapping");o(Lze,"readTagProperty");o(Rze,"readAnchorProperty");o(Nze,"readAlias");o(A1,"composeNode");o(Ize,"readDocument");o(Jne,"loadDocuments");o(Mze,"loadAll$1");o(Oze,"load$1");Pze=Mze,Bze=Oze,eae={loadAll:Pze,load:Bze},tae=Object.prototype.toString,rae=Object.prototype.hasOwnProperty,$I=65279,Fze=9,gb=10,$ze=13,zze=32,Gze=33,Vze=34,NI=35,qze=37,Wze=38,Uze=39,Hze=42,iae=44,Yze=45,e5=58,jze=61,Xze=62,Kze=63,Qze=64,nae=91,aae=93,Zze=96,sae=123,Jze=124,oae=125,fs={};fs[0]="\\0";fs[7]="\\a";fs[8]="\\b";fs[9]="\\t";fs[10]="\\n";fs[11]="\\v";fs[12]="\\f";fs[13]="\\r";fs[27]="\\e";fs[34]='\\"';fs[92]="\\\\";fs[133]="\\N";fs[160]="\\_";fs[8232]="\\L";fs[8233]="\\P";eGe=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],tGe=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;o(rGe,"compileStyleMap");o(iGe,"encodeHex");nGe=1,yb=2;o(aGe,"State");o(Rne,"indentString");o(II,"generateNextLine");o(sGe,"testImplicitResolving");o(t5,"isWhitespace");o(vb,"isPrintable");o(Nne,"isNsCharOrWhitespace");o(Ine,"isPlainSafe");o(oGe,"isPlainSafeFirst");o(lGe,"isPlainSafeLast");o(pb,"codePointAt");o(lae,"needIndentIndicator");cae=1,MI=2,uae=3,hae=4,w1=5;o(cGe,"chooseScalarStyle");o(uGe,"writeScalar");o(Mne,"blockHeader");o(One,"dropEndingNewline");o(hGe,"foldString");o(Pne,"foldLine");o(fGe,"escapeString");o(dGe,"writeFlowSequence");o(Bne,"writeBlockSequence");o(pGe,"writeFlowMapping");o(mGe,"writeBlockMapping");o(Fne,"detectType");o($h,"writeNode");o(gGe,"getDuplicateReferences");o(OI,"inspectNode");o(yGe,"dump$1");vGe=yGe,xGe={dump:vGe};o(zI,"renamed");cd=Gne,ud=eae.load,eFt=eae.loadAll,tFt=xGe.dump,rFt=zI("safeLoad","load"),iFt=zI("safeLoadAll","loadAll"),nFt=zI("safeDump","dump")});function WI(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function yae(t){_0=t}function Ei(t,e=""){let r=typeof t=="string"?t:t.source,i={replace:o((n,a)=>{let s=typeof a=="string"?a:a.source;return s=s.replace(Gs.caret,"$1"),r=r.replace(n,s),i},"replace"),getRegex:o(()=>new RegExp(r,e),"getRegex")};return i}function Eu(t,e){if(e){if(Gs.escapeTest.test(t))return t.replace(Gs.escapeReplace,dae)}else if(Gs.escapeTestNoEncode.test(t))return t.replace(Gs.escapeReplaceNoEncode,dae);return t}function pae(t){try{t=encodeURI(t).replace(Gs.percentDecode,"%")}catch{return null}return t}function mae(t,e){let r=t.replace(Gs.findPipe,(a,s,l)=>{let u=!1,h=s;for(;--h>=0&&l[h]==="\\";)u=!u;return u?"|":" |"}),i=r.split(Gs.splitPipe),n=0;if(i[0].trim()||i.shift(),i.length>0&&!i.at(-1)?.trim()&&i.pop(),e)if(i.length>e)i.splice(e);else for(;i.length0?-2:-1}function gae(t,e,r,i,n){let a=e.href,s=e.title||null,l=t[1].replace(n.other.outputLinkReplace,"$1");i.state.inLink=!0;let u={type:t[0].charAt(0)==="!"?"image":"link",raw:r,href:a,title:s,text:l,tokens:i.inlineTokens(l)};return i.state.inLink=!1,u}function eVe(t,e,r){let i=t.match(r.other.indentCodeCompensation);if(i===null)return e;let n=i[1];return e.split(` +`).map(a=>{let s=a.match(r.other.beginningSpace);if(s===null)return a;let[l]=s;return l.length>=n.length?a.slice(n.length):a}).join(` +`)}function bi(t,e){return A0.parse(t,e)}var _0,Cb,Gs,bGe,TGe,kGe,wb,CGe,UI,vae,xae,wGe,HI,EGe,YI,SGe,AGe,l5,jI,_Ge,bae,DGe,XI,fae,LGe,RGe,NGe,IGe,Tae,MGe,c5,KI,kae,OGe,Cae,PGe,BGe,FGe,wae,$Ge,zGe,Eae,GGe,VGe,qGe,WGe,UGe,HGe,YGe,a5,jGe,Sae,Aae,XGe,QI,KGe,GI,QGe,n5,bb,ZGe,dae,s5,zh,o5,ZI,Gh,kb,tVe,A0,sFt,oFt,lFt,cFt,uFt,hFt,fFt,_ae=P(()=>{"use strict";o(WI,"L");_0=WI();o(yae,"G");Cb={exec:o(()=>null,"exec")};o(Ei,"h");Gs={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ xX]\] +/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:o(t=>new RegExp(`^( {0,3}${t})((?:[ ][^\\n]*)?(?:\\n|$))`),"listItemRegex"),nextBulletRegex:o(t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),"nextBulletRegex"),hrRegex:o(t=>new RegExp(`^ {0,${Math.min(3,t-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),"hrRegex"),fencesBeginRegex:o(t=>new RegExp(`^ {0,${Math.min(3,t-1)}}(?:\`\`\`|~~~)`),"fencesBeginRegex"),headingBeginRegex:o(t=>new RegExp(`^ {0,${Math.min(3,t-1)}}#`),"headingBeginRegex"),htmlBeginRegex:o(t=>new RegExp(`^ {0,${Math.min(3,t-1)}}<(?:[a-z].*>|!--)`,"i"),"htmlBeginRegex")},bGe=/^(?:[ \t]*(?:\n|$))+/,TGe=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,kGe=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,wb=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,CGe=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,UI=/(?:[*+-]|\d{1,9}[.)])/,vae=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,xae=Ei(vae).replace(/bull/g,UI).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),wGe=Ei(vae).replace(/bull/g,UI).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),HI=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,EGe=/^[^\n]+/,YI=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,SGe=Ei(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",YI).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),AGe=Ei(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,UI).getRegex(),l5="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",jI=/|$))/,_Ge=Ei("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",jI).replace("tag",l5).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),bae=Ei(HI).replace("hr",wb).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",l5).getRegex(),DGe=Ei(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",bae).getRegex(),XI={blockquote:DGe,code:TGe,def:SGe,fences:kGe,heading:CGe,hr:wb,html:_Ge,lheading:xae,list:AGe,newline:bGe,paragraph:bae,table:Cb,text:EGe},fae=Ei("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",wb).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",l5).getRegex(),LGe={...XI,lheading:wGe,table:fae,paragraph:Ei(HI).replace("hr",wb).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",fae).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",l5).getRegex()},RGe={...XI,html:Ei(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",jI).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:Cb,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Ei(HI).replace("hr",wb).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",xae).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},NGe=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,IGe=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Tae=/^( {2,}|\\)\n(?!\s*$)/,MGe=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\]*?>/g,wae=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,$Ge=Ei(wae,"u").replace(/punct/g,c5).getRegex(),zGe=Ei(wae,"u").replace(/punct/g,Cae).getRegex(),Eae="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",GGe=Ei(Eae,"gu").replace(/notPunctSpace/g,kae).replace(/punctSpace/g,KI).replace(/punct/g,c5).getRegex(),VGe=Ei(Eae,"gu").replace(/notPunctSpace/g,BGe).replace(/punctSpace/g,PGe).replace(/punct/g,Cae).getRegex(),qGe=Ei("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,kae).replace(/punctSpace/g,KI).replace(/punct/g,c5).getRegex(),WGe=Ei(/\\(punct)/,"gu").replace(/punct/g,c5).getRegex(),UGe=Ei(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),HGe=Ei(jI).replace("(?:-->|$)","-->").getRegex(),YGe=Ei("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",HGe).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),a5=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`[^`]*`|[^\[\]\\`])*?/,jGe=Ei(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",a5).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Sae=Ei(/^!?\[(label)\]\[(ref)\]/).replace("label",a5).replace("ref",YI).getRegex(),Aae=Ei(/^!?\[(ref)\](?:\[\])?/).replace("ref",YI).getRegex(),XGe=Ei("reflink|nolink(?!\\()","g").replace("reflink",Sae).replace("nolink",Aae).getRegex(),QI={_backpedal:Cb,anyPunctuation:WGe,autolink:UGe,blockSkip:FGe,br:Tae,code:IGe,del:Cb,emStrongLDelim:$Ge,emStrongRDelimAst:GGe,emStrongRDelimUnd:qGe,escape:NGe,link:jGe,nolink:Aae,punctuation:OGe,reflink:Sae,reflinkSearch:XGe,tag:YGe,text:MGe,url:Cb},KGe={...QI,link:Ei(/^!?\[(label)\]\((.*?)\)/).replace("label",a5).getRegex(),reflink:Ei(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",a5).getRegex()},GI={...QI,emStrongRDelimAst:VGe,emStrongLDelim:zGe,url:Ei(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},dae=o(t=>ZGe[t],"ke");o(Eu,"w");o(pae,"J");o(mae,"V");o(Tb,"z");o(JGe,"ge");o(gae,"fe");o(eVe,"Je");s5=class{static{o(this,"y")}options;rules;lexer;constructor(t){this.options=t||_0}space(t){let e=this.rules.block.newline.exec(t);if(e&&e[0].length>0)return{type:"space",raw:e[0]}}code(t){let e=this.rules.block.code.exec(t);if(e){let r=e[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:e[0],codeBlockStyle:"indented",text:this.options.pedantic?r:Tb(r,` +`)}}}fences(t){let e=this.rules.block.fences.exec(t);if(e){let r=e[0],i=eVe(r,e[3]||"",this.rules);return{type:"code",raw:r,lang:e[2]?e[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):e[2],text:i}}}heading(t){let e=this.rules.block.heading.exec(t);if(e){let r=e[2].trim();if(this.rules.other.endingHash.test(r)){let i=Tb(r,"#");(this.options.pedantic||!i||this.rules.other.endingSpaceChar.test(i))&&(r=i.trim())}return{type:"heading",raw:e[0],depth:e[1].length,text:r,tokens:this.lexer.inline(r)}}}hr(t){let e=this.rules.block.hr.exec(t);if(e)return{type:"hr",raw:Tb(e[0],` +`)}}blockquote(t){let e=this.rules.block.blockquote.exec(t);if(e){let r=Tb(e[0],` +`).split(` +`),i="",n="",a=[];for(;r.length>0;){let s=!1,l=[],u;for(u=0;u1,n={type:"list",raw:"",ordered:i,start:i?+r.slice(0,-1):"",loose:!1,items:[]};r=i?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=i?r:"[*+-]");let a=this.rules.other.listItemRegex(r),s=!1;for(;t;){let u=!1,h="",f="";if(!(e=a.exec(t))||this.rules.block.hr.test(t))break;h=e[0],t=t.substring(h.length);let d=e[2].split(` +`,1)[0].replace(this.rules.other.listReplaceTabs,x=>" ".repeat(3*x.length)),p=t.split(` +`,1)[0],m=!d.trim(),g=0;if(this.options.pedantic?(g=2,f=d.trimStart()):m?g=e[1].length+1:(g=e[2].search(this.rules.other.nonSpaceChar),g=g>4?1:g,f=d.slice(g),g+=e[1].length),m&&this.rules.other.blankLine.test(p)&&(h+=p+` +`,t=t.substring(p.length+1),u=!0),!u){let x=this.rules.other.nextBulletRegex(g),b=this.rules.other.hrRegex(g),T=this.rules.other.fencesBeginRegex(g),w=this.rules.other.headingBeginRegex(g),k=this.rules.other.htmlBeginRegex(g);for(;t;){let C=t.split(` +`,1)[0],E;if(p=C,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),E=p):E=p.replace(this.rules.other.tabCharGlobal," "),T.test(p)||w.test(p)||k.test(p)||x.test(p)||b.test(p))break;if(E.search(this.rules.other.nonSpaceChar)>=g||!p.trim())f+=` +`+E.slice(g);else{if(m||d.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||T.test(d)||w.test(d)||b.test(d))break;f+=` +`+p}!m&&!p.trim()&&(m=!0),h+=C+` +`,t=t.substring(C.length+1),d=E.slice(g)}}n.loose||(s?n.loose=!0:this.rules.other.doubleBlankLine.test(h)&&(s=!0));let y=null,v;this.options.gfm&&(y=this.rules.other.listIsTask.exec(f),y&&(v=y[0]!=="[ ] ",f=f.replace(this.rules.other.listReplaceTask,""))),n.items.push({type:"list_item",raw:h,task:!!y,checked:v,loose:!1,text:f,tokens:[]}),n.raw+=h}let l=n.items.at(-1);if(l)l.raw=l.raw.trimEnd(),l.text=l.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let u=0;ud.type==="space"),f=h.length>0&&h.some(d=>this.rules.other.anyLine.test(d.raw));n.loose=f}if(n.loose)for(let u=0;u({text:l,tokens:this.lexer.inline(l),header:!1,align:a.align[u]})));return a}}lheading(t){let e=this.rules.block.lheading.exec(t);if(e)return{type:"heading",raw:e[0],depth:e[2].charAt(0)==="="?1:2,text:e[1],tokens:this.lexer.inline(e[1])}}paragraph(t){let e=this.rules.block.paragraph.exec(t);if(e){let r=e[1].charAt(e[1].length-1)===` +`?e[1].slice(0,-1):e[1];return{type:"paragraph",raw:e[0],text:r,tokens:this.lexer.inline(r)}}}text(t){let e=this.rules.block.text.exec(t);if(e)return{type:"text",raw:e[0],text:e[0],tokens:this.lexer.inline(e[0])}}escape(t){let e=this.rules.inline.escape.exec(t);if(e)return{type:"escape",raw:e[0],text:e[1]}}tag(t){let e=this.rules.inline.tag.exec(t);if(e)return!this.lexer.state.inLink&&this.rules.other.startATag.test(e[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(e[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(e[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(e[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:e[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:e[0]}}link(t){let e=this.rules.inline.link.exec(t);if(e){let r=e[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(r)){if(!this.rules.other.endAngleBracket.test(r))return;let a=Tb(r.slice(0,-1),"\\");if((r.length-a.length)%2===0)return}else{let a=JGe(e[2],"()");if(a===-2)return;if(a>-1){let s=(e[0].indexOf("!")===0?5:4)+e[1].length+a;e[2]=e[2].substring(0,a),e[0]=e[0].substring(0,s).trim(),e[3]=""}}let i=e[2],n="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(i);a&&(i=a[1],n=a[3])}else n=e[3]?e[3].slice(1,-1):"";return i=i.trim(),this.rules.other.startAngleBracket.test(i)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(r)?i=i.slice(1):i=i.slice(1,-1)),gae(e,{href:i&&i.replace(this.rules.inline.anyPunctuation,"$1"),title:n&&n.replace(this.rules.inline.anyPunctuation,"$1")},e[0],this.lexer,this.rules)}}reflink(t,e){let r;if((r=this.rules.inline.reflink.exec(t))||(r=this.rules.inline.nolink.exec(t))){let i=(r[2]||r[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=e[i.toLowerCase()];if(!n){let a=r[0].charAt(0);return{type:"text",raw:a,text:a}}return gae(r,n,r[0],this.lexer,this.rules)}}emStrong(t,e,r=""){let i=this.rules.inline.emStrongLDelim.exec(t);if(!(!i||i[3]&&r.match(this.rules.other.unicodeAlphaNumeric))&&(!(i[1]||i[2])||!r||this.rules.inline.punctuation.exec(r))){let n=[...i[0]].length-1,a,s,l=n,u=0,h=i[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(h.lastIndex=0,e=e.slice(-1*t.length+n);(i=h.exec(e))!=null;){if(a=i[1]||i[2]||i[3]||i[4]||i[5]||i[6],!a)continue;if(s=[...a].length,i[3]||i[4]){l+=s;continue}else if((i[5]||i[6])&&n%3&&!((n+s)%3)){u+=s;continue}if(l-=s,l>0)continue;s=Math.min(s,s+l+u);let f=[...i[0]][0].length,d=t.slice(0,n+i.index+f+s);if(Math.min(n,s)%2){let m=d.slice(1,-1);return{type:"em",raw:d,text:m,tokens:this.lexer.inlineTokens(m)}}let p=d.slice(2,-2);return{type:"strong",raw:d,text:p,tokens:this.lexer.inlineTokens(p)}}}}codespan(t){let e=this.rules.inline.code.exec(t);if(e){let r=e[2].replace(this.rules.other.newLineCharGlobal," "),i=this.rules.other.nonSpaceChar.test(r),n=this.rules.other.startingSpaceChar.test(r)&&this.rules.other.endingSpaceChar.test(r);return i&&n&&(r=r.substring(1,r.length-1)),{type:"codespan",raw:e[0],text:r}}}br(t){let e=this.rules.inline.br.exec(t);if(e)return{type:"br",raw:e[0]}}del(t){let e=this.rules.inline.del.exec(t);if(e)return{type:"del",raw:e[0],text:e[2],tokens:this.lexer.inlineTokens(e[2])}}autolink(t){let e=this.rules.inline.autolink.exec(t);if(e){let r,i;return e[2]==="@"?(r=e[1],i="mailto:"+r):(r=e[1],i=r),{type:"link",raw:e[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}url(t){let e;if(e=this.rules.inline.url.exec(t)){let r,i;if(e[2]==="@")r=e[0],i="mailto:"+r;else{let n;do n=e[0],e[0]=this.rules.inline._backpedal.exec(e[0])?.[0]??"";while(n!==e[0]);r=e[0],e[1]==="www."?i="http://"+e[0]:i=e[0]}return{type:"link",raw:e[0],text:r,href:i,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(t){let e=this.rules.inline.text.exec(t);if(e){let r=this.lexer.state.inRawBlock;return{type:"text",raw:e[0],text:e[0],escaped:r}}}},zh=class VI{static{o(this,"l")}tokens;options;state;tokenizer;inlineQueue;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||_0,this.options.tokenizer=this.options.tokenizer||new s5,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let r={other:Gs,block:n5.normal,inline:bb.normal};this.options.pedantic?(r.block=n5.pedantic,r.inline=bb.pedantic):this.options.gfm&&(r.block=n5.gfm,this.options.breaks?r.inline=bb.breaks:r.inline=bb.gfm),this.tokenizer.rules=r}static get rules(){return{block:n5,inline:bb}}static lex(e,r){return new VI(r).lex(e)}static lexInline(e,r){return new VI(r).inlineTokens(e)}lex(e){e=e.replace(Gs.carriageReturn,` +`),this.blockTokens(e,this.tokens);for(let r=0;r(n=s.call({lexer:this},e,r))?(e=e.substring(n.raw.length),r.push(n),!0):!1))continue;if(n=this.tokenizer.space(e)){e=e.substring(n.raw.length);let s=r.at(-1);n.raw.length===1&&s!==void 0?s.raw+=` +`:r.push(n);continue}if(n=this.tokenizer.code(e)){e=e.substring(n.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+n.raw,s.text+=` +`+n.text,this.inlineQueue.at(-1).src=s.text):r.push(n);continue}if(n=this.tokenizer.fences(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.heading(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.hr(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.blockquote(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.list(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.html(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.def(e)){e=e.substring(n.raw.length);let s=r.at(-1);s?.type==="paragraph"||s?.type==="text"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+n.raw,s.text+=` +`+n.raw,this.inlineQueue.at(-1).src=s.text):this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title},r.push(n));continue}if(n=this.tokenizer.table(e)){e=e.substring(n.raw.length),r.push(n);continue}if(n=this.tokenizer.lheading(e)){e=e.substring(n.raw.length),r.push(n);continue}let a=e;if(this.options.extensions?.startBlock){let s=1/0,l=e.slice(1),u;this.options.extensions.startBlock.forEach(h=>{u=h.call({lexer:this},l),typeof u=="number"&&u>=0&&(s=Math.min(s,u))}),s<1/0&&s>=0&&(a=e.substring(0,s+1))}if(this.state.top&&(n=this.tokenizer.paragraph(a))){let s=r.at(-1);i&&s?.type==="paragraph"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+n.raw,s.text+=` +`+n.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(n),i=a.length!==e.length,e=e.substring(n.raw.length);continue}if(n=this.tokenizer.text(e)){e=e.substring(n.raw.length);let s=r.at(-1);s?.type==="text"?(s.raw+=(s.raw.endsWith(` +`)?"":` +`)+n.raw,s.text+=` +`+n.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=s.text):r.push(n);continue}if(e){let s="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(s);break}else throw new Error(s)}}return this.state.top=!0,r}inline(e,r=[]){return this.inlineQueue.push({src:e,tokens:r}),r}inlineTokens(e,r=[]){let i=e,n=null;if(this.tokens.links){let l=Object.keys(this.tokens.links);if(l.length>0)for(;(n=this.tokenizer.rules.inline.reflinkSearch.exec(i))!=null;)l.includes(n[0].slice(n[0].lastIndexOf("[")+1,-1))&&(i=i.slice(0,n.index)+"["+"a".repeat(n[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(n=this.tokenizer.rules.inline.anyPunctuation.exec(i))!=null;)i=i.slice(0,n.index)+"++"+i.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;(n=this.tokenizer.rules.inline.blockSkip.exec(i))!=null;)i=i.slice(0,n.index)+"["+"a".repeat(n[0].length-2)+"]"+i.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);i=this.options.hooks?.emStrongMask?.call({lexer:this},i)??i;let a=!1,s="";for(;e;){a||(s=""),a=!1;let l;if(this.options.extensions?.inline?.some(h=>(l=h.call({lexer:this},e,r))?(e=e.substring(l.raw.length),r.push(l),!0):!1))continue;if(l=this.tokenizer.escape(e)){e=e.substring(l.raw.length),r.push(l);continue}if(l=this.tokenizer.tag(e)){e=e.substring(l.raw.length),r.push(l);continue}if(l=this.tokenizer.link(e)){e=e.substring(l.raw.length),r.push(l);continue}if(l=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(l.raw.length);let h=r.at(-1);l.type==="text"&&h?.type==="text"?(h.raw+=l.raw,h.text+=l.text):r.push(l);continue}if(l=this.tokenizer.emStrong(e,i,s)){e=e.substring(l.raw.length),r.push(l);continue}if(l=this.tokenizer.codespan(e)){e=e.substring(l.raw.length),r.push(l);continue}if(l=this.tokenizer.br(e)){e=e.substring(l.raw.length),r.push(l);continue}if(l=this.tokenizer.del(e)){e=e.substring(l.raw.length),r.push(l);continue}if(l=this.tokenizer.autolink(e)){e=e.substring(l.raw.length),r.push(l);continue}if(!this.state.inLink&&(l=this.tokenizer.url(e))){e=e.substring(l.raw.length),r.push(l);continue}let u=e;if(this.options.extensions?.startInline){let h=1/0,f=e.slice(1),d;this.options.extensions.startInline.forEach(p=>{d=p.call({lexer:this},f),typeof d=="number"&&d>=0&&(h=Math.min(h,d))}),h<1/0&&h>=0&&(u=e.substring(0,h+1))}if(l=this.tokenizer.inlineText(u)){e=e.substring(l.raw.length),l.raw.slice(-1)!=="_"&&(s=l.raw.slice(-1)),a=!0;let h=r.at(-1);h?.type==="text"?(h.raw+=l.raw,h.text+=l.text):r.push(l);continue}if(e){let h="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(h);break}else throw new Error(h)}}return r}},o5=class{static{o(this,"P")}options;parser;constructor(t){this.options=t||_0}space(t){return""}code({text:t,lang:e,escaped:r}){let i=(e||"").match(Gs.notSpaceStart)?.[0],n=t.replace(Gs.endingNewline,"")+` +`;return i?'
'+(r?n:Eu(n,!0))+`
+`:"
"+(r?n:Eu(n,!0))+`
+`}blockquote({tokens:t}){return`
+${this.parser.parse(t)}
+`}html({text:t}){return t}def(t){return""}heading({tokens:t,depth:e}){return`${this.parser.parseInline(t)} +`}hr(t){return`
+`}list(t){let e=t.ordered,r=t.start,i="";for(let s=0;s +`+i+" +`}listitem(t){let e="";if(t.task){let r=this.checkbox({checked:!!t.checked});t.loose?t.tokens[0]?.type==="paragraph"?(t.tokens[0].text=r+" "+t.tokens[0].text,t.tokens[0].tokens&&t.tokens[0].tokens.length>0&&t.tokens[0].tokens[0].type==="text"&&(t.tokens[0].tokens[0].text=r+" "+Eu(t.tokens[0].tokens[0].text),t.tokens[0].tokens[0].escaped=!0)):t.tokens.unshift({type:"text",raw:r+" ",text:r+" ",escaped:!0}):e+=r+" "}return e+=this.parser.parse(t.tokens,!!t.loose),`
  • ${e}
  • +`}checkbox({checked:t}){return"'}paragraph({tokens:t}){return`

    ${this.parser.parseInline(t)}

    +`}table(t){let e="",r="";for(let n=0;n${i}`),` + +`+e+` +`+i+`
    +`}tablerow({text:t}){return` +${t} +`}tablecell(t){let e=this.parser.parseInline(t.tokens),r=t.header?"th":"td";return(t.align?`<${r} align="${t.align}">`:`<${r}>`)+e+` +`}strong({tokens:t}){return`${this.parser.parseInline(t)}`}em({tokens:t}){return`${this.parser.parseInline(t)}`}codespan({text:t}){return`${Eu(t,!0)}`}br(t){return"
    "}del({tokens:t}){return`${this.parser.parseInline(t)}`}link({href:t,title:e,tokens:r}){let i=this.parser.parseInline(r),n=pae(t);if(n===null)return i;t=n;let a='
    ",a}image({href:t,title:e,text:r,tokens:i}){i&&(r=this.parser.parseInline(i,this.parser.textRenderer));let n=pae(t);if(n===null)return Eu(r);t=n;let a=`${r}{let s=n[a].flat(1/0);r=r.concat(this.walkTokens(s,e))}):n.tokens&&(r=r.concat(this.walkTokens(n.tokens,e)))}}return r}use(...t){let e=this.defaults.extensions||{renderers:{},childTokens:{}};return t.forEach(r=>{let i={...r};if(i.async=this.defaults.async||i.async||!1,r.extensions&&(r.extensions.forEach(n=>{if(!n.name)throw new Error("extension name required");if("renderer"in n){let a=e.renderers[n.name];a?e.renderers[n.name]=function(...s){let l=n.renderer.apply(this,s);return l===!1&&(l=a.apply(this,s)),l}:e.renderers[n.name]=n.renderer}if("tokenizer"in n){if(!n.level||n.level!=="block"&&n.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let a=e[n.level];a?a.unshift(n.tokenizer):e[n.level]=[n.tokenizer],n.start&&(n.level==="block"?e.startBlock?e.startBlock.push(n.start):e.startBlock=[n.start]:n.level==="inline"&&(e.startInline?e.startInline.push(n.start):e.startInline=[n.start]))}"childTokens"in n&&n.childTokens&&(e.childTokens[n.name]=n.childTokens)}),i.extensions=e),r.renderer){let n=this.defaults.renderer||new o5(this.defaults);for(let a in r.renderer){if(!(a in n))throw new Error(`renderer '${a}' does not exist`);if(["options","parser"].includes(a))continue;let s=a,l=r.renderer[s],u=n[s];n[s]=(...h)=>{let f=l.apply(n,h);return f===!1&&(f=u.apply(n,h)),f||""}}i.renderer=n}if(r.tokenizer){let n=this.defaults.tokenizer||new s5(this.defaults);for(let a in r.tokenizer){if(!(a in n))throw new Error(`tokenizer '${a}' does not exist`);if(["options","rules","lexer"].includes(a))continue;let s=a,l=r.tokenizer[s],u=n[s];n[s]=(...h)=>{let f=l.apply(n,h);return f===!1&&(f=u.apply(n,h)),f}}i.tokenizer=n}if(r.hooks){let n=this.defaults.hooks||new kb;for(let a in r.hooks){if(!(a in n))throw new Error(`hook '${a}' does not exist`);if(["options","block"].includes(a))continue;let s=a,l=r.hooks[s],u=n[s];kb.passThroughHooks.has(a)?n[s]=h=>{if(this.defaults.async&&kb.passThroughHooksRespectAsync.has(a))return Promise.resolve(l.call(n,h)).then(d=>u.call(n,d));let f=l.call(n,h);return u.call(n,f)}:n[s]=(...h)=>{let f=l.apply(n,h);return f===!1&&(f=u.apply(n,h)),f}}i.hooks=n}if(r.walkTokens){let n=this.defaults.walkTokens,a=r.walkTokens;i.walkTokens=function(s){let l=[];return l.push(a.call(this,s)),n&&(l=l.concat(n.call(this,s))),l}}this.defaults={...this.defaults,...i}}),this}setOptions(t){return this.defaults={...this.defaults,...t},this}lexer(t,e){return zh.lex(t,e??this.defaults)}parser(t,e){return Gh.parse(t,e??this.defaults)}parseMarkdown(t){return(e,r)=>{let i={...r},n={...this.defaults,...i},a=this.onError(!!n.silent,!!n.async);if(this.defaults.async===!0&&i.async===!1)return a(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof e>"u"||e===null)return a(new Error("marked(): input parameter is undefined or null"));if(typeof e!="string")return a(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(e)+", string expected"));n.hooks&&(n.hooks.options=n,n.hooks.block=t);let s=n.hooks?n.hooks.provideLexer():t?zh.lex:zh.lexInline,l=n.hooks?n.hooks.provideParser():t?Gh.parse:Gh.parseInline;if(n.async)return Promise.resolve(n.hooks?n.hooks.preprocess(e):e).then(u=>s(u,n)).then(u=>n.hooks?n.hooks.processAllTokens(u):u).then(u=>n.walkTokens?Promise.all(this.walkTokens(u,n.walkTokens)).then(()=>u):u).then(u=>l(u,n)).then(u=>n.hooks?n.hooks.postprocess(u):u).catch(a);try{n.hooks&&(e=n.hooks.preprocess(e));let u=s(e,n);n.hooks&&(u=n.hooks.processAllTokens(u)),n.walkTokens&&this.walkTokens(u,n.walkTokens);let h=l(u,n);return n.hooks&&(h=n.hooks.postprocess(h)),h}catch(u){return a(u)}}}onError(t,e){return r=>{if(r.message+=` +Please report this to https://github.com/markedjs/marked.`,t){let i="

    An error occurred:

    "+Eu(r.message+"",!0)+"
    ";return e?Promise.resolve(i):i}if(e)return Promise.reject(r);throw r}}},A0=new tVe;o(bi,"d");bi.options=bi.setOptions=function(t){return A0.setOptions(t),bi.defaults=A0.defaults,yae(bi.defaults),bi};bi.getDefaults=WI;bi.defaults=_0;bi.use=function(...t){return A0.use(...t),bi.defaults=A0.defaults,yae(bi.defaults),bi};bi.walkTokens=function(t,e){return A0.walkTokens(t,e)};bi.parseInline=A0.parseInline;bi.Parser=Gh;bi.parser=Gh.parse;bi.Renderer=o5;bi.TextRenderer=ZI;bi.Lexer=zh;bi.lexer=zh.lex;bi.Tokenizer=s5;bi.Hooks=kb;bi.parse=bi;sFt=bi.options,oFt=bi.setOptions,lFt=bi.use,cFt=bi.walkTokens,uFt=bi.parseInline,hFt=Gh.parse,fFt=zh.lex});function rVe(t,{markdownAutoWrap:e}){let i=t.replace(//g,` +`).replace(/\n{2,}/g,` +`);return Z4(i)}function Dae(t){return t.split(/\\n|\n|/gi).map(e=>e.trim().match(/<[^>]+>|[^\s<>]+/g)?.map(r=>({content:r,type:"normal"}))??[])}function Lae(t,e={}){let r=rVe(t,e),i=bi.lexer(r),n=[[]],a=0;function s(l,u="normal"){l.type==="text"?l.text.split(` +`).forEach((f,d)=>{d!==0&&(a++,n.push([])),f.split(" ").forEach(p=>{p=p.replace(/'/g,"'"),p&&n[a].push({content:p,type:u})})}):l.type==="strong"||l.type==="em"?l.tokens.forEach(h=>{s(h,l.type)}):l.type==="html"&&n[a].push({content:l.text,type:"normal"})}return o(s,"processNode"),i.forEach(l=>{l.type==="paragraph"?l.tokens?.forEach(u=>{s(u)}):l.type==="html"?n[a].push({content:l.text,type:"normal"}):n[a].push({content:l.raw,type:"normal"})}),n}function Rae(t){return t?`

    ${t.replace(/\\n|\n/g,"
    ")}

    `:""}function Nae(t,{markdownAutoWrap:e}={}){let r=bi.lexer(t);function i(n){return n.type==="text"?e===!1?n.text.replace(/\n */g,"
    ").replace(/ /g," "):n.text.replace(/\n */g,"
    "):n.type==="strong"?`${n.tokens?.map(i).join("")}`:n.type==="em"?`${n.tokens?.map(i).join("")}`:n.type==="paragraph"?`

    ${n.tokens?.map(i).join("")}

    `:n.type==="space"?"":n.type==="html"?`${n.text}`:n.type==="escape"?n.text:(Q.warn(`Unsupported markdown: ${n.type}`),n.raw)}return o(i,"output"),r.map(i).join("")}var Iae=P(()=>{"use strict";_ae();oL();bt();o(rVe,"preprocessMarkdown");o(Dae,"nonMarkdownToLines");o(Lae,"markdownToLines");o(Rae,"nonMarkdownToHTML");o(Nae,"markdownToHTML")});function iVe(t){return Intl.Segmenter?[...new Intl.Segmenter().segment(t)].map(e=>e.segment):[...t]}function nVe(t,e){let r=iVe(e.content);return Mae(t,[],r,e.type)}function Mae(t,e,r,i){if(r.length===0)return[{content:e.join(""),type:i},{content:"",type:i}];let[n,...a]=r,s=[...e,n];return t([{content:s.join(""),type:i}])?Mae(t,s,a,i):(e.length===0&&n&&(e.push(n),r.shift()),[{content:e.join(""),type:i},{content:r.join(""),type:i}])}function Oae(t,e){if(t.some(({content:r})=>r.includes(` +`)))throw new Error("splitLineToFitWidth does not support newlines in the line");return JI(t,e)}function JI(t,e,r=[],i=[]){if(t.length===0)return i.length>0&&r.push(i),r.length>0?r:[];let n="";t[0].content===" "&&(n=" ",t.shift());let a=t.shift()??{content:" ",type:"normal"},s=[...i];if(n!==""&&s.push({content:n,type:"normal"}),s.push(a),e(s))return JI(t,e,r,s);if(i.length>0)r.push(i),t.unshift(a);else if(a.content){let[l,u]=nVe(e,a);r.push([l]),u.content&&t.unshift(u)}return JI(t,e,r)}var Pae=P(()=>{"use strict";o(iVe,"splitTextToChars");o(nVe,"splitWordToFitWidth");o(Mae,"splitWordToFitWidthRecursion");o(Oae,"splitLineToFitWidth");o(JI,"splitLineToFitWidthRecursion")});function Bae(t,e){e&&t.attr("style",e)}async function aVe(t,e,r,i,n=!1,a=Lt()){let s=t.append("foreignObject");s.attr("width",`${Math.min(10*r,Fae)}px`),s.attr("height",`${Math.min(10*r,Fae)}px`);let l=s.append("xhtml:div"),u=sn(e.label)?await Rg(e.label.replace(lt.lineBreakRegex,` +`),a):Tr(e.label,a),h=e.isNode?"nodeLabel":"edgeLabel",f=l.append("span");f.html(u),Bae(f,e.labelStyle),f.attr("class",`${h} ${i}`),Bae(l,e.labelStyle),l.style("display","table-cell"),l.style("white-space","nowrap"),l.style("line-height","1.5"),r!==Number.POSITIVE_INFINITY&&(l.style("max-width",r+"px"),l.style("text-align","center")),l.attr("xmlns","http://www.w3.org/1999/xhtml"),n&&l.attr("class","labelBkg");let d=l.node().getBoundingClientRect();return d.width===r&&(l.style("display","table"),l.style("white-space","break-spaces"),l.style("width",r+"px"),d=l.node().getBoundingClientRect()),s.node()}function eM(t,e,r,i=!1){let n=t.append("tspan").attr("class","text-outer-tspan").attr("x",0).attr("y",e*r-.1+"em").attr("dy",r+"em");return i&&n.attr("text-anchor","middle"),n}function sVe(t,e,r){let i=t.append("text"),n=eM(i,1,e);tM(n,r);let a=n.node().getComputedTextLength();return i.remove(),a}function zae(t,e,r){let i=t.append("text"),n=eM(i,1,e);tM(n,[{content:r,type:"normal"}]);let a=n.node()?.getBoundingClientRect();return a&&i.remove(),a}function oVe(t,e,r,i=!1,n=!1){let s=e.append("g"),l=s.insert("rect").attr("class","background").attr("style","stroke: none"),u=s.append("text").attr("y","-10.1");n&&u.attr("text-anchor","middle");let h=0;for(let f of r){let d=o(m=>sVe(s,1.1,m)<=t,"checkWidth"),p=d(f)?[f]:Oae(f,d);for(let m of p){let g=eM(u,h,1.1,n);tM(g,m),h++}}if(i){let f=u.node().getBBox(),d=2;return l.attr("x",f.x-d).attr("y",f.y-d).attr("width",f.width+2*d).attr("height",f.height+2*d),s.node()}else return u.node()}function $ae(t){let e=/&(amp|lt|gt);/g;return t.replace(e,(r,i)=>{switch(i){case"amp":return"&";case"lt":return"<";case"gt":return">";default:return r}})}function tM(t,e){t.text(""),e.forEach((r,i)=>{let n=t.append("tspan").attr("font-style",r.type==="em"?"italic":"normal").attr("class","text-inner-tspan").attr("font-weight",r.type==="strong"?"bold":"normal");i===0?n.text($ae(r.content)):n.text(" "+$ae(r.content))})}async function lVe(t,e={}){let r=[];t.replace(/(fa[bklrs]?):fa-([\w-]+)/g,(n,a,s)=>(r.push((async()=>{let l=`${a}:${s}`;return await WK(l)?await fo(l,void 0,{class:"label-icon"}):``})()),n));let i=await Promise.all(r);return t.replace(/(fa[bklrs]?):fa-([\w-]+)/g,()=>i.shift()??"")}var Fae,Vi,To=P(()=>{"use strict";Pr();Vr();bt();Iae();er();lu();Pae();Sr();o(Bae,"applyStyle");Fae=16384;o(aVe,"addHtmlSpan");o(eM,"createTspan");o(sVe,"computeWidthOfText");o(zae,"computeDimensionOfText");o(oVe,"createFormattedText");o($ae,"decodeHTMLEntities");o(tM,"updateTextContentAndStyles");o(lVe,"replaceIconSubstring");Vi=o(async(t,e="",{style:r="",isTitle:i=!1,classes:n="",useHtmlLabels:a=!0,markdown:s=!0,isNode:l=!0,width:u=200,addSvgBackground:h=!1}={},f)=>{if(Q.debug("XYZ createText",e,r,i,n,a,l,"addSvgBackground: ",h),a){let d=s?Nae(e,f):Rae(e),p=await lVe(zs(d),f),m=e.replace(/\\\\/g,"\\"),g={isNode:l,label:sn(e)?m:p,labelStyle:r.replace("fill:","color:")};return await aVe(t,g,u,n,h,f)}else{let d=zs(e.replace(//g,"
    ")),p=s?Lae(d.replace("
    ","
    "),f):Dae(d),m=oVe(u,t,p,e?h:!1,!l);if(l){/stroke:/.exec(r)&&(r=r.replace("stroke:","lineColor:"));let g=r.replace(/stroke:[^;]+;?/g,"").replace(/stroke-width:[^;]+;?/g,"").replace(/fill:[^;]+;?/g,"").replace(/color:/g,"fill:");Ze(m).attr("style",g)}else{let g=r.replace(/stroke:[^;]+;?/g,"").replace(/stroke-width:[^;]+;?/g,"").replace(/fill:[^;]+;?/g,"").replace(/background:/g,"fill:");Ze(m).select("rect").attr("style",g.replace(/background:/g,"fill:"));let y=r.replace(/stroke:[^;]+;?/g,"").replace(/stroke-width:[^;]+;?/g,"").replace(/fill:[^;]+;?/g,"").replace(/color:/g,"fill:");Ze(m).select("text").attr("style",y)}return i?Ze(m).selectAll("tspan.text-outer-tspan").classed("title-row",!0):Ze(m).selectAll("tspan.text-outer-tspan").classed("row",!0),m}},"createText")});async function u5(t,e){let r=t.getElementsByTagName("img");if(!r||r.length===0)return;let i=e.replace(/]*>/g,"").trim()==="";await Promise.all([...r].map(n=>new Promise(a=>{function s(){if(n.style.display="flex",n.style.flexDirection="column",i){let l=ge().fontSize?ge().fontSize:window.getComputedStyle(document.body).fontSize,u=5,[h=fr.fontSize]=$s(l),f=h*u+"px";n.style.minWidth=f,n.style.maxWidth=f}else n.style.width="100%";a(n)}o(s,"setupImage"),setTimeout(()=>{n.complete&&s()}),n.addEventListener("error",s),n.addEventListener("load",s)})))}var rM=P(()=>{"use strict";Ut();wa();er();o(u5,"configureLabelImages")});function rr(t){let e=t.map((r,i)=>`${i===0?"M":"L"}${r.x},${r.y}`);return e.push("Z"),e.join(" ")}function Ml(t,e,r,i,n,a){let s=[],u=r-t,h=i-e,f=u/a,d=2*Math.PI/f,p=e+h/2;for(let m=0;m<=50;m++){let g=m/50,y=t+g*u,v=p+n*Math.sin(d*(y-t));s.push({x:y,y:v})}return s}function D0(t,e,r,i,n,a){let s=[],l=n*Math.PI/180,f=(a*Math.PI/180-l)/(i-1);for(let d=0;du.tagName==="path"),r=document.createElementNS("http://www.w3.org/2000/svg","path"),i=e.map(u=>u.getAttribute("d")).filter(u=>u!==null).join(" ");r.setAttribute("d",i);let n=e.find(u=>u.getAttribute("fill")!=="none"),a=e.find(u=>u.getAttribute("stroke")!=="none"),s=o((u,h)=>u?.getAttribute(h)??void 0,"getAttr");if(n){let u={fill:s(n,"fill"),"fill-opacity":s(n,"fill-opacity")??"1"};Object.entries(u).forEach(([h,f])=>{f&&r.setAttribute(h,f)})}if(a){let u={stroke:s(a,"stroke"),"stroke-width":s(a,"stroke-width")??"1","stroke-opacity":s(a,"stroke-opacity")??"1"};Object.entries(u).forEach(([h,f])=>{f&&r.setAttribute(h,f)})}let l=document.createElementNS("http://www.w3.org/2000/svg","g");return l.appendChild(r),l}var vt,h5,at,mt,zt=P(()=>{"use strict";To();Ut();Sr();Pr();Vr();er();rM();vt=o(async(t,e,r)=>{let i,n=e.useHtmlLabels||ls(ge()?.htmlLabels);r?i=r:i="node default";let a=t.insert("g").attr("class",i).attr("id",e.domId||e.id),s=a.insert("g").attr("class","label").attr("style",xi(e.labelStyle)),l;e.label===void 0?l="":l=typeof e.label=="string"?e.label:e.label[0];let u=!!e.icon||!!e.img,h=e.labelType==="markdown",f=await Vi(s,Tr(zs(l),ge()),{useHtmlLabels:n,width:e.width||ge().flowchart?.wrappingWidth,classes:h?"markdown-node-label":"",style:e.labelStyle,addSvgBackground:u,markdown:h},ge()),d=f.getBBox(),p=(e?.padding??0)/2;if(n){let m=f.children[0],g=Ze(f);await u5(m,l),d=m.getBoundingClientRect(),g.attr("width",d.width),g.attr("height",d.height)}return n?s.attr("transform","translate("+-d.width/2+", "+-d.height/2+")"):s.attr("transform","translate(0, "+-d.height/2+")"),e.centerLabel&&s.attr("transform","translate("+-d.width/2+", "+-d.height/2+")"),s.insert("rect",":first-child"),{shapeSvg:a,bbox:d,halfPadding:p,label:s}},"labelHelper"),h5=o(async(t,e,r)=>{let i=r.useHtmlLabels??Or(ge()),n=t.insert("g").attr("class","label").attr("style",r.labelStyle||""),a=await Vi(n,Tr(zs(e),ge()),{useHtmlLabels:i,width:r.width||ge()?.flowchart?.wrappingWidth,style:r.labelStyle,addSvgBackground:!!r.icon||!!r.img}),s=a.getBBox(),l=r.padding/2;if(Or(ge())){let u=a.children[0],h=Ze(a);s=u.getBoundingClientRect(),h.attr("width",s.width),h.attr("height",s.height)}return i?n.attr("transform","translate("+-s.width/2+", "+-s.height/2+")"):n.attr("transform","translate(0, "+-s.height/2+")"),r.centerLabel&&n.attr("transform","translate("+-s.width/2+", "+-s.height/2+")"),n.insert("rect",":first-child"),{shapeSvg:t,bbox:s,halfPadding:l,label:n}},"insertLabel"),at=o((t,e)=>{let r=e.node().getBBox();t.width=r.width,t.height=r.height},"updateNodeBounds"),mt=o((t,e)=>(t.look==="handDrawn"?"rough-node":"node")+" "+t.cssClasses+" "+(e||""),"getNodeClasses");o(rr,"createPathFromPoints");o(Ml,"generateFullSineWavePoints");o(D0,"generateCirclePoints");o(iM,"mergePaths")});function cVe(t,e){return t.intersect(e)}var Gae,Vae=P(()=>{"use strict";o(cVe,"intersectNode");Gae=cVe});function uVe(t,e,r,i){var n=t.x,a=t.y,s=n-i.x,l=a-i.y,u=Math.sqrt(e*e*l*l+r*r*s*s),h=Math.abs(e*r*s/u);i.x{"use strict";o(uVe,"intersectEllipse");f5=uVe});function hVe(t,e,r){return f5(t,e,e,r)}var qae,Wae=P(()=>{"use strict";nM();o(hVe,"intersectCircle");qae=hVe});function fVe(t,e,r,i){{let n=e.y-t.y,a=t.x-e.x,s=e.x*t.y-t.x*e.y,l=n*r.x+a*r.y+s,u=n*i.x+a*i.y+s,h=1e-6;if(l!==0&&u!==0&&Uae(l,u))return;let f=i.y-r.y,d=r.x-i.x,p=i.x*r.y-r.x*i.y,m=f*t.x+d*t.y+p,g=f*e.x+d*e.y+p;if(Math.abs(m)0}var Hae,Yae=P(()=>{"use strict";o(fVe,"intersectLine");o(Uae,"sameSign");Hae=fVe});function dVe(t,e,r){let i=t.x,n=t.y,a=[],s=Number.POSITIVE_INFINITY,l=Number.POSITIVE_INFINITY;typeof e.forEach=="function"?e.forEach(function(f){s=Math.min(s,f.x),l=Math.min(l,f.y)}):(s=Math.min(s,e.x),l=Math.min(l,e.y));let u=i-t.width/2-s,h=n-t.height/2-l;for(let f=0;f1&&a.sort(function(f,d){let p=f.x-r.x,m=f.y-r.y,g=Math.sqrt(p*p+m*m),y=d.x-r.x,v=d.y-r.y,x=Math.sqrt(y*y+v*v);return g{"use strict";Yae();o(dVe,"intersectPolygon");jae=dVe});var pVe,hd,aM=P(()=>{"use strict";pVe=o((t,e)=>{var r=t.x,i=t.y,n=e.x-r,a=e.y-i,s=t.width/2,l=t.height/2,u,h;return Math.abs(a)*s>Math.abs(n)*l?(a<0&&(l=-l),u=a===0?0:l*n/a,h=l):(n<0&&(s=-s),u=s,h=n===0?0:s*a/n),{x:r+u,y:i+h}},"intersectRect"),hd=pVe});var et,Xt=P(()=>{"use strict";Vae();Wae();nM();Xae();aM();et={node:Gae,circle:qae,ellipse:f5,polygon:jae,rect:hd}});var Kae,Su,mVe,Eb,tt,st,gVe,Ht=P(()=>{"use strict";Ut();Kae=o(t=>{let{handDrawnSeed:e}=ge();return{fill:t,hachureAngle:120,hachureGap:4,fillWeight:2,roughness:.7,stroke:t,seed:e}},"solidStateFill"),Su=o(t=>{let e=mVe([...t.cssCompiledStyles||[],...t.cssStyles||[],...t.labelStyle||[]]);return{stylesMap:e,stylesArray:[...e]}},"compileStyles"),mVe=o(t=>{let e=new Map;return t.forEach(r=>{let[i,n]=r.split(":");e.set(i.trim(),n?.trim())}),e},"styles2Map"),Eb=o(t=>t==="color"||t==="font-size"||t==="font-family"||t==="font-weight"||t==="font-style"||t==="text-decoration"||t==="text-align"||t==="text-transform"||t==="line-height"||t==="letter-spacing"||t==="word-spacing"||t==="text-shadow"||t==="text-overflow"||t==="white-space"||t==="word-wrap"||t==="word-break"||t==="overflow-wrap"||t==="hyphens","isLabelStyle"),tt=o(t=>{let{stylesArray:e}=Su(t),r=[],i=[],n=[],a=[];return e.forEach(s=>{let l=s[0];Eb(l)?r.push(s.join(":")+" !important"):(i.push(s.join(":")+" !important"),l.includes("stroke")&&n.push(s.join(":")+" !important"),l==="fill"&&a.push(s.join(":")+" !important"))}),{labelStyles:r.join(";"),nodeStyles:i.join(";"),stylesArray:e,borderStyles:n,backgroundStyles:a}},"styles2String"),st=o((t,e)=>{let{themeVariables:r,handDrawnSeed:i}=ge(),{nodeBorder:n,mainBkg:a}=r,{stylesMap:s}=Su(t);return Object.assign({roughness:.7,fill:s.get("fill")||a,fillStyle:"hachure",fillWeight:4,hachureGap:5.2,stroke:s.get("stroke")||n,seed:i,strokeWidth:s.get("stroke-width")?.replace("px","")||1.3,fillLineDash:[0,0],strokeLineDash:gVe(s.get("stroke-dasharray"))},e)},"userNodeOverrides"),gVe=o(t=>{if(!t)return[0,0];let e=t.trim().split(/\s+/).map(Number);if(e.length===1){let n=isNaN(e[0])?0:e[0];return[n,n]}let r=isNaN(e[0])?0:e[0],i=isNaN(e[1])?0:e[1];return[r,i]},"getStrokeDashArray")});function sM(t,e,r){if(t&&t.length){let[i,n]=e,a=Math.PI/180*r,s=Math.cos(a),l=Math.sin(a);for(let u of t){let[h,f]=u;u[0]=(h-i)*s-(f-n)*l+i,u[1]=(h-i)*l+(f-n)*s+n}}}function yVe(t,e){return t[0]===e[0]&&t[1]===e[1]}function vVe(t,e,r,i=1){let n=r,a=Math.max(e,.1),s=t[0]&&t[0][0]&&typeof t[0][0]=="number"?[t]:t,l=[0,0];if(n)for(let h of s)sM(h,l,n);let u=(function(h,f,d){let p=[];for(let b of h){let T=[...b];yVe(T[0],T[T.length-1])||T.push([T[0][0],T[0][1]]),T.length>2&&p.push(T)}let m=[];f=Math.max(f,.1);let g=[];for(let b of p)for(let T=0;Tb.yminT.ymin?1:b.xT.x?1:b.ymax===T.ymax?0:(b.ymax-T.ymax)/Math.abs(b.ymax-T.ymax))),!g.length)return m;let y=[],v=g[0].ymin,x=0;for(;y.length||g.length;){if(g.length){let b=-1;for(let T=0;Tv);T++)b=T;g.splice(0,b+1).forEach((T=>{y.push({s:v,edge:T})}))}if(y=y.filter((b=>!(b.edge.ymax<=v))),y.sort(((b,T)=>b.edge.x===T.edge.x?0:(b.edge.x-T.edge.x)/Math.abs(b.edge.x-T.edge.x))),(d!==1||x%f==0)&&y.length>1)for(let b=0;b=y.length)break;let w=y[b].edge,k=y[T].edge;m.push([[Math.round(w.x),v],[Math.round(k.x),v]])}v+=d,y.forEach((b=>{b.edge.x=b.edge.x+d*b.edge.islope})),x++}return m})(s,a,i);if(n){for(let h of s)sM(h,l,-n);(function(h,f,d){let p=[];h.forEach((m=>p.push(...m))),sM(p,f,d)})(u,l,-n)}return u}function Db(t,e){var r;let i=e.hachureAngle+90,n=e.hachureGap;n<0&&(n=4*e.strokeWidth),n=Math.round(Math.max(n,.1));let a=1;return e.roughness>=1&&(((r=e.randomizer)===null||r===void 0?void 0:r.next())||Math.random())>.7&&(a=n),vVe(t,n,i,a||1)}function T5(t){let e=t[0],r=t[1];return Math.sqrt(Math.pow(e[0]-r[0],2)+Math.pow(e[1]-r[1],2))}function lM(t,e){return t.type===e}function kM(t){let e=[],r=(function(s){let l=new Array;for(;s!=="";)if(s.match(/^([ \t\r\n,]+)/))s=s.substr(RegExp.$1.length);else if(s.match(/^([aAcChHlLmMqQsStTvVzZ])/))l[l.length]={type:xVe,text:RegExp.$1},s=s.substr(RegExp.$1.length);else{if(!s.match(/^(([-+]?[0-9]+(\.[0-9]*)?|[-+]?\.[0-9]+)([eE][-+]?[0-9]+)?)/))return[];l[l.length]={type:oM,text:`${parseFloat(RegExp.$1)}`},s=s.substr(RegExp.$1.length)}return l[l.length]={type:Qae,text:""},l})(t),i="BOD",n=0,a=r[n];for(;!lM(a,Qae);){let s=0,l=[];if(i==="BOD"){if(a.text!=="M"&&a.text!=="m")return kM("M0,0"+t);n++,s=d5[a.text],i=a.text}else lM(a,oM)?s=d5[i]:(n++,s=d5[a.text],i=a.text);if(!(n+sf%2?h+r:h+e));a.push({key:"C",data:u}),e=u[4],r=u[5];break}case"Q":a.push({key:"Q",data:[...l]}),e=l[2],r=l[3];break;case"q":{let u=l.map(((h,f)=>f%2?h+r:h+e));a.push({key:"Q",data:u}),e=u[2],r=u[3];break}case"A":a.push({key:"A",data:[...l]}),e=l[5],r=l[6];break;case"a":e+=l[5],r+=l[6],a.push({key:"A",data:[l[0],l[1],l[2],l[3],l[4],e,r]});break;case"H":a.push({key:"H",data:[...l]}),e=l[0];break;case"h":e+=l[0],a.push({key:"H",data:[e]});break;case"V":a.push({key:"V",data:[...l]}),r=l[0];break;case"v":r+=l[0],a.push({key:"V",data:[r]});break;case"S":a.push({key:"S",data:[...l]}),e=l[2],r=l[3];break;case"s":{let u=l.map(((h,f)=>f%2?h+r:h+e));a.push({key:"S",data:u}),e=u[2],r=u[3];break}case"T":a.push({key:"T",data:[...l]}),e=l[0],r=l[1];break;case"t":e+=l[0],r+=l[1],a.push({key:"T",data:[e,r]});break;case"Z":case"z":a.push({key:"Z",data:[]}),e=i,r=n}return a}function sse(t){let e=[],r="",i=0,n=0,a=0,s=0,l=0,u=0;for(let{key:h,data:f}of t){switch(h){case"M":e.push({key:"M",data:[...f]}),[i,n]=f,[a,s]=f;break;case"C":e.push({key:"C",data:[...f]}),i=f[4],n=f[5],l=f[2],u=f[3];break;case"L":e.push({key:"L",data:[...f]}),[i,n]=f;break;case"H":i=f[0],e.push({key:"L",data:[i,n]});break;case"V":n=f[0],e.push({key:"L",data:[i,n]});break;case"S":{let d=0,p=0;r==="C"||r==="S"?(d=i+(i-l),p=n+(n-u)):(d=i,p=n),e.push({key:"C",data:[d,p,...f]}),l=f[0],u=f[1],i=f[2],n=f[3];break}case"T":{let[d,p]=f,m=0,g=0;r==="Q"||r==="T"?(m=i+(i-l),g=n+(n-u)):(m=i,g=n);let y=i+2*(m-i)/3,v=n+2*(g-n)/3,x=d+2*(m-d)/3,b=p+2*(g-p)/3;e.push({key:"C",data:[y,v,x,b,d,p]}),l=m,u=g,i=d,n=p;break}case"Q":{let[d,p,m,g]=f,y=i+2*(d-i)/3,v=n+2*(p-n)/3,x=m+2*(d-m)/3,b=g+2*(p-g)/3;e.push({key:"C",data:[y,v,x,b,m,g]}),l=d,u=p,i=m,n=g;break}case"A":{let d=Math.abs(f[0]),p=Math.abs(f[1]),m=f[2],g=f[3],y=f[4],v=f[5],x=f[6];d===0||p===0?(e.push({key:"C",data:[i,n,v,x,v,x]}),i=v,n=x):(i!==v||n!==x)&&(ose(i,n,v,x,d,p,m,g,y).forEach((function(b){e.push({key:"C",data:b})})),i=v,n=x);break}case"Z":e.push({key:"Z",data:[]}),i=a,n=s}r=h}return e}function Sb(t,e,r){return[t*Math.cos(r)-e*Math.sin(r),t*Math.sin(r)+e*Math.cos(r)]}function ose(t,e,r,i,n,a,s,l,u,h){let f=(d=s,Math.PI*d/180);var d;let p=[],m=0,g=0,y=0,v=0;if(h)[m,g,y,v]=h;else{[t,e]=Sb(t,e,-f),[r,i]=Sb(r,i,-f);let _=(t-r)/2,D=(e-i)/2,N=_*_/(n*n)+D*D/(a*a);N>1&&(N=Math.sqrt(N),n*=N,a*=N);let R=n*n,B=a*a,O=R*B-R*D*D-B*_*_,$=R*D*D+B*_*_,z=(l===u?-1:1)*Math.sqrt(Math.abs(O/$));y=z*n*D/a+(t+r)/2,v=z*-a*_/n+(e+i)/2,m=Math.asin(parseFloat(((e-v)/a).toFixed(9))),g=Math.asin(parseFloat(((i-v)/a).toFixed(9))),tg&&(m-=2*Math.PI),!u&&g>m&&(g-=2*Math.PI)}let x=g-m;if(Math.abs(x)>120*Math.PI/180){let _=g,D=r,N=i;g=u&&g>m?m+120*Math.PI/180*1:m+120*Math.PI/180*-1,p=ose(r=y+n*Math.cos(g),i=v+a*Math.sin(g),D,N,n,a,s,0,u,[g,_,y,v])}x=g-m;let b=Math.cos(m),T=Math.sin(m),w=Math.cos(g),k=Math.sin(g),C=Math.tan(x/4),E=4/3*n*C,S=4/3*a*C,L=[t,e],M=[t+E*T,e-S*b],I=[r+E*k,i-S*w],A=[r,i];if(M[0]=2*L[0]-M[0],M[1]=2*L[1]-M[1],h)return[M,I,A].concat(p);{p=[M,I,A].concat(p);let _=[];for(let D=0;D2){let n=[];for(let a=0;a2*Math.PI&&(m=0,g=2*Math.PI);let y=2*Math.PI/u.curveStepCount,v=Math.min(y/2,(g-m)/2),x=ise(v,h,f,d,p,m,g,1,u);if(!u.disableMultiStroke){let b=ise(v,h,f,d,p,m,g,1.5,u);x.push(...b)}return s&&(l?x.push(...fd(h,f,h+d*Math.cos(m),f+p*Math.sin(m),u),...fd(h,f,h+d*Math.cos(g),f+p*Math.sin(g),u)):x.push({op:"lineTo",data:[h,f]},{op:"lineTo",data:[h+d*Math.cos(m),f+p*Math.sin(m)]})),{type:"path",ops:x}}function ese(t,e){let r=sse(ase(kM(t))),i=[],n=[0,0],a=[0,0];for(let{key:s,data:l}of r)switch(s){case"M":a=[l[0],l[1]],n=[l[0],l[1]];break;case"L":i.push(...fd(a[0],a[1],l[0],l[1],e)),a=[l[0],l[1]];break;case"C":{let[u,h,f,d,p,m]=l;i.push(...kVe(u,h,f,d,p,m,a,e)),a=[p,m];break}case"Z":i.push(...fd(a[0],a[1],n[0],n[1],e)),a=[n[0],n[1]]}return{type:"path",ops:i}}function cM(t,e){let r=[];for(let i of t)if(i.length){let n=e.maxRandomnessOffset||0,a=i.length;if(a>2){r.push({op:"move",data:[i[0][0]+xr(n,e),i[0][1]+xr(n,e)]});for(let s=1;s500?.4:-.0016668*u+1.233334;let f=n.maxRandomnessOffset||0;f*f*100>l&&(f=u/10);let d=f/2,p=.2+.2*use(n),m=n.bowing*n.maxRandomnessOffset*(i-e)/200,g=n.bowing*n.maxRandomnessOffset*(t-r)/200;m=xr(m,n,h),g=xr(g,n,h);let y=[],v=o(()=>xr(d,n,h),"M"),x=o(()=>xr(f,n,h),"k"),b=n.preserveVertices;return a&&(s?y.push({op:"move",data:[t+(b?0:v()),e+(b?0:v())]}):y.push({op:"move",data:[t+(b?0:xr(f,n,h)),e+(b?0:xr(f,n,h))]})),s?y.push({op:"bcurveTo",data:[m+t+(r-t)*p+v(),g+e+(i-e)*p+v(),m+t+2*(r-t)*p+v(),g+e+2*(i-e)*p+v(),r+(b?0:v()),i+(b?0:v())]}):y.push({op:"bcurveTo",data:[m+t+(r-t)*p+x(),g+e+(i-e)*p+x(),m+t+2*(r-t)*p+x(),g+e+2*(i-e)*p+x(),r+(b?0:x()),i+(b?0:x())]}),y}function p5(t,e,r){if(!t.length)return[];let i=[];i.push([t[0][0]+xr(e,r),t[0][1]+xr(e,r)]),i.push([t[0][0]+xr(e,r),t[0][1]+xr(e,r)]);for(let n=1;n3){let a=[],s=1-r.curveTightness;n.push({op:"move",data:[t[1][0],t[1][1]]});for(let l=1;l+21&&n.push(l)):n.push(l),n.push(t[e+3])}else{let u=t[e+0],h=t[e+1],f=t[e+2],d=t[e+3],p=L0(u,h,.5),m=L0(h,f,.5),g=L0(f,d,.5),y=L0(p,m,.5),v=L0(m,g,.5),x=L0(y,v,.5);xM([u,p,y,x],0,r,n),xM([x,v,g,d],0,r,n)}var a,s;return n}function wVe(t,e){return b5(t,0,t.length,e)}function b5(t,e,r,i,n){let a=n||[],s=t[e],l=t[r-1],u=0,h=1;for(let f=e+1;fu&&(u=d,h=f)}return Math.sqrt(u)>i?(b5(t,e,h+1,i,a),b5(t,h,r,i,a)):(a.length||a.push(s),a.push(l)),a}function uM(t,e=.15,r){let i=[],n=(t.length-1)/3;for(let a=0;a0?b5(i,0,i.length,r):i}var _b,hM,fM,dM,pM,mM,ko,gM,xVe,oM,Qae,d5,bVe,el,D1,bM,m5,TM,rt,Yt=P(()=>{"use strict";o(sM,"t");o(yVe,"e");o(vVe,"s");o(Db,"n");_b=class{static{o(this,"o")}constructor(e){this.helper=e}fillPolygons(e,r){return this._fillPolygons(e,r)}_fillPolygons(e,r){let i=Db(e,r);return{type:"fillSketch",ops:this.renderLines(i,r)}}renderLines(e,r){let i=[];for(let n of e)i.push(...this.helper.doubleLineOps(n[0][0],n[0][1],n[1][0],n[1][1],r));return i}};o(T5,"a");hM=class extends _b{static{o(this,"h")}fillPolygons(e,r){let i=r.hachureGap;i<0&&(i=4*r.strokeWidth),i=Math.max(i,.1);let n=Db(e,Object.assign({},r,{hachureGap:i})),a=Math.PI/180*r.hachureAngle,s=[],l=.5*i*Math.cos(a),u=.5*i*Math.sin(a);for(let[h,f]of n)T5([h,f])&&s.push([[h[0]-l,h[1]+u],[...f]],[[h[0]+l,h[1]-u],[...f]]);return{type:"fillSketch",ops:this.renderLines(s,r)}}},fM=class extends _b{static{o(this,"r")}fillPolygons(e,r){let i=this._fillPolygons(e,r),n=Object.assign({},r,{hachureAngle:r.hachureAngle+90}),a=this._fillPolygons(e,n);return i.ops=i.ops.concat(a.ops),i}},dM=class{static{o(this,"i")}constructor(e){this.helper=e}fillPolygons(e,r){let i=Db(e,r=Object.assign({},r,{hachureAngle:0}));return this.dotsOnLines(i,r)}dotsOnLines(e,r){let i=[],n=r.hachureGap;n<0&&(n=4*r.strokeWidth),n=Math.max(n,.1);let a=r.fillWeight;a<0&&(a=r.strokeWidth/2);let s=n/4;for(let l of e){let u=T5(l),h=u/n,f=Math.ceil(h)-1,d=u-f*n,p=(l[0][0]+l[1][0])/2-n/4,m=Math.min(l[0][1],l[1][1]);for(let g=0;g{let l=T5(s),u=Math.floor(l/(i+n)),h=(l+n-u*(i+n))/2,f=s[0],d=s[1];f[0]>d[0]&&(f=s[1],d=s[0]);let p=Math.atan((d[1]-f[1])/(d[0]-f[0]));for(let m=0;m{let s=T5(a),l=Math.round(s/(2*r)),u=a[0],h=a[1];u[0]>h[0]&&(u=a[1],h=a[0]);let f=Math.atan((h[1]-u[1])/(h[0]-u[0]));for(let d=0;d2*Math.PI&&(E=0,S=2*Math.PI);let L=(S-E)/b.curveStepCount,M=[];for(let I=E;I<=S;I+=L)M.push([T+k*Math.cos(I),w+C*Math.sin(I)]);return M.push([T+k*Math.cos(S),w+C*Math.sin(S)]),M.push([T,w]),_1([M],b)})(e,r,i,n,a,s,h));return h.stroke!==el&&f.push(d),this._d("arc",f,h)}curve(e,r){let i=this._o(r),n=[],a=Zae(e,i);if(i.fill&&i.fill!==el)if(i.fillStyle==="solid"){let s=Zae(e,Object.assign(Object.assign({},i),{disableMultiStroke:!0,roughness:i.roughness?i.roughness+i.fillShapeRoughnessGain:0}));n.push({type:"fillPath",ops:this._mergedShape(s.ops)})}else{let s=[],l=e;if(l.length){let u=typeof l[0][0]=="number"?[l]:l;for(let h of u)h.length<3?s.push(...h):h.length===3?s.push(...uM(nse([h[0],h[0],h[1],h[2]]),10,(1+i.roughness)/2)):s.push(...uM(nse(h),10,(1+i.roughness)/2))}s.length&&n.push(_1([s],i))}return i.stroke!==el&&n.push(a),this._d("curve",n,i)}polygon(e,r){let i=this._o(r),n=[],a=g5(e,!0,i);return i.fill&&(i.fillStyle==="solid"?n.push(cM([e],i)):n.push(_1([e],i))),i.stroke!==el&&n.push(a),this._d("polygon",n,i)}path(e,r){let i=this._o(r),n=[];if(!e)return this._d("path",n,i);e=(e||"").replace(/\n/g," ").replace(/(-\s)/g,"-").replace("/(ss)/g"," ");let a=i.fill&&i.fill!=="transparent"&&i.fill!==el,s=i.stroke!==el,l=!!(i.simplification&&i.simplification<1),u=(function(f,d,p){let m=sse(ase(kM(f))),g=[],y=[],v=[0,0],x=[],b=o(()=>{x.length>=4&&y.push(...uM(x,d)),x=[]},"i"),T=o(()=>{b(),y.length&&(g.push(y),y=[])},"c");for(let{key:k,data:C}of m)switch(k){case"M":T(),v=[C[0],C[1]],y.push(v);break;case"L":b(),y.push([C[0],C[1]]);break;case"C":if(!x.length){let E=y.length?y[y.length-1]:v;x.push([E[0],E[1]])}x.push([C[0],C[1]]),x.push([C[2],C[3]]),x.push([C[4],C[5]]);break;case"Z":b(),y.push([v[0],v[1]])}if(T(),!p)return g;let w=[];for(let k of g){let C=wVe(k,p);C.length&&w.push(C)}return w})(e,1,l?4-4*(i.simplification||1):(1+i.roughness)/2),h=ese(e,i);if(a)if(i.fillStyle==="solid")if(u.length===1){let f=ese(e,Object.assign(Object.assign({},i),{disableMultiStroke:!0,roughness:i.roughness?i.roughness+i.fillShapeRoughnessGain:0}));n.push({type:"fillPath",ops:this._mergedShape(f.ops)})}else n.push(cM(u,i));else n.push(_1(u,i));return s&&(l?u.forEach((f=>{n.push(g5(f,!1,i))})):n.push(h)),this._d("path",n,i)}opsToPath(e,r){let i="";for(let n of e.ops){let a=typeof r=="number"&&r>=0?n.data.map((s=>+s.toFixed(r))):n.data;switch(n.op){case"move":i+=`M${a[0]} ${a[1]} `;break;case"bcurveTo":i+=`C${a[0]} ${a[1]}, ${a[2]} ${a[3]}, ${a[4]} ${a[5]} `;break;case"lineTo":i+=`L${a[0]} ${a[1]} `}}return i.trim()}toPaths(e){let r=e.sets||[],i=e.options||this.defaultOptions,n=[];for(let a of r){let s=null;switch(a.type){case"path":s={d:this.opsToPath(a),stroke:i.stroke,strokeWidth:i.strokeWidth,fill:el};break;case"fillPath":s={d:this.opsToPath(a),stroke:el,strokeWidth:0,fill:i.fill||el};break;case"fillSketch":s=this.fillSketch(a,i)}s&&n.push(s)}return n}fillSketch(e,r){let i=r.fillWeight;return i<0&&(i=r.strokeWidth/2),{d:this.opsToPath(e),stroke:r.fill||el,strokeWidth:i,fill:el}}_mergedShape(e){return e.filter(((r,i)=>i===0||r.op!=="move"))}},bM=class{static{o(this,"st")}constructor(e,r){this.canvas=e,this.ctx=this.canvas.getContext("2d"),this.gen=new D1(r)}draw(e){let r=e.sets||[],i=e.options||this.getDefaultOptions(),n=this.ctx,a=e.options.fixedDecimalPlaceDigits;for(let s of r)switch(s.type){case"path":n.save(),n.strokeStyle=i.stroke==="none"?"transparent":i.stroke,n.lineWidth=i.strokeWidth,i.strokeLineDash&&n.setLineDash(i.strokeLineDash),i.strokeLineDashOffset&&(n.lineDashOffset=i.strokeLineDashOffset),this._drawToContext(n,s,a),n.restore();break;case"fillPath":{n.save(),n.fillStyle=i.fill||"";let l=e.shape==="curve"||e.shape==="polygon"||e.shape==="path"?"evenodd":"nonzero";this._drawToContext(n,s,a,l),n.restore();break}case"fillSketch":this.fillSketch(n,s,i)}}fillSketch(e,r,i){let n=i.fillWeight;n<0&&(n=i.strokeWidth/2),e.save(),i.fillLineDash&&e.setLineDash(i.fillLineDash),i.fillLineDashOffset&&(e.lineDashOffset=i.fillLineDashOffset),e.strokeStyle=i.fill||"",e.lineWidth=n,this._drawToContext(e,r,i.fixedDecimalPlaceDigits),e.restore()}_drawToContext(e,r,i,n="nonzero"){e.beginPath();for(let a of r.ops){let s=typeof i=="number"&&i>=0?a.data.map((l=>+l.toFixed(i))):a.data;switch(a.op){case"move":e.moveTo(s[0],s[1]);break;case"bcurveTo":e.bezierCurveTo(s[0],s[1],s[2],s[3],s[4],s[5]);break;case"lineTo":e.lineTo(s[0],s[1])}}r.type==="fillPath"?e.fill(n):e.stroke()}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}line(e,r,i,n,a){let s=this.gen.line(e,r,i,n,a);return this.draw(s),s}rectangle(e,r,i,n,a){let s=this.gen.rectangle(e,r,i,n,a);return this.draw(s),s}ellipse(e,r,i,n,a){let s=this.gen.ellipse(e,r,i,n,a);return this.draw(s),s}circle(e,r,i,n){let a=this.gen.circle(e,r,i,n);return this.draw(a),a}linearPath(e,r){let i=this.gen.linearPath(e,r);return this.draw(i),i}polygon(e,r){let i=this.gen.polygon(e,r);return this.draw(i),i}arc(e,r,i,n,a,s,l=!1,u){let h=this.gen.arc(e,r,i,n,a,s,l,u);return this.draw(h),h}curve(e,r){let i=this.gen.curve(e,r);return this.draw(i),i}path(e,r){let i=this.gen.path(e,r);return this.draw(i),i}},m5="http://www.w3.org/2000/svg",TM=class{static{o(this,"ot")}constructor(e,r){this.svg=e,this.gen=new D1(r)}draw(e){let r=e.sets||[],i=e.options||this.getDefaultOptions(),n=this.svg.ownerDocument||window.document,a=n.createElementNS(m5,"g"),s=e.options.fixedDecimalPlaceDigits;for(let l of r){let u=null;switch(l.type){case"path":u=n.createElementNS(m5,"path"),u.setAttribute("d",this.opsToPath(l,s)),u.setAttribute("stroke",i.stroke),u.setAttribute("stroke-width",i.strokeWidth+""),u.setAttribute("fill","none"),i.strokeLineDash&&u.setAttribute("stroke-dasharray",i.strokeLineDash.join(" ").trim()),i.strokeLineDashOffset&&u.setAttribute("stroke-dashoffset",`${i.strokeLineDashOffset}`);break;case"fillPath":u=n.createElementNS(m5,"path"),u.setAttribute("d",this.opsToPath(l,s)),u.setAttribute("stroke","none"),u.setAttribute("stroke-width","0"),u.setAttribute("fill",i.fill||""),e.shape!=="curve"&&e.shape!=="polygon"||u.setAttribute("fill-rule","evenodd");break;case"fillSketch":u=this.fillSketch(n,l,i)}u&&a.appendChild(u)}return a}fillSketch(e,r,i){let n=i.fillWeight;n<0&&(n=i.strokeWidth/2);let a=e.createElementNS(m5,"path");return a.setAttribute("d",this.opsToPath(r,i.fixedDecimalPlaceDigits)),a.setAttribute("stroke",i.fill||""),a.setAttribute("stroke-width",n+""),a.setAttribute("fill","none"),i.fillLineDash&&a.setAttribute("stroke-dasharray",i.fillLineDash.join(" ").trim()),i.fillLineDashOffset&&a.setAttribute("stroke-dashoffset",`${i.fillLineDashOffset}`),a}get generator(){return this.gen}getDefaultOptions(){return this.gen.defaultOptions}opsToPath(e,r){return this.gen.opsToPath(e,r)}line(e,r,i,n,a){let s=this.gen.line(e,r,i,n,a);return this.draw(s)}rectangle(e,r,i,n,a){let s=this.gen.rectangle(e,r,i,n,a);return this.draw(s)}ellipse(e,r,i,n,a){let s=this.gen.ellipse(e,r,i,n,a);return this.draw(s)}circle(e,r,i,n){let a=this.gen.circle(e,r,i,n);return this.draw(a)}linearPath(e,r){let i=this.gen.linearPath(e,r);return this.draw(i)}polygon(e,r){let i=this.gen.polygon(e,r);return this.draw(i)}arc(e,r,i,n,a,s,l=!1,u){let h=this.gen.arc(e,r,i,n,a,s,l,u);return this.draw(h)}curve(e,r){let i=this.gen.curve(e,r);return this.draw(i)}path(e,r){let i=this.gen.path(e,r);return this.draw(i)}},rt={canvas:o((t,e)=>new bM(t,e),"canvas"),svg:o((t,e)=>new TM(t,e),"svg"),generator:o(t=>new D1(t),"generator"),newSeed:o(()=>D1.newSeed(),"newSeed")}});function hse(t,e){let{labelStyles:r}=tt(e);e.labelStyle=r;let i=mt(e),n=i;i||(n="anchor");let a=t.insert("g").attr("class",n).attr("id",e.domId||e.id),s=1,{cssStyles:l}=e,u=rt.svg(a),h=st(e,{fill:"black",stroke:"none",fillStyle:"solid"});e.look!=="handDrawn"&&(h.roughness=0);let f=u.circle(0,0,s*2,h),d=a.insert(()=>f,":first-child");return d.attr("class","anchor").attr("style",xi(l)),at(e,d),e.intersect=function(p){return Q.info("Circle intersect",e,s,p),et.circle(e,s,p)},a}var fse=P(()=>{"use strict";bt();zt();Xt();Ht();Yt();er();o(hse,"anchor")});function dse(t,e,r,i,n,a,s){let u=(t+r)/2,h=(e+i)/2,f=Math.atan2(i-e,r-t),d=(r-t)/2,p=(i-e)/2,m=d/n,g=p/a,y=Math.sqrt(m**2+g**2);if(y>1)throw new Error("The given radii are too small to create an arc between the points.");let v=Math.sqrt(1-y**2),x=u+v*a*Math.sin(f)*(s?-1:1),b=h-v*n*Math.cos(f)*(s?-1:1),T=Math.atan2((e-b)/a,(t-x)/n),k=Math.atan2((i-b)/a,(r-x)/n)-T;s&&k<0&&(k+=2*Math.PI),!s&&k>0&&(k-=2*Math.PI);let C=[];for(let E=0;E<20;E++){let S=E/19,L=T+S*k,M=x+n*Math.cos(L),I=b+a*Math.sin(L);C.push({x:M,y:I})}return C}function EVe(t,e,r){let[i,n]=[e,r].sort((a,s)=>s-a);return n*(1-Math.sqrt(1-(t/i/2)**2))}async function pse(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?16:n,s=e.look==="neo"?12:n,l=o(L=>L+s,"calcTotalHeight"),u=o(L=>{let M=L/2;return[M/(2.5+L/50),M]},"calcEllipseRadius"),{shapeSvg:h,bbox:f}=await vt(t,e,mt(e)),d=l(e?.height?e?.height:f.height),[p,m]=u(d),g=EVe(d,p,m),v=(e?.width?e?.width:f.width)+a*2+g-g,x=d,{cssStyles:b}=e,T=[{x:v/2,y:-x/2},{x:-v/2,y:-x/2},...dse(-v/2,-x/2,-v/2,x/2,p,m,!1),{x:v/2,y:x/2},...dse(v/2,x/2,v/2,-x/2,p,m,!0)],w=rt.svg(h),k=st(e,{});e.look!=="handDrawn"&&(k.roughness=0,k.fillStyle="solid");let C=rr(T),E=w.path(C,k),S=h.insert(()=>E,":first-child");return S.attr("class","basic label-container outer-path"),b&&e.look!=="handDrawn"&&S.selectAll("path").attr("style",b),i&&e.look!=="handDrawn"&&S.selectAll("path").attr("style",i),S.attr("transform",`translate(${p/2}, 0)`),at(e,S),e.intersect=function(L){return et.polygon(e,T,L)},h}var mse=P(()=>{"use strict";zt();Xt();Ht();Yt();o(dse,"generateArcPoints");o(EVe,"calculateArcSagitta");o(pse,"bowTieRect")});function ds(t,e,r,i){return t.insert("polygon",":first-child").attr("points",i.map(function(n){return n.x+","+n.y}).join(" ")).attr("class","label-container").attr("transform","translate("+-e/2+","+r/2+")")}var Vh=P(()=>{"use strict";o(ds,"insertPolygonShape")});async function gse(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?28:n,s=e.look==="neo"?24:n,{shapeSvg:l,bbox:u}=await vt(t,e,mt(e)),h=(e?.width??u.width)+(e.look==="neo"?a*2:a+k5),f=(e?.height??u.height)+(e.look==="neo"?s*2:s),d=0,p=h,m=-f,g=0,y=[{x:d+k5,y:m},{x:p,y:m},{x:p,y:g},{x:d,y:g},{x:d,y:m+k5},{x:d+k5,y:m}],v,{cssStyles:x}=e;if(e.look==="handDrawn"){let b=rt.svg(l),T=st(e,{}),w=rr(y),k=b.path(w,T);v=l.insert(()=>k,":first-child").attr("transform",`translate(${-h/2}, ${f/2})`),x&&v.attr("style",x)}else v=ds(l,h,f,y);return i&&v.attr("style",i),at(e,v),e.intersect=function(b){return et.polygon(e,y,b)},l}var k5,yse=P(()=>{"use strict";zt();Xt();Ht();Yt();Vh();zt();k5=12;o(gse,"card")});function vse(t,e){let{nodeStyles:r}=tt(e);e.label="";let i=t.insert("g").attr("class",mt(e)).attr("id",e.domId??e.id),{cssStyles:n}=e,a=Math.max(28,e.width??0),s=[{x:0,y:a/2},{x:a/2,y:0},{x:0,y:-a/2},{x:-a/2,y:0}],l=rt.svg(i),u=st(e,{});e.look!=="handDrawn"&&(u.roughness=0,u.fillStyle="solid");let h=rr(s),f=l.path(h,u),d=i.insert(()=>f,":first-child");return n&&e.look!=="handDrawn"&&d.selectAll("path").attr("style",n),r&&e.look!=="handDrawn"&&d.selectAll("path").attr("style",r),e.width=28,e.height=28,e.intersect=function(p){return et.polygon(e,s,p)},i}var xse=P(()=>{"use strict";Xt();Yt();Ht();zt();o(vse,"choice")});async function C5(t,e,r){let{labelStyles:i,nodeStyles:n}=tt(e);e.labelStyle=i;let{shapeSvg:a,bbox:s,halfPadding:l}=await vt(t,e,mt(e)),u=16,h=r?.padding??l,f=e.look==="neo"?s.width/2+u*2:s.width/2+h,d,{cssStyles:p}=e;if(e.look==="handDrawn"){let m=rt.svg(a),g=st(e,{}),y=m.circle(0,0,f*2,g);d=a.insert(()=>y,":first-child"),d.attr("class","basic label-container").attr("style",xi(p))}else d=a.insert("circle",":first-child").attr("class","basic label-container").attr("style",n).attr("r",f).attr("cx",0).attr("cy",0);return at(e,d),e.calcIntersect=function(m,g){let y=m.width/2;return et.circle(m,y,g)},e.intersect=function(m){return Q.info("Circle intersect",e,f,m),et.circle(e,f,m)},a}var CM=P(()=>{"use strict";Yt();bt();er();Xt();Ht();zt();o(C5,"circle")});function SVe(t){let e=Math.cos(Math.PI/4),r=Math.sin(Math.PI/4),i=t*2,n={x:i/2*e,y:i/2*r},a={x:-(i/2)*e,y:i/2*r},s={x:-(i/2)*e,y:-(i/2)*r},l={x:i/2*e,y:-(i/2)*r};return`M ${a.x},${a.y} L ${l.x},${l.y} + M ${n.x},${n.y} L ${s.x},${s.y}`}function bse(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r,e.label="";let n=t.insert("g").attr("class",mt(e)).attr("id",e.domId??e.id),a=Math.max(30,e?.width??0),{cssStyles:s}=e,l=rt.svg(n),u=st(e,{});e.look!=="handDrawn"&&(u.roughness=0,u.fillStyle="solid");let h=l.circle(0,0,a*2,u),f=SVe(a),d=l.path(f,u),p=n.insert(()=>h,":first-child");return p.insert(()=>d),p.attr("class","outer-path"),s&&e.look!=="handDrawn"&&p.selectAll("path").attr("style",s),i&&e.look!=="handDrawn"&&p.selectAll("path").attr("style",i),at(e,p),e.intersect=function(m){return Q.info("crossedCircle intersect",e,{radius:a,point:m}),et.circle(e,a,m)},n}var Tse=P(()=>{"use strict";bt();zt();Ht();Yt();Xt();o(SVe,"createLine");o(bse,"crossedCircle")});function dd(t,e,r,i=100,n=0,a=180){let s=[],l=n*Math.PI/180,f=(a*Math.PI/180-l)/(i-1);for(let d=0;dk,":first-child").attr("stroke-opacity",0),C.insert(()=>T,":first-child"),C.attr("class","text"),p&&e.look!=="handDrawn"&&C.selectAll("path").attr("style",p),i&&e.look!=="handDrawn"&&C.selectAll("path").attr("style",i),C.attr("transform",`translate(${d}, 0)`),s.attr("transform",`translate(${-h/2+d-(a.x-(a.left??0))},${-f/2+(e.padding??0)/2-(a.y-(a.top??0))})`),at(e,C),e.intersect=function(E){return et.polygon(e,g,E)},n}var Cse=P(()=>{"use strict";zt();Xt();Ht();Yt();o(dd,"generateCirclePoints");o(kse,"curlyBraceLeft")});function pd(t,e,r,i=100,n=0,a=180){let s=[],l=n*Math.PI/180,f=(a*Math.PI/180-l)/(i-1);for(let d=0;dk,":first-child").attr("stroke-opacity",0),C.insert(()=>T,":first-child"),C.attr("class","text"),p&&e.look!=="handDrawn"&&C.selectAll("path").attr("style",p),i&&e.look!=="handDrawn"&&C.selectAll("path").attr("style",i),C.attr("transform",`translate(${-d}, 0)`),s.attr("transform",`translate(${-h/2+(e.padding??0)/2-(a.x-(a.left??0))},${-f/2+(e.padding??0)/2-(a.y-(a.top??0))})`),at(e,C),e.intersect=function(E){return et.polygon(e,g,E)},n}var Ese=P(()=>{"use strict";zt();Xt();Ht();Yt();o(pd,"generateCirclePoints");o(wse,"curlyBraceRight")});function ps(t,e,r,i=100,n=0,a=180){let s=[],l=n*Math.PI/180,f=(a*Math.PI/180-l)/(i-1);for(let d=0;dL,":first-child").attr("stroke-opacity",0),M.insert(()=>w,":first-child"),M.insert(()=>E,":first-child"),M.attr("class","text"),p&&e.look!=="handDrawn"&&M.selectAll("path").attr("style",p),i&&e.look!=="handDrawn"&&M.selectAll("path").attr("style",i),M.attr("transform",`translate(${d-d/4}, 0)`),s.attr("transform",`translate(${-h/2+(e.padding??0)/2-(a.x-(a.left??0))},${-f/2+(e.padding??0)/2-(a.y-(a.top??0))})`),at(e,M),e.intersect=function(I){return et.polygon(e,y,I)},n}var Ase=P(()=>{"use strict";zt();Xt();Ht();Yt();o(ps,"generateCirclePoints");o(Sse,"curlyBraces")});async function _se(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?16:n,s=e.look==="neo"?12:n,l=20,u=5,{shapeSvg:h,bbox:f}=await vt(t,e,mt(e)),d=Math.max(l,(f.width+a*2)*1.25,e?.width??0),p=Math.max(u,f.height+s*2,e?.height??0),m=p/2,{cssStyles:g}=e,y=rt.svg(h),v=st(e,{});e.look!=="handDrawn"&&(v.roughness=0,v.fillStyle="solid");let x=d,b=p,T=x-m,w=b/4,k=[{x:T,y:0},{x:w,y:0},{x:0,y:b/2},{x:w,y:b},{x:T,y:b},...D0(-T,-b/2,m,50,270,90)],C=rr(k),E=y.path(C,v),S=h.insert(()=>E,":first-child");return S.attr("class","basic label-container outer-path"),g&&e.look!=="handDrawn"&&S.selectChildren("path").attr("style",g),i&&e.look!=="handDrawn"&&S.selectChildren("path").attr("style",i),S.attr("transform",`translate(${-d/2}, ${-p/2})`),at(e,S),e.intersect=function(L){return et.polygon(e,k,L)},h}var Dse=P(()=>{"use strict";zt();Xt();Ht();Yt();o(_se,"curvedTrapezoid")});async function Nse(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?24:n,s=e.look==="neo"?24:n;if(e.width||e.height){let v=e.width??0;e.width=(e.width??0)-s,e.widthk,":first-child"),g=l.insert(()=>w,":first-child"),g.attr("class","basic label-container"),y&&g.attr("style",y)}else{let v=AVe(0,0,f,m,d,p);g=l.insert("path",":first-child").attr("d",v).attr("class","basic label-container outer-path").attr("style",xi(y)).attr("style",i)}return g.attr("label-offset-y",p),g.attr("transform",`translate(${-f/2}, ${-(m/2+p)})`),at(e,g),h.attr("transform",`translate(${-(u.width/2)-(u.x-(u.left??0))}, ${-(u.height/2)+(e.padding??0)/1.5-(u.y-(u.top??0))})`),e.intersect=function(v){let x=et.rect(e,v),b=x.x-(e.x??0);if(d!=0&&(Math.abs(b)<(e.width??0)/2||Math.abs(b)==(e.width??0)/2&&Math.abs(x.y-(e.y??0))>(e.height??0)/2-p)){let T=p*p*(1-b*b/(d*d));T>0&&(T=Math.sqrt(T)),T=p-T,v.y-(e.y??0)>0&&(T=-T),x.y+=T}return x},l}var AVe,_Ve,DVe,Lse,Rse,Ise=P(()=>{"use strict";zt();Xt();Ht();Yt();er();AVe=o((t,e,r,i,n,a)=>[`M${t},${e+a}`,`a${n},${a} 0,0,0 ${r},0`,`a${n},${a} 0,0,0 ${-r},0`,`l0,${i}`,`a${n},${a} 0,0,0 ${r},0`,`l0,${-i}`].join(" "),"createCylinderPathD"),_Ve=o((t,e,r,i,n,a)=>[`M${t},${e+a}`,`M${t+r},${e+a}`,`a${n},${a} 0,0,0 ${-r},0`,`l0,${i}`,`a${n},${a} 0,0,0 ${r},0`,`l0,${-i}`].join(" "),"createOuterCylinderPathD"),DVe=o((t,e,r,i,n,a)=>[`M${t-r/2},${-i/2}`,`a${n},${a} 0,0,0 ${r},0`].join(" "),"createInnerCylinderPathD"),Lse=8,Rse=8;o(Nse,"cylinder")});async function Mse(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.look==="neo"?16:e.padding??0,a=e.look==="neo"?16:e.padding??0,{shapeSvg:s,bbox:l,label:u}=await vt(t,e,mt(e)),h=l.width+n,f=l.height+a,d=f*.2,p=-h/2,m=-f/2-d/2,{cssStyles:g}=e,y=rt.svg(s),v=st(e,{});e.look!=="handDrawn"&&(v.roughness=0,v.fillStyle="solid");let x=[{x:p,y:m+d},{x:-p,y:m+d},{x:-p,y:-m},{x:p,y:-m},{x:p,y:m},{x:-p,y:m},{x:-p,y:m+d}],b=y.polygon(x.map(w=>[w.x,w.y]),v),T=s.insert(()=>b,":first-child");return T.attr("class","basic label-container outer-path"),g&&e.look!=="handDrawn"&&T.selectAll("path").attr("style",g),i&&e.look!=="handDrawn"&&T.selectAll("path").attr("style",i),u.attr("transform",`translate(${p+(e.padding??0)/2-(l.x-(l.left??0))}, ${m+d+(e.padding??0)/2-(l.y-(l.top??0))})`),at(e,T),e.intersect=function(w){return et.rect(e,w)},s}var Ose=P(()=>{"use strict";zt();Xt();Ht();Yt();o(Mse,"dividedRectangle")});async function Pse(t,e){let{labelStyles:r,nodeStyles:i}=tt(e),n=e.look==="neo"?12:5;e.labelStyle=r;let a=e.padding??0,s=e.look==="neo"?16:a,{shapeSvg:l,bbox:u}=await vt(t,e,mt(e)),h=(e?.width?e?.width/2:u.width/2)+(s??0),f=h-n,d,{cssStyles:p}=e;if(e.look==="handDrawn"){let m=rt.svg(l),g=st(e,{roughness:.2,strokeWidth:2.5}),y=st(e,{roughness:.2,strokeWidth:1.5}),v=m.circle(0,0,h*2,g),x=m.circle(0,0,f*2,y);d=l.insert("g",":first-child"),d.attr("class",xi(e.cssClasses)).attr("style",xi(p)),d.node()?.appendChild(v),d.node()?.appendChild(x)}else{d=l.insert("g",":first-child");let m=d.insert("circle",":first-child"),g=d.insert("circle");d.attr("class","basic label-container").attr("style",i),m.attr("class","outer-circle").attr("style",i).attr("r",h).attr("cx",0).attr("cy",0),g.attr("class","inner-circle").attr("style",i).attr("r",f).attr("cx",0).attr("cy",0)}return at(e,d),e.intersect=function(m){return Q.info("DoubleCircle intersect",e,h,m),et.circle(e,h,m)},l}var Bse=P(()=>{"use strict";bt();zt();Xt();Ht();Yt();er();o(Pse,"doublecircle")});function Fse(t,e,{config:{themeVariables:r}}){let{labelStyles:i,nodeStyles:n}=tt(e);e.label="",e.labelStyle=i;let a=t.insert("g").attr("class",mt(e)).attr("id",e.domId??e.id),s=7,{cssStyles:l}=e,u=rt.svg(a),{nodeBorder:h}=r,f=st(e,{fillStyle:"solid"});e.look!=="handDrawn"&&(f.roughness=0);let d=u.circle(0,0,s*2,f),p=a.insert(()=>d,":first-child");return p.selectAll("path").attr("style",`fill: ${h} !important;`),l&&l.length>0&&e.look!=="handDrawn"&&p.selectAll("path").attr("style",l),n&&e.look!=="handDrawn"&&p.selectAll("path").attr("style",n),at(e,p),e.intersect=function(m){return Q.info("filledCircle intersect",e,{radius:s,point:m}),et.circle(e,s,m)},a}var $se=P(()=>{"use strict";Yt();bt();Xt();Ht();zt();o(Fse,"filledCircle")});async function Vse(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?n*2:n;(e.width||e.height)&&(e.height=e?.height??0,e.heightx,":first-child").attr("transform",`translate(${-f/2}, ${f/2})`).attr("class","outer-path");return m&&e.look!=="handDrawn"&&b.selectChildren("path").attr("style",m),i&&e.look!=="handDrawn"&&b.selectChildren("path").attr("style",i),e.width=h,e.height=f,at(e,b),u.attr("transform",`translate(${-l.width/2-(l.x-(l.left??0))}, ${-f/2+(e.padding??0)/2+(l.y-(l.top??0))})`),e.intersect=function(T){return Q.info("Triangle intersect",e,p,T),et.polygon(e,p,T)},s}var zse,Gse,qse=P(()=>{"use strict";bt();zt();Xt();Ht();Yt();zt();zse=10,Gse=10;o(Vse,"flippedTriangle")});function Wse(t,e,{dir:r,config:{state:i,themeVariables:n}}){let{nodeStyles:a}=tt(e);e.label="";let s=t.insert("g").attr("class",mt(e)).attr("id",e.domId??e.id),{cssStyles:l}=e,u=Math.max(70,e?.width??0),h=Math.max(10,e?.height??0);r==="LR"&&(u=Math.max(10,e?.width??0),h=Math.max(70,e?.height??0));let f=-1*u/2,d=-1*h/2,p=rt.svg(s),m=st(e,{stroke:n.lineColor,fill:n.lineColor});e.look!=="handDrawn"&&(m.roughness=0,m.fillStyle="solid");let g=p.rectangle(f,d,u,h,m),y=s.insert(()=>g,":first-child");l&&e.look!=="handDrawn"&&y.selectAll("path").attr("style",l),a&&e.look!=="handDrawn"&&y.selectAll("path").attr("style",a),at(e,y);let v=i?.padding??0;return e.width&&e.height&&(e.width+=v/2||0,e.height+=v/2||0),e.intersect=function(x){return et.rect(e,x)},s}var Use=P(()=>{"use strict";Yt();Xt();Ht();zt();o(Wse,"forkJoin")});async function Hse(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=15,a=10,s=e.look==="neo"?16:e.padding??0,l=e.look==="neo"?12:e.padding??0;(e.width||e.height)&&(e.height=(e?.height??0)-l*2,e.heightb,":first-child");return T.attr("class","basic label-container outer-path"),m&&e.look!=="handDrawn"&&T.selectChildren("path").attr("style",m),i&&e.look!=="handDrawn"&&T.selectChildren("path").attr("style",i),at(e,T),e.intersect=function(w){return Q.info("Pill intersect",e,{radius:p,point:w}),et.polygon(e,v,w)},u}var Yse=P(()=>{"use strict";bt();zt();Xt();Ht();Yt();o(Hse,"halfRoundedRectangle")});async function jse(t,e){let{labelStyles:r,nodeStyles:i}=tt(e),n=e.look==="neo"?3.5:4;e.labelStyle=r;let a=e.padding??0,s=70,l=32,u=e.look==="neo"?s:a,h=e.look==="neo"?l:a;if(e.width||e.height){let T=(e.height??0)/n;e.width=(e?.width??0)-2*T-h,e.height=(e.height??0)-u}let{shapeSvg:f,bbox:d}=await vt(t,e,mt(e)),p=(e?.height?e?.height:d.height)+u,m=p/n,g=(e?.width?e?.width:d.width)+2*m+h,y=[{x:m,y:0},{x:g-m,y:0},{x:g,y:-p/2},{x:g-m,y:-p},{x:m,y:-p},{x:0,y:-p/2}],v,{cssStyles:x}=e;if(e.look==="handDrawn"){let b=rt.svg(f),T=st(e,{}),w=LVe(0,0,g,p,m),k=b.path(w,T);v=f.insert(()=>k,":first-child").attr("transform",`translate(${-g/2}, ${p/2})`),x&&v.attr("style",x)}else v=ds(f,g,p,y);return i&&v.attr("style",i),e.width=g,e.height=p,at(e,v),e.intersect=function(b){return et.polygon(e,y,b)},f}var LVe,Xse=P(()=>{"use strict";zt();Xt();Ht();Yt();Vh();LVe=o((t,e,r,i,n)=>[`M${t+n},${e}`,`L${t+r-n},${e}`,`L${t+r},${e-i/2}`,`L${t+r-n},${e-i}`,`L${t+n},${e-i}`,`L${t},${e-i/2}`,"Z"].join(" "),"createHexagonPathD");o(jse,"hexagon")});async function Kse(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.label="",e.labelStyle=r;let{shapeSvg:n}=await vt(t,e,mt(e)),a=Math.max(30,e?.width??0),s=Math.max(30,e?.height??0),{cssStyles:l}=e,u=rt.svg(n),h=st(e,{});e.look!=="handDrawn"&&(h.roughness=0,h.fillStyle="solid");let f=[{x:0,y:0},{x:a,y:0},{x:0,y:s},{x:a,y:s}],d=rr(f),p=u.path(d,h),m=n.insert(()=>p,":first-child");return m.attr("class","basic label-container outer-path"),l&&e.look!=="handDrawn"&&m.selectChildren("path").attr("style",l),i&&e.look!=="handDrawn"&&m.selectChildren("path").attr("style",i),m.attr("transform",`translate(${-a/2}, ${-s/2})`),at(e,m),e.intersect=function(g){return Q.info("Pill intersect",e,{points:f}),et.polygon(e,f,g)},n}var Qse=P(()=>{"use strict";bt();zt();Xt();Ht();Yt();o(Kse,"hourglass")});async function Zse(t,e,{config:{themeVariables:r,flowchart:i}}){let{labelStyles:n}=tt(e);e.labelStyle=n;let a=e.assetHeight??48,s=e.assetWidth??48,l=Math.max(a,s),u=i?.wrappingWidth;e.width=Math.max(l,u??0);let{shapeSvg:h,bbox:f,label:d}=await vt(t,e,"icon-shape default"),p=e.pos==="t",m=l,g=l,{nodeBorder:y}=r,{stylesMap:v}=Su(e),x=-g/2,b=-m/2,T=e.label?8:0,w=rt.svg(h),k=st(e,{stroke:"none",fill:"none"});e.look!=="handDrawn"&&(k.roughness=0,k.fillStyle="solid");let C=w.rectangle(x,b,g,m,k),E=Math.max(g,f.width),S=m+f.height+T,L=w.rectangle(-E/2,-S/2,E,S,{...k,fill:"transparent",stroke:"none"}),M=h.insert(()=>C,":first-child"),I=h.insert(()=>L);if(e.icon){let A=h.append("g");A.html(`${await fo(e.icon,{height:l,width:l,fallbackPrefix:""})}`);let _=A.node().getBBox(),D=_.width,N=_.height,R=_.x,B=_.y;A.attr("transform",`translate(${-D/2-R},${p?f.height/2+T/2-N/2-B:-f.height/2-T/2-N/2-B})`),A.attr("style",`color: ${v.get("stroke")??y};`)}return d.attr("transform",`translate(${-f.width/2-(f.x-(f.left??0))},${p?-S/2:S/2-f.height})`),M.attr("transform",`translate(0,${p?f.height/2+T/2:-f.height/2-T/2})`),at(e,I),e.intersect=function(A){if(Q.info("iconSquare intersect",e,A),!e.label)return et.rect(e,A);let _=e.x??0,D=e.y??0,N=e.height??0,R=[];return p?R=[{x:_-f.width/2,y:D-N/2},{x:_+f.width/2,y:D-N/2},{x:_+f.width/2,y:D-N/2+f.height+T},{x:_+g/2,y:D-N/2+f.height+T},{x:_+g/2,y:D+N/2},{x:_-g/2,y:D+N/2},{x:_-g/2,y:D-N/2+f.height+T},{x:_-f.width/2,y:D-N/2+f.height+T}]:R=[{x:_-g/2,y:D-N/2},{x:_+g/2,y:D-N/2},{x:_+g/2,y:D-N/2+m},{x:_+f.width/2,y:D-N/2+m},{x:_+f.width/2/2,y:D+N/2},{x:_-f.width/2,y:D+N/2},{x:_-f.width/2,y:D-N/2+m},{x:_-g/2,y:D-N/2+m}],et.polygon(e,R,A)},h}var Jse=P(()=>{"use strict";Yt();bt();lu();Xt();Ht();zt();o(Zse,"icon")});async function eoe(t,e,{config:{themeVariables:r,flowchart:i}}){let{labelStyles:n}=tt(e);e.labelStyle=n;let a=e.assetHeight??48,s=e.assetWidth??48,l=Math.max(a,s),u=i?.wrappingWidth;e.width=Math.max(l,u??0);let{shapeSvg:h,bbox:f,label:d}=await vt(t,e,"icon-shape default"),p=20,m=e.label?8:0,g=e.pos==="t",{nodeBorder:y,mainBkg:v}=r,{stylesMap:x}=Su(e),b=rt.svg(h),T=st(e,{});e.look!=="handDrawn"&&(T.roughness=0,T.fillStyle="solid");let w=x.get("fill");T.stroke=w??v;let k=h.append("g");e.icon&&k.html(`${await fo(e.icon,{height:l,width:l,fallbackPrefix:""})}`);let C=k.node().getBBox(),E=C.width,S=C.height,L=C.x,M=C.y,I=Math.max(E,S)*Math.SQRT2+p*2,A=b.circle(0,0,I,T),_=Math.max(I,f.width),D=I+f.height+m,N=b.rectangle(-_/2,-D/2,_,D,{...T,fill:"transparent",stroke:"none"}),R=h.insert(()=>A,":first-child"),B=h.insert(()=>N);return k.attr("transform",`translate(${-E/2-L},${g?f.height/2+m/2-S/2-M:-f.height/2-m/2-S/2-M})`),k.attr("style",`color: ${x.get("stroke")??y};`),d.attr("transform",`translate(${-f.width/2-(f.x-(f.left??0))},${g?-D/2:D/2-f.height})`),R.attr("transform",`translate(0,${g?f.height/2+m/2:-f.height/2-m/2})`),at(e,B),e.intersect=function(O){return Q.info("iconSquare intersect",e,O),et.rect(e,O)},h}var toe=P(()=>{"use strict";Yt();bt();lu();Xt();Ht();zt();o(eoe,"iconCircle")});var Co,R0=P(()=>{"use strict";Co=o((t,e,r,i,n)=>["M",t+n,e,"H",t+r-n,"A",n,n,0,0,1,t+r,e+n,"V",e+i-n,"A",n,n,0,0,1,t+r-n,e+i,"H",t+n,"A",n,n,0,0,1,t,e+i-n,"V",e+n,"A",n,n,0,0,1,t+n,e,"Z"].join(" "),"createRoundedRectPathD")});async function roe(t,e,{config:{themeVariables:r,flowchart:i}}){let{labelStyles:n}=tt(e);e.labelStyle=n;let a=e.assetHeight??48,s=e.assetWidth??48,l=Math.max(a,s),u=i?.wrappingWidth;e.width=Math.max(l,u??0);let{shapeSvg:h,bbox:f,halfPadding:d,label:p}=await vt(t,e,"icon-shape default"),m=e.pos==="t",g=l+d*2,y=l+d*2,{nodeBorder:v,mainBkg:x}=r,{stylesMap:b}=Su(e),T=-y/2,w=-g/2,k=e.label?8:0,C=rt.svg(h),E=st(e,{});e.look!=="handDrawn"&&(E.roughness=0,E.fillStyle="solid");let S=b.get("fill");E.stroke=S??x;let L=C.path(Co(T,w,y,g,5),E),M=Math.max(y,f.width),I=g+f.height+k,A=C.rectangle(-M/2,-I/2,M,I,{...E,fill:"transparent",stroke:"none"}),_=h.insert(()=>L,":first-child").attr("class","icon-shape2"),D=h.insert(()=>A);if(e.icon){let N=h.append("g");N.html(`${await fo(e.icon,{height:l,width:l,fallbackPrefix:""})}`);let R=N.node().getBBox(),B=R.width,O=R.height,$=R.x,z=R.y;N.attr("transform",`translate(${-B/2-$},${m?f.height/2+k/2-O/2-z:-f.height/2-k/2-O/2-z})`),N.attr("style",`color: ${b.get("stroke")??v};`)}return p.attr("transform",`translate(${-f.width/2-(f.x-(f.left??0))},${m?-I/2:I/2-f.height})`),_.attr("transform",`translate(0,${m?f.height/2+k/2:-f.height/2-k/2})`),at(e,D),e.intersect=function(N){if(Q.info("iconSquare intersect",e,N),!e.label)return et.rect(e,N);let R=e.x??0,B=e.y??0,O=e.height??0,$=[];return m?$=[{x:R-f.width/2,y:B-O/2},{x:R+f.width/2,y:B-O/2},{x:R+f.width/2,y:B-O/2+f.height+k},{x:R+y/2,y:B-O/2+f.height+k},{x:R+y/2,y:B+O/2},{x:R-y/2,y:B+O/2},{x:R-y/2,y:B-O/2+f.height+k},{x:R-f.width/2,y:B-O/2+f.height+k}]:$=[{x:R-y/2,y:B-O/2},{x:R+y/2,y:B-O/2},{x:R+y/2,y:B-O/2+g},{x:R+f.width/2,y:B-O/2+g},{x:R+f.width/2/2,y:B+O/2},{x:R-f.width/2,y:B+O/2},{x:R-f.width/2,y:B-O/2+g},{x:R-y/2,y:B-O/2+g}],et.polygon(e,$,N)},h}var ioe=P(()=>{"use strict";Yt();bt();lu();Xt();Ht();R0();zt();o(roe,"iconRounded")});async function noe(t,e,{config:{themeVariables:r,flowchart:i}}){let{labelStyles:n}=tt(e);e.labelStyle=n;let a=e.assetHeight??48,s=e.assetWidth??48,l=Math.max(a,s),u=i?.wrappingWidth;e.width=Math.max(l,u??0);let{shapeSvg:h,bbox:f,halfPadding:d,label:p}=await vt(t,e,"icon-shape default"),m=e.pos==="t",g=l+d*2,y=l+d*2,{nodeBorder:v,mainBkg:x}=r,{stylesMap:b}=Su(e),T=-y/2,w=-g/2,k=e.label?8:0,C=rt.svg(h),E=st(e,{});e.look!=="handDrawn"&&(E.roughness=0,E.fillStyle="solid");let S=b.get("fill");E.stroke=S??x;let L=C.path(Co(T,w,y,g,.1),E),M=Math.max(y,f.width),I=g+f.height+k,A=C.rectangle(-M/2,-I/2,M,I,{...E,fill:"transparent",stroke:"none"}),_=h.insert(()=>L,":first-child"),D=h.insert(()=>A);if(e.icon){let N=h.append("g");N.html(`${await fo(e.icon,{height:l,width:l,fallbackPrefix:""})}`);let R=N.node().getBBox(),B=R.width,O=R.height,$=R.x,z=R.y;N.attr("transform",`translate(${-B/2-$},${m?f.height/2+k/2-O/2-z:-f.height/2-k/2-O/2-z})`),N.attr("style",`color: ${b.get("stroke")??v};`)}return p.attr("transform",`translate(${-f.width/2-(f.x-(f.left??0))},${m?-I/2:I/2-f.height})`),_.attr("transform",`translate(0,${m?f.height/2+k/2:-f.height/2-k/2})`),at(e,D),e.intersect=function(N){if(Q.info("iconSquare intersect",e,N),!e.label)return et.rect(e,N);let R=e.x??0,B=e.y??0,O=e.height??0,$=[];return m?$=[{x:R-f.width/2,y:B-O/2},{x:R+f.width/2,y:B-O/2},{x:R+f.width/2,y:B-O/2+f.height+k},{x:R+y/2,y:B-O/2+f.height+k},{x:R+y/2,y:B+O/2},{x:R-y/2,y:B+O/2},{x:R-y/2,y:B-O/2+f.height+k},{x:R-f.width/2,y:B-O/2+f.height+k}]:$=[{x:R-y/2,y:B-O/2},{x:R+y/2,y:B-O/2},{x:R+y/2,y:B-O/2+g},{x:R+f.width/2,y:B-O/2+g},{x:R+f.width/2/2,y:B+O/2},{x:R-f.width/2,y:B+O/2},{x:R-f.width/2,y:B-O/2+g},{x:R-y/2,y:B-O/2+g}],et.polygon(e,$,N)},h}var aoe=P(()=>{"use strict";Yt();bt();lu();Xt();R0();Ht();zt();o(noe,"iconSquare")});async function soe(t,e,{config:{flowchart:r}}){let i=new Image;i.src=e?.img??"",await i.decode();let n=Number(i.naturalWidth.toString().replace("px","")),a=Number(i.naturalHeight.toString().replace("px",""));e.imageAspectRatio=n/a;let{labelStyles:s}=tt(e);e.labelStyle=s;let l=r?.wrappingWidth;e.defaultWidth=r?.wrappingWidth;let u=Math.max(e.label?l??0:0,e?.assetWidth??n),h=e.constraint==="on"&&e?.assetHeight?e.assetHeight*e.imageAspectRatio:u,f=e.constraint==="on"?h/e.imageAspectRatio:e?.assetHeight??a;e.width=Math.max(h,l??0);let{shapeSvg:d,bbox:p,label:m}=await vt(t,e,"image-shape default"),g=e.pos==="t",y=-h/2,v=-f/2,x=e.label?8:0,b=rt.svg(d),T=st(e,{});e.look!=="handDrawn"&&(T.roughness=0,T.fillStyle="solid");let w=b.rectangle(y,v,h,f,T),k=Math.max(h,p.width),C=f+p.height+x,E=b.rectangle(-k/2,-C/2,k,C,{...T,fill:"none",stroke:"none"}),S=d.insert(()=>w,":first-child"),L=d.insert(()=>E);if(e.img){let M=d.append("image");M.attr("href",e.img),M.attr("width",h),M.attr("height",f),M.attr("preserveAspectRatio","none"),M.attr("transform",`translate(${-h/2},${g?C/2-f:-C/2})`)}return m.attr("transform",`translate(${-p.width/2-(p.x-(p.left??0))},${g?-f/2-p.height/2-x/2:f/2-p.height/2+x/2})`),S.attr("transform",`translate(0,${g?p.height/2+x/2:-p.height/2-x/2})`),at(e,L),e.intersect=function(M){if(Q.info("iconSquare intersect",e,M),!e.label)return et.rect(e,M);let I=e.x??0,A=e.y??0,_=e.height??0,D=[];return g?D=[{x:I-p.width/2,y:A-_/2},{x:I+p.width/2,y:A-_/2},{x:I+p.width/2,y:A-_/2+p.height+x},{x:I+h/2,y:A-_/2+p.height+x},{x:I+h/2,y:A+_/2},{x:I-h/2,y:A+_/2},{x:I-h/2,y:A-_/2+p.height+x},{x:I-p.width/2,y:A-_/2+p.height+x}]:D=[{x:I-h/2,y:A-_/2},{x:I+h/2,y:A-_/2},{x:I+h/2,y:A-_/2+f},{x:I+p.width/2,y:A-_/2+f},{x:I+p.width/2/2,y:A+_/2},{x:I-p.width/2,y:A+_/2},{x:I-p.width/2,y:A-_/2+f},{x:I-h/2,y:A-_/2+f}],et.polygon(e,D,M)},d}var ooe=P(()=>{"use strict";Yt();bt();Xt();Ht();zt();o(soe,"imageSquare")});async function loe(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=n,s=e.look==="neo"?n*2:n,{shapeSvg:l,bbox:u}=await vt(t,e,mt(e)),h=Math.max(u.width+(s??0)*2,e?.width??0),f=Math.max(u.height+(a??0)*2,e?.height??0),d=[{x:0,y:0},{x:h,y:0},{x:h+3*f/6,y:-f},{x:-3*f/6,y:-f}],p,{cssStyles:m}=e;if(e.look==="handDrawn"){let g=rt.svg(l),y=st(e,{}),v=rr(d),x=g.path(v,y);p=l.insert(()=>x,":first-child").attr("transform",`translate(${-h/2}, ${f/2})`),m&&p.attr("style",m)}else p=ds(l,h,f,d);return i&&p.attr("style",i),e.width=h,e.height=f,at(e,p),e.intersect=function(g){return et.polygon(e,d,g)},l}var coe=P(()=>{"use strict";zt();Xt();Ht();Yt();Vh();o(loe,"inv_trapezoid")});async function qh(t,e,r){let{labelStyles:i,nodeStyles:n}=tt(e);e.labelStyle=i;let{shapeSvg:a,bbox:s}=await vt(t,e,mt(e)),l=Math.max(s.width+r.labelPaddingX*2,e?.width||0),u=Math.max(s.height+r.labelPaddingY*2,e?.height||0),h=-l/2,f=-u/2,d,{rx:p,ry:m}=e,{cssStyles:g}=e;if(r?.rx&&r.ry&&(p=r.rx,m=r.ry),e.look==="handDrawn"){let y=rt.svg(a),v=st(e,{}),x=p||m?y.path(Co(h,f,l,u,p||0),v):y.rectangle(h,f,l,u,v);d=a.insert(()=>x,":first-child"),d.attr("class","basic label-container").attr("style",xi(g))}else d=a.insert("rect",":first-child"),d.attr("class","basic label-container").attr("style",n).attr("rx",xi(p)).attr("ry",xi(m)).attr("x",h).attr("y",f).attr("width",l).attr("height",u);return at(e,d),e.calcIntersect=function(y,v){return et.rect(y,v)},e.intersect=function(y){return et.rect(e,y)},a}var L1=P(()=>{"use strict";zt();Xt();R0();Ht();Yt();er();o(qh,"drawRect")});async function uoe(t,e){let{shapeSvg:r,bbox:i,label:n}=await vt(t,e,"label"),a=r.insert("rect",":first-child");return a.attr("width",.1).attr("height",.1),r.attr("class","label edgeLabel"),n.attr("transform",`translate(${-(i.width/2)-(i.x-(i.left??0))}, ${-(i.height/2)-(i.y-(i.top??0))})`),at(e,a),e.intersect=function(u){return et.rect(e,u)},r}var hoe=P(()=>{"use strict";L1();zt();Xt();o(uoe,"labelRect")});async function foe(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=n,s=e.look==="neo"?n*2:n,{shapeSvg:l,bbox:u}=await vt(t,e,mt(e)),h=(e?.height??u.height)+a,f=(e?.width??u.width)+s,d=[{x:0,y:0},{x:f+3*h/6,y:0},{x:f,y:-h},{x:-(3*h)/6,y:-h}],p,{cssStyles:m}=e;if(e.look==="handDrawn"){let g=rt.svg(l),y=st(e,{}),v=rr(d),x=g.path(v,y);p=l.insert(()=>x,":first-child").attr("transform",`translate(${-f/2}, ${h/2})`),m&&p.attr("style",m)}else p=ds(l,f,h,d);return i&&p.attr("style",i),e.width=f,e.height=h,at(e,p),e.intersect=function(g){return et.polygon(e,d,g)},l}var doe=P(()=>{"use strict";zt();Xt();Ht();Yt();Vh();o(foe,"lean_left")});async function poe(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=n,s=e.look==="neo"?n*2:n,{shapeSvg:l,bbox:u}=await vt(t,e,mt(e)),h=(e?.height??u.height)+a,f=(e?.width??u.width)+s,d=[{x:-3*h/6,y:0},{x:f,y:0},{x:f+3*h/6,y:-h},{x:0,y:-h}],p,{cssStyles:m}=e;if(e.look==="handDrawn"){let g=rt.svg(l),y=st(e,{}),v=rr(d),x=g.path(v,y);p=l.insert(()=>x,":first-child").attr("transform",`translate(${-f/2}, ${h/2})`),m&&p.attr("style",m)}else p=ds(l,f,h,d);return i&&p.attr("style",i),e.width=f,e.height=h,at(e,p),e.intersect=function(g){return et.polygon(e,d,g)},l}var moe=P(()=>{"use strict";zt();Xt();Ht();Yt();Vh();o(poe,"lean_right")});function goe(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.label="",e.labelStyle=r;let n=t.insert("g").attr("class",mt(e)).attr("id",e.domId??e.id),{cssStyles:a}=e,s=Math.max(35,e?.width??0),l=Math.max(35,e?.height??0),u=7,h=[{x:s,y:0},{x:0,y:l+u/2},{x:s-2*u,y:l+u/2},{x:0,y:2*l},{x:s,y:l-u/2},{x:2*u,y:l-u/2}],f=rt.svg(n),d=st(e,{});e.look!=="handDrawn"&&(d.roughness=0,d.fillStyle="solid");let p=rr(h),m=f.path(p,d),g=n.insert(()=>m,":first-child");return g.attr("class","outer-path"),a&&e.look!=="handDrawn"&&g.selectAll("path").attr("style",a),i&&e.look!=="handDrawn"&&g.selectAll("path").attr("style",i),g.attr("transform",`translate(-${s/2},${-l})`),at(e,g),e.intersect=function(y){return Q.info("lightningBolt intersect",e,y),et.polygon(e,h,y)},n}var yoe=P(()=>{"use strict";bt();zt();Ht();Yt();Xt();zt();o(goe,"lightningBolt")});async function boe(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?16:n,s=e.look==="neo"?24:n;if(e.width||e.height){let x=e.width??0;e.width=(e.width??0)-a,e.widthC,":first-child").attr("class","line"),y=l.insert(()=>k,":first-child"),y.attr("class","basic label-container"),v&&y.attr("style",v)}else{let x=RVe(0,0,f,m,d,p,g);y=l.insert("path",":first-child").attr("d",x).attr("class","basic label-container outer-path").attr("style",xi(v)).attr("style",i)}return y.attr("label-offset-y",p),y.attr("transform",`translate(${-f/2}, ${-(m/2+p)})`),at(e,y),h.attr("transform",`translate(${-(u.width/2)-(u.x-(u.left??0))}, ${-(u.height/2)+p-(u.y-(u.top??0))})`),e.intersect=function(x){let b=et.rect(e,x),T=b.x-(e.x??0);if(d!=0&&(Math.abs(T)<(e.width??0)/2||Math.abs(T)==(e.width??0)/2&&Math.abs(b.y-(e.y??0))>(e.height??0)/2-p)){let w=p*p*(1-T*T/(d*d));w>0&&(w=Math.sqrt(w)),w=p-w,x.y-(e.y??0)>0&&(w=-w),b.y+=w}return b},l}var RVe,NVe,IVe,voe,xoe,Toe=P(()=>{"use strict";zt();Xt();Ht();Yt();er();RVe=o((t,e,r,i,n,a,s)=>[`M${t},${e+a}`,`a${n},${a} 0,0,0 ${r},0`,`a${n},${a} 0,0,0 ${-r},0`,`l0,${i}`,`a${n},${a} 0,0,0 ${r},0`,`l0,${-i}`,`M${t},${e+a+s}`,`a${n},${a} 0,0,0 ${r},0`].join(" "),"createCylinderPathD"),NVe=o((t,e,r,i,n,a,s)=>[`M${t},${e+a}`,`M${t+r},${e+a}`,`a${n},${a} 0,0,0 ${-r},0`,`l0,${i}`,`a${n},${a} 0,0,0 ${r},0`,`l0,${-i}`,`M${t},${e+a+s}`,`a${n},${a} 0,0,0 ${r},0`].join(" "),"createOuterCylinderPathD"),IVe=o((t,e,r,i,n,a)=>[`M${t-r/2},${-i/2}`,`a${n},${a} 0,0,0 ${r},0`].join(" "),"createInnerCylinderPathD"),voe=10,xoe=10;o(boe,"linedCylinder")});async function koe(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?16:n,s=e.look==="neo"?12:n;if(e.width||e.height){let w=e.width;e.width=(w??0)*10/11-a*2,e.width<10&&(e.width=10),e.height=(e?.height??0)-s*2,e.height<10&&(e.height=10)}let{shapeSvg:l,bbox:u,label:h}=await vt(t,e,mt(e)),f=(e?.width?e?.width:u.width)+(a??0)*2,d=(e?.height?e?.height:u.height)+(s??0)*2,p=e.look==="neo"?d/4:d/8,m=d+p,{cssStyles:g}=e,y=rt.svg(l),v=st(e,{});e.look!=="handDrawn"&&(v.roughness=0,v.fillStyle="solid");let x=[{x:-f/2-f/2*.1,y:-m/2},{x:-f/2-f/2*.1,y:m/2},...Ml(-f/2-f/2*.1,m/2,f/2+f/2*.1,m/2,p,.8),{x:f/2+f/2*.1,y:-m/2},{x:-f/2-f/2*.1,y:-m/2},{x:-f/2,y:-m/2},{x:-f/2,y:m/2*1.1},{x:-f/2,y:-m/2}],b=y.polygon(x.map(w=>[w.x,w.y]),v),T=l.insert(()=>b,":first-child");return T.attr("class","basic label-container outer-path"),g&&e.look!=="handDrawn"&&T.selectAll("path").attr("style",g),i&&e.look!=="handDrawn"&&T.selectAll("path").attr("style",i),T.attr("transform",`translate(0,${-p/2})`),h.attr("transform",`translate(${-f/2+(e.padding??0)+f/2*.1/2-(u.x-(u.left??0))},${-d/2+(e.padding??0)-p/2-(u.y-(u.top??0))})`),at(e,T),e.intersect=function(w){return et.polygon(e,x,w)},l}var Coe=P(()=>{"use strict";zt();Xt();Yt();Ht();o(koe,"linedWaveEdgedRect")});async function woe(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?16:n,s=e.look==="neo"?12:n,l=e.look==="neo"?10:5;(e.width||e.height)&&(e.width=Math.max((e?.width??0)-a*2-2*l,10),e.height=Math.max((e?.height??0)-s*2-2*l,10));let{shapeSvg:u,bbox:h,label:f}=await vt(t,e,mt(e)),d=(e?.width?e?.width:h.width)+a*2+2*l,p=(e?.height?e?.height:h.height)+s*2+2*l,m=d-2*l,g=p-2*l,y=-m/2,v=-g/2,{cssStyles:x}=e,b=rt.svg(u),T=st(e,{}),w=[{x:y-l,y:v+l},{x:y-l,y:v+g+l},{x:y+m-l,y:v+g+l},{x:y+m-l,y:v+g},{x:y+m,y:v+g},{x:y+m,y:v+g-l},{x:y+m+l,y:v+g-l},{x:y+m+l,y:v-l},{x:y+l,y:v-l},{x:y+l,y:v},{x:y,y:v},{x:y,y:v+l}],k=[{x:y,y:v+l},{x:y+m-l,y:v+l},{x:y+m-l,y:v+g},{x:y+m,y:v+g},{x:y+m,y:v},{x:y,y:v}];e.look!=="handDrawn"&&(T.roughness=0,T.fillStyle="solid");let C=rr(w),E=b.path(C,T),S=rr(k),L=b.path(S,T);e.look!=="handDrawn"&&(E=iM(E),L=iM(L));let M=u.insert("g",":first-child");return M.insert(()=>E),M.insert(()=>L),M.attr("class","basic label-container outer-path"),x&&e.look!=="handDrawn"&&M.selectAll("path").attr("style",x),i&&e.look!=="handDrawn"&&M.selectAll("path").attr("style",i),f.attr("transform",`translate(${-(h.width/2)-l-(h.x-(h.left??0))}, ${-(h.height/2)+l-(h.y-(h.top??0))})`),at(e,M),e.intersect=function(I){return et.polygon(e,w,I)},u}var Eoe=P(()=>{"use strict";zt();Ht();Yt();Xt();o(woe,"multiRect")});async function Soe(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let{shapeSvg:n,bbox:a,label:s}=await vt(t,e,mt(e)),l=e.padding??0,u=e.look==="neo"?16:l,h=e.look==="neo"?12:l,f=!0;(e.width||e.height)&&(f=!1,e.width=(e?.width??0)-u*2,e.height=(e?.height??0)-h*3);let d=Math.max(a.width,e?.width??0)+u*2,p=Math.max(a.height,e?.height??0)+h*3,m=e.look==="neo"?p/4:p/8,g=p+(f?m/2:-m/2),y=-d/2,v=-g/2,x=10,{cssStyles:b}=e,T=Ml(y-x,v+g+x,y+d-x,v+g+x,m,.8),w=T?.[T.length-1],k=[{x:y-x,y:v+x},{x:y-x,y:v+g+x},...T,{x:y+d-x,y:w.y-x},{x:y+d,y:w.y-x},{x:y+d,y:w.y-2*x},{x:y+d+x,y:w.y-2*x},{x:y+d+x,y:v-x},{x:y+x,y:v-x},{x:y+x,y:v},{x:y,y:v},{x:y,y:v+x}],C=[{x:y,y:v+x},{x:y+d-x,y:v+x},{x:y+d-x,y:w.y-x},{x:y+d,y:w.y-x},{x:y+d,y:v},{x:y,y:v}],E=rt.svg(n),S=st(e,{});e.look!=="handDrawn"&&(S.roughness=0,S.fillStyle="solid");let L=rr(k),M=E.path(L,S),I=rr(C),A=E.path(I,S),_=n.insert(()=>M,":first-child");return _.insert(()=>A),_.attr("class","basic label-container outer-path"),b&&e.look!=="handDrawn"&&_.selectAll("path").attr("style",b),i&&e.look!=="handDrawn"&&_.selectAll("path").attr("style",i),_.attr("transform",`translate(0,${-m/2})`),s.attr("transform",`translate(${-(a.width/2)-x-(a.x-(a.left??0))}, ${-(a.height/2)+x-m/2-(a.y-(a.top??0))})`),at(e,_),e.intersect=function(D){return et.polygon(e,k,D)},n}var Aoe=P(()=>{"use strict";zt();Xt();Yt();Ht();o(Soe,"multiWaveEdgedRectangle")});async function _oe(t,e,{config:{themeVariables:r}}){let{labelStyles:i,nodeStyles:n}=tt(e);e.labelStyle=i,e.useHtmlLabels||Or(Lt())||(e.centerLabel=!0);let{shapeSvg:s,bbox:l,label:u}=await vt(t,e,mt(e)),h=Math.max(l.width+(e.padding??0)*2,e?.width??0),f=Math.max(l.height+(e.padding??0)*2,e?.height??0),d=-h/2,p=-f/2,{cssStyles:m}=e,g=rt.svg(s),y=st(e,{fill:r.noteBkgColor,stroke:r.noteBorderColor});e.look!=="handDrawn"&&(y.roughness=0,y.fillStyle="solid");let v=g.rectangle(d,p,h,f,y),x=s.insert(()=>v,":first-child");return x.attr("class","basic label-container outer-path"),u.attr("class","label noteLabel"),m&&e.look!=="handDrawn"&&x.selectAll("path").attr("style",m),n&&e.look!=="handDrawn"&&x.selectAll("path").attr("style",n),u.attr("transform",`translate(${-l.width/2-(l.x-(l.left??0))}, ${-(l.height/2)-(l.y-(l.top??0))})`),at(e,x),e.intersect=function(b){return et.rect(e,b)},s}var Doe=P(()=>{"use strict";Yt();Xt();Ht();zt();Sr();Sr();o(_oe,"note")});async function Loe(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let{shapeSvg:n,bbox:a}=await vt(t,e,mt(e)),s=a.width+(e.padding??0),l=a.height+(e.padding??0),u=s+l,h=.5,f=[{x:u/2,y:0},{x:u,y:-u/2},{x:u/2,y:-u},{x:0,y:-u/2}],d,{cssStyles:p}=e;if(e.look==="handDrawn"){let m=rt.svg(n),g=st(e,{}),y=MVe(0,0,u),v=m.path(y,g);d=n.insert(()=>v,":first-child").attr("transform",`translate(${-u/2+h}, ${u/2})`),p&&d.attr("style",p)}else d=ds(n,u,u,f),d.attr("transform",`translate(${-u/2+h}, ${u/2})`);return i&&d.attr("style",i),at(e,d),e.calcIntersect=function(m,g){let y=m.width,v=[{x:y/2,y:0},{x:y,y:-y/2},{x:y/2,y:-y},{x:0,y:-y/2}],x=et.polygon(m,v,g);return{x:x.x-.5,y:x.y-.5}},e.intersect=function(m){return this.calcIntersect(e,m)},n}var MVe,Roe=P(()=>{"use strict";zt();Xt();Ht();Yt();Vh();MVe=o((t,e,r)=>[`M${t+r/2},${e}`,`L${t+r},${e-r/2}`,`L${t+r/2},${e-r}`,`L${t},${e-r/2}`,"Z"].join(" "),"createDecisionBoxPathD");o(Loe,"question")});async function Noe(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?21:n??0,s=e.look==="neo"?12:n??0,{shapeSvg:l,bbox:u,label:h}=await vt(t,e,mt(e)),f=(e?.width??u.width)+(e.look==="neo"?a*2:a),d=(e?.height??u.height)+(e.look==="neo"?s*2:s),p=-f/2,m=-d/2,g=m/2,y=[{x:p+g,y:m},{x:p,y:0},{x:p+g,y:-m},{x:-p,y:-m},{x:-p,y:m}],{cssStyles:v}=e,x=rt.svg(l),b=st(e,{});e.look!=="handDrawn"&&(b.roughness=0,b.fillStyle="solid");let T=rr(y),w=x.path(T,b),k=l.insert(()=>w,":first-child");return k.attr("class","basic label-container outer-path"),v&&e.look!=="handDrawn"&&k.selectAll("path").attr("style",v),i&&e.look!=="handDrawn"&&k.selectAll("path").attr("style",i),k.attr("transform",`translate(${-g/2},0)`),h.attr("transform",`translate(${-g/2-u.width/2-(u.x-(u.left??0))}, ${-(u.height/2)-(u.y-(u.top??0))})`),at(e,k),e.intersect=function(C){return et.polygon(e,y,C)},l}var Ioe=P(()=>{"use strict";zt();Xt();Ht();Yt();o(Noe,"rect_left_inv_arrow")});var OVe,Dc,w5=P(()=>{"use strict";Sr();Ut();To();OVe=o(async(t,e,r,i=!1,n=!1)=>{let a=e||"";typeof a=="object"&&(a=a[0]);let s=ge(),l=Or(s);return await Vi(t,a,{style:r,isTitle:i,useHtmlLabels:l,markdown:!1,isNode:n,width:Number.POSITIVE_INFINITY},s)},"createLabel"),Dc=OVe});async function Moe(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n;e.cssClasses?n="node "+e.cssClasses:n="node default";let a=t.insert("g").attr("class",n).attr("id",e.domId||e.id),s=a.insert("g"),l=a.insert("g").attr("class","label").attr("style",i),u=e.description,h=e.label,f=await Dc(l,h,e.labelStyle,!0,!0),d={width:0,height:0};if(Or(ge())){let S=f.children[0],L=Ze(f);d=S.getBoundingClientRect(),L.attr("width",d.width),L.attr("height",d.height)}Q.info("Text 2",u);let p=u||[],m=f.getBBox(),g=await Dc(l,Array.isArray(p)?p.join("
    "):p,e.labelStyle,!0,!0),y=g.children[0],v=Ze(g);d=y.getBoundingClientRect(),v.attr("width",d.width),v.attr("height",d.height);let x=(e.padding||0)/2;Ze(g).attr("transform","translate( "+(d.width>m.width?0:(m.width-d.width)/2)+", "+(m.height+x+5)+")"),Ze(f).attr("transform","translate( "+(d.width(Q.debug("Rough node insert CXC",M),I),":first-child"),C=a.insert(()=>(Q.debug("Rough node insert CXC",M),M),":first-child")}else C=s.insert("rect",":first-child"),E=s.insert("line"),C.attr("class","outer title-state").attr("style",i).attr("x",-d.width/2-x).attr("y",-d.height/2-x).attr("width",d.width+(e.padding||0)).attr("height",d.height+(e.padding||0)),E.attr("class","divider").attr("x1",-d.width/2-x).attr("x2",d.width/2+x).attr("y1",-d.height/2-x+m.height+x).attr("y2",-d.height/2-x+m.height+x);return at(e,C),e.intersect=function(S){return et.rect(e,S)},a}var Ooe=P(()=>{"use strict";Pr();zt();w5();Xt();Ht();Yt();Ut();R0();bt();Sr();o(Moe,"rectWithTitle")});async function Poe(t,e,{config:{themeVariables:r}}){let i=r?.radius??5,n={rx:i,ry:i,classes:"",labelPaddingX:(e?.padding??0)*1,labelPaddingY:(e?.padding??0)*1};return qh(t,e,n)}var Boe=P(()=>{"use strict";L1();o(Poe,"roundedRect")});async function Foe(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.look==="neo"?16:e.padding??0,a=e.look==="neo"?12:e.padding??0,{shapeSvg:s,bbox:l,label:u}=await vt(t,e,mt(e)),h=(e?.width??l.width)+n*2+(e.look==="neo"?N0:N0*2),f=(e?.height??l.height)+a*2,d=h-N0,p=f,m=N0-h/2,g=-f/2,{cssStyles:y}=e,v=rt.svg(s),x=st(e,{});e.look!=="handDrawn"&&(x.roughness=0,x.fillStyle="solid");let b=[{x:m,y:g},{x:m+d,y:g},{x:m+d,y:g+p},{x:m-N0,y:g+p},{x:m-N0,y:g},{x:m,y:g},{x:m,y:g+p}],T=v.polygon(b.map(k=>[k.x,k.y]),x),w=s.insert(()=>T,":first-child");return w.attr("class","basic label-container outer-path").attr("style",xi(y)),i&&e.look!=="handDrawn"&&w.selectAll("path").attr("style",i),y&&e.look!=="handDrawn"&&w.selectAll("path").attr("style",i),u.attr("transform",`translate(${N0/2-l.width/2-(l.x-(l.left??0))}, ${-(l.height/2)-(l.y-(l.top??0))})`),at(e,w),e.intersect=function(k){return et.rect(e,k)},s}var N0,$oe=P(()=>{"use strict";zt();Xt();Ht();Yt();er();N0=8;o(Foe,"shadedProcess")});async function zoe(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?16:n,s=e.look==="neo"?12:n;(e.width||e.height)&&(e.width=Math.max((e?.width??0)-a*2,10),e.height=Math.max((e?.height??0)/1.5-s*2,10));let{shapeSvg:l,bbox:u,label:h}=await vt(t,e,mt(e)),f=(e?.width?e?.width:u.width)+a*2,d=((e?.height?e?.height:u.height)+s*2)*1.5,p=f,m=d/1.5,g=-p/2,y=-m/2,{cssStyles:v}=e,x=rt.svg(l),b=st(e,{});e.look!=="handDrawn"&&(b.roughness=0,b.fillStyle="solid");let T=[{x:g,y},{x:g,y:y+m},{x:g+p,y:y+m},{x:g+p,y:y-m/2}],w=rr(T),k=x.path(w,b),C=l.insert(()=>k,":first-child");return C.attr("class","basic label-container outer-path"),v&&e.look!=="handDrawn"&&C.selectChildren("path").attr("style",v),i&&e.look!=="handDrawn"&&C.selectChildren("path").attr("style",i),C.attr("transform",`translate(0, ${m/4})`),h.attr("transform",`translate(${-p/2+(e.padding??0)-(u.x-(u.left??0))}, ${-m/4+(e.padding??0)-(u.y-(u.top??0))})`),at(e,C),e.intersect=function(E){return et.polygon(e,T,E)},l}var Goe=P(()=>{"use strict";zt();Xt();Ht();Yt();o(zoe,"slopedRect")});async function Voe(t,e){let r=e.padding??0,i=e.look==="neo"?16:r*2,n=e.look==="neo"?12:r,a={rx:0,ry:0,classes:"",labelPaddingX:e.labelPaddingX??i,labelPaddingY:n};return qh(t,e,a)}var qoe=P(()=>{"use strict";L1();o(Voe,"squareRect")});async function Woe(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?20:n,s=e.look==="neo"?12:n,{shapeSvg:l,bbox:u}=await vt(t,e,mt(e)),h=u.height+(e.look==="neo"?s*2:s),f=u.width+h/4+(e.look==="neo"?a*2:a),d=h/2,{cssStyles:p}=e,m=rt.svg(l),g=st(e,{});e.look!=="handDrawn"&&(g.roughness=0,g.fillStyle="solid");let y=[{x:-f/2+d,y:-h/2},{x:f/2-d,y:-h/2},...D0(-f/2+d,0,d,50,90,270),{x:f/2-d,y:h/2},...D0(f/2-d,0,d,50,270,450)],v=rr(y),x=m.path(v,g),b=l.insert(()=>x,":first-child");return b.attr("class","basic label-container outer-path"),p&&e.look!=="handDrawn"&&b.selectChildren("path").attr("style",p),i&&e.look!=="handDrawn"&&b.selectChildren("path").attr("style",i),at(e,b),e.intersect=function(T){return et.polygon(e,y,T)},l}var Uoe=P(()=>{"use strict";zt();Xt();Ht();Yt();o(Woe,"stadium")});async function Hoe(t,e){let r={rx:e.look==="neo"?3:5,ry:e.look==="neo"?3:5,classes:"flowchart-node"};return qh(t,e,r)}var Yoe=P(()=>{"use strict";L1();o(Hoe,"state")});function joe(t,e,{config:{themeVariables:r}}){let{labelStyles:i,nodeStyles:n}=tt(e);e.labelStyle=i;let{cssStyles:a}=e,{lineColor:s,stateBorder:l,nodeBorder:u,nodeShadow:h}=r;(e.width||e.height)&&((e.width??0)<14&&(e.width=14),(e.height??0)<14&&(e.height=14)),e.width||(e.width=14),e.height||(e.height=14);let f=t.insert("g").attr("class","node default").attr("id",e.domId??e.id),d=rt.svg(f),p=st(e,{});e.look!=="handDrawn"&&(p.roughness=0,p.fillStyle="solid");let m=d.circle(0,0,e.width,{...p,stroke:s,strokeWidth:2}),g=l??u,y=(e.width??0)*5/14,v=d.circle(0,0,y,{...p,fill:g,stroke:g,strokeWidth:2,fillStyle:"solid"}),x=f.insert(()=>m,":first-child");if(x.insert(()=>v),e.look!=="handDrawn"&&x.attr("class","outer-path"),a&&x.selectAll("path").attr("style",a),n&&x.selectAll("path").attr("style",n),e.width<25&&h&&e.look!=="handDrawn"){let b=t.node()?.ownerSVGElement?.id??"",T=b?`${b}-drop-shadow-small`:"drop-shadow-small";x.attr("style",`filter:url(#${T})`)}return at(e,x),e.intersect=function(b){return et.circle(e,(e.width??0)/2,b)},f}var Xoe=P(()=>{"use strict";Yt();Xt();Ht();zt();o(joe,"stateEnd")});function Koe(t,e,{config:{themeVariables:r}}){let{lineColor:i,nodeShadow:n}=r;(e.width||e.height)&&((e.width??0)<14&&(e.width=14),(e.height??0)<14&&(e.height=14)),e.width||(e.width=14),e.height||(e.height=14);let a=t.insert("g").attr("class","node default").attr("id",e.domId||e.id),s;if(e.look==="handDrawn"){let u=rt.svg(a).circle(0,0,e.width,Kae(i));s=a.insert(()=>u),s.attr("class","state-start").attr("r",(e.width??7)/2).attr("width",e.width??14).attr("height",e.height??14)}else s=a.insert("circle",":first-child"),s.attr("class","state-start").attr("r",(e.width??7)/2).attr("width",e.width??14).attr("height",e.height??14);if(e.width<25&&n&&e.look!=="handDrawn"){let l=t.node()?.ownerSVGElement?.id??"",u=l?`${l}-drop-shadow-small`:"drop-shadow-small";s.attr("style",`filter:url(#${u})`)}return at(e,s),e.intersect=function(l){return et.circle(e,(e.width??7)/2,l)},a}var Qoe=P(()=>{"use strict";Yt();Xt();Ht();zt();o(Koe,"stateStart")});async function Zoe(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e?.padding??8,a=e.look==="neo"?28:n,s=e.look==="neo"?12:n,{shapeSvg:l,bbox:u}=await vt(t,e,mt(e)),h=(e?.width??u.width)+2*R1+a,f=(e?.height??u.height)+s,d=h-2*R1,p=f,m=-h/2,g=-f/2,y=[{x:0,y:0},{x:d,y:0},{x:d,y:-p},{x:0,y:-p},{x:0,y:0},{x:-8,y:0},{x:d+8,y:0},{x:d+8,y:-p},{x:-8,y:-p},{x:-8,y:0}];if(e.look==="handDrawn"){let v=rt.svg(l),x=st(e,{}),b=v.rectangle(m,g,d+16,p,x),T=v.line(m+R1,g,m+R1,g+p,x),w=v.line(m+R1+d,g,m+R1+d,g+p,x);l.insert(()=>T,":first-child"),l.insert(()=>w,":first-child");let k=l.insert(()=>b,":first-child"),{cssStyles:C}=e;k.attr("class","basic label-container").attr("style",xi(C)),at(e,k)}else{let v=ds(l,d,p,y);i&&v.attr("style",i),at(e,v)}return e.intersect=function(v){return et.polygon(e,y,v)},l}var R1,Joe=P(()=>{"use strict";zt();Xt();Ht();Yt();Vh();er();R1=8;o(Zoe,"subroutine")});async function ele(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?16:n,s=e.look==="neo"?12:n;(e.width||e.height)&&(e.height=Math.max((e?.height??0)-s*2,10),e.width=Math.max((e?.width??0)-a*2-wM*(e.height+s*2),10));let{shapeSvg:l,bbox:u}=await vt(t,e,mt(e)),h=(e?.height?e?.height:u.height)+s*2,f=wM*h,d=wM*h,m=(e?.width?e?.width:u.width)+a*2+f-f,g=h,y=-m/2,v=-g/2,{cssStyles:x}=e,b=rt.svg(l),T=st(e,{}),w=[{x:y-f/2,y:v},{x:y+m+f/2,y:v},{x:y+m+f/2,y:v+g},{x:y-f/2,y:v+g}],k=[{x:y+m-f/2,y:v+g},{x:y+m+f/2,y:v+g},{x:y+m+f/2,y:v+g-d}];e.look!=="handDrawn"&&(T.roughness=0,T.fillStyle="solid");let C=rr(w),E=b.path(C,T),S=rr(k),L=b.path(S,{...T,fillStyle:"solid"}),M=l.insert(()=>L,":first-child");return M.insert(()=>E,":first-child"),M.attr("class","basic label-container outer-path"),x&&e.look!=="handDrawn"&&M.selectAll("path").attr("style",x),i&&e.look!=="handDrawn"&&M.selectAll("path").attr("style",i),at(e,M),e.intersect=function(I){return et.polygon(e,w,I)},l}var wM,tle=P(()=>{"use strict";zt();Ht();Yt();Xt();wM=.2;o(ele,"taggedRect")});async function rle(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let{shapeSvg:n,bbox:a,label:s}=await vt(t,e,mt(e)),l=Math.max(a.width+(e.padding??0)*2,e?.width??0),u=Math.max(a.height+(e.padding??0)*2,e?.height??0),h=u/8,f=.2*l,d=.2*u,p=u+h,{cssStyles:m}=e,g=rt.svg(n),y=st(e,{});e.look!=="handDrawn"&&(y.roughness=0,y.fillStyle="solid");let v=[{x:-l/2-l/2*.1,y:p/2},...Ml(-l/2-l/2*.1,p/2,l/2+l/2*.1,p/2,h,.8),{x:l/2+l/2*.1,y:-p/2},{x:-l/2-l/2*.1,y:-p/2}],x=-l/2+l/2*.1,b=-p/2-d*.4,T=[{x:x+l-f,y:(b+u)*1.3},{x:x+l,y:b+u-d},{x:x+l,y:(b+u)*.9},...Ml(x+l,(b+u)*1.25,x+l-f,(b+u)*1.3,-u*.02,.5)],w=rr(v),k=g.path(w,y),C=rr(T),E=g.path(C,{...y,fillStyle:"solid"}),S=n.insert(()=>E,":first-child");return S.insert(()=>k,":first-child"),S.attr("class","basic label-container outer-path"),m&&e.look!=="handDrawn"&&S.selectAll("path").attr("style",m),i&&e.look!=="handDrawn"&&S.selectAll("path").attr("style",i),S.attr("transform",`translate(0,${-h/2})`),s.attr("transform",`translate(${-l/2+(e.padding??0)-(a.x-(a.left??0))},${-u/2+(e.padding??0)-h/2-(a.y-(a.top??0))})`),at(e,S),e.intersect=function(L){return et.polygon(e,v,L)},n}var ile=P(()=>{"use strict";zt();Xt();Yt();Ht();o(rle,"taggedWaveEdgedRectangle")});async function nle(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let{shapeSvg:n,bbox:a}=await vt(t,e,mt(e)),s=Math.max(a.width+(e.padding??0),e?.width||0),l=Math.max(a.height+(e.padding??0),e?.height||0),u=-s/2,h=-l/2,f=n.insert("rect",":first-child");return f.attr("class","text").attr("style",i).attr("rx",0).attr("ry",0).attr("x",u).attr("y",h).attr("width",s).attr("height",l),at(e,f),e.intersect=function(d){return et.rect(e,d)},n}var ale=P(()=>{"use strict";zt();Xt();Ht();o(nle,"text")});async function lle(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?12:n/2;if(e.width||e.height){let y=e.height??0;e.height=(e.height??0)-a,e.heightT,":first-child"),g=s.insert(()=>b,":first-child"),g.attr("class","basic label-container"),m&&g.attr("style",m)}else{let y=PVe(0,0,p,h,d,f);g=s.insert("path",":first-child").attr("d",y).attr("class","basic label-container").attr("style",xi(m)).attr("style",i),g.attr("class","basic label-container outer-path"),m&&g.selectAll("path").attr("style",m),i&&g.selectAll("path").attr("style",i)}return g.attr("label-offset-x",d),g.attr("transform",`translate(${-p/2}, ${h/2} )`),u.attr("transform",`translate(${-(l.width/2)-d-(l.x-(l.left??0))}, ${-(l.height/2)-(l.y-(l.top??0))})`),at(e,g),e.intersect=function(y){let v=et.rect(e,y),x=v.y-(e.y??0);if(f!=0&&(Math.abs(x)<(e.height??0)/2||Math.abs(x)==(e.height??0)/2&&Math.abs(v.x-(e.x??0))>(e.width??0)/2-d)){let b=d*d*(1-x*x/(f*f));b!=0&&(b=Math.sqrt(Math.abs(b))),b=d-b,y.x-(e.x??0)>0&&(b=-b),v.x+=b}return v},s}var PVe,BVe,FVe,sle,ole,cle=P(()=>{"use strict";zt();Ht();Yt();Xt();er();PVe=o((t,e,r,i,n,a)=>`M${t},${e} + a${n},${a} 0,0,1 0,${-i} + l${r},0 + a${n},${a} 0,0,1 0,${i} + M${r},${-i} + a${n},${a} 0,0,0 0,${i} + l${-r},0`,"createCylinderPathD"),BVe=o((t,e,r,i,n,a)=>[`M${t},${e}`,`M${t+r},${e}`,`a${n},${a} 0,0,0 0,${-i}`,`l${-r},0`,`a${n},${a} 0,0,0 0,${i}`,`l${r},0`].join(" "),"createOuterCylinderPathD"),FVe=o((t,e,r,i,n,a)=>[`M${t+r/2},${-i/2}`,`a${n},${a} 0,0,0 0,${i}`].join(" "),"createInnerCylinderPathD"),sle=5,ole=10;o(lle,"tiltedCylinder")});async function ule(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=(e.look==="neo",n),s=e.look==="neo"?n*2:n,{shapeSvg:l,bbox:u}=await vt(t,e,mt(e)),h=(e?.height??u.height)+a,f=(e?.width??u.width)+s,d=[{x:-3*h/6,y:0},{x:f+3*h/6,y:0},{x:f,y:-h},{x:0,y:-h}],p,{cssStyles:m}=e;if(e.look==="handDrawn"){let g=rt.svg(l),y=st(e,{}),v=rr(d),x=g.path(v,y);p=l.insert(()=>x,":first-child").attr("transform",`translate(${-f/2}, ${h/2})`),m&&p.attr("style",m)}else p=ds(l,f,h,d);return i&&p.attr("style",i),e.width=f,e.height=h,at(e,p),e.intersect=function(g){return et.polygon(e,d,g)},l}var hle=P(()=>{"use strict";zt();Xt();Ht();Yt();Vh();o(ule,"trapezoid")});async function fle(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?16:n,s=e.look==="neo"?12:n,l=15,u=5;(e.width||e.height)&&(e.height=(e.height??0)-s*2,e.heightb,":first-child");return T.attr("class","basic label-container outer-path"),m&&e.look!=="handDrawn"&&T.selectChildren("path").attr("style",m),i&&e.look!=="handDrawn"&&T.selectChildren("path").attr("style",i),at(e,T),e.intersect=function(w){return et.polygon(e,v,w)},h}var dle=P(()=>{"use strict";zt();Xt();Ht();Yt();o(fle,"trapezoidalPentagon")});async function gle(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?n*2:n;(e.width||e.height)&&(e.width=((e?.width??0)-a)/2,e.widthb,":first-child").attr("transform",`translate(${-d/2}, ${d/2})`).attr("class","outer-path");return g&&e.look!=="handDrawn"&&T.selectChildren("path").attr("style",g),i&&e.look!=="handDrawn"&&T.selectChildren("path").attr("style",i),e.width=f,e.height=d,at(e,T),u.attr("transform",`translate(${-l.width/2-(l.x-(l.left??0))}, ${d/2-(l.height+(e.padding??0)/(h?2:1)-(l.y-(l.top??0)))})`),e.intersect=function(w){return Q.info("Triangle intersect",e,m,w),et.polygon(e,m,w)},s}var ple,mle,yle=P(()=>{"use strict";bt();zt();Xt();Ht();Yt();zt();Vr();Ut();ple=10,mle=10;o(gle,"triangle")});async function vle(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?16:n,s=e.look==="neo"?12:n,l=!0;(e.width||e.height)&&(l=!1,e.width=(e?.width??0)-a*2,e.width<10&&(e.width=10),e.height=(e?.height??0)-s*2,e.height<10&&(e.height=10));let{shapeSvg:u,bbox:h,label:f}=await vt(t,e,mt(e)),d=(e?.width?e?.width:h.width)+(a??0)*2,p=(e?.height?e?.height:h.height)+(s??0)*2,m=e.look==="neo"?p/4:p/8,g=p+(l?m:-m),{cssStyles:y}=e,x=14-d,b=x>0?x/2:0,T=rt.svg(u),w=st(e,{});e.look!=="handDrawn"&&(w.roughness=0,w.fillStyle="solid");let k=[{x:-d/2-b,y:g/2},...Ml(-d/2-b,g/2,d/2+b,g/2,m,.8),{x:d/2+b,y:-g/2},{x:-d/2-b,y:-g/2}],C=rr(k),E=T.path(C,w),S=u.insert(()=>E,":first-child");return S.attr("class","basic label-container outer-path"),y&&e.look!=="handDrawn"&&S.selectAll("path").attr("style",y),i&&e.look!=="handDrawn"&&S.selectAll("path").attr("style",i),S.attr("transform",`translate(0,${-m/2})`),f.attr("transform",`translate(${-d/2+(e.padding??0)-(h.x-(h.left??0))},${-p/2+(e.padding??0)-m-(h.y-(h.top??0))})`),at(e,S),e.intersect=function(L){return et.polygon(e,k,L)},u}var xle=P(()=>{"use strict";zt();Xt();Yt();Ht();o(vle,"waveEdgedRectangle")});async function ble(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.padding??0,a=e.look==="neo"?16:n,s=e.look==="neo"?20:n;if(e.width||e.height){e.width=e?.width??0,e.width<20&&(e.width=20),e.height=e?.height??0,e.height<10&&(e.height=10);let w=Math.min(e.height*.2,e.height/4);e.height=Math.ceil(e.height-s-w*(20/9)),e.width=e.width-a*2}let{shapeSvg:l,bbox:u}=await vt(t,e,mt(e)),h=(e?.width?e?.width:u.width)+a*2,f=(e?.height?e?.height:u.height)+s,d=f/8,p=f+d*2,{cssStyles:m}=e,g=rt.svg(l),y=st(e,{});e.look!=="handDrawn"&&(y.roughness=0,y.fillStyle="solid");let v=[{x:-h/2,y:p/2},...Ml(-h/2,p/2,h/2,p/2,d,1),{x:h/2,y:-p/2},...Ml(h/2,-p/2,-h/2,-p/2,d,-1)],x=rr(v),b=g.path(x,y),T=l.insert(()=>b,":first-child");return T.attr("class","basic label-container"),m&&e.look!=="handDrawn"&&T.selectAll("path").attr("style",m),i&&e.look!=="handDrawn"&&T.selectAll("path").attr("style",i),at(e,T),e.intersect=function(w){return et.polygon(e,v,w)},l}var Tle=P(()=>{"use strict";zt();Xt();Ht();Yt();o(ble,"waveRectangle")});async function kle(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e.look==="neo"?16:e.padding??0,a=e.look==="neo"?12:e.padding??0;(e.width||e.height)&&(e.width=Math.max((e?.width??0)-n*2-On,10),e.height=Math.max((e?.height??0)-a*2-On,10));let{shapeSvg:s,bbox:l,label:u}=await vt(t,e,mt(e)),h=(e?.width?e?.width:l.width)+n*2+On,f=(e?.height?e?.height:l.height)+a*2+On,d=h-On,p=f-On,m=-d/2,g=-p/2,{cssStyles:y}=e,v=rt.svg(s),x=st(e,{}),b=[{x:m-On,y:g-On},{x:m-On,y:g+p},{x:m+d,y:g+p},{x:m+d,y:g-On}],T=`M${m-On},${g-On} L${m+d},${g-On} L${m+d},${g+p} L${m-On},${g+p} L${m-On},${g-On} + M${m-On},${g} L${m+d},${g} + M${m},${g-On} L${m},${g+p}`;e.look!=="handDrawn"&&(x.roughness=0,x.fillStyle="solid");let w=v.path(T,x),k=s.insert(()=>w,":first-child");return k.attr("transform",`translate(${On/2}, ${On/2})`),k.attr("class","basic label-container outer-path"),y&&e.look!=="handDrawn"&&k.selectAll("path").attr("style",y),i&&e.look!=="handDrawn"&&k.selectAll("path").attr("style",i),u.attr("transform",`translate(${-(l.width/2)+On/2-(l.x-(l.left??0))}, ${-(l.height/2)+On/2-(l.y-(l.top??0))})`),at(e,k),e.intersect=function(C){return et.polygon(e,b,C)},s}var On,Cle=P(()=>{"use strict";zt();Ht();Yt();Xt();On=10;o(kle,"windowPane")});async function EM(t,e){let r=e;r.alias&&(e.label=r.alias);let{theme:i,themeVariables:n}=Lt(),{rowEven:a,rowOdd:s,nodeBorder:l,borderColorArray:u}=n;if(e.look==="handDrawn"){let{themeVariables:Z}=Lt(),{background:Y}=Z,ae={...e,id:e.id+"-background",domId:(e.domId||e.id)+"-background",look:"default",cssStyles:["stroke: none",`fill: ${Y}`]};await EM(t,ae)}let h=Lt();e.useHtmlLabels=h.htmlLabels;let f=h.er?.diagramPadding??10,d=h.er?.entityPadding??6,{cssStyles:p}=e,{labelStyles:m,nodeStyles:g}=tt(e);if(r.attributes.length===0&&e.label){let Z={rx:0,ry:0,labelPaddingX:f,labelPaddingY:f*1.5,classes:""};Ra(e.label,h)+Z.labelPaddingX*20){let Z=x.width+f*2-(k+C+E+S);k+=Z/I,C+=Z/I,E>0&&(E+=Z/I),S>0&&(S+=Z/I)}let _=k+C+E+S,D=rt.svg(v),N=st(e,{});e.look!=="handDrawn"&&(N.roughness=0,N.fillStyle="solid");let R=0;w.length>0&&(R=w.reduce((Z,Y)=>Z+(Y?.rowHeight??0),0));let B=Math.max(A.width+f*2,e?.width||0,_),O=Math.max((R??0)+x.height,e?.height||0),$=-B/2,z=-O/2;if(v.selectAll("g:not(:first-child)").each((Z,Y,ae)=>{let J=Ze(ae[Y]),ee=J.attr("transform"),re=0,te=0;if(ee){let de=RegExp(/translate\(([^,]+),([^)]+)\)/).exec(ee);de&&(re=parseFloat(de[1]),te=parseFloat(de[2]),J.attr("class").includes("attribute-name")?re+=k:J.attr("class").includes("attribute-keys")?re+=k+C:J.attr("class").includes("attribute-comment")&&(re+=k+C+E))}J.attr("transform",`translate(${$+f/2+re}, ${te+z+x.height+d/2})`)}),v.select(".name").attr("transform","translate("+-x.width/2+", "+(z+d/2)+")"),i!=null&&wle.has(i)){let Z=r.colorIndex??0;v.attr("data-color-id",`color-${Z%u.length}`)}let F=D.rectangle($,z,B,O,N),V=v.insert(()=>F,":first-child").attr("class","outer-path").attr("style",p.join(""));T.push(0);for(let[Z,Y]of w.entries()){let J=(Z+1)%2===0&&Y.yOffset!==0,ee=D.rectangle($,x.height+z+Y?.yOffset,B,Y?.rowHeight,{...N,fill:J?a:s,stroke:l});v.insert(()=>ee,"g.label").attr("style",p.join("")).attr("class",`row-rect-${J?"even":"odd"}`)}let H=1e-4,X=Rb($,x.height+z,B+$,x.height+z,H),W=D.polygon(X.map(Z=>[Z.x,Z.y]),N);if(v.insert(()=>W).attr("class","divider"),X=Rb(k+$,x.height+z,k+$,O+z,H),W=D.polygon(X.map(Z=>[Z.x,Z.y]),N),v.insert(()=>W).attr("class","divider"),L){let Z=k+C+$;X=Rb(Z,x.height+z,Z,O+z,H),W=D.polygon(X.map(Y=>[Y.x,Y.y]),N),v.insert(()=>W).attr("class","divider")}if(M){let Z=k+C+E+$;X=Rb(Z,x.height+z,Z,O+z,H),W=D.polygon(X.map(Y=>[Y.x,Y.y]),N),v.insert(()=>W).attr("class","divider")}for(let Z of T){let Y=x.height+z+Z;X=Rb($,Y,B+$,Y,H),W=D.polygon(X.map(ae=>[ae.x,ae.y]),N),v.insert(()=>W).attr("class","divider")}if(at(e,V),g&&e.look!=="handDrawn")if(i!=null&&$Ve.has(i))v.selectAll("path").attr("style",g);else{let Y=g.split(";")?.filter(ae=>ae.includes("stroke"))?.map(ae=>`${ae}`).join("; ");v.selectAll("path").attr("style",Y??""),v.selectAll(".row-rect-even path").attr("style",g)}return e.intersect=function(Z){return et.rect(e,Z)},v}async function Lb(t,e,r,i=0,n=0,a=[],s=""){let l=t.insert("g").attr("class",`label ${a.join(" ")}`).attr("transform",`translate(${i}, ${n})`).attr("style",s);e!==ou(e)&&(e=ou(e),e=e.replaceAll("<","<").replaceAll(">",">"));let u=l.node().appendChild(await Vi(l,e,{width:Ra(e,r)+100,style:s,useHtmlLabels:r.htmlLabels},r));if(e.includes("<")||e.includes(">")){let f=u.children[0];for(f.textContent=f.textContent.replaceAll("<","<").replaceAll(">",">");f.childNodes[0];)f=f.childNodes[0],f.textContent=f.textContent.replaceAll("<","<").replaceAll(">",">")}let h=u.getBBox();if(ls(r.htmlLabels)){let f=u.children[0];f.style.textAlign="start";let d=Ze(u);h=f.getBoundingClientRect(),d.attr("width",h.width),d.attr("height",h.height)}return h}function Rb(t,e,r,i,n){return t===r?[{x:t-n/2,y:e},{x:t+n/2,y:e},{x:r+n/2,y:i},{x:r-n/2,y:i}]:[{x:t,y:e-n/2},{x:t,y:e+n/2},{x:r,y:i+n/2},{x:r,y:i-n/2}]}var wle,$Ve,Ele=P(()=>{"use strict";zt();Xt();Ht();Yt();L1();Sr();To();Vr();Pr();er();wle=new Set(["redux-color","redux-dark-color"]),$Ve=new Set(["redux","redux-dark","redux-color","redux-dark-color"]);o(EM,"erBox");o(Lb,"addText");o(Rb,"lineToPolygon")});async function Sle(t,e,r,i,n=r.class.padding??12){let a=i?0:3,s=t.insert("g").attr("class",mt(e)).attr("id",e.domId||e.id),l=null,u=null,h=null,f=null,d=0,p=0,m=0;if(l=s.insert("g").attr("class","annotation-group text"),e.annotations.length>0){let b=e.annotations[0];await E5(l,{text:`\xAB${b}\xBB`},0),d=l.node().getBBox().height}u=s.insert("g").attr("class","label-group text"),await E5(u,e,0,["font-weight: bolder"]);let g=u.node().getBBox();p=g.height,h=s.insert("g").attr("class","members-group text");let y=0;for(let b of e.members){let T=await E5(h,b,y,[b.parseClassifier()]);y+=T+a}m=h.node().getBBox().height,m<=0&&(m=n/2),f=s.insert("g").attr("class","methods-group text");let v=0;for(let b of e.methods){let T=await E5(f,b,v,[b.parseClassifier()]);v+=T+a}let x=s.node().getBBox();if(l!==null){let b=l.node().getBBox();l.attr("transform",`translate(${-b.width/2})`)}return u.attr("transform",`translate(${-g.width/2}, ${d})`),x=s.node().getBBox(),h.attr("transform",`translate(0, ${d+p+n*2})`),x=s.node().getBBox(),f.attr("transform",`translate(0, ${d+p+(m?m+n*4:n*2)})`),x=s.node().getBBox(),{shapeSvg:s,bbox:x}}async function E5(t,e,r,i=[]){let n=t.insert("g").attr("class","label").attr("style",i.join("; ")),a=Lt(),s="useHtmlLabels"in e?e.useHtmlLabels:ls(a.htmlLabels)??!0,l="";"text"in e?l=e.text:l=e.label,!s&&l.startsWith("\\")&&(l=l.substring(1)),sn(l)&&(s=!0);let u=await Vi(n,r2(zs(l)),{width:Ra(l,a)+50,classes:"markdown-node-label",useHtmlLabels:s},a),h,f=1;if(s){let d=u.children[0],p=Ze(u);f=d.innerHTML.split("
    ").length,d.innerHTML.includes("")&&(f+=d.innerHTML.split("").length-1);let m=d.getElementsByTagName("img");if(m){let g=l.replace(/]*>/g,"").trim()==="";await Promise.all([...m].map(y=>new Promise(v=>{function x(){if(y.style.display="flex",y.style.flexDirection="column",g){let b=a.fontSize?.toString()??window.getComputedStyle(document.body).fontSize,w=parseInt(b,10)*5+"px";y.style.minWidth=w,y.style.maxWidth=w}else y.style.width="100%";v(y)}o(x,"setupImage"),setTimeout(()=>{y.complete&&x()}),y.addEventListener("error",x),y.addEventListener("load",x)})))}h=d.getBoundingClientRect(),p.attr("width",h.width),p.attr("height",h.height)}else{i.includes("font-weight: bolder")&&Ze(u).selectAll("tspan").attr("font-weight",""),f=u.children.length;let d=u.children[0];(u.textContent===""||u.textContent.includes(">"))&&(d.textContent=l[0]+l.substring(1).replaceAll(">",">").replaceAll("<","<").trim(),l[1]===" "&&(d.textContent=d.textContent[0]+" "+d.textContent.substring(1))),d.textContent==="undefined"&&(d.textContent=""),h=u.getBBox()}return n.attr("transform","translate(0,"+(-h.height/(2*f)+r)+")"),h.height}var Ale=P(()=>{"use strict";Pr();Sr();zt();er();Ut();To();Vr();o(Sle,"textHelper");o(E5,"addText")});async function _le(t,e){let r=ge(),{themeVariables:i}=r,{useGradient:n}=i,a=r.class.padding??12,s=a,l=e.useHtmlLabels??ls(r.htmlLabels)??!0,u=e;u.annotations=u.annotations??[],u.members=u.members??[],u.methods=u.methods??[];let{shapeSvg:h,bbox:f}=await Sle(t,e,r,l,s),{labelStyles:d,nodeStyles:p}=tt(e);e.labelStyle=d,e.cssStyles=u.styles||"";let m=u.styles?.join(";")||p||"";e.cssStyles||(e.cssStyles=m.replaceAll("!important","").split(";"));let g=u.members.length===0&&u.methods.length===0&&!r.class?.hideEmptyMembersBox,y=rt.svg(h),v=st(e,{});e.look!=="handDrawn"&&(v.roughness=0,v.fillStyle="solid");let x=Math.max(e.width??0,f.width),b=Math.max(e.height??0,f.height),T=(e.height??0)>f.height;u.members.length===0&&u.methods.length===0?b+=s:u.members.length>0&&u.methods.length===0&&(b+=s*2);let w=-x/2,k=-b/2,C=g?a*2:u.members.length===0&&u.methods.length===0?-a:0;T&&(C=a*2);let E=y.rectangle(w-a,k-a-(g?a:u.members.length===0&&u.methods.length===0?-a/2:0),x+2*a,b+2*a+C,v),S=h.insert(()=>E,":first-child");S.attr("class","basic label-container outer-path");let L=S.node().getBBox(),M=h.select(".annotation-group").node().getBBox().height-(g?a/2:0)||0,I=h.select(".label-group").node().getBBox().height-(g?a/2:0)||0,A=h.select(".members-group").node().getBBox().height-(g?a/2:0)||0,_=(M+I+k+a-(k-a-(g?a:u.members.length===0&&u.methods.length===0?-a/2:0)))/2;if(h.selectAll(".text").each((D,N,R)=>{let B=Ze(R[N]),O=B.attr("transform"),$=0;if(O){let H=RegExp(/translate\(([^,]+),([^)]+)\)/).exec(O);H&&($=parseFloat(H[2]))}let z=$+k+a-(g?a:u.members.length===0&&u.methods.length===0?-a/2:0);if(B.attr("class").includes("methods-group")){let V=Math.max(A,s/2);T?z=Math.max(_,M+I+V+k+s*2+a)+s*2:z=M+I+V+k+s*4+a}u.members.length===0&&u.methods.length===0&&r.class?.hideEmptyMembersBox&&(u.annotations.length>0?z=$-s:z=$),l||(z-=4);let F=w;(B.attr("class").includes("label-group")||B.attr("class").includes("annotation-group"))&&(F=-B.node()?.getBBox().width/2||0,h.selectAll("text").each(function(V,H,X){window.getComputedStyle(X[H]).textAnchor==="middle"&&(F=0)})),B.attr("transform",`translate(${F}, ${z})`)}),u.members.length>0||u.methods.length>0||g){let D=M+I+k+a,N=y.line(L.x,D,L.x+L.width,D+.001,v);h.insert(()=>N).attr("class",`divider${e.look==="neo"&&!n?" neo-line":""}`).attr("style",m)}if(g||u.members.length>0||u.methods.length>0){let D=M+I+A+k+s*2+a,N=y.line(L.x,T?Math.max(_,D):D,L.x+L.width,(T?Math.max(_,D):D)+.001,v);h.insert(()=>N).attr("class",`divider${e.look==="neo"&&!n?" neo-line":""}`).attr("style",m)}if(u.look!=="handDrawn"&&h.selectAll("path").attr("style",m),S.select(":nth-child(2)").attr("style",m),h.selectAll(".divider").select("path").attr("style",m),e.labelStyle?h.selectAll("span").attr("style",e.labelStyle):h.selectAll("span").attr("style",m),!l){let D=RegExp(/color\s*:\s*([^;]*)/),N=D.exec(m);if(N){let R=N[0].replace("color","fill");h.selectAll("tspan").attr("style",R)}else if(d){let R=D.exec(d);if(R){let B=R[0].replace("color","fill");h.selectAll("tspan").attr("style",B)}}}return at(e,S),e.intersect=function(D){return et.rect(e,D)},h}var Dle=P(()=>{"use strict";zt();Ut();Pr();Yt();Ht();Xt();Ale();Vr();o(_le,"classBox")});async function Lle(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let n=e,a=e,s=20,l=20,u="verifyMethod"in e,h=mt(e),{themeVariables:f}=ge(),{borderColorArray:d,requirementEdgeLabelBackground:p}=f,m=t.insert("g").attr("class",h).attr("id",e.domId??e.id),g;u?g=await Wh(m,`<<${n.type}>>`,0,e.labelStyle):g=await Wh(m,"<<Element>>",0,e.labelStyle);let y=g,v=await Wh(m,n.name,y,e.labelStyle+"; font-weight: bold;");if(y+=v+l,u){let L=await Wh(m,`${n.requirementId?`ID: ${n.requirementId}`:""}`,y,e.labelStyle);y+=L;let M=await Wh(m,`${n.text?`Text: ${n.text}`:""}`,y,e.labelStyle);y+=M;let I=await Wh(m,`${n.risk?`Risk: ${n.risk}`:""}`,y,e.labelStyle);y+=I,await Wh(m,`${n.verifyMethod?`Verification: ${n.verifyMethod}`:""}`,y,e.labelStyle)}else{let L=await Wh(m,`${a.type?`Type: ${a.type}`:""}`,y,e.labelStyle);y+=L,await Wh(m,`${a.docRef?`Doc Ref: ${a.docRef}`:""}`,y,e.labelStyle)}let x=(m.node()?.getBBox().width??200)+s,b=(m.node()?.getBBox().height??200)+s,T=-x/2,w=-b/2,k=rt.svg(m),C=st(e,{});e.look!=="handDrawn"&&(C.roughness=0,C.fillStyle="solid");let E=k.rectangle(T,w,x,b,C),S=m.insert(()=>E,":first-child");if(S.attr("class","basic label-container outer-path").attr("style",i),d?.length){let L=e.colorIndex??0;m.attr("data-color-id",`color-${L%d.length}`)}if(m.selectAll(".label").each((L,M,I)=>{let A=Ze(I[M]),_=A.attr("transform"),D=0,N=0;if(_){let $=RegExp(/translate\(([^,]+),([^)]+)\)/).exec(_);$&&(D=parseFloat($[1]),N=parseFloat($[2]))}let R=N-b/2,B=T+s/2;(M===0||M===1)&&(B=D),A.attr("transform",`translate(${B}, ${R+s})`)}),y>g+v+l){let L=w+g+v+l,M;if(e.look==="neo"){let _=[[T,L],[T+x,L],[T+x,L+.001],[T,L+.001]];M=k.polygon(_,C)}else M=k.line(T,L,T+x,L,C);m.insert(()=>M).attr("class","divider")}return at(e,S),e.intersect=function(L){return et.rect(e,L)},i&&e.look!=="handDrawn"&&(p||d?.length)&&m.selectAll("path").attr("style",i),m}async function Wh(t,e,r,i=""){if(e==="")return 0;let n=t.insert("g").attr("class","label").attr("style",i),a=ge(),s=a.htmlLabels??!0,l=await Vi(n,r2(zs(e)),{width:Ra(e,a)+50,classes:"markdown-node-label",useHtmlLabels:s,style:i},a),u;if(s){let h=l.children[0],f=Ze(l);u=h.getBoundingClientRect(),f.attr("width",u.width),f.attr("height",u.height)}else{let h=l.children[0];for(let f of h.children)i&&f.setAttribute("style",i);u=l.getBBox(),u.height+=6}return n.attr("transform",`translate(${-u.width/2},${-u.height/2+r})`),u.height}var Rle=P(()=>{"use strict";zt();Xt();Ht();Yt();er();Ut();To();Pr();o(Lle,"requirementBox");o(Wh,"addText")});async function Nle(t,e,{config:r}){let{labelStyles:i,nodeStyles:n}=tt(e);e.labelStyle=i||"";let a=10,s=e.width;e.width=(e.width??200)-10;let{shapeSvg:l,bbox:u,label:h}=await vt(t,e,mt(e)),f=e.padding||10,d="",p;"ticket"in e&&e.ticket&&r?.kanban?.ticketBaseUrl&&(d=r?.kanban?.ticketBaseUrl.replace("#TICKET#",e.ticket),p=l.insert("svg:a",":first-child").attr("class","kanban-ticket-link").attr("xlink:href",d).attr("target","_blank"));let m={useHtmlLabels:e.useHtmlLabels,labelStyle:e.labelStyle||"",width:e.width,img:e.img,padding:e.padding||8,centerLabel:!1},g,y;p?{label:g,bbox:y}=await h5(p,"ticket"in e&&e.ticket||"",m):{label:g,bbox:y}=await h5(l,"ticket"in e&&e.ticket||"",m);let{label:v,bbox:x}=await h5(l,"assigned"in e&&e.assigned||"",m);e.width=s;let b=10,T=e?.width||0,w=Math.max(y.height,x.height)/2,k=Math.max(u.height+b*2,e?.height||0)+w,C=-T/2,E=-k/2;h.attr("transform","translate("+(f-T/2)+", "+(-w-u.height/2)+")"),g.attr("transform","translate("+(f-T/2)+", "+(-w+u.height/2)+")"),v.attr("transform","translate("+(f+T/2-x.width-2*a)+", "+(-w+u.height/2)+")");let S,{rx:L,ry:M}=e,{cssStyles:I}=e;if(e.look==="handDrawn"){let A=rt.svg(l),_=st(e,{}),D=L||M?A.path(Co(C,E,T,k,L||0),_):A.rectangle(C,E,T,k,_);S=l.insert(()=>D,":first-child"),S.attr("class","basic label-container").attr("style",I||null)}else{S=l.insert("rect",":first-child"),S.attr("class","basic label-container __APA__").attr("style",n).attr("rx",L??5).attr("ry",M??5).attr("x",C).attr("y",E).attr("width",T).attr("height",k);let A="priority"in e&&e.priority;if(A){let _=l.append("line"),D=C+2,N=E+Math.floor((L??0)/2),R=E+k-Math.floor((L??0)/2);_.attr("x1",D).attr("y1",N).attr("x2",D).attr("y2",R).attr("stroke-width","4").attr("stroke",zVe(A))}}return at(e,S),e.height=k,e.intersect=function(A){return et.rect(e,A)},l}var zVe,Ile=P(()=>{"use strict";zt();Xt();R0();Ht();Yt();zVe=o(t=>{switch(t){case"Very High":return"red";case"High":return"orange";case"Medium":return null;case"Low":return"blue";case"Very Low":return"lightblue"}},"colorFromPriority");o(Nle,"kanbanItem")});async function Mle(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let{shapeSvg:n,bbox:a,halfPadding:s,label:l}=await vt(t,e,mt(e)),u=a.width+10*s,h=a.height+8*s,f=.15*u,{cssStyles:d}=e,p=a.width+20,m=a.height+20,g=Math.max(u,p),y=Math.max(h,m);l.attr("transform",`translate(${-a.width/2}, ${-a.height/2})`);let v,x=`M0 0 + a${f},${f} 1 0,0 ${g*.25},${-1*y*.1} + a${f},${f} 1 0,0 ${g*.25},0 + a${f},${f} 1 0,0 ${g*.25},0 + a${f},${f} 1 0,0 ${g*.25},${y*.1} + + a${f},${f} 1 0,0 ${g*.15},${y*.33} + a${f*.8},${f*.8} 1 0,0 0,${y*.34} + a${f},${f} 1 0,0 ${-1*g*.15},${y*.33} + + a${f},${f} 1 0,0 ${-1*g*.25},${y*.15} + a${f},${f} 1 0,0 ${-1*g*.25},0 + a${f},${f} 1 0,0 ${-1*g*.25},0 + a${f},${f} 1 0,0 ${-1*g*.25},${-1*y*.15} + + a${f},${f} 1 0,0 ${-1*g*.1},${-1*y*.33} + a${f*.8},${f*.8} 1 0,0 0,${-1*y*.34} + a${f},${f} 1 0,0 ${g*.1},${-1*y*.33} + H0 V0 Z`;if(e.look==="handDrawn"){let b=rt.svg(n),T=st(e,{}),w=b.path(x,T);v=n.insert(()=>w,":first-child"),v.attr("class","basic label-container").attr("style",xi(d))}else v=n.insert("path",":first-child").attr("class","basic label-container").attr("style",i).attr("d",x);return v.attr("transform",`translate(${-g/2}, ${-y/2})`),at(e,v),e.calcIntersect=function(b,T){return et.rect(b,T)},e.intersect=function(b){return Q.info("Bang intersect",e,b),et.rect(e,b)},n}var Ole=P(()=>{"use strict";bt();zt();Xt();Ht();Yt();er();o(Mle,"bang")});async function Ple(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let{shapeSvg:n,bbox:a,halfPadding:s,label:l}=await vt(t,e,mt(e)),u=a.width+2*s,h=a.height+2*s,f=.15*u,d=.25*u,p=.35*u,m=.2*u,{cssStyles:g}=e,y,v=`M0 0 + a${f},${f} 0 0,1 ${u*.25},${-1*u*.1} + a${p},${p} 1 0,1 ${u*.4},${-1*u*.1} + a${d},${d} 1 0,1 ${u*.35},${u*.2} + + a${f},${f} 1 0,1 ${u*.15},${h*.35} + a${m},${m} 1 0,1 ${-1*u*.15},${h*.65} + + a${d},${f} 1 0,1 ${-1*u*.25},${u*.15} + a${p},${p} 1 0,1 ${-1*u*.5},0 + a${f},${f} 1 0,1 ${-1*u*.25},${-1*u*.15} + + a${f},${f} 1 0,1 ${-1*u*.1},${-1*h*.35} + a${m},${m} 1 0,1 ${u*.1},${-1*h*.65} + H0 V0 Z`;if(e.look==="handDrawn"){let x=rt.svg(n),b=st(e,{}),T=x.path(v,b);y=n.insert(()=>T,":first-child"),y.attr("class","basic label-container").attr("style",xi(g))}else y=n.insert("path",":first-child").attr("class","basic label-container").attr("style",i).attr("d",v);return l.attr("transform",`translate(${-a.width/2}, ${-a.height/2})`),y.attr("transform",`translate(${-u/2}, ${-h/2})`),at(e,y),e.calcIntersect=function(x,b){return et.rect(x,b)},e.intersect=function(x){return Q.info("Cloud intersect",e,x),et.rect(e,x)},n}var Ble=P(()=>{"use strict";Yt();bt();er();Xt();Ht();zt();o(Ple,"cloud")});async function Fle(t,e){let{labelStyles:r,nodeStyles:i}=tt(e);e.labelStyle=r;let{shapeSvg:n,bbox:a,halfPadding:s,label:l}=await vt(t,e,mt(e)),u=a.width+8*s,h=a.height+2*s,f=5,d=e.look==="neo"?` + M${-u/2} ${h/2-f} + v${-h+2*f} + q0,-${f} ${f},-${f} + h${u-2*f} + q${f},0 ${f},${f} + v${h-f} + H${-u/2} + Z + `:` + M${-u/2} ${h/2-f} + v${-h+2*f} + q0,-${f} ${f},-${f} + h${u-2*f} + q${f},0 ${f},${f} + v${h-2*f} + q0,${f} ${-f},${f} + h${-(u-2*f)} + q${-f},0 ${-f},${-f} + Z + `;if(!e.domId)throw new Error(`defaultMindmapNode: node "${e.id}" is missing a domId \u2014 was render.ts domId prefixing skipped?`);let p=n.append("path").attr("id",e.domId).attr("class","node-bkg node-"+e.type).attr("style",i).attr("d",d);return n.append("line").attr("class","node-line-").attr("x1",-u/2).attr("y1",h/2).attr("x2",u/2).attr("y2",h/2),l.attr("transform",`translate(${-a.width/2}, ${-a.height/2})`),n.append(()=>l.node()),at(e,p),e.calcIntersect=function(m,g){return et.rect(m,g)},e.intersect=function(m){return et.rect(e,m)},n}var $le=P(()=>{"use strict";Xt();Ht();zt();o(Fle,"defaultMindmapNode")});async function zle(t,e){let r={padding:e.padding??0};return C5(t,e,r)}var Gle=P(()=>{"use strict";CM();o(zle,"mindmapCircle")});function Vle(t){return t in SM}var GVe,VVe,SM,AM=P(()=>{"use strict";fse();mse();yse();xse();CM();Tse();Cse();Ese();Ase();Dse();Ise();Ose();Bse();$se();qse();Use();Yse();Xse();Qse();Jse();toe();ioe();aoe();ooe();coe();hoe();doe();moe();yoe();Toe();Coe();Eoe();Aoe();Doe();Roe();Ioe();Ooe();Boe();$oe();Goe();qoe();Uoe();Yoe();Xoe();Qoe();Joe();tle();ile();ale();cle();hle();dle();yle();xle();Tle();Cle();Ele();Dle();Rle();Ile();Ole();Ble();$le();Gle();GVe=[{semanticName:"Process",name:"Rectangle",shortName:"rect",description:"Standard process shape",aliases:["proc","process","rectangle"],internalAliases:["squareRect"],handler:Voe},{semanticName:"Event",name:"Rounded Rectangle",shortName:"rounded",description:"Represents an event",aliases:["event"],internalAliases:["roundedRect"],handler:Poe},{semanticName:"Terminal Point",name:"Stadium",shortName:"stadium",description:"Terminal point",aliases:["terminal","pill"],handler:Woe},{semanticName:"Subprocess",name:"Framed Rectangle",shortName:"fr-rect",description:"Subprocess",aliases:["subprocess","subproc","framed-rectangle","subroutine"],handler:Zoe},{semanticName:"Database",name:"Cylinder",shortName:"cyl",description:"Database storage",aliases:["db","database","cylinder"],handler:Nse},{semanticName:"Start",name:"Circle",shortName:"circle",description:"Starting point",aliases:["circ"],handler:C5},{semanticName:"Bang",name:"Bang",shortName:"bang",description:"Bang",aliases:["bang"],handler:Mle},{semanticName:"Cloud",name:"Cloud",shortName:"cloud",description:"cloud",aliases:["cloud"],handler:Ple},{semanticName:"Decision",name:"Diamond",shortName:"diam",description:"Decision-making step",aliases:["decision","diamond","question"],handler:Loe},{semanticName:"Prepare Conditional",name:"Hexagon",shortName:"hex",description:"Preparation or condition step",aliases:["hexagon","prepare"],handler:jse},{semanticName:"Data Input/Output",name:"Lean Right",shortName:"lean-r",description:"Represents input or output",aliases:["lean-right","in-out"],internalAliases:["lean_right"],handler:poe},{semanticName:"Data Input/Output",name:"Lean Left",shortName:"lean-l",description:"Represents output or input",aliases:["lean-left","out-in"],internalAliases:["lean_left"],handler:foe},{semanticName:"Priority Action",name:"Trapezoid Base Bottom",shortName:"trap-b",description:"Priority action",aliases:["priority","trapezoid-bottom","trapezoid"],handler:ule},{semanticName:"Manual Operation",name:"Trapezoid Base Top",shortName:"trap-t",description:"Represents a manual task",aliases:["manual","trapezoid-top","inv-trapezoid"],internalAliases:["inv_trapezoid"],handler:loe},{semanticName:"Stop",name:"Double Circle",shortName:"dbl-circ",description:"Represents a stop point",aliases:["double-circle"],internalAliases:["doublecircle"],handler:Pse},{semanticName:"Text Block",name:"Text Block",shortName:"text",description:"Text block",handler:nle},{semanticName:"Card",name:"Notched Rectangle",shortName:"notch-rect",description:"Represents a card",aliases:["card","notched-rectangle"],handler:gse},{semanticName:"Lined/Shaded Process",name:"Lined Rectangle",shortName:"lin-rect",description:"Lined process shape",aliases:["lined-rectangle","lined-process","lin-proc","shaded-process"],handler:Foe},{semanticName:"Start",name:"Small Circle",shortName:"sm-circ",description:"Small starting point",aliases:["start","small-circle"],internalAliases:["stateStart"],handler:Koe},{semanticName:"Stop",name:"Framed Circle",shortName:"fr-circ",description:"Stop point",aliases:["stop","framed-circle"],internalAliases:["stateEnd"],handler:joe},{semanticName:"Fork/Join",name:"Filled Rectangle",shortName:"fork",description:"Fork or join in process flow",aliases:["join"],internalAliases:["forkJoin"],handler:Wse},{semanticName:"Collate",name:"Hourglass",shortName:"hourglass",description:"Represents a collate operation",aliases:["hourglass","collate"],handler:Kse},{semanticName:"Comment",name:"Curly Brace",shortName:"brace",description:"Adds a comment",aliases:["comment","brace-l"],handler:kse},{semanticName:"Comment Right",name:"Curly Brace",shortName:"brace-r",description:"Adds a comment",handler:wse},{semanticName:"Comment with braces on both sides",name:"Curly Braces",shortName:"braces",description:"Adds a comment",handler:Sse},{semanticName:"Com Link",name:"Lightning Bolt",shortName:"bolt",description:"Communication link",aliases:["com-link","lightning-bolt"],handler:goe},{semanticName:"Document",name:"Document",shortName:"doc",description:"Represents a document",aliases:["doc","document"],handler:vle},{semanticName:"Delay",name:"Half-Rounded Rectangle",shortName:"delay",description:"Represents a delay",aliases:["half-rounded-rectangle"],handler:Hse},{semanticName:"Direct Access Storage",name:"Horizontal Cylinder",shortName:"h-cyl",description:"Direct access storage",aliases:["das","horizontal-cylinder"],handler:lle},{semanticName:"Disk Storage",name:"Lined Cylinder",shortName:"lin-cyl",description:"Disk storage",aliases:["disk","lined-cylinder"],handler:boe},{semanticName:"Display",name:"Curved Trapezoid",shortName:"curv-trap",description:"Represents a display",aliases:["curved-trapezoid","display"],handler:_se},{semanticName:"Divided Process",name:"Divided Rectangle",shortName:"div-rect",description:"Divided process shape",aliases:["div-proc","divided-rectangle","divided-process"],handler:Mse},{semanticName:"Extract",name:"Triangle",shortName:"tri",description:"Extraction process",aliases:["extract","triangle"],handler:gle},{semanticName:"Internal Storage",name:"Window Pane",shortName:"win-pane",description:"Internal storage",aliases:["internal-storage","window-pane"],handler:kle},{semanticName:"Junction",name:"Filled Circle",shortName:"f-circ",description:"Junction point",aliases:["junction","filled-circle"],handler:Fse},{semanticName:"Loop Limit",name:"Trapezoidal Pentagon",shortName:"notch-pent",description:"Loop limit step",aliases:["loop-limit","notched-pentagon"],handler:fle},{semanticName:"Manual File",name:"Flipped Triangle",shortName:"flip-tri",description:"Manual file operation",aliases:["manual-file","flipped-triangle"],handler:Vse},{semanticName:"Manual Input",name:"Sloped Rectangle",shortName:"sl-rect",description:"Manual input step",aliases:["manual-input","sloped-rectangle"],handler:zoe},{semanticName:"Multi-Document",name:"Stacked Document",shortName:"docs",description:"Multiple documents",aliases:["documents","st-doc","stacked-document"],handler:Soe},{semanticName:"Multi-Process",name:"Stacked Rectangle",shortName:"st-rect",description:"Multiple processes",aliases:["procs","processes","stacked-rectangle"],handler:woe},{semanticName:"Stored Data",name:"Bow Tie Rectangle",shortName:"bow-rect",description:"Stored data",aliases:["stored-data","bow-tie-rectangle"],handler:pse},{semanticName:"Summary",name:"Crossed Circle",shortName:"cross-circ",description:"Summary",aliases:["summary","crossed-circle"],handler:bse},{semanticName:"Tagged Document",name:"Tagged Document",shortName:"tag-doc",description:"Tagged document",aliases:["tag-doc","tagged-document"],handler:rle},{semanticName:"Tagged Process",name:"Tagged Rectangle",shortName:"tag-rect",description:"Tagged process",aliases:["tagged-rectangle","tag-proc","tagged-process"],handler:ele},{semanticName:"Paper Tape",name:"Flag",shortName:"flag",description:"Paper tape",aliases:["paper-tape"],handler:ble},{semanticName:"Odd",name:"Odd",shortName:"odd",description:"Odd shape",internalAliases:["rect_left_inv_arrow"],handler:Noe},{semanticName:"Lined Document",name:"Lined Document",shortName:"lin-doc",description:"Lined document",aliases:["lined-document"],handler:koe}],VVe=o(()=>{let e=[...Object.entries({state:Hoe,choice:vse,note:_oe,rectWithTitle:Moe,labelRect:uoe,iconSquare:noe,iconCircle:eoe,icon:Zse,iconRounded:roe,imageSquare:soe,anchor:hse,kanbanItem:Nle,mindmapCircle:zle,defaultMindmapNode:Fle,classBox:_le,erBox:EM,requirementBox:Lle}),...GVe.flatMap(r=>[r.shortName,..."aliases"in r?r.aliases:[],..."internalAliases"in r?r.internalAliases:[]].map(n=>[n,r.handler]))];return Object.fromEntries(e)},"generateShapeMap"),SM=VVe();o(Vle,"isValidShape")});var qVe,S5,qle=P(()=>{"use strict";Pr();xb();Ut();bt();AM();er();Vr();Ki();y0();zx();qVe="flowchart-",S5=class{constructor(){this.vertexCounter=0;this.config=ge();this.diagramId="";this.vertices=new Map;this.edges=[];this.classes=new Map;this.subGraphs=[];this.subGraphLookup=new Map;this.tooltips=new Map;this.subCount=0;this.firstGraphFlag=!0;this.secCount=-1;this.posCrossRef=[];this.funs=[];this.setAccTitle=Ar;this.setAccDescription=Lr;this.setDiagramTitle=Mr;this.getAccTitle=Dr;this.getAccDescription=Rr;this.getDiagramTitle=Nr;this.funs.push(this.setupToolTips.bind(this)),this.addVertex=this.addVertex.bind(this),this.firstGraph=this.firstGraph.bind(this),this.setDirection=this.setDirection.bind(this),this.addSubGraph=this.addSubGraph.bind(this),this.addLink=this.addLink.bind(this),this.setLink=this.setLink.bind(this),this.updateLink=this.updateLink.bind(this),this.addClass=this.addClass.bind(this),this.setClass=this.setClass.bind(this),this.destructLink=this.destructLink.bind(this),this.setClickEvent=this.setClickEvent.bind(this),this.setTooltip=this.setTooltip.bind(this),this.updateLinkInterpolate=this.updateLinkInterpolate.bind(this),this.setClickFun=this.setClickFun.bind(this),this.bindFunctions=this.bindFunctions.bind(this),this.lex={firstGraph:this.firstGraph.bind(this)},this.clear(),this.setGen("gen-2")}static{o(this,"FlowDB")}sanitizeText(e){return lt.sanitizeText(e,this.config)}sanitizeNodeLabelType(e){switch(e){case"markdown":case"string":case"text":return e;default:return"markdown"}}setDiagramId(e){this.diagramId=e}lookUpDomId(e){for(let r of this.vertices.values())if(r.id===e)return this.diagramId?`${this.diagramId}-${r.domId}`:r.domId;return this.diagramId?`${this.diagramId}-${e}`:e}addVertex(e,r,i,n,a,s,l={},u){if(!e||e.trim().length===0)return;let h;if(u!==void 0){let m;u.includes(` +`)?m=u+` +`:m=`{ +`+u+` +}`,h=ud(m,{schema:cd})}let f=this.edges.find(m=>m.id===e);if(f){let m=h;m?.animate!==void 0&&(f.animate=m.animate),m?.animation!==void 0&&(f.animation=m.animation),m?.curve!==void 0&&(f.interpolate=m.curve);return}let d,p=this.vertices.get(e);if(p===void 0&&(r===void 0&&i===void 0&&n!==void 0&&n!==null&&Q.warn(`Style applied to unknown node "${e}". This may indicate a typo. The node will be created automatically.`),p={id:e,labelType:"text",domId:qVe+e+"-"+this.vertexCounter,styles:[],classes:[]},this.vertices.set(e,p)),this.vertexCounter++,r!==void 0?(this.config=ge(),d=this.sanitizeText(r.text.trim()),p.labelType=r.type,d.startsWith('"')&&d.endsWith('"')&&(d=d.substring(1,d.length-1)),p.text=d):p.text===void 0&&(p.text=e),i!==void 0&&(p.type=i),n?.forEach(m=>{p.styles.push(m)}),a?.forEach(m=>{p.classes.push(m)}),s!==void 0&&(p.dir=s),p.props===void 0?p.props=l:l!==void 0&&Object.assign(p.props,l),h!==void 0){if(h.shape){if(h.shape!==h.shape.toLowerCase()||h.shape.includes("_"))throw new Error(`No such shape: ${h.shape}. Shape names should be lowercase.`);if(!Vle(h.shape))throw new Error(`No such shape: ${h.shape}.`);p.type=h?.shape}h?.label&&(p.text=h?.label,p.labelType=this.sanitizeNodeLabelType(h?.labelType)),h?.icon&&(p.icon=h?.icon,!h.label?.trim()&&p.text===e&&(p.text="")),h?.form&&(p.form=h?.form),h?.pos&&(p.pos=h?.pos),h?.img&&(p.img=h?.img,!h.label?.trim()&&p.text===e&&(p.text="")),h?.constraint&&(p.constraint=h.constraint),h.w&&(p.assetWidth=Number(h.w)),h.h&&(p.assetHeight=Number(h.h))}}addSingleLink(e,r,i,n){let l={start:e,end:r,type:void 0,text:"",labelType:"text",classes:[],isUserDefinedId:!1,interpolate:this.edges.defaultInterpolate};Q.info("abc78 Got edge...",l);let u=i.text;if(u!==void 0&&(l.text=this.sanitizeText(u.text.trim()),l.text.startsWith('"')&&l.text.endsWith('"')&&(l.text=l.text.substring(1,l.text.length-1)),l.labelType=this.sanitizeNodeLabelType(u.type)),i!==void 0&&(l.type=i.type,l.stroke=i.stroke,l.length=i.length>10?10:i.length),n&&!this.edges.some(h=>h.id===n))l.id=n,l.isUserDefinedId=!0;else{let h=this.edges.filter(f=>f.start===l.start&&f.end===l.end);h.length===0?l.id=Cu(l.start,l.end,{counter:0,prefix:"L"}):l.id=Cu(l.start,l.end,{counter:h.length+1,prefix:"L"})}if(this.edges.length<(this.config.maxEdges??500))Q.info("Pushing edge..."),this.edges.push(l);else throw new Error(`Edge limit exceeded. ${this.edges.length} edges found, but the limit is ${this.config.maxEdges}. + +Initialize mermaid with maxEdges set to a higher number to allow more edges. +You cannot set this config via configuration inside the diagram as it is a secure config. +You have to call mermaid.initialize.`)}isLinkData(e){return e!==null&&typeof e=="object"&&"id"in e&&typeof e.id=="string"}addLink(e,r,i){let n=this.isLinkData(i)?i.id.replace("@",""):void 0;Q.info("addLink",e,r,n);for(let a of e)for(let s of r){let l=a===e[e.length-1],u=s===r[0];l&&u?this.addSingleLink(a,s,i,n):this.addSingleLink(a,s,i,void 0)}}updateLinkInterpolate(e,r){e.forEach(i=>{i==="default"?this.edges.defaultInterpolate=r:this.edges[i].interpolate=r})}updateLink(e,r){e.forEach(i=>{if(typeof i=="number"&&i>=this.edges.length)throw new Error(`The index ${i} for linkStyle is out of bounds. Valid indices for linkStyle are between 0 and ${this.edges.length-1}. (Help: Ensure that the index is within the range of existing edges.)`);i==="default"?this.edges.defaultStyle=r:(this.edges[i].style=r,(this.edges[i]?.style?.length??0)>0&&!this.edges[i]?.style?.some(n=>n?.startsWith("fill"))&&this.edges[i]?.style?.push("fill:none"))})}addClass(e,r){let i=r.join().replace(/\\,/g,"\xA7\xA7\xA7").replace(/,/g,";").replace(/§§§/g,",").split(";");e.split(",").forEach(n=>{let a=this.classes.get(n);a===void 0&&(a={id:n,styles:[],textStyles:[]},this.classes.set(n,a)),i?.forEach(s=>{if(/color/.exec(s)){let l=s.replace("fill","bgFill");a.textStyles.push(l)}a.styles.push(s)})})}setDirection(e){this.direction=e.trim(),/.*/.exec(this.direction)&&(this.direction="LR"),/.*v/.exec(this.direction)&&(this.direction="TB"),this.direction==="TD"&&(this.direction="TB")}setClass(e,r){for(let i of e.split(",")){let n=this.vertices.get(i);n&&n.classes.push(r);let a=this.edges.find(l=>l.id===i);a&&a.classes.push(r);let s=this.subGraphLookup.get(i);s&&s.classes.push(r)}}setTooltip(e,r){if(r!==void 0){r=this.sanitizeText(r);for(let i of e.split(","))this.tooltips.set(this.version==="gen-1"?this.lookUpDomId(i):i,r)}}setClickFun(e,r,i){if(ge().securityLevel!=="loose"||r===void 0)return;let n=[];if(typeof i=="string"){n=i.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);for(let s=0;s{let s=this.lookUpDomId(e),l=document.querySelector(`[id="${s}"]`);l!==null&&l.addEventListener("click",()=>{Kt.runFunc(r,...n)},!1)}))}setLink(e,r,i){e.split(",").forEach(n=>{let a=this.vertices.get(n);a!==void 0&&(a.link=Kt.formatUrl(r,this.config),a.linkTarget=i)}),this.setClass(e,"clickable")}getTooltip(e){return this.tooltips.get(e)}setClickEvent(e,r,i){e.split(",").forEach(n=>{this.setClickFun(n,r,i)}),this.setClass(e,"clickable")}bindFunctions(e){this.funs.forEach(r=>{r(e)})}getDirection(){return this.direction?.trim()}getVertices(){return this.vertices}getEdges(){return this.edges}getClasses(){return this.classes}setupToolTips(e){let r=E3();Ze(e).select("svg").selectAll("g.node").on("mouseover",a=>{let s=Ze(a.currentTarget),l=s.attr("title");if(l===null)return;let u=a.currentTarget?.getBoundingClientRect();r.transition().duration(200).style("opacity",".9"),r.text(s.attr("title")).style("left",window.scrollX+u.left+(u.right-u.left)/2+"px").style("top",window.scrollY+u.bottom+"px"),r.html(Tl.sanitize(l)),s.classed("hover",!0)}).on("mouseout",a=>{r.transition().duration(500).style("opacity",0),Ze(a.currentTarget).classed("hover",!1)})}clear(e="gen-2"){this.vertices=new Map,this.classes=new Map,this.edges=[],this.funs=[this.setupToolTips.bind(this)],this.diagramId="",this.subGraphs=[],this.subGraphLookup=new Map,this.subCount=0,this.tooltips=new Map,this.firstGraphFlag=!0,this.version=e,this.config=ge(),wr()}setGen(e){this.version=e||"gen-2"}defaultStyle(){return"fill:#ffa;stroke: #f66; stroke-width: 3px; stroke-dasharray: 5, 5;fill:#ffa;stroke: #666;"}addSubGraph(e,r,i){let n=e.text.trim(),a=i.text;e===i&&/\s/.exec(i.text)&&(n=void 0);let l=o(p=>{let m={boolean:{},number:{},string:{}},g=[],y;return{nodeList:p.filter(function(x){let b=typeof x;return x.stmt&&x.stmt==="dir"?(y=x.value,!1):x.trim()===""?!1:b in m?m[b].hasOwnProperty(x)?!1:m[b][x]=!0:g.includes(x)?!1:g.push(x)}),dir:y}},"uniq")(r.flat()),u=l.nodeList,h=l.dir,f=ge().flowchart??{};if(h=h??(f.inheritDir?this.getDirection()??ge().direction??void 0:void 0),this.version==="gen-1")for(let p=0;p2e3)return{result:!1,count:0};if(this.posCrossRef[this.secCount]=r,this.subGraphs[r].id===e)return{result:!0,count:0};let n=0,a=1;for(;n=0){let l=this.indexNodes2(e,s);if(l.result)return{result:!0,count:a+l.count};a=a+l.count}n=n+1}return{result:!1,count:a}}getDepthFirstPos(e){return this.posCrossRef[e]}indexNodes(){this.secCount=-1,this.subGraphs.length>0&&this.indexNodes2("none",this.subGraphs.length-1)}getSubGraphs(){return this.subGraphs}firstGraph(){return this.firstGraphFlag?(this.firstGraphFlag=!1,!0):!1}destructStartLink(e){let r=e.trim(),i="arrow_open";switch(r[0]){case"<":i="arrow_point",r=r.slice(1);break;case"x":i="arrow_cross",r=r.slice(1);break;case"o":i="arrow_circle",r=r.slice(1);break}let n="normal";return r.includes("=")&&(n="thick"),r.includes(".")&&(n="dotted"),{type:i,stroke:n}}countChar(e,r){let i=r.length,n=0;for(let a=0;a":n="arrow_point",r.startsWith("<")&&(n="double_"+n,i=i.slice(1));break;case"o":n="arrow_circle",r.startsWith("o")&&(n="double_"+n,i=i.slice(1));break}let a="normal",s=i.length-1;i.startsWith("=")&&(a="thick"),i.startsWith("~")&&(a="invisible");let l=this.countChar(".",i);return l&&(a="dotted",s=l),{type:n,stroke:a,length:s}}destructLink(e,r){let i=this.destructEndLink(e),n;if(r){if(n=this.destructStartLink(r),n.stroke!==i.stroke)return{type:"INVALID",stroke:"INVALID"};if(n.type==="arrow_open")n.type=i.type;else{if(n.type!==i.type)return{type:"INVALID",stroke:"INVALID"};n.type="double_"+n.type}return n.type==="double_arrow"&&(n.type="double_arrow_point"),n.length=i.length,n}return i}exists(e,r){for(let i of e)if(i.nodes.includes(r))return!0;return!1}makeUniq(e,r){let i=[];return e.nodes.forEach((n,a)=>{this.exists(r,n)||i.push(e.nodes[a])}),{nodes:i}}getTypeFromVertex(e){if(e.img)return"imageSquare";if(e.icon)return e.form==="circle"?"iconCircle":e.form==="square"?"iconSquare":e.form==="rounded"?"iconRounded":"icon";switch(e.type){case"square":case void 0:return"squareRect";case"round":return"roundedRect";case"ellipse":return"ellipse";default:return e.type}}findNode(e,r){return e.find(i=>i.id===r)}destructEdgeType(e){let r="none",i="arrow_point";switch(e){case"arrow_point":case"arrow_circle":case"arrow_cross":i=e;break;case"double_arrow_point":case"double_arrow_circle":case"double_arrow_cross":r=e.replace("double_",""),i=r;break}return{arrowTypeStart:r,arrowTypeEnd:i}}addNodeFromVertex(e,r,i,n,a,s){let l=i.get(e.id),u=n.get(e.id)??!1,h=this.findNode(r,e.id);if(h)h.cssStyles=e.styles,h.cssCompiledStyles=this.getCompiledStyles(e.classes),h.cssClasses=e.classes.join(" ");else{let f={id:e.id,label:e.text,labelType:e.labelType,labelStyle:"",parentId:l,padding:a.flowchart?.padding||8,cssStyles:e.styles,cssCompiledStyles:this.getCompiledStyles(["default","node",...e.classes]),cssClasses:"default "+e.classes.join(" "),dir:e.dir,domId:e.domId,look:s,link:e.link,linkTarget:e.linkTarget,tooltip:this.getTooltip(e.id),icon:e.icon,pos:e.pos,img:e.img,assetWidth:e.assetWidth,assetHeight:e.assetHeight,constraint:e.constraint};u?r.push({...f,isGroup:!0,shape:"rect"}):r.push({...f,isGroup:!1,shape:this.getTypeFromVertex(e)})}}getCompiledStyles(e){let r=[];for(let i of e){let n=this.classes.get(i);n?.styles&&(r=[...r,...n.styles??[]].map(a=>a.trim())),n?.textStyles&&(r=[...r,...n.textStyles??[]].map(a=>a.trim()))}return r}getData(){let e=ge(),r=[],i=[],n=this.getSubGraphs(),a=new Map,s=new Map;for(let h=n.length-1;h>=0;h--){let f=n[h];f.nodes.length>0&&s.set(f.id,!0);for(let d of f.nodes)a.set(d,f.id)}for(let h=n.length-1;h>=0;h--){let f=n[h];r.push({id:f.id,label:f.title,labelStyle:"",labelType:f.labelType,parentId:a.get(f.id),padding:8,cssCompiledStyles:this.getCompiledStyles(f.classes),cssClasses:f.classes.join(" "),shape:"rect",dir:f.dir,isGroup:!0,look:e.look})}this.getVertices().forEach(h=>{this.addNodeFromVertex(h,r,a,s,e,e.look||"classic")});let u=this.getEdges();return u.forEach((h,f)=>{let{arrowTypeStart:d,arrowTypeEnd:p}=this.destructEdgeType(h.type),m=[...u.defaultStyle??[]];h.style&&m.push(...h.style);let g={id:Cu(h.start,h.end,{counter:f,prefix:"L"},h.id),isUserDefinedId:h.isUserDefinedId,start:h.start,end:h.end,type:h.type??"normal",label:h.text,labelType:h.labelType,labelpos:"c",thickness:h.stroke,minlen:h.length,classes:h?.stroke==="invisible"?"":"edge-thickness-normal edge-pattern-solid flowchart-link",arrowTypeStart:h?.stroke==="invisible"||h?.type==="arrow_open"?"none":d,arrowTypeEnd:h?.stroke==="invisible"||h?.type==="arrow_open"?"none":p,arrowheadStyle:"fill: #333",cssCompiledStyles:this.getCompiledStyles(h.classes),labelStyle:m,style:m,pattern:h.stroke,look:e.look,animate:h.animate,animation:h.animation,curve:h.interpolate||this.edges.defaultInterpolate||e.flowchart?.curve};i.push(g)}),{nodes:r,edges:i,other:{},config:e}}defaultConfig(){return iw.flowchart}}});var Ol,I0=P(()=>{"use strict";Pr();Ol=o((t,e)=>{let r;return e==="sandbox"&&(r=Ze("#i"+t)),(e==="sandbox"?Ze(r.nodes()[0].contentDocument.body):Ze("body")).select(`[id="${t}"]`)},"getDiagramElement")});var Uh,Nb=P(()=>{"use strict";Uh=o(({flowchart:t})=>{let e=t?.subGraphTitleMargin?.top??0,r=t?.subGraphTitleMargin?.bottom??0,i=e+r;return{subGraphTitleTopMargin:e,subGraphTitleBottomMargin:r,subGraphTitleTotalMargin:i}},"getSubGraphTitleMargins")});var Wle,WVe,UVe,HVe,YVe,jVe,XVe,Ule,N1,Hle,A5=P(()=>{"use strict";Ut();Sr();bt();Nb();Pr();Yt();To();aM();w5();R0();Ht();Wle=o(async(t,e)=>{Q.info("Creating subgraph rect for ",e.id,e);let r=ge(),{themeVariables:i,handDrawnSeed:n}=r,{clusterBkg:a,clusterBorder:s}=i,{labelStyles:l,nodeStyles:u,borderStyles:h,backgroundStyles:f}=tt(e),d=t.insert("g").attr("class","cluster "+e.cssClasses).attr("id",e.domId).attr("data-look",e.look),p=Or(r),m=d.insert("g").attr("class","cluster-label "),g;e.labelType==="markdown"?g=await Vi(m,e.label,{style:e.labelStyle,useHtmlLabels:p,isNode:!0,width:e.width}):g=await Dc(m,e.label,e.labelStyle||"",!1,!0);let y=g.getBBox();if(Or(r)){let E=g.children[0],S=Ze(g);y=E.getBoundingClientRect(),S.attr("width",y.width),S.attr("height",y.height)}let v=e.width<=y.width+e.padding?y.width+e.padding:e.width;e.width<=y.width+e.padding?e.diff=(v-e.width)/2-e.padding:e.diff=-e.padding;let x=e.height,b=e.x-v/2,T=e.y-x/2;Q.trace("Data ",e,JSON.stringify(e));let w;if(e.look==="handDrawn"){let E=rt.svg(d),S=st(e,{roughness:.7,fill:a,stroke:s,fillWeight:3,seed:n}),L=E.path(Co(b,T,v,x,0),S);w=d.insert(()=>(Q.debug("Rough node insert CXC",L),L),":first-child"),w.select("path:nth-child(2)").attr("style",h.join(";")),w.select("path").attr("style",f.join(";").replace("fill","stroke"))}else w=d.insert("rect",":first-child"),w.attr("style",u).attr("rx",e.rx).attr("ry",e.ry).attr("x",b).attr("y",T).attr("width",v).attr("height",x);let{subGraphTitleTopMargin:k}=Uh(r);if(m.attr("transform",`translate(${e.x-y.width/2}, ${e.y-e.height/2+k})`),l){let E=m.select("span");E&&E.attr("style",l)}let C=w.node().getBBox();return e.offsetX=0,e.width=C.width,e.height=C.height,e.offsetY=y.height-e.padding/2,e.intersect=function(E){return hd(e,E)},{cluster:d,labelBBox:y}},"rect"),WVe=o((t,e)=>{let r=t.insert("g").attr("class","note-cluster").attr("id",e.domId),i=r.insert("rect",":first-child"),n=0*e.padding,a=n/2;i.attr("rx",e.rx).attr("ry",e.ry).attr("x",e.x-e.width/2-a).attr("y",e.y-e.height/2-a).attr("width",e.width+n).attr("height",e.height+n).attr("fill","none");let s=i.node().getBBox();return e.width=s.width,e.height=s.height,e.intersect=function(l){return hd(e,l)},{cluster:r,labelBBox:{width:0,height:0}}},"noteGroup"),UVe=o(async(t,e)=>{let r=ge(),{themeVariables:i,handDrawnSeed:n}=r,{altBackground:a,compositeBackground:s,compositeTitleBackground:l,nodeBorder:u}=i,h=t.insert("g").attr("class",e.cssClasses).attr("id",e.domId).attr("data-id",e.id).attr("data-look",e.look),f=h.insert("g",":first-child"),d=h.insert("g").attr("class","cluster-label"),p=h.append("rect"),m=await Dc(d,e.label,e.labelStyle,void 0,!0),g=m.getBBox();if(Or(r)){let L=m.children[0],M=Ze(m);g=L.getBoundingClientRect(),M.attr("width",g.width),M.attr("height",g.height)}let y=0*e.padding,v=y/2,x=(e.width<=g.width+e.padding?g.width+e.padding:e.width)+y;e.width<=g.width+e.padding?e.diff=(x-e.width)/2-e.padding:e.diff=-e.padding;let b=e.height+y,T=e.height+y-g.height-6,w=e.x-x/2,k=e.y-b/2;e.width=x;let C=e.y-e.height/2-v+g.height+2,E;if(e.look==="handDrawn"){let L=e.cssClasses.includes("statediagram-cluster-alt"),M=rt.svg(h),I=e.rx||e.ry?M.path(Co(w,k,x,b,10),{roughness:.7,fill:l,fillStyle:"solid",stroke:u,seed:n}):M.rectangle(w,k,x,b,{seed:n});E=h.insert(()=>I,":first-child");let A=M.rectangle(w,C,x,T,{fill:L?a:s,fillStyle:L?"hachure":"solid",stroke:u,seed:n});E=h.insert(()=>I,":first-child"),p=h.insert(()=>A)}else E=f.insert("rect",":first-child"),E.attr("class","outer").attr("x",w).attr("y",k).attr("width",x).attr("height",b).attr("data-look",e.look),p.attr("class","inner").attr("x",w).attr("y",C).attr("width",x).attr("height",T);d.attr("transform",`translate(${e.x-g.width/2}, ${k+1-(Or(r)?0:3)})`);let S=E.node().getBBox();return e.height=S.height,e.offsetX=0,e.offsetY=g.height-e.padding/2,e.labelBBox=g,e.intersect=function(L){return hd(e,L)},{cluster:h,labelBBox:g}},"roundedWithTitle"),HVe=o(async(t,e)=>{Q.info("Creating subgraph rect for ",e.id,e);let r=ge(),{themeVariables:i,handDrawnSeed:n}=r,{clusterBkg:a,clusterBorder:s}=i,{labelStyles:l,nodeStyles:u,borderStyles:h,backgroundStyles:f}=tt(e),d=t.insert("g").attr("class","cluster "+e.cssClasses).attr("id",e.domId).attr("data-look",e.look),p=Or(r),m=d.insert("g").attr("class","cluster-label "),g=await Vi(m,e.label,{style:e.labelStyle,useHtmlLabels:p,isNode:!0,width:e.width}),y=g.getBBox();if(Or(r)){let E=g.children[0],S=Ze(g);y=E.getBoundingClientRect(),S.attr("width",y.width),S.attr("height",y.height)}let v=e.width<=y.width+e.padding?y.width+e.padding:e.width;e.width<=y.width+e.padding?e.diff=(v-e.width)/2-e.padding:e.diff=-e.padding;let x=e.height,b=e.x-v/2,T=e.y-x/2;Q.trace("Data ",e,JSON.stringify(e));let w;if(e.look==="handDrawn"){let E=rt.svg(d),S=st(e,{roughness:.7,fill:a,stroke:s,fillWeight:4,seed:n}),L=E.path(Co(b,T,v,x,e.rx),S);w=d.insert(()=>(Q.debug("Rough node insert CXC",L),L),":first-child"),w.select("path:nth-child(2)").attr("style",h.join(";")),w.select("path").attr("style",f.join(";").replace("fill","stroke"))}else w=d.insert("rect",":first-child"),w.attr("style",u).attr("rx",e.rx).attr("ry",e.ry).attr("x",b).attr("y",T).attr("width",v).attr("height",x);let{subGraphTitleTopMargin:k}=Uh(r);if(m.attr("transform",`translate(${e.x-y.width/2}, ${e.y-e.height/2+k})`),l){let E=m.select("span");E&&E.attr("style",l)}let C=w.node().getBBox();return e.offsetX=0,e.width=C.width,e.height=C.height,e.offsetY=y.height-e.padding/2,e.intersect=function(E){return hd(e,E)},{cluster:d,labelBBox:y}},"kanbanSection"),YVe=o((t,e)=>{let r=ge(),{themeVariables:i,handDrawnSeed:n}=r,{nodeBorder:a}=i,s=t.insert("g").attr("class",e.cssClasses).attr("id",e.domId).attr("data-look",e.look),l=s.insert("g",":first-child"),u=0*e.padding,h=e.width+u;e.diff=-e.padding;let f=e.height+u,d=e.x-h/2,p=e.y-f/2;e.width=h;let m;if(e.look==="handDrawn"){let v=rt.svg(s).rectangle(d,p,h,f,{fill:"lightgrey",roughness:.5,strokeLineDash:[5],stroke:a,seed:n});m=s.insert(()=>v,":first-child")}else{m=l.insert("rect",":first-child");let y="outer";e.look,y="divider",m.attr("class",y).attr("x",d).attr("y",p).attr("width",h).attr("height",f).attr("data-look",e.look)}let g=m.node().getBBox();return e.height=g.height,e.offsetX=0,e.offsetY=0,e.intersect=function(y){return hd(e,y)},{cluster:s,labelBBox:{}}},"divider"),jVe=Wle,XVe={rect:Wle,squareRect:jVe,roundedWithTitle:UVe,noteGroup:WVe,divider:YVe,kanbanSection:HVe},Ule=new Map,N1=o(async(t,e)=>{let r=e.shape||"rect",i=await XVe[r](t,e);return Ule.set(e.id,i),i},"insertCluster"),Hle=o(()=>{Ule=new Map},"clear")});var Pl,_M=P(()=>{"use strict";Pl=o((t,e)=>{if(e)return"translate("+-t.width/2+", "+-t.height/2+")";let r=t.x??0,i=t.y??0;return"translate("+-(r+t.width/2)+", "+-(i+t.height/2)+")"},"computeLabelTransform")});function _5(t,e){if(t===void 0||e===void 0)return{angle:0,deltaX:0,deltaY:0};t=dn(t),e=dn(e);let[r,i]=[t.x,t.y],[n,a]=[e.x,e.y],s=n-r,l=a-i;return{angle:Math.atan(l/s),deltaX:s,deltaY:l}}var Ka,DM,dn,D5,LM=P(()=>{"use strict";Ka={aggregation:17.25,extension:17.25,composition:17.25,dependency:6,lollipop:13.5,arrow_point:4,arrow_barb:0,arrow_barb_neo:5.5},DM={arrow_point:4,arrow_cross:12.5,arrow_circle:12.5};o(_5,"calculateDeltaAndAngle");dn=o(t=>Array.isArray(t)?{x:t[0],y:t[1]}:t,"pointTransformer"),D5=o(t=>({x:o(function(e,r,i){let n=0,a=dn(i[0]).x=0?1:-1)}else if(r===i.length-1&&Object.hasOwn(Ka,t.arrowTypeEnd)){let{angle:m,deltaX:g}=_5(i[i.length-1],i[i.length-2]);n=Ka[t.arrowTypeEnd]*Math.cos(m)*(g>=0?1:-1)}let s=Math.abs(dn(e).x-dn(i[i.length-1]).x),l=Math.abs(dn(e).y-dn(i[i.length-1]).y),u=Math.abs(dn(e).x-dn(i[0]).x),h=Math.abs(dn(e).y-dn(i[0]).y),f=Ka[t.arrowTypeStart],d=Ka[t.arrowTypeEnd],p=1;if(s0&&l0&&h=0?1:-1)}else if(r===i.length-1&&Object.hasOwn(Ka,t.arrowTypeEnd)){let{angle:m,deltaY:g}=_5(i[i.length-1],i[i.length-2]);n=Ka[t.arrowTypeEnd]*Math.abs(Math.sin(m))*(g>=0?1:-1)}let s=Math.abs(dn(e).y-dn(i[i.length-1]).y),l=Math.abs(dn(e).x-dn(i[i.length-1]).x),u=Math.abs(dn(e).y-dn(i[0]).y),h=Math.abs(dn(e).x-dn(i[0]).x),f=Ka[t.arrowTypeStart],d=Ka[t.arrowTypeEnd],p=1;if(s0&&l0&&h{"use strict";bt();jle=o((t,e,r,i,n,a=!1,s)=>{e.arrowTypeStart&&Yle(t,"start",e.arrowTypeStart,r,i,n,a,s),e.arrowTypeEnd&&Yle(t,"end",e.arrowTypeEnd,r,i,n,a,s)},"addEdgeMarkers"),KVe={arrow_cross:{type:"cross",fill:!1},arrow_point:{type:"point",fill:!0},arrow_barb:{type:"barb",fill:!0},arrow_barb_neo:{type:"barb",fill:!0},arrow_circle:{type:"circle",fill:!1},aggregation:{type:"aggregation",fill:!1},extension:{type:"extension",fill:!1},composition:{type:"composition",fill:!0},dependency:{type:"dependency",fill:!0},lollipop:{type:"lollipop",fill:!1},only_one:{type:"onlyOne",fill:!1},zero_or_one:{type:"zeroOrOne",fill:!1},one_or_more:{type:"oneOrMore",fill:!1},zero_or_more:{type:"zeroOrMore",fill:!1},requirement_arrow:{type:"requirement_arrow",fill:!1},requirement_contains:{type:"requirement_contains",fill:!1}},QVe=["cross","point","circle","lollipop","aggregation","extension","composition","dependency","barb"],Yle=o((t,e,r,i,n,a,s=!1,l)=>{let u=KVe[r],h=u&&QVe.includes(u.type);if(!u){Q.warn(`Unknown arrow type: ${r}`);return}let f=u.type,m=`${n}_${a}-${f}${e==="start"?"Start":"End"}${s&&h?"-margin":""}`;if(l&&l.trim()!==""){let g=l.replace(/[^\dA-Za-z]/g,"_"),y=`${m}_${g}`;if(!document.getElementById(y)){let v=document.getElementById(m);if(v){let x=v.cloneNode(!0);x.id=y,x.querySelectorAll("path, circle, line").forEach(T=>{T.setAttribute("stroke",l),u.fill&&T.setAttribute("fill",l)}),v.parentNode?.appendChild(x)}}t.attr(`marker-${e}`,`url(${i}#${y})`)}else t.attr(`marker-${e}`,`url(${i}#${m})`)},"addEdgeMarker")});function L5(t,e){Or(ge())&&t&&(t.style.width=e.length*9+"px",t.style.height="12px")}function tqe(t){let e=[],r=[];for(let i=1;i5&&Math.abs(a.y-n.y)>5||n.y===a.y&&a.x===s.x&&Math.abs(a.x-n.x)>5&&Math.abs(a.y-s.y)>5)&&(e.push(a),r.push(i))}return{cornerPoints:e,cornerPointPositions:r}}function nqe(t,e){if(t.length<2)return"";let r="",i=t.length,n=1e-5;for(let a=0;a({...n}));if(t.length>=2&&Ka[e.arrowTypeStart]){let n=Ka[e.arrowTypeStart],a=t[0],s=t[1],{angle:l}=Zle(a,s),u=n*Math.cos(l),h=n*Math.sin(l);r[0].x=a.x+u,r[0].y=a.y+h}let i=t.length;if(i>=2&&Ka[e.arrowTypeEnd]){let n=Ka[e.arrowTypeEnd],a=t[i-1],s=t[i-2],{angle:l}=Zle(s,a),u=n*Math.cos(l),h=n*Math.sin(l);r[i-1].x=a.x-u,r[i-1].y=a.y-h}return r}var ZVe,R5,Qa,Jle,Ib,N5,I5,JVe,eqe,Kle,Qle,rqe,iqe,M5,RM=P(()=>{"use strict";Ut();Sr();bt();To();_M();er();LM();Nb();Pr();Yt();w5();Xle();Ht();ZVe=o(t=>typeof t=="string"?t:ge()?.flowchart?.curve,"resolveEdgeCurveType"),R5=new Map,Qa=new Map,Jle=o(()=>{R5.clear(),Qa.clear()},"clear"),Ib=o(t=>t?typeof t=="string"?t:t.reduce((e,r)=>e+";"+r,""):"","getLabelStyles"),N5=o(async(t,e)=>{let r=ge(),i=Or(r),{labelStyles:n}=tt(e);e.labelStyle=n;let a=t.insert("g").attr("class","edgeLabel"),s=a.insert("g").attr("class","label").attr("data-id",e.id),l=e.labelType==="markdown",h=await Vi(t,e.label,{style:Ib(e.labelStyle),useHtmlLabels:i,addSvgBackground:!0,isNode:!1,markdown:l,width:l?void 0:void 0},r);s.node().appendChild(h),Q.info("abc82",e,e.labelType);let f=h.getBBox(),d=f;if(i){let m=h.children[0],g=Ze(h);f=m.getBoundingClientRect(),d=f,g.attr("width",f.width),g.attr("height",f.height)}else{let m=Ze(h).select("text").node();m&&typeof m.getBBox=="function"&&(d=m.getBBox())}s.attr("transform",Pl(d,i)),R5.set(e.id,a),e.width=f.width,e.height=f.height;let p;if(e.startLabelLeft){let m=t.insert("g").attr("class","edgeTerminals"),g=m.insert("g").attr("class","inner"),y=await Dc(g,e.startLabelLeft,Ib(e.labelStyle)||"",!1,!1);p=y;let v=y.getBBox();if(i){let x=y.children[0],b=Ze(y);v=x.getBoundingClientRect(),b.attr("width",v.width),b.attr("height",v.height)}g.attr("transform",Pl(v,i)),Qa.get(e.id)||Qa.set(e.id,{}),Qa.get(e.id).startLeft=m,L5(p,e.startLabelLeft)}if(e.startLabelRight){let m=t.insert("g").attr("class","edgeTerminals"),g=m.insert("g").attr("class","inner"),y=await Dc(g,e.startLabelRight,Ib(e.labelStyle)||"",!1,!1);p=y,g.node().appendChild(y);let v=y.getBBox();if(i){let x=y.children[0],b=Ze(y);v=x.getBoundingClientRect(),b.attr("width",v.width),b.attr("height",v.height)}g.attr("transform",Pl(v,i)),Qa.get(e.id)||Qa.set(e.id,{}),Qa.get(e.id).startRight=m,L5(p,e.startLabelRight)}if(e.endLabelLeft){let m=t.insert("g").attr("class","edgeTerminals"),g=m.insert("g").attr("class","inner"),y=await Dc(g,e.endLabelLeft,Ib(e.labelStyle)||"",!1,!1);p=y;let v=y.getBBox();if(i){let x=y.children[0],b=Ze(y);v=x.getBoundingClientRect(),b.attr("width",v.width),b.attr("height",v.height)}g.attr("transform",Pl(v,i)),m.node().appendChild(y),Qa.get(e.id)||Qa.set(e.id,{}),Qa.get(e.id).endLeft=m,L5(p,e.endLabelLeft)}if(e.endLabelRight){let m=t.insert("g").attr("class","edgeTerminals"),g=m.insert("g").attr("class","inner"),y=await Dc(g,e.endLabelRight,Ib(e.labelStyle)||"",!1,!1);p=y;let v=y.getBBox();if(i){let x=y.children[0],b=Ze(y);v=x.getBoundingClientRect(),b.attr("width",v.width),b.attr("height",v.height)}g.attr("transform",Pl(v,i)),m.node().appendChild(y),Qa.get(e.id)||Qa.set(e.id,{}),Qa.get(e.id).endRight=m,L5(p,e.endLabelRight)}return h},"insertEdgeLabel");o(L5,"setTerminalWidth");I5=o((t,e)=>{Q.debug("Moving label abc88 ",t.id,t.label,R5.get(t.id),e);let r=e.updatedPath?e.updatedPath:e.originalPath,i=ge(),{subGraphTitleTotalMargin:n}=Uh(i);if(t.label){let a=R5.get(t.id),s=t.x,l=t.y;if(r){let u=Kt.calcLabelPosition(r);Q.debug("Moving label "+t.label+" from (",s,",",l,") to (",u.x,",",u.y,") abc88"),e.updatedPath&&(s=u.x,l=u.y)}a.attr("transform",`translate(${s}, ${l+n/2})`)}if(t.startLabelLeft){let a=Qa.get(t.id).startLeft,s=t.x,l=t.y;if(r){let u=Kt.calcTerminalLabelPosition(t.arrowTypeStart?10:0,"start_left",r);s=u.x,l=u.y}a.attr("transform",`translate(${s}, ${l})`)}if(t.startLabelRight){let a=Qa.get(t.id).startRight,s=t.x,l=t.y;if(r){let u=Kt.calcTerminalLabelPosition(t.arrowTypeStart?10:0,"start_right",r);s=u.x,l=u.y}a.attr("transform",`translate(${s}, ${l})`)}if(t.endLabelLeft){let a=Qa.get(t.id).endLeft,s=t.x,l=t.y;if(r){let u=Kt.calcTerminalLabelPosition(t.arrowTypeEnd?10:0,"end_left",r);s=u.x,l=u.y}a.attr("transform",`translate(${s}, ${l})`)}if(t.endLabelRight){let a=Qa.get(t.id).endRight,s=t.x,l=t.y;if(r){let u=Kt.calcTerminalLabelPosition(t.arrowTypeEnd?10:0,"end_right",r);s=u.x,l=u.y}a.attr("transform",`translate(${s}, ${l})`)}},"positionEdgeLabel"),JVe=o((t,e)=>{let r=t.x,i=t.y,n=Math.abs(e.x-r),a=Math.abs(e.y-i),s=t.width/2,l=t.height/2;return n>=s||a>=l},"outsideNode"),eqe=o((t,e,r)=>{Q.debug(`intersection calc abc89: + outsidePoint: ${JSON.stringify(e)} + insidePoint : ${JSON.stringify(r)} + node : x:${t.x} y:${t.y} w:${t.width} h:${t.height}`);let i=t.x,n=t.y,a=Math.abs(i-r.x),s=t.width/2,l=r.xMath.abs(i-e.x)*u){let d=r.y{Q.warn("abc88 cutPathAtIntersect",t,e);let r=[],i=t[0],n=!1;return t.forEach(a=>{if(Q.info("abc88 checking point",a,e),!JVe(e,a)&&!n){let s=eqe(e,i,a);Q.debug("abc88 inside",a,i,s),Q.debug("abc88 intersection",s,e);let l=!1;r.forEach(u=>{l=l||u.x===s.x&&u.y===s.y}),r.some(u=>u.x===s.x&&u.y===s.y)?Q.warn("abc88 no intersect",s,r):r.push(s),n=!0}else Q.warn("abc88 outside",a,i),i=a,n||r.push(a)}),Q.debug("returning points",r),r},"cutPathAtIntersect");o(tqe,"extractCornerPoints");Qle=o(function(t,e,r){let i=e.x-t.x,n=e.y-t.y,a=Math.sqrt(i*i+n*n),s=r/a;return{x:e.x-s*i,y:e.y-s*n}},"findAdjacentPoint"),rqe=o(function(t){let{cornerPointPositions:e}=tqe(t),r=[];for(let i=0;i10&&Math.abs(a.y-n.y)>=10){Q.debug("Corner point fixing",Math.abs(a.x-n.x),Math.abs(a.y-n.y));let m=5;s.x===l.x?p={x:h<0?l.x-m+d:l.x+m-d,y:f<0?l.y-d:l.y+d}:p={x:h<0?l.x-d:l.x+d,y:f<0?l.y-m+d:l.y+m-d}}else Q.debug("Corner point skipping fixing",Math.abs(a.x-n.x),Math.abs(a.y-n.y));r.push(p,u)}else r.push(t[i]);return r},"fixCorners"),iqe=o((t,e,r)=>{let i=t-e-r,n=2,a=2,s=n+a,l=Math.floor(i/s),u=Array(l).fill(`${n} ${a}`).join(" ");return`0 ${e} ${u} ${r}`},"generateDashArray"),M5=o(function(t,e,r,i,n,a,s,l=!1){if(!s)throw new Error(`insertEdge: missing diagramId for edge "${e.id}" \u2014 edge IDs require a diagram prefix for uniqueness`);let{handDrawnSeed:u}=ge(),h=e.points,f=!1,d=n;var p=a;let m=[];for(let B in e.cssCompiledStyles)Eb(B)||m.push(e.cssCompiledStyles[B]);Q.debug("UIO intersect check",e.points,p.x,d.x),p.intersect&&d.intersect&&!l&&(h=h.slice(1,e.points.length-1),h.unshift(d.intersect(h[0])),Q.debug("Last point UIO",e.start,"-->",e.end,h[h.length-1],p,p.intersect(h[h.length-1])),h.push(p.intersect(h[h.length-1])));let g=btoa(JSON.stringify(h));e.toCluster&&(Q.info("to cluster abc88",r.get(e.toCluster)),h=Kle(e.points,r.get(e.toCluster).node),f=!0),e.fromCluster&&(Q.debug("from cluster abc88",r.get(e.fromCluster),JSON.stringify(h,null,2)),h=Kle(h.reverse(),r.get(e.fromCluster).node).reverse(),f=!0);let y=h.filter(B=>!Number.isNaN(B.y)),v=ZVe(e.curve);v!=="rounded"&&(y=rqe(y));let x=yu;switch(v){case"linear":x=yu;break;case"basis":x=wc;break;case"cardinal":x=U2;break;case"bumpX":x=z2;break;case"bumpY":x=G2;break;case"catmullRom":x=j2;break;case"monotoneX":x=X2;break;case"monotoneY":x=K2;break;case"natural":x=n1;break;case"step":x=a1;break;case"stepAfter":x=Z2;break;case"stepBefore":x=Q2;break;case"rounded":x=yu;break;default:x=wc}let{x:b,y:T}=D5(e),w=Cc().x(b).y(T).curve(x),k;switch(e.thickness){case"normal":k="edge-thickness-normal";break;case"thick":k="edge-thickness-thick";break;case"invisible":k="edge-thickness-invisible";break;default:k="edge-thickness-normal"}switch(e.pattern){case"solid":k+=" edge-pattern-solid";break;case"dotted":k+=" edge-pattern-dotted";break;case"dashed":k+=" edge-pattern-dashed";break;default:k+=" edge-pattern-solid"}let C,E=v==="rounded"?nqe(aqe(y,e),5):w(y),S=Array.isArray(e.style)?e.style:[e.style],L=S.find(B=>B?.startsWith("stroke:")),M="";e.animate&&(M="edge-animation-fast"),e.animation&&(M="edge-animation-"+e.animation);let I=!1;if(e.look==="handDrawn"){let B=rt.svg(t);Object.assign([],y);let O=B.path(E,{roughness:.3,seed:u});k+=" transition",C=Ze(O).select("path").attr("id",`${s}-${e.id}`).attr("class"," "+k+(e.classes?" "+e.classes:"")+(M?" "+M:"")).attr("style",S?S.reduce((z,F)=>z+";"+F,""):"");let $=C.attr("d");C.attr("d",$),t.node().appendChild(C.node())}else{let B=m.join(";"),O=S?S.reduce((X,W)=>X+W+";",""):"",$=(B?B+";"+O+";":O)+";"+(S?S.reduce((X,W)=>X+";"+W,""):"");C=t.append("path").attr("d",E).attr("id",`${s}-${e.id}`).attr("class"," "+k+(e.classes?" "+e.classes:"")+(M?" "+M:"")).attr("style",$),L=$.match(/stroke:([^;]+)/)?.[1],I=e.animate===!0||!!e.animation||B.includes("animation");let z=C.node(),F=typeof z.getTotalLength=="function"?z.getTotalLength():0,V=DM[e.arrowTypeStart]||0,H=DM[e.arrowTypeEnd]||0;if(e.look==="neo"&&!I){let W=`stroke-dasharray: ${e.pattern==="dotted"||e.pattern==="dashed"?iqe(F,V,H):`0 ${V} ${F-V-H} ${H}`}; stroke-dashoffset: 0;`;C.attr("style",W+C.attr("style"))}}C.attr("data-edge",!0),C.attr("data-et","edge"),C.attr("data-id",e.id),C.attr("data-points",g),C.attr("data-look",xi(e.look)),e.showPoints&&y.forEach(B=>{t.append("circle").style("stroke","red").style("fill","red").attr("r",1).attr("cx",B.x).attr("cy",B.y)});let A="";(ge().flowchart.arrowMarkerAbsolute||ge().state.arrowMarkerAbsolute)&&(A=window.location.protocol+"//"+window.location.host+window.location.pathname+window.location.search,A=A.replace(/\(/g,"\\(").replace(/\)/g,"\\)")),Q.info("arrowTypeStart",e.arrowTypeStart),Q.info("arrowTypeEnd",e.arrowTypeEnd);let _=!I&&e?.look==="neo";jle(C,e,A,s,i,_,L);let D=Math.floor(h.length/2),N=h[D];Kt.isLabelCoordinateInPath(N,C.attr("d"))||(f=!0);let R={};return f&&(R.updatedPath=h),R.originalPath=e.points,R},"insertEdge");o(nqe,"generateRoundedPath");o(Zle,"calculateDeltaAndAngle");o(aqe,"applyMarkerOffsetsToPoints")});var sqe,oqe,lqe,cqe,uqe,hqe,fqe,dqe,pqe,mqe,gqe,yqe,vqe,xqe,bqe,Tqe,kqe,Cqe,wqe,Eqe,Sqe,Aqe,_qe,Dqe,O5,NM=P(()=>{"use strict";bt();Sr();sqe=o((t,e,r,i)=>{e.forEach(n=>{Dqe[n](t,r,i)})},"insertMarkers"),oqe=o((t,e,r)=>{Q.trace("Making markers for ",r),t.append("defs").append("marker").attr("id",r+"_"+e+"-extensionStart").attr("class","marker extension "+e).attr("refX",18).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").attr("markerUnits","userSpaceOnUse").append("path").attr("d","M 1,7 L18,13 V 1 Z"),t.append("defs").append("marker").attr("id",r+"_"+e+"-extensionEnd").attr("class","marker extension "+e).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 1,1 V 13 L18,7 Z"),t.append("marker").attr("id",r+"_"+e+"-extensionStart-margin").attr("class","marker extension "+e).attr("refX",18).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").attr("markerUnits","userSpaceOnUse").attr("viewBox","0 0 20 14").append("polygon").attr("points","10,7 18,13 18,1").style("stroke-width",2).style("stroke-dasharray","0"),t.append("defs").append("marker").attr("id",r+"_"+e+"-extensionEnd-margin").attr("class","marker extension "+e).attr("refX",9).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").attr("markerUnits","userSpaceOnUse").attr("viewBox","0 0 20 14").append("polygon").attr("points","10,1 10,13 18,7").style("stroke-width",2).style("stroke-dasharray","0")},"extension"),lqe=o((t,e,r)=>{t.append("defs").append("marker").attr("id",r+"_"+e+"-compositionStart").attr("class","marker composition "+e).attr("refX",18).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),t.append("defs").append("marker").attr("id",r+"_"+e+"-compositionEnd").attr("class","marker composition "+e).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),t.append("defs").append("marker").attr("id",r+"_"+e+"-compositionStart-margin").attr("class","marker composition "+e).attr("refX",15).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").attr("markerUnits","userSpaceOnUse").append("path").style("stroke-width",0).attr("viewBox","0 0 15 15").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),t.append("defs").append("marker").attr("id",r+"_"+e+"-compositionEnd-margin").attr("class","marker composition "+e).attr("refX",3.5).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").attr("markerUnits","userSpaceOnUse").append("path").style("stroke-width",0).attr("d","M 18,7 L9,13 L1,7 L9,1 Z")},"composition"),cqe=o((t,e,r)=>{t.append("defs").append("marker").attr("id",r+"_"+e+"-aggregationStart").attr("class","marker aggregation "+e).attr("refX",18).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),t.append("defs").append("marker").attr("id",r+"_"+e+"-aggregationEnd").attr("class","marker aggregation "+e).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),t.append("defs").append("marker").attr("id",r+"_"+e+"-aggregationStart-margin").attr("class","marker aggregation "+e).attr("refX",15).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").attr("markerUnits","userSpaceOnUse").append("path").style("stroke-width",2).attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),t.append("defs").append("marker").attr("id",r+"_"+e+"-aggregationEnd-margin").attr("class","marker aggregation "+e).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").attr("markerUnits","userSpaceOnUse").append("path").style("stroke-width",2).attr("d","M 18,7 L9,13 L1,7 L9,1 Z")},"aggregation"),uqe=o((t,e,r)=>{t.append("defs").append("marker").attr("id",r+"_"+e+"-dependencyStart").attr("class","marker dependency "+e).attr("refX",6).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 5,7 L9,13 L1,7 L9,1 Z"),t.append("defs").append("marker").attr("id",r+"_"+e+"-dependencyEnd").attr("class","marker dependency "+e).attr("refX",13).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L14,7 L9,1 Z"),t.append("defs").append("marker").attr("id",r+"_"+e+"-dependencyStart-margin").attr("class","marker dependency "+e).attr("refX",4).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").attr("markerUnits","userSpaceOnUse").append("path").style("stroke-width",0).attr("d","M 5,7 L9,13 L1,7 L9,1 Z"),t.append("defs").append("marker").attr("id",r+"_"+e+"-dependencyEnd-margin").attr("class","marker dependency "+e).attr("refX",16).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").attr("markerUnits","userSpaceOnUse").append("path").style("stroke-width",0).attr("d","M 18,7 L9,13 L14,7 L9,1 Z")},"dependency"),hqe=o((t,e,r)=>{t.append("defs").append("marker").attr("id",r+"_"+e+"-lollipopStart").attr("class","marker lollipop "+e).attr("refX",13).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("circle").attr("fill","transparent").attr("cx",7).attr("cy",7).attr("r",6),t.append("defs").append("marker").attr("id",r+"_"+e+"-lollipopEnd").attr("class","marker lollipop "+e).attr("refX",1).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("circle").attr("fill","transparent").attr("cx",7).attr("cy",7).attr("r",6),t.append("defs").append("marker").attr("id",r+"_"+e+"-lollipopStart-margin").attr("class","marker lollipop "+e).attr("refX",13).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").attr("markerUnits","userSpaceOnUse").append("circle").attr("fill","transparent").attr("cx",7).attr("cy",7).attr("r",6).attr("stroke-width",2),t.append("defs").append("marker").attr("id",r+"_"+e+"-lollipopEnd-margin").attr("class","marker lollipop "+e).attr("refX",1).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").attr("markerUnits","userSpaceOnUse").append("circle").attr("fill","transparent").attr("cx",7).attr("cy",7).attr("r",6).attr("stroke-width",2)},"lollipop"),fqe=o((t,e,r)=>{t.append("marker").attr("id",r+"_"+e+"-pointEnd").attr("class","marker "+e).attr("viewBox","0 0 10 10").attr("refX",5).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",8).attr("markerHeight",8).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0"),t.append("marker").attr("id",r+"_"+e+"-pointStart").attr("class","marker "+e).attr("viewBox","0 0 10 10").attr("refX",4.5).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",8).attr("markerHeight",8).attr("orient","auto").append("path").attr("d","M 0 5 L 10 10 L 10 0 z").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0"),t.append("marker").attr("id",r+"_"+e+"-pointEnd-margin").attr("class","marker "+e).attr("viewBox","0 0 11.5 14").attr("refX",11.5).attr("refY",7).attr("markerUnits","userSpaceOnUse").attr("markerWidth",10.5).attr("markerHeight",14).attr("orient","auto").append("path").attr("d","M 0 0 L 11.5 7 L 0 14 z").attr("class","arrowMarkerPath").style("stroke-width",0).style("stroke-dasharray","1,0"),t.append("marker").attr("id",r+"_"+e+"-pointStart-margin").attr("class","marker "+e).attr("viewBox","0 0 11.5 14").attr("refX",1).attr("refY",7).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11.5).attr("markerHeight",14).attr("orient","auto").append("polygon").attr("points","0,7 11.5,14 11.5,0").attr("class","arrowMarkerPath").style("stroke-width",0).style("stroke-dasharray","1,0")},"point"),dqe=o((t,e,r)=>{t.append("marker").attr("id",r+"_"+e+"-circleEnd").attr("class","marker "+e).attr("viewBox","0 0 10 10").attr("refX",11).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("circle").attr("cx","5").attr("cy","5").attr("r","5").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0"),t.append("marker").attr("id",r+"_"+e+"-circleStart").attr("class","marker "+e).attr("viewBox","0 0 10 10").attr("refX",-1).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("circle").attr("cx","5").attr("cy","5").attr("r","5").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0"),t.append("marker").attr("id",r+"_"+e+"-circleEnd-margin").attr("class","marker "+e).attr("viewBox","0 0 10 10").attr("refY",5).attr("refX",12.25).attr("markerUnits","userSpaceOnUse").attr("markerWidth",14).attr("markerHeight",14).attr("orient","auto").append("circle").attr("cx","5").attr("cy","5").attr("r","5").attr("class","arrowMarkerPath").style("stroke-width",0).style("stroke-dasharray","1,0"),t.append("marker").attr("id",r+"_"+e+"-circleStart-margin").attr("class","marker "+e).attr("viewBox","0 0 10 10").attr("refX",-2).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",14).attr("markerHeight",14).attr("orient","auto").append("circle").attr("cx","5").attr("cy","5").attr("r","5").attr("class","arrowMarkerPath").style("stroke-width",0).style("stroke-dasharray","1,0")},"circle"),pqe=o((t,e,r)=>{t.append("marker").attr("id",r+"_"+e+"-crossEnd").attr("class","marker cross "+e).attr("viewBox","0 0 11 11").attr("refX",12).attr("refY",5.2).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("path").attr("d","M 1,1 l 9,9 M 10,1 l -9,9").attr("class","arrowMarkerPath").style("stroke-width",2).style("stroke-dasharray","1,0"),t.append("marker").attr("id",r+"_"+e+"-crossStart").attr("class","marker cross "+e).attr("viewBox","0 0 11 11").attr("refX",-1).attr("refY",5.2).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("path").attr("d","M 1,1 l 9,9 M 10,1 l -9,9").attr("class","arrowMarkerPath").style("stroke-width",2).style("stroke-dasharray","1,0"),t.append("marker").attr("id",r+"_"+e+"-crossEnd-margin").attr("class","marker cross "+e).attr("viewBox","0 0 15 15").attr("refX",17.7).attr("refY",7.5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto").append("path").attr("d","M 1,1 L 14,14 M 1,14 L 14,1").attr("class","arrowMarkerPath").style("stroke-width",2.5),t.append("marker").attr("id",r+"_"+e+"-crossStart-margin").attr("class","marker cross "+e).attr("viewBox","0 0 15 15").attr("refX",-3.5).attr("refY",7.5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto").append("path").attr("d","M 1,1 L 14,14 M 1,14 L 14,1").attr("class","arrowMarkerPath").style("stroke-width",2.5).style("stroke-dasharray","1,0")},"cross"),mqe=o((t,e,r)=>{t.append("defs").append("marker").attr("id",r+"_"+e+"-barbEnd").attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",14).attr("markerUnits","userSpaceOnUse").attr("orient","auto").append("path").attr("d","M 19,7 L9,13 L14,7 L9,1 Z")},"barb"),gqe=o((t,e,r)=>{let i=Lt(),{themeVariables:n}=i,{transitionColor:a}=n;t.append("defs").append("marker").attr("id",r+"_"+e+"-barbEnd").attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",14).attr("markerUnits","strokeWidth").attr("orient","auto").append("path").attr("d","M 19,7 L11,14 L13,7 L11,0 Z"),t.append("defs").append("marker").attr("id",r+"_"+e+"-barbEnd-margin").attr("refX",17).attr("refY",7).attr("markerWidth",20).attr("markerHeight",14).attr("markerUnits","userSpaceOnUse").attr("orient","auto").append("path").attr("d","M 19,7 L11,14 L13,7 L11,0 Z").attr("fill",`${a}`)},"barbNeo"),yqe=o((t,e,r)=>{t.append("defs").append("marker").attr("id",r+"_"+e+"-onlyOneStart").attr("class","marker onlyOne "+e).attr("refX",0).attr("refY",9).attr("markerWidth",18).attr("markerHeight",18).attr("orient","auto").append("path").attr("d","M9,0 L9,18 M15,0 L15,18"),t.append("defs").append("marker").attr("id",r+"_"+e+"-onlyOneEnd").attr("class","marker onlyOne "+e).attr("refX",18).attr("refY",9).attr("markerWidth",18).attr("markerHeight",18).attr("orient","auto").append("path").attr("d","M3,0 L3,18 M9,0 L9,18")},"only_one"),vqe=o((t,e,r)=>{let i=t.append("defs").append("marker").attr("id",r+"_"+e+"-zeroOrOneStart").attr("class","marker zeroOrOne "+e).attr("refX",0).attr("refY",9).attr("markerWidth",30).attr("markerHeight",18).attr("orient","auto");i.append("circle").attr("fill","white").attr("cx",21).attr("cy",9).attr("r",6),i.append("path").attr("d","M9,0 L9,18");let n=t.append("defs").append("marker").attr("id",r+"_"+e+"-zeroOrOneEnd").attr("class","marker zeroOrOne "+e).attr("refX",30).attr("refY",9).attr("markerWidth",30).attr("markerHeight",18).attr("orient","auto");n.append("circle").attr("fill","white").attr("cx",9).attr("cy",9).attr("r",6),n.append("path").attr("d","M21,0 L21,18")},"zero_or_one"),xqe=o((t,e,r)=>{t.append("defs").append("marker").attr("id",r+"_"+e+"-oneOrMoreStart").attr("class","marker oneOrMore "+e).attr("refX",18).attr("refY",18).attr("markerWidth",45).attr("markerHeight",36).attr("orient","auto").append("path").attr("d","M0,18 Q 18,0 36,18 Q 18,36 0,18 M42,9 L42,27"),t.append("defs").append("marker").attr("id",r+"_"+e+"-oneOrMoreEnd").attr("class","marker oneOrMore "+e).attr("refX",27).attr("refY",18).attr("markerWidth",45).attr("markerHeight",36).attr("orient","auto").append("path").attr("d","M3,9 L3,27 M9,18 Q27,0 45,18 Q27,36 9,18")},"one_or_more"),bqe=o((t,e,r)=>{let i=t.append("defs").append("marker").attr("id",r+"_"+e+"-zeroOrMoreStart").attr("class","marker zeroOrMore "+e).attr("refX",18).attr("refY",18).attr("markerWidth",57).attr("markerHeight",36).attr("orient","auto");i.append("circle").attr("fill","white").attr("cx",48).attr("cy",18).attr("r",6),i.append("path").attr("d","M0,18 Q18,0 36,18 Q18,36 0,18");let n=t.append("defs").append("marker").attr("id",r+"_"+e+"-zeroOrMoreEnd").attr("class","marker zeroOrMore "+e).attr("refX",39).attr("refY",18).attr("markerWidth",57).attr("markerHeight",36).attr("orient","auto");n.append("circle").attr("fill","white").attr("cx",9).attr("cy",18).attr("r",6),n.append("path").attr("d","M21,18 Q39,0 57,18 Q39,36 21,18")},"zero_or_more"),Tqe=o((t,e,r)=>{let i=Lt(),{themeVariables:n}=i,{strokeWidth:a}=n;t.append("defs").append("marker").attr("id",r+"_"+e+"-onlyOneStart").attr("class","marker onlyOne "+e).attr("refX",0).attr("refY",9).attr("markerWidth",18).attr("markerHeight",18).attr("orient","auto").attr("markerUnits","userSpaceOnUse").append("path").attr("d","M9,0 L9,18 M15,0 L15,18").attr("stroke-width",`${a}`),t.append("defs").append("marker").attr("id",r+"_"+e+"-onlyOneEnd").attr("class","marker onlyOne "+e).attr("refX",18).attr("refY",9).attr("markerWidth",18).attr("markerHeight",18).attr("orient","auto").attr("markerUnits","userSpaceOnUse").append("path").attr("d","M3,0 L3,18 M9,0 L9,18").attr("stroke-width",`${a}`)},"only_one_neo"),kqe=o((t,e,r)=>{let i=Lt(),{themeVariables:n}=i,{strokeWidth:a,mainBkg:s}=n,l=t.append("defs").append("marker").attr("id",r+"_"+e+"-zeroOrOneStart").attr("class","marker zeroOrOne "+e).attr("refX",0).attr("refY",9).attr("markerWidth",30).attr("markerHeight",18).attr("orient","auto").attr("markerUnits","userSpaceOnUse");l.append("circle").attr("fill",s??"white").attr("cx",21).attr("cy",9).attr("stroke-width",`${a}`).attr("r",6),l.append("path").attr("d","M9,0 L9,18").attr("stroke-width",`${a}`);let u=t.append("defs").append("marker").attr("id",r+"_"+e+"-zeroOrOneEnd").attr("class","marker zeroOrOne "+e).attr("refX",30).attr("refY",9).attr("markerWidth",30).attr("markerHeight",18).attr("markerUnits","userSpaceOnUse").attr("orient","auto");u.append("circle").attr("fill",s??"white").attr("cx",9).attr("cy",9).attr("stroke-width",`${a}`).attr("r",6),u.append("path").attr("d","M21,0 L21,18").attr("stroke-width",`${a}`)},"zero_or_one_neo"),Cqe=o((t,e,r)=>{let i=Lt(),{themeVariables:n}=i,{strokeWidth:a}=n;t.append("defs").append("marker").attr("id",r+"_"+e+"-oneOrMoreStart").attr("class","marker oneOrMore "+e).attr("refX",18).attr("refY",18).attr("markerWidth",45).attr("markerHeight",36).attr("orient","auto").attr("markerUnits","userSpaceOnUse").append("path").attr("d","M0,18 Q 18,0 36,18 Q 18,36 0,18 M42,9 L42,27").attr("stroke-width",`${a}`),t.append("defs").append("marker").attr("id",r+"_"+e+"-oneOrMoreEnd").attr("class","marker oneOrMore "+e).attr("refX",27).attr("refY",18).attr("markerWidth",45).attr("markerHeight",36).attr("markerUnits","userSpaceOnUse").attr("orient","auto").append("path").attr("d","M3,9 L3,27 M9,18 Q27,0 45,18 Q27,36 9,18").attr("stroke-width",`${a}`)},"one_or_more_neo"),wqe=o((t,e,r)=>{let i=Lt(),{themeVariables:n}=i,{strokeWidth:a,mainBkg:s}=n,l=t.append("defs").append("marker").attr("id",r+"_"+e+"-zeroOrMoreStart").attr("class","marker zeroOrMore "+e).attr("refX",18).attr("refY",18).attr("markerWidth",57).attr("markerHeight",36).attr("markerUnits","userSpaceOnUse").attr("orient","auto");l.append("circle").attr("fill",s??"white").attr("cx",45.5).attr("cy",18).attr("r",6).attr("stroke-width",`${a}`),l.append("path").attr("d","M0,18 Q18,0 36,18 Q18,36 0,18").attr("stroke-width",`${a}`);let u=t.append("defs").append("marker").attr("id",r+"_"+e+"-zeroOrMoreEnd").attr("class","marker zeroOrMore "+e).attr("refX",39).attr("refY",18).attr("markerWidth",57).attr("markerHeight",36).attr("orient","auto").attr("markerUnits","userSpaceOnUse");u.append("circle").attr("fill",s??"white").attr("cx",11).attr("cy",18).attr("r",6).attr("stroke-width",`${a}`),u.append("path").attr("d","M21,18 Q39,0 57,18 Q39,36 21,18").attr("stroke-width",`${a}`)},"zero_or_more_neo"),Eqe=o((t,e,r)=>{t.append("defs").append("marker").attr("id",r+"_"+e+"-requirement_arrowEnd").attr("refX",20).attr("refY",10).attr("markerWidth",20).attr("markerHeight",20).attr("orient","auto").append("path").attr("d",`M0,0 + L20,10 + M20,10 + L0,20`)},"requirement_arrow"),Sqe=o((t,e,r)=>{let i=Lt(),{themeVariables:n}=i,{strokeWidth:a}=n;t.append("defs").append("marker").attr("id",r+"_"+e+"-requirement_arrowEnd").attr("refX",20).attr("refY",10).attr("markerWidth",20).attr("markerHeight",20).attr("orient","auto").attr("markerUnits","userSpaceOnUse").attr("stroke-width",`${a}`).attr("viewBox","0 0 25 20").append("path").attr("d",`M0,0 + L20,10 + M20,10 + L0,20`).attr("stroke-linejoin","miter")},"requirement_arrow_neo"),Aqe=o((t,e,r)=>{let i=t.append("defs").append("marker").attr("id",r+"_"+e+"-requirement_containsStart").attr("refX",0).attr("refY",10).attr("markerWidth",20).attr("markerHeight",20).attr("orient","auto").append("g");i.append("circle").attr("cx",10).attr("cy",10).attr("r",9).attr("fill","none"),i.append("line").attr("x1",1).attr("x2",19).attr("y1",10).attr("y2",10),i.append("line").attr("y1",1).attr("y2",19).attr("x1",10).attr("x2",10)},"requirement_contains"),_qe=o((t,e,r)=>{let i=Lt(),{themeVariables:n}=i,{strokeWidth:a}=n,s=t.append("defs").append("marker").attr("id",r+"_"+e+"-requirement_containsStart").attr("refX",0).attr("refY",10).attr("markerWidth",20).attr("markerHeight",20).attr("orient","auto").attr("markerUnits","userSpaceOnUse").append("g");s.append("circle").attr("cx",10).attr("cy",10).attr("r",9).attr("fill","none"),s.append("line").attr("x1",1).attr("x2",19).attr("y1",10).attr("y2",10),s.append("line").attr("y1",1).attr("y2",19).attr("x1",10).attr("x2",10),s.selectAll("*").attr("stroke-width",`${a}`)},"requirement_contains_neo"),Dqe={extension:oqe,composition:lqe,aggregation:cqe,dependency:uqe,lollipop:hqe,point:fqe,circle:dqe,cross:pqe,barb:mqe,barbNeo:gqe,only_one:yqe,zero_or_one:vqe,one_or_more:xqe,zero_or_more:bqe,only_one_neo:Tqe,zero_or_one_neo:kqe,one_or_more_neo:Cqe,zero_or_more_neo:wqe,requirement_arrow:Eqe,requirement_contains:Aqe,requirement_arrow_neo:Sqe,requirement_contains_neo:_qe},O5=sqe});async function I1(t,e,r){let i,n;e.shape==="rect"&&(e.rx&&e.ry?e.shape="roundedRect":e.shape="squareRect");let a=e.shape?SM[e.shape]:void 0;if(!a)throw new Error(`No such shape: ${e.shape}. Please check your syntax.`);if(e.link){let s;r.config.securityLevel==="sandbox"?s="_top":e.linkTarget&&(s=e.linkTarget||"_blank"),i=t.insert("svg:a").attr("xlink:href",e.link).attr("target",s??null),n=await a(i,e,r)}else n=await a(t,e,r),i=n;return i.attr("data-look",xi(e.look)),e.tooltip&&n.attr("title",e.tooltip),P5.set(e.id,i),e.haveCallback&&i.attr("class",i.attr("class")+" clickable"),i}var P5,ece,tce,Mb,B5=P(()=>{"use strict";bt();AM();er();P5=new Map;o(I1,"insertNode");ece=o((t,e)=>{P5.set(e.id,t)},"setNodeElem"),tce=o(()=>{P5.clear()},"clear"),Mb=o(t=>{let e=P5.get(t.id);Q.trace("Transforming node",t.diff,t,"translate("+(t.x-t.width/2-5)+", "+t.width/2+")");let r=8,i=t.diff||0;return t.clusterNode?e.attr("transform","translate("+(t.x+i-t.width/2)+", "+(t.y-t.height/2-r)+")"):e.attr("transform","translate("+t.x+", "+t.y+")"),i},"positionNode")});var rce,ice=P(()=>{"use strict";Sr();Vr();bt();A5();RM();NM();B5();zt();er();rce={common:lt,getConfig:Lt,insertCluster:N1,insertEdge:M5,insertEdgeLabel:N5,insertMarkers:O5,insertNode:I1,interpolateToCurve:yI,labelHelper:vt,log:Q,positionEdgeLabel:I5}});function Rqe(t){return typeof t=="symbol"||En(t)&&Xa(t)==Lqe}var Lqe,tl,M0=P(()=>{"use strict";Oh();Dl();Lqe="[object Symbol]";o(Rqe,"isSymbol");tl=Rqe});function Nqe(t,e){for(var r=-1,i=t==null?0:t.length,n=Array(i);++r{"use strict";o(Nqe,"arrayMap");wo=Nqe});function sce(t){if(typeof t=="string")return t;if(Gt(t))return wo(t,sce)+"";if(tl(t))return ace?ace.call(t):"";var e=t+"";return e=="0"&&1/t==-Iqe?"-0":e}var Iqe,nce,ace,oce,lce=P(()=>{"use strict";v0();O0();fn();M0();Iqe=1/0,nce=Da?Da.prototype:void 0,ace=nce?nce.toString:void 0;o(sce,"baseToString");oce=sce});function Oqe(t){for(var e=t.length;e--&&Mqe.test(t.charAt(e)););return e}var Mqe,cce,uce=P(()=>{"use strict";Mqe=/\s/;o(Oqe,"trimmedEndIndex");cce=Oqe});function Bqe(t){return t&&t.slice(0,cce(t)+1).replace(Pqe,"")}var Pqe,hce,fce=P(()=>{"use strict";uce();Pqe=/^\s+/;o(Bqe,"baseTrim");hce=Bqe});function Vqe(t){if(typeof t=="number")return t;if(tl(t))return dce;if(Gi(t)){var e=typeof t.valueOf=="function"?t.valueOf():t;t=Gi(e)?e+"":e}if(typeof t!="string")return t===0?t:+t;t=hce(t);var r=$qe.test(t);return r||zqe.test(t)?Gqe(t.slice(2),r?2:8):Fqe.test(t)?dce:+t}var dce,Fqe,$qe,zqe,Gqe,pce,mce=P(()=>{"use strict";fce();Zo();M0();dce=NaN,Fqe=/^[-+]0x[0-9a-f]+$/i,$qe=/^0b[01]+$/i,zqe=/^0o[0-7]+$/i,Gqe=parseInt;o(Vqe,"toNumber");pce=Vqe});function Wqe(t){if(!t)return t===0?t:0;if(t=pce(t),t===gce||t===-gce){var e=t<0?-1:1;return e*qqe}return t===t?t:0}var gce,qqe,M1,IM=P(()=>{"use strict";mce();gce=1/0,qqe=17976931348623157e292;o(Wqe,"toFinite");M1=Wqe});function Uqe(t){var e=M1(t),r=e%1;return e===e?r?e-r:e:0}var Au,O1=P(()=>{"use strict";IM();o(Uqe,"toInteger");Au=Uqe});var Hqe,F5,yce=P(()=>{"use strict";Zf();Al();Hqe=mo(In,"WeakMap"),F5=Hqe});function Yqe(){}var Sn,MM=P(()=>{"use strict";o(Yqe,"noop");Sn=Yqe});function jqe(t,e){for(var r=-1,i=t==null?0:t.length;++r{"use strict";o(jqe,"arrayEach");$5=jqe});function Xqe(t,e,r,i){for(var n=t.length,a=r+(i?1:-1);i?a--:++a{"use strict";o(Xqe,"baseFindIndex");z5=Xqe});function Kqe(t){return t!==t}var vce,xce=P(()=>{"use strict";o(Kqe,"baseIsNaN");vce=Kqe});function Qqe(t,e,r){for(var i=r-1,n=t.length;++i{"use strict";o(Qqe,"strictIndexOf");bce=Qqe});function Zqe(t,e,r){return e===e?bce(t,e,r):z5(t,vce,r)}var P1,G5=P(()=>{"use strict";PM();xce();Tce();o(Zqe,"baseIndexOf");P1=Zqe});function Jqe(t,e){var r=t==null?0:t.length;return!!r&&P1(t,e,0)>-1}var V5,BM=P(()=>{"use strict";G5();o(Jqe,"arrayIncludes");V5=Jqe});var eWe,kce,Cce=P(()=>{"use strict";nI();eWe=P3(Object.keys,Object),kce=eWe});function iWe(t){if(!bu(t))return kce(t);var e=[];for(var r in Object(t))rWe.call(t,r)&&r!="constructor"&&e.push(r);return e}var tWe,rWe,B1,q5=P(()=>{"use strict";v1();Cce();tWe=Object.prototype,rWe=tWe.hasOwnProperty;o(iWe,"baseKeys");B1=iWe});function nWe(t){return Mn(t)?G3(t):B1(t)}var ni,_u=P(()=>{"use strict";cI();q5();Ll();o(nWe,"keys");ni=nWe});var aWe,sWe,oWe,Za,wce=P(()=>{"use strict";k1();C0();dI();Ll();v1();_u();aWe=Object.prototype,sWe=aWe.hasOwnProperty,oWe=W3(function(t,e){if(bu(e)||Mn(e)){Il(e,ni(e),t);return}for(var r in e)sWe.call(e,r)&&Tu(t,r,e[r])}),Za=oWe});function uWe(t,e){if(Gt(t))return!1;var r=typeof t;return r=="number"||r=="symbol"||r=="boolean"||t==null||tl(t)?!0:cWe.test(t)||!lWe.test(t)||e!=null&&t in Object(e)}var lWe,cWe,F1,W5=P(()=>{"use strict";fn();M0();lWe=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,cWe=/^\w*$/;o(uWe,"isKey");F1=uWe});function fWe(t){var e=u1(t,function(i){return r.size===hWe&&r.clear(),i}),r=e.cache;return e}var hWe,Ece,Sce=P(()=>{"use strict";QN();hWe=500;o(fWe,"memoizeCapped");Ece=fWe});var dWe,pWe,mWe,Ace,_ce=P(()=>{"use strict";Sce();dWe=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,pWe=/\\(\\)?/g,mWe=Ece(function(t){var e=[];return t.charCodeAt(0)===46&&e.push(""),t.replace(dWe,function(r,i,n,a){e.push(n?a.replace(pWe,"$1"):i||r)}),e}),Ace=mWe});function gWe(t){return t==null?"":oce(t)}var U5,FM=P(()=>{"use strict";lce();o(gWe,"toString");U5=gWe});function yWe(t,e){return Gt(t)?t:F1(t,e)?[t]:Ace(U5(t))}var md,Ob=P(()=>{"use strict";fn();W5();_ce();FM();o(yWe,"castPath");md=yWe});function xWe(t){if(typeof t=="string"||tl(t))return t;var e=t+"";return e=="0"&&1/t==-vWe?"-0":e}var vWe,Du,$1=P(()=>{"use strict";M0();vWe=1/0;o(xWe,"toKey");Du=xWe});function bWe(t,e){e=md(e,t);for(var r=0,i=e.length;t!=null&&r{"use strict";Ob();$1();o(bWe,"baseGet");gd=bWe});function TWe(t,e,r){var i=t==null?void 0:gd(t,e);return i===void 0?r:i}var Dce,Lce=P(()=>{"use strict";Pb();o(TWe,"get");Dce=TWe});function kWe(t,e){for(var r=-1,i=e.length,n=t.length;++r{"use strict";o(kWe,"arrayPush");z1=kWe});function CWe(t){return Gt(t)||Sc(t)||!!(Rce&&t&&t[Rce])}var Rce,Nce,Ice=P(()=>{"use strict";v0();x1();fn();Rce=Da?Da.isConcatSpreadable:void 0;o(CWe,"isFlattenable");Nce=CWe});function Mce(t,e,r,i,n){var a=-1,s=t.length;for(r||(r=Nce),n||(n=[]);++a0&&r(l)?e>1?Mce(l,e-1,r,i,n):z1(n,l):i||(n[n.length]=l)}return n}var Lu,G1=P(()=>{"use strict";H5();Ice();o(Mce,"baseFlatten");Lu=Mce});function wWe(t){var e=t==null?0:t.length;return e?Lu(t,1):[]}var di,Y5=P(()=>{"use strict";G1();o(wWe,"flatten");di=wWe});function EWe(t){return q3(V3(t,void 0,di),t+"")}var Oce,Pce=P(()=>{"use strict";Y5();uI();fI();o(EWe,"flatRest");Oce=EWe});function SWe(t,e,r){var i=-1,n=t.length;e<0&&(e=-e>n?0:n+e),r=r>n?n:r,r<0&&(r+=n),n=e>r?0:r-e>>>0,e>>>=0;for(var a=Array(n);++i{"use strict";o(SWe,"baseSlice");j5=SWe});function OWe(t){return MWe.test(t)}var AWe,_We,DWe,LWe,RWe,NWe,IWe,MWe,Bce,Fce=P(()=>{"use strict";AWe="\\ud800-\\udfff",_We="\\u0300-\\u036f",DWe="\\ufe20-\\ufe2f",LWe="\\u20d0-\\u20ff",RWe=_We+DWe+LWe,NWe="\\ufe0e\\ufe0f",IWe="\\u200d",MWe=RegExp("["+IWe+AWe+RWe+NWe+"]");o(OWe,"hasUnicode");Bce=OWe});function PWe(t,e,r,i){var n=-1,a=t==null?0:t.length;for(i&&a&&(r=t[++n]);++n{"use strict";o(PWe,"arrayReduce");$ce=PWe});function BWe(t,e){return t&&Il(e,ni(e),t)}var Gce,Vce=P(()=>{"use strict";C0();_u();o(BWe,"baseAssign");Gce=BWe});function FWe(t,e){return t&&Il(e,go(e),t)}var qce,Wce=P(()=>{"use strict";C0();ad();o(FWe,"baseAssignIn");qce=FWe});function $We(t,e){for(var r=-1,i=t==null?0:t.length,n=0,a=[];++r{"use strict";o($We,"arrayFilter");V1=$We});function zWe(){return[]}var K5,zM=P(()=>{"use strict";o(zWe,"stubArray");K5=zWe});var GWe,VWe,Uce,qWe,q1,Q5=P(()=>{"use strict";X5();zM();GWe=Object.prototype,VWe=GWe.propertyIsEnumerable,Uce=Object.getOwnPropertySymbols,qWe=Uce?function(t){return t==null?[]:(t=Object(t),V1(Uce(t),function(e){return VWe.call(t,e)}))}:K5,q1=qWe});function WWe(t,e){return Il(t,q1(t),e)}var Hce,Yce=P(()=>{"use strict";C0();Q5();o(WWe,"copySymbols");Hce=WWe});var UWe,HWe,Z5,GM=P(()=>{"use strict";H5();B3();Q5();zM();UWe=Object.getOwnPropertySymbols,HWe=UWe?function(t){for(var e=[];t;)z1(e,q1(t)),t=y1(t);return e}:K5,Z5=HWe});function YWe(t,e){return Il(t,Z5(t),e)}var jce,Xce=P(()=>{"use strict";C0();GM();o(YWe,"copySymbolsIn");jce=YWe});function jWe(t,e,r){var i=e(t);return Gt(t)?i:z1(i,r(t))}var J5,VM=P(()=>{"use strict";H5();fn();o(jWe,"baseGetAllKeys");J5=jWe});function XWe(t){return J5(t,ni,q1)}var Bb,qM=P(()=>{"use strict";VM();Q5();_u();o(XWe,"getAllKeys");Bb=XWe});function KWe(t){return J5(t,go,Z5)}var eE,WM=P(()=>{"use strict";VM();GM();ad();o(KWe,"getAllKeysIn");eE=KWe});var QWe,tE,Kce=P(()=>{"use strict";Zf();Al();QWe=mo(In,"DataView"),tE=QWe});var ZWe,rE,Qce=P(()=>{"use strict";Zf();Al();ZWe=mo(In,"Promise"),rE=ZWe});var JWe,yd,UM=P(()=>{"use strict";Zf();Al();JWe=mo(In,"Set"),yd=JWe});var Zce,eUe,Jce,eue,tue,rue,tUe,rUe,iUe,nUe,aUe,P0,rl,B0=P(()=>{"use strict";Kce();D3();Qce();UM();yce();Oh();jN();Zce="[object Map]",eUe="[object Object]",Jce="[object Promise]",eue="[object Set]",tue="[object WeakMap]",rue="[object DataView]",tUe=Ph(tE),rUe=Ph(td),iUe=Ph(rE),nUe=Ph(yd),aUe=Ph(F5),P0=Xa;(tE&&P0(new tE(new ArrayBuffer(1)))!=rue||td&&P0(new td)!=Zce||rE&&P0(rE.resolve())!=Jce||yd&&P0(new yd)!=eue||F5&&P0(new F5)!=tue)&&(P0=o(function(t){var e=Xa(t),r=e==eUe?t.constructor:void 0,i=r?Ph(r):"";if(i)switch(i){case tUe:return rue;case rUe:return Zce;case iUe:return Jce;case nUe:return eue;case aUe:return tue}return e},"getTag"));rl=P0});function lUe(t){var e=t.length,r=new t.constructor(e);return e&&typeof t[0]=="string"&&oUe.call(t,"index")&&(r.index=t.index,r.input=t.input),r}var sUe,oUe,iue,nue=P(()=>{"use strict";sUe=Object.prototype,oUe=sUe.hasOwnProperty;o(lUe,"initCloneArray");iue=lUe});function cUe(t,e){var r=e?g1(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.byteLength)}var aue,sue=P(()=>{"use strict";I3();o(cUe,"cloneDataView");aue=cUe});function hUe(t){var e=new t.constructor(t.source,uUe.exec(t));return e.lastIndex=t.lastIndex,e}var uUe,oue,lue=P(()=>{"use strict";uUe=/\w*$/;o(hUe,"cloneRegExp");oue=hUe});function fUe(t){return uue?Object(uue.call(t)):{}}var cue,uue,hue,fue=P(()=>{"use strict";v0();cue=Da?Da.prototype:void 0,uue=cue?cue.valueOf:void 0;o(fUe,"cloneSymbol");hue=fUe});function NUe(t,e,r){var i=t.constructor;switch(e){case TUe:return g1(t);case dUe:case pUe:return new i(+t);case kUe:return aue(t,r);case CUe:case wUe:case EUe:case SUe:case AUe:case _Ue:case DUe:case LUe:case RUe:return M3(t,r);case mUe:return new i;case gUe:case xUe:return new i(t);case yUe:return oue(t);case vUe:return new i;case bUe:return hue(t)}}var dUe,pUe,mUe,gUe,yUe,vUe,xUe,bUe,TUe,kUe,CUe,wUe,EUe,SUe,AUe,_Ue,DUe,LUe,RUe,due,pue=P(()=>{"use strict";I3();sue();lue();fue();rI();dUe="[object Boolean]",pUe="[object Date]",mUe="[object Map]",gUe="[object Number]",yUe="[object RegExp]",vUe="[object Set]",xUe="[object String]",bUe="[object Symbol]",TUe="[object ArrayBuffer]",kUe="[object DataView]",CUe="[object Float32Array]",wUe="[object Float64Array]",EUe="[object Int8Array]",SUe="[object Int16Array]",AUe="[object Int32Array]",_Ue="[object Uint8Array]",DUe="[object Uint8ClampedArray]",LUe="[object Uint16Array]",RUe="[object Uint32Array]";o(NUe,"initCloneByTag");due=NUe});function MUe(t){return En(t)&&rl(t)==IUe}var IUe,mue,gue=P(()=>{"use strict";B0();Dl();IUe="[object Map]";o(MUe,"baseIsMap");mue=MUe});var yue,OUe,vue,xue=P(()=>{"use strict";gue();k0();cb();yue=Nl&&Nl.isMap,OUe=yue?Rl(yue):mue,vue=OUe});function BUe(t){return En(t)&&rl(t)==PUe}var PUe,bue,Tue=P(()=>{"use strict";B0();Dl();PUe="[object Set]";o(BUe,"baseIsSet");bue=BUe});var kue,FUe,Cue,wue=P(()=>{"use strict";Tue();k0();cb();kue=Nl&&Nl.isSet,FUe=kue?Rl(kue):bue,Cue=FUe});function iE(t,e,r,i,n,a){var s,l=e&$Ue,u=e&zUe,h=e&GUe;if(r&&(s=n?r(t,i,n,a):r(t)),s!==void 0)return s;if(!Gi(t))return t;var f=Gt(t);if(f){if(s=iue(t),!l)return O3(t,s)}else{var d=rl(t),p=d==Sue||d==HUe;if(Ac(t))return N3(t,l);if(d==Aue||d==Eue||p&&!n){if(s=u||p?{}:F3(t),!l)return u?jce(t,qce(s,t)):Hce(t,Gce(s,t))}else{if(!Qi[d])return n?t:{};s=due(t,d,l)}}a||(a=new vu);var m=a.get(t);if(m)return m;a.set(t,s),Cue(t)?t.forEach(function(v){s.add(iE(v,e,r,v,t,a))}):vue(t)&&t.forEach(function(v,x){s.set(x,iE(v,e,r,x,t,a))});var g=h?u?eE:Bb:u?go:ni,y=f?void 0:g(t);return $5(y||t,function(v,x){y&&(x=v,v=t[x]),Tu(s,x,iE(v,e,r,x,t,a))}),s}var $Ue,zUe,GUe,Eue,VUe,qUe,WUe,UUe,Sue,HUe,YUe,jUe,Aue,XUe,KUe,QUe,ZUe,JUe,eHe,tHe,rHe,iHe,nHe,aHe,sHe,oHe,lHe,cHe,uHe,Qi,nE,HM=P(()=>{"use strict";sb();OM();k1();Vce();Wce();eI();iI();Yce();Xce();qM();WM();B0();nue();pue();aI();fn();T1();xue();Zo();wue();_u();ad();$Ue=1,zUe=2,GUe=4,Eue="[object Arguments]",VUe="[object Array]",qUe="[object Boolean]",WUe="[object Date]",UUe="[object Error]",Sue="[object Function]",HUe="[object GeneratorFunction]",YUe="[object Map]",jUe="[object Number]",Aue="[object Object]",XUe="[object RegExp]",KUe="[object Set]",QUe="[object String]",ZUe="[object Symbol]",JUe="[object WeakMap]",eHe="[object ArrayBuffer]",tHe="[object DataView]",rHe="[object Float32Array]",iHe="[object Float64Array]",nHe="[object Int8Array]",aHe="[object Int16Array]",sHe="[object Int32Array]",oHe="[object Uint8Array]",lHe="[object Uint8ClampedArray]",cHe="[object Uint16Array]",uHe="[object Uint32Array]",Qi={};Qi[Eue]=Qi[VUe]=Qi[eHe]=Qi[tHe]=Qi[qUe]=Qi[WUe]=Qi[rHe]=Qi[iHe]=Qi[nHe]=Qi[aHe]=Qi[sHe]=Qi[YUe]=Qi[jUe]=Qi[Aue]=Qi[XUe]=Qi[KUe]=Qi[QUe]=Qi[ZUe]=Qi[oHe]=Qi[lHe]=Qi[cHe]=Qi[uHe]=!0;Qi[UUe]=Qi[Sue]=Qi[JUe]=!1;o(iE,"baseClone");nE=iE});function fHe(t){return nE(t,hHe)}var hHe,Si,YM=P(()=>{"use strict";HM();hHe=4;o(fHe,"clone");Si=fHe});function mHe(t){return nE(t,dHe|pHe)}var dHe,pHe,jM,_ue=P(()=>{"use strict";HM();dHe=1,pHe=4;o(mHe,"cloneDeep");jM=mHe});function gHe(t){for(var e=-1,r=t==null?0:t.length,i=0,n=[];++e{"use strict";o(gHe,"compact");Ru=gHe});function vHe(t){return this.__data__.set(t,yHe),this}var yHe,Lue,Rue=P(()=>{"use strict";yHe="__lodash_hash_undefined__";o(vHe,"setCacheAdd");Lue=vHe});function xHe(t){return this.__data__.has(t)}var Nue,Iue=P(()=>{"use strict";o(xHe,"setCacheHas");Nue=xHe});function aE(t){var e=-1,r=t==null?0:t.length;for(this.__data__=new b0;++e{"use strict";L3();Rue();Iue();o(aE,"SetCache");aE.prototype.add=aE.prototype.push=Lue;aE.prototype.has=Nue;W1=aE});function bHe(t,e){for(var r=-1,i=t==null?0:t.length;++r{"use strict";o(bHe,"arraySome");oE=bHe});function THe(t,e){return t.has(e)}var U1,lE=P(()=>{"use strict";o(THe,"cacheHas");U1=THe});function wHe(t,e,r,i,n,a){var s=r&kHe,l=t.length,u=e.length;if(l!=u&&!(s&&u>l))return!1;var h=a.get(t),f=a.get(e);if(h&&f)return h==e&&f==t;var d=-1,p=!0,m=r&CHe?new W1:void 0;for(a.set(t,e),a.set(e,t);++d{"use strict";sE();XM();lE();kHe=1,CHe=2;o(wHe,"equalArrays");cE=wHe});function EHe(t){var e=-1,r=Array(t.size);return t.forEach(function(i,n){r[++e]=[n,i]}),r}var Mue,Oue=P(()=>{"use strict";o(EHe,"mapToArray");Mue=EHe});function SHe(t){var e=-1,r=Array(t.size);return t.forEach(function(i){r[++e]=i}),r}var H1,uE=P(()=>{"use strict";o(SHe,"setToArray");H1=SHe});function zHe(t,e,r,i,n,a,s){switch(r){case $He:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case FHe:return!(t.byteLength!=e.byteLength||!a(new m1(t),new m1(e)));case DHe:case LHe:case IHe:return _l(+t,+e);case RHe:return t.name==e.name&&t.message==e.message;case MHe:case PHe:return t==e+"";case NHe:var l=Mue;case OHe:var u=i&AHe;if(l||(l=H1),t.size!=e.size&&!u)return!1;var h=s.get(t);if(h)return h==e;i|=_He,s.set(t,e);var f=cE(l(t),l(e),i,n,a,s);return s.delete(t),f;case BHe:if(QM)return QM.call(t)==QM.call(e)}return!1}var AHe,_He,DHe,LHe,RHe,NHe,IHe,MHe,OHe,PHe,BHe,FHe,$He,Pue,QM,Bue,Fue=P(()=>{"use strict";v0();tI();x0();KM();Oue();uE();AHe=1,_He=2,DHe="[object Boolean]",LHe="[object Date]",RHe="[object Error]",NHe="[object Map]",IHe="[object Number]",MHe="[object RegExp]",OHe="[object Set]",PHe="[object String]",BHe="[object Symbol]",FHe="[object ArrayBuffer]",$He="[object DataView]",Pue=Da?Da.prototype:void 0,QM=Pue?Pue.valueOf:void 0;o(zHe,"equalByTag");Bue=zHe});function WHe(t,e,r,i,n,a){var s=r&GHe,l=Bb(t),u=l.length,h=Bb(e),f=h.length;if(u!=f&&!s)return!1;for(var d=u;d--;){var p=l[d];if(!(s?p in e:qHe.call(e,p)))return!1}var m=a.get(t),g=a.get(e);if(m&&g)return m==e&&g==t;var y=!0;a.set(t,e),a.set(e,t);for(var v=s;++d{"use strict";qM();GHe=1,VHe=Object.prototype,qHe=VHe.hasOwnProperty;o(WHe,"equalObjects");$ue=WHe});function YHe(t,e,r,i,n,a){var s=Gt(t),l=Gt(e),u=s?Vue:rl(t),h=l?Vue:rl(e);u=u==Gue?hE:u,h=h==Gue?hE:h;var f=u==hE,d=h==hE,p=u==h;if(p&&Ac(t)){if(!Ac(e))return!1;s=!0,f=!1}if(p&&!f)return a||(a=new vu),s||id(t)?cE(t,e,r,i,n,a):Bue(t,e,u,r,i,n,a);if(!(r&UHe)){var m=f&&que.call(t,"__wrapped__"),g=d&&que.call(e,"__wrapped__");if(m||g){var y=m?t.value():t,v=g?e.value():e;return a||(a=new vu),n(y,v,r,i,a)}}return p?(a||(a=new vu),$ue(t,e,r,i,n,a)):!1}var UHe,Gue,Vue,hE,HHe,que,Wue,Uue=P(()=>{"use strict";sb();KM();Fue();zue();B0();fn();T1();ub();UHe=1,Gue="[object Arguments]",Vue="[object Array]",hE="[object Object]",HHe=Object.prototype,que=HHe.hasOwnProperty;o(YHe,"baseIsEqualDeep");Wue=YHe});function Hue(t,e,r,i,n){return t===e?!0:t==null||e==null||!En(t)&&!En(e)?t!==t&&e!==e:Wue(t,e,r,i,Hue,n)}var fE,ZM=P(()=>{"use strict";Uue();Dl();o(Hue,"baseIsEqual");fE=Hue});function KHe(t,e,r,i){var n=r.length,a=n,s=!i;if(t==null)return!a;for(t=Object(t);n--;){var l=r[n];if(s&&l[2]?l[1]!==t[l[0]]:!(l[0]in t))return!1}for(;++n{"use strict";sb();ZM();jHe=1,XHe=2;o(KHe,"baseIsMatch");Yue=KHe});function QHe(t){return t===t&&!Gi(t)}var dE,JM=P(()=>{"use strict";Zo();o(QHe,"isStrictComparable");dE=QHe});function ZHe(t){for(var e=ni(t),r=e.length;r--;){var i=e[r],n=t[i];e[r]=[i,n,dE(n)]}return e}var Xue,Kue=P(()=>{"use strict";JM();_u();o(ZHe,"getMatchData");Xue=ZHe});function JHe(t,e){return function(r){return r==null?!1:r[t]===e&&(e!==void 0||t in Object(r))}}var pE,eO=P(()=>{"use strict";o(JHe,"matchesStrictComparable");pE=JHe});function eYe(t){var e=Xue(t);return e.length==1&&e[0][2]?pE(e[0][0],e[0][1]):function(r){return r===t||Yue(r,t,e)}}var Que,Zue=P(()=>{"use strict";jue();Kue();eO();o(eYe,"baseMatches");Que=eYe});function tYe(t,e){return t!=null&&e in Object(t)}var Jue,ehe=P(()=>{"use strict";o(tYe,"baseHasIn");Jue=tYe});function rYe(t,e,r){e=md(e,t);for(var i=-1,n=e.length,a=!1;++i{"use strict";Ob();x1();fn();fb();$3();$1();o(rYe,"hasPath");mE=rYe});function iYe(t,e){return t!=null&&mE(t,e,Jue)}var gE,rO=P(()=>{"use strict";ehe();tO();o(iYe,"hasIn");gE=iYe});function sYe(t,e){return F1(t)&&dE(e)?pE(Du(t),e):function(r){var i=Dce(r,t);return i===void 0&&i===e?gE(r,t):fE(e,i,nYe|aYe)}}var nYe,aYe,the,rhe=P(()=>{"use strict";ZM();Lce();rO();W5();JM();eO();$1();nYe=1,aYe=2;o(sYe,"baseMatchesProperty");the=sYe});function oYe(t){return function(e){return e?.[t]}}var yE,iO=P(()=>{"use strict";o(oYe,"baseProperty");yE=oYe});function lYe(t){return function(e){return gd(e,t)}}var ihe,nhe=P(()=>{"use strict";Pb();o(lYe,"basePropertyDeep");ihe=lYe});function cYe(t){return F1(t)?yE(Du(t)):ihe(t)}var ahe,she=P(()=>{"use strict";iO();nhe();W5();$1();o(cYe,"property");ahe=cYe});function uYe(t){return typeof t=="function"?t:t==null?La:typeof t=="object"?Gt(t)?the(t[0],t[1]):Que(t):ahe(t)}var Pi,Vs=P(()=>{"use strict";Zue();rhe();Fh();fn();she();o(uYe,"baseIteratee");Pi=uYe});function hYe(t,e,r,i){for(var n=-1,a=t==null?0:t.length;++n{"use strict";o(hYe,"arrayAggregator");ohe=hYe});function fYe(t,e){return t&&p1(t,e,ni)}var Y1,vE=P(()=>{"use strict";R3();_u();o(fYe,"baseForOwn");Y1=fYe});function dYe(t,e){return function(r,i){if(r==null)return r;if(!Mn(r))return t(r,i);for(var n=r.length,a=e?n:-1,s=Object(r);(e?a--:++a{"use strict";Ll();o(dYe,"createBaseEach");che=dYe});var pYe,Eo,vd=P(()=>{"use strict";vE();uhe();pYe=che(Y1),Eo=pYe});function mYe(t,e,r,i){return Eo(t,function(n,a,s){e(i,n,r(n),s)}),i}var hhe,fhe=P(()=>{"use strict";vd();o(mYe,"baseAggregator");hhe=mYe});function gYe(t,e){return function(r,i){var n=Gt(r)?ohe:hhe,a=e?e():{};return n(r,t,Pi(i,2),a)}}var dhe,phe=P(()=>{"use strict";lhe();fhe();Vs();fn();o(gYe,"createAggregator");dhe=gYe});var yYe,xE,mhe=P(()=>{"use strict";Al();yYe=o(function(){return In.Date.now()},"now"),xE=yYe});var ghe,vYe,xYe,xd,yhe=P(()=>{"use strict";C1();x0();w0();ad();ghe=Object.prototype,vYe=ghe.hasOwnProperty,xYe=ku(function(t,e){t=Object(t);var r=-1,i=e.length,n=i>2?e[2]:void 0;for(n&&Jo(e[0],e[1],n)&&(i=1);++r{"use strict";o(bYe,"arrayIncludesWith");bE=bYe});function kYe(t,e,r,i){var n=-1,a=V5,s=!0,l=t.length,u=[],h=e.length;if(!l)return u;r&&(e=wo(e,Rl(r))),i?(a=bE,s=!1):e.length>=TYe&&(a=U1,s=!1,e=new W1(e));e:for(;++n{"use strict";sE();BM();nO();O0();k0();lE();TYe=200;o(kYe,"baseDifference");vhe=kYe});var CYe,bd,bhe=P(()=>{"use strict";xhe();G1();C1();z3();CYe=ku(function(t,e){return T0(t)?vhe(t,Lu(e,1,T0,!0)):[]}),bd=CYe});function wYe(t){var e=t==null?0:t.length;return e?t[e-1]:void 0}var Na,The=P(()=>{"use strict";o(wYe,"last");Na=wYe});function EYe(t,e,r){var i=t==null?0:t.length;return i?(e=r||e===void 0?1:Au(e),j5(t,e<0?0:e,i)):[]}var zn,khe=P(()=>{"use strict";$M();O1();o(EYe,"drop");zn=EYe});function SYe(t,e,r){var i=t==null?0:t.length;return i?(e=r||e===void 0?1:Au(e),e=i-e,j5(t,0,e<0?0:e)):[]}var Hh,Che=P(()=>{"use strict";$M();O1();o(SYe,"dropRight");Hh=SYe});function AYe(t){return typeof t=="function"?t:La}var j1,TE=P(()=>{"use strict";Fh();o(AYe,"castFunction");j1=AYe});function _Ye(t,e){var r=Gt(t)?$5:Eo;return r(t,j1(e))}var Pe,kE=P(()=>{"use strict";OM();vd();TE();fn();o(_Ye,"forEach");Pe=_Ye});var whe=P(()=>{"use strict";kE()});function DYe(t,e){for(var r=-1,i=t==null?0:t.length;++r{"use strict";o(DYe,"arrayEvery");Ehe=DYe});function LYe(t,e){var r=!0;return Eo(t,function(i,n,a){return r=!!e(i,n,a),r}),r}var Ahe,_he=P(()=>{"use strict";vd();o(LYe,"baseEvery");Ahe=LYe});function RYe(t,e,r){var i=Gt(t)?Ehe:Ahe;return r&&Jo(t,e,r)&&(e=void 0),i(t,Pi(e,3))}var ms,Dhe=P(()=>{"use strict";She();_he();Vs();fn();w0();o(RYe,"every");ms=RYe});function NYe(t,e){var r=[];return Eo(t,function(i,n,a){e(i,n,a)&&r.push(i)}),r}var CE,aO=P(()=>{"use strict";vd();o(NYe,"baseFilter");CE=NYe});function IYe(t,e){var r=Gt(t)?V1:CE;return r(t,Pi(e,3))}var pi,sO=P(()=>{"use strict";X5();aO();Vs();fn();o(IYe,"filter");pi=IYe});function MYe(t){return function(e,r,i){var n=Object(e);if(!Mn(e)){var a=Pi(r,3);e=ni(e),r=o(function(l){return a(n[l],l,n)},"predicate")}var s=t(e,r,i);return s>-1?n[a?e[s]:s]:void 0}}var Lhe,Rhe=P(()=>{"use strict";Vs();Ll();_u();o(MYe,"createFind");Lhe=MYe});function PYe(t,e,r){var i=t==null?0:t.length;if(!i)return-1;var n=r==null?0:Au(r);return n<0&&(n=OYe(i+n,0)),z5(t,Pi(e,3),n)}var OYe,Nhe,Ihe=P(()=>{"use strict";PM();Vs();O1();OYe=Math.max;o(PYe,"findIndex");Nhe=PYe});var BYe,qs,Mhe=P(()=>{"use strict";Rhe();Ihe();BYe=Lhe(Nhe),qs=BYe});function FYe(t){return t&&t.length?t[0]:void 0}var Ia,Ohe=P(()=>{"use strict";o(FYe,"head");Ia=FYe});var Phe=P(()=>{"use strict";Ohe()});function $Ye(t,e){var r=-1,i=Mn(t)?Array(t.length):[];return Eo(t,function(n,a,s){i[++r]=e(n,a,s)}),i}var wE,oO=P(()=>{"use strict";vd();Ll();o($Ye,"baseMap");wE=$Ye});function zYe(t,e){var r=Gt(t)?wo:wE;return r(t,Pi(e,3))}var ht,X1=P(()=>{"use strict";O0();Vs();oO();fn();o(zYe,"map");ht=zYe});function GYe(t,e){return Lu(ht(t,e),1)}var Ja,lO=P(()=>{"use strict";G1();X1();o(GYe,"flatMap");Ja=GYe});function VYe(t,e){return t==null?t:p1(t,j1(e),go)}var cO,Bhe=P(()=>{"use strict";R3();TE();ad();o(VYe,"forIn");cO=VYe});function qYe(t,e){return t&&Y1(t,j1(e))}var uO,Fhe=P(()=>{"use strict";vE();TE();o(qYe,"forOwn");uO=qYe});var WYe,UYe,HYe,hO,$he=P(()=>{"use strict";d1();phe();WYe=Object.prototype,UYe=WYe.hasOwnProperty,HYe=dhe(function(t,e,r){UYe.call(t,r)?t[r].push(e):xu(t,r,[e])}),hO=HYe});function YYe(t,e){return t>e}var zhe,Ghe=P(()=>{"use strict";o(YYe,"baseGt");zhe=YYe});function KYe(t,e){return t!=null&&XYe.call(t,e)}var jYe,XYe,Vhe,qhe=P(()=>{"use strict";jYe=Object.prototype,XYe=jYe.hasOwnProperty;o(KYe,"baseHas");Vhe=KYe});function QYe(t,e){return t!=null&&mE(t,e,Vhe)}var Vt,Whe=P(()=>{"use strict";qhe();tO();o(QYe,"has");Vt=QYe});function JYe(t){return typeof t=="string"||!Gt(t)&&En(t)&&Xa(t)==ZYe}var ZYe,Gn,EE=P(()=>{"use strict";Oh();fn();Dl();ZYe="[object String]";o(JYe,"isString");Gn=JYe});function eje(t,e){return wo(e,function(r){return t[r]})}var Uhe,Hhe=P(()=>{"use strict";O0();o(eje,"baseValues");Uhe=eje});function tje(t){return t==null?[]:Uhe(t,ni(t))}var qr,fO=P(()=>{"use strict";Hhe();_u();o(tje,"values");qr=tje});function ije(t,e,r,i){t=Mn(t)?t:qr(t),r=r&&!i?Au(r):0;var n=t.length;return r<0&&(r=rje(n+r,0)),Gn(t)?r<=n&&t.indexOf(e,r)>-1:!!n&&P1(t,e,r)>-1}var rje,pn,Yhe=P(()=>{"use strict";G5();Ll();EE();O1();fO();rje=Math.max;o(ije,"includes");pn=ije});function aje(t,e,r){var i=t==null?0:t.length;if(!i)return-1;var n=r==null?0:Au(r);return n<0&&(n=nje(i+n,0)),P1(t,e,n)}var nje,SE,jhe=P(()=>{"use strict";G5();O1();nje=Math.max;o(aje,"indexOf");SE=aje});function uje(t){if(t==null)return!0;if(Mn(t)&&(Gt(t)||typeof t=="string"||typeof t.splice=="function"||Ac(t)||id(t)||Sc(t)))return!t.length;var e=rl(t);if(e==sje||e==oje)return!t.size;if(bu(t))return!B1(t).length;for(var r in t)if(cje.call(t,r))return!1;return!0}var sje,oje,lje,cje,_r,AE=P(()=>{"use strict";q5();B0();x1();fn();Ll();T1();v1();ub();sje="[object Map]",oje="[object Set]",lje=Object.prototype,cje=lje.hasOwnProperty;o(uje,"isEmpty");_r=uje});function fje(t){return En(t)&&Xa(t)==hje}var hje,Xhe,Khe=P(()=>{"use strict";Oh();Dl();hje="[object RegExp]";o(fje,"baseIsRegExp");Xhe=fje});var Qhe,dje,Bl,Zhe=P(()=>{"use strict";Khe();k0();cb();Qhe=Nl&&Nl.isRegExp,dje=Qhe?Rl(Qhe):Xhe,Bl=dje});function pje(t){return t===void 0}var Br,Jhe=P(()=>{"use strict";o(pje,"isUndefined");Br=pje});function mje(t,e){return t{"use strict";o(mje,"baseLt");_E=mje});function gje(t,e){var r={};return e=Pi(e,3),Y1(t,function(i,n,a){xu(r,n,e(i,n,a))}),r}var F0,efe=P(()=>{"use strict";d1();vE();Vs();o(gje,"mapValues");F0=gje});function yje(t,e,r){for(var i=-1,n=t.length;++i{"use strict";M0();o(yje,"baseExtremum");K1=yje});function vje(t){return t&&t.length?K1(t,La,zhe):void 0}var So,tfe=P(()=>{"use strict";DE();Ghe();Fh();o(vje,"max");So=vje});function xje(t){return t&&t.length?K1(t,La,_E):void 0}var Lc,pO=P(()=>{"use strict";DE();dO();Fh();o(xje,"min");Lc=xje});function bje(t,e){return t&&t.length?K1(t,Pi(e,2),_E):void 0}var $0,rfe=P(()=>{"use strict";DE();Vs();dO();o(bje,"minBy");$0=bje});function kje(t){if(typeof t!="function")throw new TypeError(Tje);return function(){var e=arguments;switch(e.length){case 0:return!t.call(this);case 1:return!t.call(this,e[0]);case 2:return!t.call(this,e[0],e[1]);case 3:return!t.call(this,e[0],e[1],e[2])}return!t.apply(this,e)}}var Tje,ife,nfe=P(()=>{"use strict";Tje="Expected a function";o(kje,"negate");ife=kje});function Cje(t,e,r,i){if(!Gi(t))return t;e=md(e,t);for(var n=-1,a=e.length,s=a-1,l=t;l!=null&&++n{"use strict";k1();Ob();fb();Zo();$1();o(Cje,"baseSet");afe=Cje});function wje(t,e,r){for(var i=-1,n=e.length,a={};++i{"use strict";Pb();sfe();Ob();o(wje,"basePickBy");LE=wje});function Eje(t,e){if(t==null)return{};var r=wo(eE(t),function(i){return[i]});return e=Pi(e),LE(t,r,function(i,n){return e(i,n[0])})}var Ao,ofe=P(()=>{"use strict";O0();Vs();mO();WM();o(Eje,"pickBy");Ao=Eje});function Sje(t,e){var r=t.length;for(t.sort(e);r--;)t[r]=t[r].value;return t}var lfe,cfe=P(()=>{"use strict";o(Sje,"baseSortBy");lfe=Sje});function Aje(t,e){if(t!==e){var r=t!==void 0,i=t===null,n=t===t,a=tl(t),s=e!==void 0,l=e===null,u=e===e,h=tl(e);if(!l&&!h&&!a&&t>e||a&&s&&u&&!l&&!h||i&&s&&u||!r&&u||!n)return 1;if(!i&&!a&&!h&&t{"use strict";M0();o(Aje,"compareAscending");ufe=Aje});function _je(t,e,r){for(var i=-1,n=t.criteria,a=e.criteria,s=n.length,l=r.length;++i=l)return u;var h=r[i];return u*(h=="desc"?-1:1)}}return t.index-e.index}var ffe,dfe=P(()=>{"use strict";hfe();o(_je,"compareMultiple");ffe=_je});function Dje(t,e,r){e.length?e=wo(e,function(a){return Gt(a)?function(s){return gd(s,a.length===1?a[0]:a)}:a}):e=[La];var i=-1;e=wo(e,Rl(Pi));var n=wE(t,function(a,s,l){var u=wo(e,function(h){return h(a)});return{criteria:u,index:++i,value:a}});return lfe(n,function(a,s){return ffe(a,s,r)})}var pfe,mfe=P(()=>{"use strict";O0();Pb();Vs();oO();cfe();k0();dfe();Fh();fn();o(Dje,"baseOrderBy");pfe=Dje});var Lje,gfe,yfe=P(()=>{"use strict";iO();Lje=yE("length"),gfe=Lje});function Vje(t){for(var e=vfe.lastIndex=0;vfe.test(t);)++e;return e}var xfe,Rje,Nje,Ije,Mje,Oje,Pje,gO,yO,Bje,bfe,Tfe,kfe,Fje,Cfe,wfe,$je,zje,Gje,vfe,Efe,Sfe=P(()=>{"use strict";xfe="\\ud800-\\udfff",Rje="\\u0300-\\u036f",Nje="\\ufe20-\\ufe2f",Ije="\\u20d0-\\u20ff",Mje=Rje+Nje+Ije,Oje="\\ufe0e\\ufe0f",Pje="["+xfe+"]",gO="["+Mje+"]",yO="\\ud83c[\\udffb-\\udfff]",Bje="(?:"+gO+"|"+yO+")",bfe="[^"+xfe+"]",Tfe="(?:\\ud83c[\\udde6-\\uddff]){2}",kfe="[\\ud800-\\udbff][\\udc00-\\udfff]",Fje="\\u200d",Cfe=Bje+"?",wfe="["+Oje+"]?",$je="(?:"+Fje+"(?:"+[bfe,Tfe,kfe].join("|")+")"+wfe+Cfe+")*",zje=wfe+Cfe+$je,Gje="(?:"+[bfe+gO+"?",gO,Tfe,kfe,Pje].join("|")+")",vfe=RegExp(yO+"(?="+yO+")|"+Gje+zje,"g");o(Vje,"unicodeSize");Efe=Vje});function qje(t){return Bce(t)?Efe(t):gfe(t)}var Afe,_fe=P(()=>{"use strict";yfe();Fce();Sfe();o(qje,"stringSize");Afe=qje});function Wje(t,e){return LE(t,e,function(r,i){return gE(t,i)})}var Dfe,Lfe=P(()=>{"use strict";mO();rO();o(Wje,"basePick");Dfe=Wje});var Uje,z0,Rfe=P(()=>{"use strict";Lfe();Pce();Uje=Oce(function(t,e){return t==null?{}:Dfe(t,e)}),z0=Uje});function jje(t,e,r,i){for(var n=-1,a=Yje(Hje((e-t)/(r||1)),0),s=Array(a);a--;)s[i?a:++n]=t,t+=r;return s}var Hje,Yje,Nfe,Ife=P(()=>{"use strict";Hje=Math.ceil,Yje=Math.max;o(jje,"baseRange");Nfe=jje});function Xje(t){return function(e,r,i){return i&&typeof i!="number"&&Jo(e,r,i)&&(r=i=void 0),e=M1(e),r===void 0?(r=e,e=0):r=M1(r),i=i===void 0?e{"use strict";Ife();w0();IM();o(Xje,"createRange");Mfe=Xje});var Kje,Fl,Pfe=P(()=>{"use strict";Ofe();Kje=Mfe(),Fl=Kje});function Qje(t,e,r,i,n){return n(t,function(a,s,l){r=i?(i=!1,a):e(r,a,s,l)}),r}var Bfe,Ffe=P(()=>{"use strict";o(Qje,"baseReduce");Bfe=Qje});function Zje(t,e,r){var i=Gt(t)?$ce:Bfe,n=arguments.length<3;return i(t,Pi(e,4),r,n,Eo)}var mi,vO=P(()=>{"use strict";zce();vd();Vs();Ffe();fn();o(Zje,"reduce");mi=Zje});function Jje(t,e){var r=Gt(t)?V1:CE;return r(t,ife(Pi(e,3)))}var Td,$fe=P(()=>{"use strict";X5();aO();Vs();fn();nfe();o(Jje,"reject");Td=Jje});function rXe(t){if(t==null)return 0;if(Mn(t))return Gn(t)?Afe(t):t.length;var e=rl(t);return e==eXe||e==tXe?t.size:B1(t).length}var eXe,tXe,xO,zfe=P(()=>{"use strict";q5();B0();Ll();EE();_fe();eXe="[object Map]",tXe="[object Set]";o(rXe,"size");xO=rXe});function iXe(t,e){var r;return Eo(t,function(i,n,a){return r=e(i,n,a),!r}),!!r}var Gfe,Vfe=P(()=>{"use strict";vd();o(iXe,"baseSome");Gfe=iXe});function nXe(t,e,r){var i=Gt(t)?oE:Gfe;return r&&Jo(t,e,r)&&(e=void 0),i(t,Pi(e,3))}var Fb,qfe=P(()=>{"use strict";XM();Vs();Vfe();fn();w0();o(nXe,"some");Fb=nXe});var aXe,Nu,Wfe=P(()=>{"use strict";G1();mfe();C1();w0();aXe=ku(function(t,e){if(t==null)return[];var r=e.length;return r>1&&Jo(t,e[0],e[1])?e=[]:r>2&&Jo(e[0],e[1],e[2])&&(e=[e[0]]),pfe(t,Lu(e,1),[])}),Nu=aXe});var sXe,oXe,Ufe,Hfe=P(()=>{"use strict";UM();MM();uE();sXe=1/0,oXe=yd&&1/H1(new yd([,-0]))[1]==sXe?function(t){return new yd(t)}:Sn,Ufe=oXe});function cXe(t,e,r){var i=-1,n=V5,a=t.length,s=!0,l=[],u=l;if(r)s=!1,n=bE;else if(a>=lXe){var h=e?null:Ufe(t);if(h)return H1(h);s=!1,n=U1,u=new W1}else u=e?[]:l;e:for(;++i{"use strict";sE();BM();nO();lE();Hfe();uE();lXe=200;o(cXe,"baseUniq");Q1=cXe});var uXe,bO,Yfe=P(()=>{"use strict";G1();C1();RE();z3();uXe=ku(function(t){return Q1(Lu(t,1,T0,!0))}),bO=uXe});function hXe(t){return t&&t.length?Q1(t):[]}var Z1,jfe=P(()=>{"use strict";RE();o(hXe,"uniq");Z1=hXe});function fXe(t,e){return t&&t.length?Q1(t,Pi(e,2)):[]}var Xfe,Kfe=P(()=>{"use strict";Vs();RE();o(fXe,"uniqBy");Xfe=fXe});function pXe(t){var e=++dXe;return U5(t)+e}var dXe,G0,Qfe=P(()=>{"use strict";FM();dXe=0;o(pXe,"uniqueId");G0=pXe});function mXe(t,e,r){for(var i=-1,n=t.length,a=e.length,s={};++i{"use strict";o(mXe,"baseZipObject");Zfe=mXe});function gXe(t,e){return Zfe(t||[],e||[],Tu)}var NE,ede=P(()=>{"use strict";k1();Jfe();o(gXe,"zipObject");NE=gXe});var nr=P(()=>{"use strict";wce();YM();_ue();Due();hI();yhe();bhe();khe();Che();whe();Dhe();sO();Mhe();Phe();lO();Y5();kE();Bhe();Fhe();$he();Whe();Fh();Yhe();jhe();fn();AE();tb();Zo();Zhe();EE();Jhe();_u();The();X1();efe();tfe();pI();pO();rfe();MM();mhe();Rfe();ofe();Pfe();vO();$fe();zfe();qfe();Wfe();Yfe();jfe();Qfe();fO();ede();});function rde(t,e){t[e]?t[e]++:t[e]=1}function ide(t,e){--t[e]||delete t[e]}function $b(t,e,r,i){var n=""+e,a=""+r;if(!t&&n>a){var s=n;n=a,a=s}return n+tde+a+tde+(Br(i)?yXe:i)}function vXe(t,e,r,i){var n=""+e,a=""+r;if(!t&&n>a){var s=n;n=a,a=s}var l={v:n,w:a};return i&&(l.name=i),l}function TO(t,e){return $b(t,e.v,e.w,e.name)}var yXe,V0,tde,Ai,IE=P(()=>{"use strict";nr();yXe="\0",V0="\0",tde="",Ai=class{static{o(this,"Graph")}constructor(e={}){this._isDirected=Object.prototype.hasOwnProperty.call(e,"directed")?e.directed:!0,this._isMultigraph=Object.prototype.hasOwnProperty.call(e,"multigraph")?e.multigraph:!1,this._isCompound=Object.prototype.hasOwnProperty.call(e,"compound")?e.compound:!1,this._label=void 0,this._defaultNodeLabelFn=yo(void 0),this._defaultEdgeLabelFn=yo(void 0),this._nodes={},this._isCompound&&(this._parent={},this._children={},this._children[V0]={}),this._in={},this._preds={},this._out={},this._sucs={},this._edgeObjs={},this._edgeLabels={}}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(e){return this._label=e,this}graph(){return this._label}setDefaultNodeLabel(e){return Qn(e)||(e=yo(e)),this._defaultNodeLabelFn=e,this}nodeCount(){return this._nodeCount}nodes(){return ni(this._nodes)}sources(){var e=this;return pi(this.nodes(),function(r){return _r(e._in[r])})}sinks(){var e=this;return pi(this.nodes(),function(r){return _r(e._out[r])})}setNodes(e,r){var i=arguments,n=this;return Pe(e,function(a){i.length>1?n.setNode(a,r):n.setNode(a)}),this}setNode(e,r){return Object.prototype.hasOwnProperty.call(this._nodes,e)?(arguments.length>1&&(this._nodes[e]=r),this):(this._nodes[e]=arguments.length>1?r:this._defaultNodeLabelFn(e),this._isCompound&&(this._parent[e]=V0,this._children[e]={},this._children[V0][e]=!0),this._in[e]={},this._preds[e]={},this._out[e]={},this._sucs[e]={},++this._nodeCount,this)}node(e){return this._nodes[e]}hasNode(e){return Object.prototype.hasOwnProperty.call(this._nodes,e)}removeNode(e){if(Object.prototype.hasOwnProperty.call(this._nodes,e)){var r=o(i=>this.removeEdge(this._edgeObjs[i]),"removeEdge");delete this._nodes[e],this._isCompound&&(this._removeFromParentsChildList(e),delete this._parent[e],Pe(this.children(e),i=>{this.setParent(i)}),delete this._children[e]),Pe(ni(this._in[e]),r),delete this._in[e],delete this._preds[e],Pe(ni(this._out[e]),r),delete this._out[e],delete this._sucs[e],--this._nodeCount}return this}setParent(e,r){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(Br(r))r=V0;else{r+="";for(var i=r;!Br(i);i=this.parent(i))if(i===e)throw new Error("Setting "+r+" as parent of "+e+" would create a cycle");this.setNode(r)}return this.setNode(e),this._removeFromParentsChildList(e),this._parent[e]=r,this._children[r][e]=!0,this}_removeFromParentsChildList(e){delete this._children[this._parent[e]][e]}parent(e){if(this._isCompound){var r=this._parent[e];if(r!==V0)return r}}children(e){if(Br(e)&&(e=V0),this._isCompound){var r=this._children[e];if(r)return ni(r)}else{if(e===V0)return this.nodes();if(this.hasNode(e))return[]}}predecessors(e){var r=this._preds[e];if(r)return ni(r)}successors(e){var r=this._sucs[e];if(r)return ni(r)}neighbors(e){var r=this.predecessors(e);if(r)return bO(r,this.successors(e))}isLeaf(e){var r;return this.isDirected()?r=this.successors(e):r=this.neighbors(e),r.length===0}filterNodes(e){var r=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});r.setGraph(this.graph());var i=this;Pe(this._nodes,function(s,l){e(l)&&r.setNode(l,s)}),Pe(this._edgeObjs,function(s){r.hasNode(s.v)&&r.hasNode(s.w)&&r.setEdge(s,i.edge(s))});var n={};function a(s){var l=i.parent(s);return l===void 0||r.hasNode(l)?(n[s]=l,l):l in n?n[l]:a(l)}return o(a,"findParent"),this._isCompound&&Pe(r.nodes(),function(s){r.setParent(s,a(s))}),r}setDefaultEdgeLabel(e){return Qn(e)||(e=yo(e)),this._defaultEdgeLabelFn=e,this}edgeCount(){return this._edgeCount}edges(){return qr(this._edgeObjs)}setPath(e,r){var i=this,n=arguments;return mi(e,function(a,s){return n.length>1?i.setEdge(a,s,r):i.setEdge(a,s),s}),this}setEdge(){var e,r,i,n,a=!1,s=arguments[0];typeof s=="object"&&s!==null&&"v"in s?(e=s.v,r=s.w,i=s.name,arguments.length===2&&(n=arguments[1],a=!0)):(e=s,r=arguments[1],i=arguments[3],arguments.length>2&&(n=arguments[2],a=!0)),e=""+e,r=""+r,Br(i)||(i=""+i);var l=$b(this._isDirected,e,r,i);if(Object.prototype.hasOwnProperty.call(this._edgeLabels,l))return a&&(this._edgeLabels[l]=n),this;if(!Br(i)&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(e),this.setNode(r),this._edgeLabels[l]=a?n:this._defaultEdgeLabelFn(e,r,i);var u=vXe(this._isDirected,e,r,i);return e=u.v,r=u.w,Object.freeze(u),this._edgeObjs[l]=u,rde(this._preds[r],e),rde(this._sucs[e],r),this._in[r][l]=u,this._out[e][l]=u,this._edgeCount++,this}edge(e,r,i){var n=arguments.length===1?TO(this._isDirected,arguments[0]):$b(this._isDirected,e,r,i);return this._edgeLabels[n]}hasEdge(e,r,i){var n=arguments.length===1?TO(this._isDirected,arguments[0]):$b(this._isDirected,e,r,i);return Object.prototype.hasOwnProperty.call(this._edgeLabels,n)}removeEdge(e,r,i){var n=arguments.length===1?TO(this._isDirected,arguments[0]):$b(this._isDirected,e,r,i),a=this._edgeObjs[n];return a&&(e=a.v,r=a.w,delete this._edgeLabels[n],delete this._edgeObjs[n],ide(this._preds[r],e),ide(this._sucs[e],r),delete this._in[r][n],delete this._out[e][n],this._edgeCount--),this}inEdges(e,r){var i=this._in[e];if(i){var n=qr(i);return r?pi(n,function(a){return a.v===r}):n}}outEdges(e,r){var i=this._out[e];if(i){var n=qr(i);return r?pi(n,function(a){return a.w===r}):n}}nodeEdges(e,r){var i=this.inEdges(e,r);if(i)return i.concat(this.outEdges(e,r))}};Ai.prototype._nodeCount=0;Ai.prototype._edgeCount=0;o(rde,"incrementOrInitEntry");o(ide,"decrementOrRemoveEntry");o($b,"edgeArgsToId");o(vXe,"edgeArgsToObj");o(TO,"edgeObjToId")});var $l=P(()=>{"use strict";IE()});function nde(t){t._prev._next=t._next,t._next._prev=t._prev,delete t._next,delete t._prev}function xXe(t,e){if(t!=="_next"&&t!=="_prev")return e}var OE,ade=P(()=>{"use strict";OE=class{static{o(this,"List")}constructor(){var e={};e._next=e._prev=e,this._sentinel=e}dequeue(){var e=this._sentinel,r=e._prev;if(r!==e)return nde(r),r}enqueue(e){var r=this._sentinel;e._prev&&e._next&&nde(e),e._next=r._next,r._next._prev=e,r._next=e,e._prev=r}toString(){for(var e=[],r=this._sentinel,i=r._prev;i!==r;)e.push(JSON.stringify(i,xXe)),i=i._prev;return"["+e.join(", ")+"]"}};o(nde,"unlink");o(xXe,"filterOutLinks")});function sde(t,e){if(t.nodeCount()<=1)return[];var r=kXe(t,e||bXe),i=TXe(r.graph,r.buckets,r.zeroIdx);return di(ht(i,function(n){return t.outEdges(n.v,n.w)}))}function TXe(t,e,r){for(var i=[],n=e[e.length-1],a=e[0],s;t.nodeCount();){for(;s=a.dequeue();)kO(t,e,r,s);for(;s=n.dequeue();)kO(t,e,r,s);if(t.nodeCount()){for(var l=e.length-2;l>0;--l)if(s=e[l].dequeue(),s){i=i.concat(kO(t,e,r,s,!0));break}}}return i}function kO(t,e,r,i,n){var a=n?[]:void 0;return Pe(t.inEdges(i.v),function(s){var l=t.edge(s),u=t.node(s.v);n&&a.push({v:s.v,w:s.w}),u.out-=l,CO(e,r,u)}),Pe(t.outEdges(i.v),function(s){var l=t.edge(s),u=s.w,h=t.node(u);h.in-=l,CO(e,r,h)}),t.removeNode(i.v),a}function kXe(t,e){var r=new Ai,i=0,n=0;Pe(t.nodes(),function(l){r.setNode(l,{v:l,in:0,out:0})}),Pe(t.edges(),function(l){var u=r.edge(l.v,l.w)||0,h=e(l),f=u+h;r.setEdge(l.v,l.w,f),n=Math.max(n,r.node(l.v).out+=h),i=Math.max(i,r.node(l.w).in+=h)});var a=Fl(n+i+3).map(function(){return new OE}),s=i+1;return Pe(r.nodes(),function(l){CO(a,s,r.node(l))}),{graph:r,buckets:a,zeroIdx:s}}function CO(t,e,r){r.out?r.in?t[r.out-r.in+e].enqueue(r):t[t.length-1].enqueue(r):t[0].enqueue(r)}var bXe,ode=P(()=>{"use strict";nr();$l();ade();bXe=yo(1);o(sde,"greedyFAS");o(TXe,"doGreedyFAS");o(kO,"removeNode");o(kXe,"buildState");o(CO,"assignBucket")});function lde(t){var e=t.graph().acyclicer==="greedy"?sde(t,r(t)):CXe(t);Pe(e,function(i){var n=t.edge(i);t.removeEdge(i),n.forwardName=i.name,n.reversed=!0,t.setEdge(i.w,i.v,n,G0("rev"))});function r(i){return function(n){return i.edge(n).weight}}o(r,"weightFn")}function CXe(t){var e=[],r={},i={};function n(a){Object.prototype.hasOwnProperty.call(i,a)||(i[a]=!0,r[a]=!0,Pe(t.outEdges(a),function(s){Object.prototype.hasOwnProperty.call(r,s.w)?e.push(s):n(s.w)}),delete r[a])}return o(n,"dfs"),Pe(t.nodes(),n),e}function cde(t){Pe(t.edges(),function(e){var r=t.edge(e);if(r.reversed){t.removeEdge(e);var i=r.forwardName;delete r.reversed,delete r.forwardName,t.setEdge(e.w,e.v,r,i)}})}var wO=P(()=>{"use strict";nr();ode();o(lde,"run");o(CXe,"dfsFAS");o(cde,"undo")});function Iu(t,e,r,i){var n;do n=G0(i);while(t.hasNode(n));return r.dummy=e,t.setNode(n,r),n}function hde(t){var e=new Ai().setGraph(t.graph());return Pe(t.nodes(),function(r){e.setNode(r,t.node(r))}),Pe(t.edges(),function(r){var i=e.edge(r.v,r.w)||{weight:0,minlen:1},n=t.edge(r);e.setEdge(r.v,r.w,{weight:i.weight+n.weight,minlen:Math.max(i.minlen,n.minlen)})}),e}function PE(t){var e=new Ai({multigraph:t.isMultigraph()}).setGraph(t.graph());return Pe(t.nodes(),function(r){t.children(r).length||e.setNode(r,t.node(r))}),Pe(t.edges(),function(r){e.setEdge(r,t.edge(r))}),e}function EO(t,e){var r=t.x,i=t.y,n=e.x-r,a=e.y-i,s=t.width/2,l=t.height/2;if(!n&&!a)throw new Error("Not possible to find intersection inside of the rectangle");var u,h;return Math.abs(a)*s>Math.abs(n)*l?(a<0&&(l=-l),u=l*n/a,h=l):(n<0&&(s=-s),u=s,h=s*a/n),{x:r+u,y:i+h}}function kd(t){var e=ht(Fl(AO(t)+1),function(){return[]});return Pe(t.nodes(),function(r){var i=t.node(r),n=i.rank;Br(n)||(e[n][i.order]=r)}),e}function fde(t){var e=Lc(ht(t.nodes(),function(r){return t.node(r).rank}));Pe(t.nodes(),function(r){var i=t.node(r);Vt(i,"rank")&&(i.rank-=e)})}function dde(t){var e=Lc(ht(t.nodes(),function(a){return t.node(a).rank})),r=[];Pe(t.nodes(),function(a){var s=t.node(a).rank-e;r[s]||(r[s]=[]),r[s].push(a)});var i=0,n=t.graph().nodeRankFactor;Pe(r,function(a,s){Br(a)&&s%n!==0?--i:i&&Pe(a,function(l){t.node(l).rank+=i})})}function SO(t,e,r,i){var n={width:0,height:0};return arguments.length>=4&&(n.rank=r,n.order=i),Iu(t,"border",n,e)}function AO(t){return So(ht(t.nodes(),function(e){var r=t.node(e).rank;if(!Br(r))return r}))}function pde(t,e){var r={lhs:[],rhs:[]};return Pe(t,function(i){e(i)?r.lhs.push(i):r.rhs.push(i)}),r}function mde(t,e){var r=xE();try{return e()}finally{console.log(t+" time: "+(xE()-r)+"ms")}}function gde(t,e){return e()}var Mu=P(()=>{"use strict";nr();$l();o(Iu,"addDummyNode");o(hde,"simplify");o(PE,"asNonCompoundGraph");o(EO,"intersectRect");o(kd,"buildLayerMatrix");o(fde,"normalizeRanks");o(dde,"removeEmptyRanks");o(SO,"addBorderNode");o(AO,"maxRank");o(pde,"partition");o(mde,"time");o(gde,"notime")});function vde(t){function e(r){var i=t.children(r),n=t.node(r);if(i.length&&Pe(i,e),Object.prototype.hasOwnProperty.call(n,"minRank")){n.borderLeft=[],n.borderRight=[];for(var a=n.minRank,s=n.maxRank+1;a{"use strict";nr();Mu();o(vde,"addBorderSegments");o(yde,"addBorderNode")});function Tde(t){var e=t.graph().rankdir.toLowerCase();(e==="lr"||e==="rl")&&Cde(t)}function kde(t){var e=t.graph().rankdir.toLowerCase();(e==="bt"||e==="rl")&&wXe(t),(e==="lr"||e==="rl")&&(EXe(t),Cde(t))}function Cde(t){Pe(t.nodes(),function(e){bde(t.node(e))}),Pe(t.edges(),function(e){bde(t.edge(e))})}function bde(t){var e=t.width;t.width=t.height,t.height=e}function wXe(t){Pe(t.nodes(),function(e){_O(t.node(e))}),Pe(t.edges(),function(e){var r=t.edge(e);Pe(r.points,_O),Object.prototype.hasOwnProperty.call(r,"y")&&_O(r)})}function _O(t){t.y=-t.y}function EXe(t){Pe(t.nodes(),function(e){DO(t.node(e))}),Pe(t.edges(),function(e){var r=t.edge(e);Pe(r.points,DO),Object.prototype.hasOwnProperty.call(r,"x")&&DO(r)})}function DO(t){var e=t.x;t.x=t.y,t.y=e}var wde=P(()=>{"use strict";nr();o(Tde,"adjust");o(kde,"undo");o(Cde,"swapWidthHeight");o(bde,"swapWidthHeightOne");o(wXe,"reverseY");o(_O,"reverseYOne");o(EXe,"swapXY");o(DO,"swapXYOne")});function Ede(t){t.graph().dummyChains=[],Pe(t.edges(),function(e){AXe(t,e)})}function AXe(t,e){var r=e.v,i=t.node(r).rank,n=e.w,a=t.node(n).rank,s=e.name,l=t.edge(e),u=l.labelRank;if(a!==i+1){t.removeEdge(e);var h=void 0,f,d;for(d=0,++i;i{"use strict";nr();Mu();o(Ede,"run");o(AXe,"normalizeEdge");o(Sde,"undo")});function zb(t){var e={};function r(i){var n=t.node(i);if(Object.prototype.hasOwnProperty.call(e,i))return n.rank;e[i]=!0;var a=Lc(ht(t.outEdges(i),function(s){return r(s.w)-t.edge(s).minlen}));return(a===Number.POSITIVE_INFINITY||a===void 0||a===null)&&(a=0),n.rank=a}o(r,"dfs"),Pe(t.sources(),r)}function q0(t,e){return t.node(e.w).rank-t.node(e.v).rank-t.edge(e).minlen}var BE=P(()=>{"use strict";nr();o(zb,"longestPath");o(q0,"slack")});function FE(t){var e=new Ai({directed:!1}),r=t.nodes()[0],i=t.nodeCount();e.setNode(r,{});for(var n,a;_Xe(e,t){"use strict";nr();$l();BE();o(FE,"feasibleTree");o(_Xe,"tightTree");o(DXe,"findMinSlackEdge");o(LXe,"shiftRanks")});var _de=P(()=>{"use strict"});var NO=P(()=>{"use strict"});var Yur,IO=P(()=>{"use strict";nr();NO();Yur=yo(1)});var Dde=P(()=>{"use strict";IO()});var MO=P(()=>{"use strict"});var Lde=P(()=>{"use strict";MO()});var nhr,Rde=P(()=>{"use strict";nr();nhr=yo(1)});function OO(t){var e={},r={},i=[];function n(a){if(Object.prototype.hasOwnProperty.call(r,a))throw new Gb;Object.prototype.hasOwnProperty.call(e,a)||(r[a]=!0,e[a]=!0,Pe(t.predecessors(a),n),delete r[a],i.push(a))}if(o(n,"visit"),Pe(t.sinks(),n),xO(e)!==t.nodeCount())throw new Gb;return i}function Gb(){}var PO=P(()=>{"use strict";nr();OO.CycleException=Gb;o(OO,"topsort");o(Gb,"CycleException");Gb.prototype=new Error});var Nde=P(()=>{"use strict";PO()});function $E(t,e,r){Gt(e)||(e=[e]);var i=(t.isDirected()?t.successors:t.neighbors).bind(t),n=[],a={};return Pe(e,function(s){if(!t.hasNode(s))throw new Error("Graph does not have node: "+s);Ide(t,s,r==="post",a,i,n)}),n}function Ide(t,e,r,i,n,a){Object.prototype.hasOwnProperty.call(i,e)||(i[e]=!0,r||a.push(e),Pe(n(e),function(s){Ide(t,s,r,i,n,a)}),r&&a.push(e))}var BO=P(()=>{"use strict";nr();o($E,"dfs");o(Ide,"doDfs")});function FO(t,e){return $E(t,e,"post")}var Mde=P(()=>{"use strict";BO();o(FO,"postorder")});function $O(t,e){return $E(t,e,"pre")}var Ode=P(()=>{"use strict";BO();o($O,"preorder")});var Pde=P(()=>{"use strict";NO();IE()});var Bde=P(()=>{"use strict";_de();IO();Dde();Lde();Rde();Nde();Mde();Ode();Pde();MO();PO()});function wd(t){t=hde(t),zb(t);var e=FE(t);GO(e),zO(e,t);for(var r,i;r=Gde(e);)i=Vde(e,t,r),qde(e,t,r,i)}function zO(t,e){var r=FO(t,t.nodes());r=r.slice(0,r.length-1),Pe(r,function(i){OXe(t,e,i)})}function OXe(t,e,r){var i=t.node(r),n=i.parent;t.edge(r,n).cutvalue=$de(t,e,r)}function $de(t,e,r){var i=t.node(r),n=i.parent,a=!0,s=e.edge(r,n),l=0;return s||(a=!1,s=e.edge(n,r)),l=s.weight,Pe(e.nodeEdges(r),function(u){var h=u.v===r,f=h?u.w:u.v;if(f!==n){var d=h===a,p=e.edge(u).weight;if(l+=d?p:-p,BXe(t,r,f)){var m=t.edge(r,f).cutvalue;l+=d?-m:m}}}),l}function GO(t,e){arguments.length<2&&(e=t.nodes()[0]),zde(t,{},1,e)}function zde(t,e,r,i,n){var a=r,s=t.node(i);return e[i]=!0,Pe(t.neighbors(i),function(l){Object.prototype.hasOwnProperty.call(e,l)||(r=zde(t,e,r,l,i))}),s.low=a,s.lim=r++,n?s.parent=n:delete s.parent,r}function Gde(t){return qs(t.edges(),function(e){return t.edge(e).cutvalue<0})}function Vde(t,e,r){var i=r.v,n=r.w;e.hasEdge(i,n)||(i=r.w,n=r.v);var a=t.node(i),s=t.node(n),l=a,u=!1;a.lim>s.lim&&(l=s,u=!0);var h=pi(e.edges(),function(f){return u===Fde(t,t.node(f.v),l)&&u!==Fde(t,t.node(f.w),l)});return $0(h,function(f){return q0(e,f)})}function qde(t,e,r,i){var n=r.v,a=r.w;t.removeEdge(n,a),t.setEdge(i.v,i.w,{}),GO(t),zO(t,e),PXe(t,e)}function PXe(t,e){var r=qs(t.nodes(),function(n){return!e.node(n).parent}),i=$O(t,r);i=i.slice(1),Pe(i,function(n){var a=t.node(n).parent,s=e.edge(n,a),l=!1;s||(s=e.edge(a,n),l=!0),e.node(n).rank=e.node(a).rank+(l?s.minlen:-s.minlen)})}function BXe(t,e,r){return t.hasEdge(e,r)}function Fde(t,e,r){return r.low<=e.lim&&e.lim<=r.lim}var Wde=P(()=>{"use strict";nr();Bde();Mu();RO();BE();wd.initLowLimValues=GO;wd.initCutValues=zO;wd.calcCutValue=$de;wd.leaveEdge=Gde;wd.enterEdge=Vde;wd.exchangeEdges=qde;o(wd,"networkSimplex");o(zO,"initCutValues");o(OXe,"assignCutValue");o($de,"calcCutValue");o(GO,"initLowLimValues");o(zde,"dfsAssignLowLim");o(Gde,"leaveEdge");o(Vde,"enterEdge");o(qde,"exchangeEdges");o(PXe,"updateRanks");o(BXe,"isTreeEdge");o(Fde,"isDescendant")});function VO(t){switch(t.graph().ranker){case"network-simplex":Ude(t);break;case"tight-tree":$Xe(t);break;case"longest-path":FXe(t);break;default:Ude(t)}}function $Xe(t){zb(t),FE(t)}function Ude(t){wd(t)}var FXe,qO=P(()=>{"use strict";RO();Wde();BE();o(VO,"rank");FXe=zb;o($Xe,"tightTreeRanker");o(Ude,"networkSimplexRanker")});function Hde(t){var e=Iu(t,"root",{},"_root"),r=zXe(t),i=So(qr(r))-1,n=2*i+1;t.graph().nestingRoot=e,Pe(t.edges(),function(s){t.edge(s).minlen*=n});var a=GXe(t)+1;Pe(t.children(),function(s){Yde(t,e,n,a,i,r,s)}),t.graph().nodeRankFactor=n}function Yde(t,e,r,i,n,a,s){var l=t.children(s);if(!l.length){s!==e&&t.setEdge(e,s,{weight:0,minlen:r});return}var u=SO(t,"_bt"),h=SO(t,"_bb"),f=t.node(s);t.setParent(u,s),f.borderTop=u,t.setParent(h,s),f.borderBottom=h,Pe(l,function(d){Yde(t,e,r,i,n,a,d);var p=t.node(d),m=p.borderTop?p.borderTop:d,g=p.borderBottom?p.borderBottom:d,y=p.borderTop?i:2*i,v=m!==g?1:n-a[s]+1;t.setEdge(u,m,{weight:y,minlen:v,nestingEdge:!0}),t.setEdge(g,h,{weight:y,minlen:v,nestingEdge:!0})}),t.parent(s)||t.setEdge(e,u,{weight:0,minlen:n+a[s]})}function zXe(t){var e={};function r(i,n){var a=t.children(i);a&&a.length&&Pe(a,function(s){r(s,n+1)}),e[i]=n}return o(r,"dfs"),Pe(t.children(),function(i){r(i,1)}),e}function GXe(t){return mi(t.edges(),function(e,r){return e+t.edge(r).weight},0)}function jde(t){var e=t.graph();t.removeNode(e.nestingRoot),delete e.nestingRoot,Pe(t.edges(),function(r){var i=t.edge(r);i.nestingEdge&&t.removeEdge(r)})}var Xde=P(()=>{"use strict";nr();Mu();o(Hde,"run");o(Yde,"dfs");o(zXe,"treeDepths");o(GXe,"sumWeights");o(jde,"cleanup")});function Kde(t,e,r){var i={},n;Pe(r,function(a){for(var s=t.parent(a),l,u;s;){if(l=t.parent(s),l?(u=i[l],i[l]=s):(u=n,n=s),u&&u!==s){e.setEdge(u,s);return}s=l}})}var Qde=P(()=>{"use strict";nr();o(Kde,"addSubgraphConstraints")});function Zde(t,e,r){var i=qXe(t),n=new Ai({compound:!0}).setGraph({root:i}).setDefaultNodeLabel(function(a){return t.node(a)});return Pe(t.nodes(),function(a){var s=t.node(a),l=t.parent(a);(s.rank===e||s.minRank<=e&&e<=s.maxRank)&&(n.setNode(a),n.setParent(a,l||i),Pe(t[r](a),function(u){var h=u.v===a?u.w:u.v,f=n.edge(h,a),d=Br(f)?0:f.weight;n.setEdge(h,a,{weight:t.edge(u).weight+d})}),Object.prototype.hasOwnProperty.call(s,"minRank")&&n.setNode(a,{borderLeft:s.borderLeft[e],borderRight:s.borderRight[e]}))}),n}function qXe(t){for(var e;t.hasNode(e=G0("_root")););return e}var Jde=P(()=>{"use strict";nr();$l();o(Zde,"buildLayerGraph");o(qXe,"createRootNode")});function epe(t,e){for(var r=0,i=1;i0;)f%2&&(d+=l[f+1]),f=f-1>>1,l[f]+=h.weight;u+=h.weight*d})),u}var tpe=P(()=>{"use strict";nr();o(epe,"crossCount");o(WXe,"twoLayerCrossCount")});function rpe(t){var e={},r=pi(t.nodes(),function(l){return!t.children(l).length}),i=So(ht(r,function(l){return t.node(l).rank})),n=ht(Fl(i+1),function(){return[]});function a(l){if(!Vt(e,l)){e[l]=!0;var u=t.node(l);n[u.rank].push(l),Pe(t.successors(l),a)}}o(a,"dfs");var s=Nu(r,function(l){return t.node(l).rank});return Pe(s,a),n}var ipe=P(()=>{"use strict";nr();o(rpe,"initOrder")});function npe(t,e){return ht(e,function(r){var i=t.inEdges(r);if(i.length){var n=mi(i,function(a,s){var l=t.edge(s),u=t.node(s.v);return{sum:a.sum+l.weight*u.order,weight:a.weight+l.weight}},{sum:0,weight:0});return{v:r,barycenter:n.sum/n.weight,weight:n.weight}}else return{v:r}})}var ape=P(()=>{"use strict";nr();o(npe,"barycenter")});function spe(t,e){var r={};Pe(t,function(n,a){var s=r[n.v]={indegree:0,in:[],out:[],vs:[n.v],i:a};Br(n.barycenter)||(s.barycenter=n.barycenter,s.weight=n.weight)}),Pe(e.edges(),function(n){var a=r[n.v],s=r[n.w];!Br(a)&&!Br(s)&&(s.indegree++,a.out.push(r[n.w]))});var i=pi(r,function(n){return!n.indegree});return UXe(i)}function UXe(t){var e=[];function r(a){return function(s){s.merged||(Br(s.barycenter)||Br(a.barycenter)||s.barycenter>=a.barycenter)&&HXe(a,s)}}o(r,"handleIn");function i(a){return function(s){s.in.push(a),--s.indegree===0&&t.push(s)}}for(o(i,"handleOut");t.length;){var n=t.pop();e.push(n),Pe(n.in.reverse(),r(n)),Pe(n.out,i(n))}return ht(pi(e,function(a){return!a.merged}),function(a){return z0(a,["vs","i","barycenter","weight"])})}function HXe(t,e){var r=0,i=0;t.weight&&(r+=t.barycenter*t.weight,i+=t.weight),e.weight&&(r+=e.barycenter*e.weight,i+=e.weight),t.vs=e.vs.concat(t.vs),t.barycenter=r/i,t.weight=i,t.i=Math.min(e.i,t.i),e.merged=!0}var ope=P(()=>{"use strict";nr();o(spe,"resolveConflicts");o(UXe,"doResolveConflicts");o(HXe,"mergeEntries")});function cpe(t,e){var r=pde(t,function(f){return Object.prototype.hasOwnProperty.call(f,"barycenter")}),i=r.lhs,n=Nu(r.rhs,function(f){return-f.i}),a=[],s=0,l=0,u=0;i.sort(YXe(!!e)),u=lpe(a,n,u),Pe(i,function(f){u+=f.vs.length,a.push(f.vs),s+=f.barycenter*f.weight,l+=f.weight,u=lpe(a,n,u)});var h={vs:di(a)};return l&&(h.barycenter=s/l,h.weight=l),h}function lpe(t,e,r){for(var i;e.length&&(i=Na(e)).i<=r;)e.pop(),t.push(i.vs),r++;return r}function YXe(t){return function(e,r){return e.barycenterr.barycenter?1:t?r.i-e.i:e.i-r.i}}var upe=P(()=>{"use strict";nr();Mu();o(cpe,"sort");o(lpe,"consumeUnsortable");o(YXe,"compareWithBias")});function WO(t,e,r,i){var n=t.children(e),a=t.node(e),s=a?a.borderLeft:void 0,l=a?a.borderRight:void 0,u={};s&&(n=pi(n,function(g){return g!==s&&g!==l}));var h=npe(t,n);Pe(h,function(g){if(t.children(g.v).length){var y=WO(t,g.v,r,i);u[g.v]=y,Object.prototype.hasOwnProperty.call(y,"barycenter")&&XXe(g,y)}});var f=spe(h,r);jXe(f,u);var d=cpe(f,i);if(s&&(d.vs=di([s,d.vs,l]),t.predecessors(s).length)){var p=t.node(t.predecessors(s)[0]),m=t.node(t.predecessors(l)[0]);Object.prototype.hasOwnProperty.call(d,"barycenter")||(d.barycenter=0,d.weight=0),d.barycenter=(d.barycenter*d.weight+p.order+m.order)/(d.weight+2),d.weight+=2}return d}function jXe(t,e){Pe(t,function(r){r.vs=di(r.vs.map(function(i){return e[i]?e[i].vs:i}))})}function XXe(t,e){Br(t.barycenter)?(t.barycenter=e.barycenter,t.weight=e.weight):(t.barycenter=(t.barycenter*t.weight+e.barycenter*e.weight)/(t.weight+e.weight),t.weight+=e.weight)}var hpe=P(()=>{"use strict";nr();ape();ope();upe();o(WO,"sortSubgraph");o(jXe,"expandSubgraphs");o(XXe,"mergeBarycenters")});function ppe(t){var e=AO(t),r=fpe(t,Fl(1,e+1),"inEdges"),i=fpe(t,Fl(e-1,-1,-1),"outEdges"),n=rpe(t);dpe(t,n);for(var a=Number.POSITIVE_INFINITY,s,l=0,u=0;u<4;++l,++u){KXe(l%2?r:i,l%4>=2),n=kd(t);var h=epe(t,n);h{"use strict";nr();$l();Mu();Qde();Jde();tpe();ipe();hpe();o(ppe,"order");o(fpe,"buildLayerGraphs");o(KXe,"sweepLayerGraphs");o(dpe,"assignOrder")});function gpe(t){var e=ZXe(t);Pe(t.graph().dummyChains,function(r){for(var i=t.node(r),n=i.edgeObj,a=QXe(t,e,n.v,n.w),s=a.path,l=a.lca,u=0,h=s[u],f=!0;r!==n.w;){if(i=t.node(r),f){for(;(h=s[u])!==l&&t.node(h).maxRanks||l>e[u].lim));for(h=u,u=i;(u=t.parent(u))!==h;)a.push(u);return{path:n.concat(a.reverse()),lca:h}}function ZXe(t){var e={},r=0;function i(n){var a=r;Pe(t.children(n),i),e[n]={low:a,lim:r++}}return o(i,"dfs"),Pe(t.children(),i),e}var ype=P(()=>{"use strict";nr();o(gpe,"parentDummyChains");o(QXe,"findPath");o(ZXe,"postorder")});function JXe(t,e){var r={};function i(n,a){var s=0,l=0,u=n.length,h=Na(a);return Pe(a,function(f,d){var p=tKe(t,f),m=p?t.node(p).order:u;(p||f===h)&&(Pe(a.slice(l,d+1),function(g){Pe(t.predecessors(g),function(y){var v=t.node(y),x=v.order;(xh)&&vpe(r,p,f)})})}o(i,"scan");function n(a,s){var l=-1,u,h=0;return Pe(s,function(f,d){if(t.node(f).dummy==="border"){var p=t.predecessors(f);p.length&&(u=t.node(p[0]).order,i(s,h,d,l,u),h=d,l=u)}i(s,h,s.length,u,a.length)}),s}return o(n,"visitLayer"),mi(e,n),r}function tKe(t,e){if(t.node(e).dummy)return qs(t.predecessors(e),function(r){return t.node(r).dummy})}function vpe(t,e,r){if(e>r){var i=e;e=r,r=i}Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{enumerable:!0,configurable:!0,value:{},writable:!0});var n=t[e];Object.defineProperty(n,r,{enumerable:!0,configurable:!0,value:!0,writable:!0})}function rKe(t,e,r){if(e>r){var i=e;e=r,r=i}return!!t[e]&&Object.prototype.hasOwnProperty.call(t[e],r)}function iKe(t,e,r,i){var n={},a={},s={};return Pe(e,function(l){Pe(l,function(u,h){n[u]=u,a[u]=u,s[u]=h})}),Pe(e,function(l){var u=-1;Pe(l,function(h){var f=i(h);if(f.length){f=Nu(f,function(y){return s[y]});for(var d=(f.length-1)/2,p=Math.floor(d),m=Math.ceil(d);p<=m;++p){var g=f[p];a[h]===h&&u{"use strict";nr();$l();Mu();o(JXe,"findType1Conflicts");o(eKe,"findType2Conflicts");o(tKe,"findOtherInnerSegmentNode");o(vpe,"addConflict");o(rKe,"hasConflict");o(iKe,"verticalAlignment");o(nKe,"horizontalCompaction");o(aKe,"buildBlockGraph");o(sKe,"findSmallestWidthAlignment");o(oKe,"alignCoordinates");o(lKe,"balance");o(xpe,"positionX");o(cKe,"sep");o(uKe,"width")});function Tpe(t){t=PE(t),hKe(t),uO(xpe(t),function(e,r){t.node(r).x=e})}function hKe(t){var e=kd(t),r=t.graph().ranksep,i=0;Pe(e,function(n){var a=So(ht(n,function(s){return t.node(s).height}));Pe(n,function(s){t.node(s).y=i+a/2}),i+=a+r})}var kpe=P(()=>{"use strict";nr();Mu();bpe();o(Tpe,"position");o(hKe,"positionY")});function Vb(t,e){var r=e&&e.debugTiming?mde:gde;r("layout",()=>{var i=r(" buildLayoutGraph",()=>kKe(t));r(" runLayout",()=>fKe(i,r)),r(" updateInputGraph",()=>dKe(t,i))})}function fKe(t,e){e(" makeSpaceForEdgeLabels",()=>CKe(t)),e(" removeSelfEdges",()=>NKe(t)),e(" acyclic",()=>lde(t)),e(" nestingGraph.run",()=>Hde(t)),e(" rank",()=>VO(PE(t))),e(" injectEdgeLabelProxies",()=>wKe(t)),e(" removeEmptyRanks",()=>dde(t)),e(" nestingGraph.cleanup",()=>jde(t)),e(" normalizeRanks",()=>fde(t)),e(" assignRankMinMax",()=>EKe(t)),e(" removeEdgeLabelProxies",()=>SKe(t)),e(" normalize.run",()=>Ede(t)),e(" parentDummyChains",()=>gpe(t)),e(" addBorderSegments",()=>vde(t)),e(" order",()=>ppe(t)),e(" insertSelfEdges",()=>IKe(t)),e(" adjustCoordinateSystem",()=>Tde(t)),e(" position",()=>Tpe(t)),e(" positionSelfEdges",()=>MKe(t)),e(" removeBorderNodes",()=>RKe(t)),e(" normalize.undo",()=>Sde(t)),e(" fixupEdgeLabelCoords",()=>DKe(t)),e(" undoCoordinateSystem",()=>kde(t)),e(" translateGraph",()=>AKe(t)),e(" assignNodeIntersects",()=>_Ke(t)),e(" reversePoints",()=>LKe(t)),e(" acyclic.undo",()=>cde(t))}function dKe(t,e){Pe(t.nodes(),function(r){var i=t.node(r),n=e.node(r);i&&(i.x=n.x,i.y=n.y,e.children(r).length&&(i.width=n.width,i.height=n.height))}),Pe(t.edges(),function(r){var i=t.edge(r),n=e.edge(r);i.points=n.points,Object.prototype.hasOwnProperty.call(n,"x")&&(i.x=n.x,i.y=n.y)}),t.graph().width=e.graph().width,t.graph().height=e.graph().height}function kKe(t){var e=new Ai({multigraph:!0,compound:!0}),r=HO(t.graph());return e.setGraph(sd({},mKe,UO(r,pKe),z0(r,gKe))),Pe(t.nodes(),function(i){var n=HO(t.node(i));e.setNode(i,xd(UO(n,yKe),vKe)),e.setParent(i,t.parent(i))}),Pe(t.edges(),function(i){var n=HO(t.edge(i));e.setEdge(i,sd({},bKe,UO(n,xKe),z0(n,TKe)))}),e}function CKe(t){var e=t.graph();e.ranksep/=2,Pe(t.edges(),function(r){var i=t.edge(r);i.minlen*=2,i.labelpos.toLowerCase()!=="c"&&(e.rankdir==="TB"||e.rankdir==="BT"?i.width+=i.labeloffset:i.height+=i.labeloffset)})}function wKe(t){Pe(t.edges(),function(e){var r=t.edge(e);if(r.width&&r.height){var i=t.node(e.v),n=t.node(e.w),a={rank:(n.rank-i.rank)/2+i.rank,e};Iu(t,"edge-proxy",a,"_ep")}})}function EKe(t){var e=0;Pe(t.nodes(),function(r){var i=t.node(r);i.borderTop&&(i.minRank=t.node(i.borderTop).rank,i.maxRank=t.node(i.borderBottom).rank,e=So(e,i.maxRank))}),t.graph().maxRank=e}function SKe(t){Pe(t.nodes(),function(e){var r=t.node(e);r.dummy==="edge-proxy"&&(t.edge(r.e).labelRank=r.rank,t.removeNode(e))})}function AKe(t){var e=Number.POSITIVE_INFINITY,r=0,i=Number.POSITIVE_INFINITY,n=0,a=t.graph(),s=a.marginx||0,l=a.marginy||0;function u(h){var f=h.x,d=h.y,p=h.width,m=h.height;e=Math.min(e,f-p/2),r=Math.max(r,f+p/2),i=Math.min(i,d-m/2),n=Math.max(n,d+m/2)}o(u,"getExtremes"),Pe(t.nodes(),function(h){u(t.node(h))}),Pe(t.edges(),function(h){var f=t.edge(h);Object.prototype.hasOwnProperty.call(f,"x")&&u(f)}),e-=s,i-=l,Pe(t.nodes(),function(h){var f=t.node(h);f.x-=e,f.y-=i}),Pe(t.edges(),function(h){var f=t.edge(h);Pe(f.points,function(d){d.x-=e,d.y-=i}),Object.prototype.hasOwnProperty.call(f,"x")&&(f.x-=e),Object.prototype.hasOwnProperty.call(f,"y")&&(f.y-=i)}),a.width=r-e+s,a.height=n-i+l}function _Ke(t){Pe(t.edges(),function(e){var r=t.edge(e),i=t.node(e.v),n=t.node(e.w),a,s;r.points?(a=r.points[0],s=r.points[r.points.length-1]):(r.points=[],a=n,s=i),r.points.unshift(EO(i,a)),r.points.push(EO(n,s))})}function DKe(t){Pe(t.edges(),function(e){var r=t.edge(e);if(Object.prototype.hasOwnProperty.call(r,"x"))switch((r.labelpos==="l"||r.labelpos==="r")&&(r.width-=r.labeloffset),r.labelpos){case"l":r.x-=r.width/2+r.labeloffset;break;case"r":r.x+=r.width/2+r.labeloffset;break}})}function LKe(t){Pe(t.edges(),function(e){var r=t.edge(e);r.reversed&&r.points.reverse()})}function RKe(t){Pe(t.nodes(),function(e){if(t.children(e).length){var r=t.node(e),i=t.node(r.borderTop),n=t.node(r.borderBottom),a=t.node(Na(r.borderLeft)),s=t.node(Na(r.borderRight));r.width=Math.abs(s.x-a.x),r.height=Math.abs(n.y-i.y),r.x=a.x+r.width/2,r.y=i.y+r.height/2}}),Pe(t.nodes(),function(e){t.node(e).dummy==="border"&&t.removeNode(e)})}function NKe(t){Pe(t.edges(),function(e){if(e.v===e.w){var r=t.node(e.v);r.selfEdges||(r.selfEdges=[]),r.selfEdges.push({e,label:t.edge(e)}),t.removeEdge(e)}})}function IKe(t){var e=kd(t);Pe(e,function(r){var i=0;Pe(r,function(n,a){var s=t.node(n);s.order=a+i,Pe(s.selfEdges,function(l){Iu(t,"selfedge",{width:l.label.width,height:l.label.height,rank:s.rank,order:a+ ++i,e:l.e,label:l.label},"_se")}),delete s.selfEdges})})}function MKe(t){Pe(t.nodes(),function(e){var r=t.node(e);if(r.dummy==="selfedge"){var i=t.node(r.e.v),n=i.x+i.width/2,a=i.y,s=r.x-n,l=i.height/2;t.setEdge(r.e,r.label),t.removeNode(e),r.label.points=[{x:n+2*s/3,y:a-l},{x:n+5*s/6,y:a-l},{x:n+s,y:a},{x:n+5*s/6,y:a+l},{x:n+2*s/3,y:a+l}],r.label.x=r.x,r.label.y=r.y}})}function UO(t,e){return F0(z0(t,e),Number)}function HO(t){var e={};return Pe(t,function(r,i){e[i.toLowerCase()]=r}),e}var pKe,mKe,gKe,yKe,vKe,xKe,bKe,TKe,Cpe=P(()=>{"use strict";nr();$l();xde();wde();wO();LO();qO();Xde();mpe();ype();kpe();Mu();o(Vb,"layout");o(fKe,"runLayout");o(dKe,"updateInputGraph");pKe=["nodesep","edgesep","ranksep","marginx","marginy"],mKe={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},gKe=["acyclicer","ranker","rankdir","align"],yKe=["width","height"],vKe={width:0,height:0},xKe=["minlen","weight","width","height","labeloffset"],bKe={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},TKe=["labelpos"];o(kKe,"buildLayoutGraph");o(CKe,"makeSpaceForEdgeLabels");o(wKe,"injectEdgeLabelProxies");o(EKe,"assignRankMinMax");o(SKe,"removeEdgeLabelProxies");o(AKe,"translateGraph");o(_Ke,"assignNodeIntersects");o(DKe,"fixupEdgeLabelCoords");o(LKe,"reversePointsForReversedEdges");o(RKe,"removeBorderNodes");o(NKe,"removeSelfEdges");o(IKe,"insertSelfEdges");o(MKe,"positionSelfEdges");o(UO,"selectNumberAttrs");o(HO,"canonicalize")});var YO=P(()=>{"use strict";wO();Cpe();LO();qO()});function zl(t){var e={options:{directed:t.isDirected(),multigraph:t.isMultigraph(),compound:t.isCompound()},nodes:OKe(t),edges:PKe(t)};return Br(t.graph())||(e.value=Si(t.graph())),e}function OKe(t){return ht(t.nodes(),function(e){var r=t.node(e),i=t.parent(e),n={v:e};return Br(r)||(n.value=r),Br(i)||(n.parent=i),n})}function PKe(t){return ht(t.edges(),function(e){var r=t.edge(e),i={v:e.v,w:e.w};return Br(e.name)||(i.name=e.name),Br(r)||(i.value=r),i})}var jO=P(()=>{"use strict";nr();IE();o(zl,"write");o(OKe,"writeNodes");o(PKe,"writeEdges")});var Wr,W0,Spe,Ape,zE,BKe,_pe,Dpe,FKe,J1,Epe,Lpe,Rpe,Npe,Ipe,Mpe=P(()=>{"use strict";bt();$l();jO();Wr=new Map,W0=new Map,Spe=new Map,Ape=o(()=>{W0.clear(),Spe.clear(),Wr.clear()},"clear"),zE=o((t,e)=>{let r=W0.get(e)||[];return Q.trace("In isDescendant",e," ",t," = ",r.includes(t)),r.includes(t)},"isDescendant"),BKe=o((t,e)=>{let r=W0.get(e)||[];return Q.info("Descendants of ",e," is ",r),Q.info("Edge is ",t),t.v===e||t.w===e?!1:r?r.includes(t.v)||zE(t.v,e)||zE(t.w,e)||r.includes(t.w):(Q.debug("Tilt, ",e,",not in descendants"),!1)},"edgeInCluster"),_pe=o((t,e,r,i)=>{Q.warn("Copying children of ",t,"root",i,"data",e.node(t),i);let n=e.children(t)||[];t!==i&&n.push(t),Q.warn("Copying (nodes) clusterId",t,"nodes",n),n.forEach(a=>{if(e.children(a).length>0)_pe(a,e,r,i);else{let s=e.node(a);Q.info("cp ",a," to ",i," with parent ",t),r.setNode(a,s),i!==e.parent(a)&&(Q.warn("Setting parent",a,e.parent(a)),r.setParent(a,e.parent(a))),t!==i&&a!==t?(Q.debug("Setting parent",a,t),r.setParent(a,t)):(Q.info("In copy ",t,"root",i,"data",e.node(t),i),Q.debug("Not Setting parent for node=",a,"cluster!==rootId",t!==i,"node!==clusterId",a!==t));let l=e.edges(a);Q.debug("Copying Edges",l),l.forEach(u=>{Q.info("Edge",u);let h=e.edge(u.v,u.w,u.name);Q.info("Edge data",h,i);try{BKe(u,i)?(Q.info("Copying as ",u.v,u.w,h,u.name),r.setEdge(u.v,u.w,h,u.name),Q.info("newGraph edges ",r.edges(),r.edge(r.edges()[0]))):Q.info("Skipping copy of edge ",u.v,"-->",u.w," rootId: ",i," clusterId:",t)}catch(f){Q.error(f)}})}Q.debug("Removing node",a),e.removeNode(a)})},"copy"),Dpe=o((t,e)=>{let r=e.children(t),i=[...r];for(let n of r)Spe.set(n,t),i=[...i,...Dpe(n,e)];return i},"extractDescendants"),FKe=o((t,e,r)=>{let i=t.edges().filter(u=>u.v===e||u.w===e),n=t.edges().filter(u=>u.v===r||u.w===r),a=i.map(u=>({v:u.v===e?r:u.v,w:u.w===e?e:u.w})),s=n.map(u=>({v:u.v,w:u.w}));return a.filter(u=>s.some(h=>u.v===h.v&&u.w===h.w))},"findCommonEdges"),J1=o((t,e,r)=>{let i=e.children(t);if(Q.trace("Searching children of id ",t,i),i.length<1)return t;let n;for(let a of i){let s=J1(a,e,r),l=FKe(e,r,s);if(s)if(l.length>0)n=s;else return s}return n},"findNonClusterChild"),Epe=o(t=>!Wr.has(t)||!Wr.get(t).externalConnections?t:Wr.has(t)?Wr.get(t).id:t,"getAnchorId"),Lpe=o((t,e)=>{if(!t||e>10){Q.debug("Opting out, no graph ");return}else Q.debug("Opting in, graph ");t.nodes().forEach(function(r){t.children(r).length>0&&(Q.warn("Cluster identified",r," Replacement id in edges: ",J1(r,t,r)),W0.set(r,Dpe(r,t)),Wr.set(r,{id:J1(r,t,r),clusterData:t.node(r)}))}),t.nodes().forEach(function(r){let i=t.children(r),n=t.edges();i.length>0?(Q.debug("Cluster identified",r,W0),n.forEach(a=>{let s=zE(a.v,r),l=zE(a.w,r);s^l&&(Q.warn("Edge: ",a," leaves cluster ",r),Q.warn("Descendants of XXX ",r,": ",W0.get(r)),Wr.get(r).externalConnections=!0)})):Q.debug("Not a cluster ",r,W0)});for(let r of Wr.keys()){let i=Wr.get(r).id,n=t.parent(i);n!==r&&Wr.has(n)&&!Wr.get(n).externalConnections&&(Wr.get(r).id=n)}t.edges().forEach(function(r){let i=t.edge(r);Q.warn("Edge "+r.v+" -> "+r.w+": "+JSON.stringify(r)),Q.warn("Edge "+r.v+" -> "+r.w+": "+JSON.stringify(t.edge(r)));let n=r.v,a=r.w;if(Q.warn("Fix XXX",Wr,"ids:",r.v,r.w,"Translating: ",Wr.get(r.v)," --- ",Wr.get(r.w)),Wr.get(r.v)||Wr.get(r.w)){if(Q.warn("Fixing and trying - removing XXX",r.v,r.w,r.name),n=Epe(r.v),a=Epe(r.w),t.removeEdge(r.v,r.w,r.name),n!==r.v){let s=t.parent(n);Wr.get(s).externalConnections=!0,i.fromCluster=r.v}if(a!==r.w){let s=t.parent(a);Wr.get(s).externalConnections=!0,i.toCluster=r.w}Q.warn("Fix Replacing with XXX",n,a,r.name),t.setEdge(n,a,i,r.name)}}),Q.warn("Adjusted Graph",zl(t)),Rpe(t,0),Q.trace(Wr)},"adjustClustersAndEdges"),Rpe=o((t,e)=>{if(Q.warn("extractor - ",e,zl(t),t.children("D")),e>10){Q.error("Bailing out");return}let r=t.nodes(),i=!1;for(let n of r){let a=t.children(n);i=i||a.length>0}if(!i){Q.debug("Done, no node has children",t.nodes());return}Q.debug("Nodes = ",r,e);for(let n of r)if(Q.debug("Extracting node",n,Wr,Wr.has(n)&&!Wr.get(n).externalConnections,!t.parent(n),t.node(n),t.children("D")," Depth ",e),!Wr.has(n))Q.debug("Not a cluster",n,e);else if(!Wr.get(n).externalConnections&&t.children(n)&&t.children(n).length>0){Q.warn("Cluster without external connections, without a parent and with children",n,e);let s=t.graph().rankdir==="TB"?"LR":"TB";Wr.get(n)?.clusterData?.dir&&(s=Wr.get(n).clusterData.dir,Q.warn("Fixing dir",Wr.get(n).clusterData.dir,s));let l=new Ai({multigraph:!0,compound:!0}).setGraph({rankdir:s,nodesep:50,ranksep:50,marginx:8,marginy:8}).setDefaultEdgeLabel(function(){return{}});Q.warn("Old graph before copy",zl(t)),_pe(n,t,l,n),t.setNode(n,{clusterNode:!0,id:n,clusterData:Wr.get(n).clusterData,label:Wr.get(n).label,graph:l}),Q.warn("New graph after copy node: (",n,")",zl(l)),Q.debug("Old graph after copy",zl(t))}else Q.warn("Cluster ** ",n," **not meeting the criteria !externalConnections:",!Wr.get(n).externalConnections," no parent: ",!t.parent(n)," children ",t.children(n)&&t.children(n).length>0,t.children("D"),e),Q.debug(Wr);r=t.nodes(),Q.warn("New list of nodes",r);for(let n of r){let a=t.node(n);Q.warn(" Now next level",n,a),a?.clusterNode&&Rpe(a.graph,e+1)}},"extractor"),Npe=o((t,e)=>{if(e.length===0)return[];let r=Object.assign([],e);return e.forEach(i=>{let n=t.children(i),a=Npe(t,n);r=[...r,...a]}),r},"sorter"),Ipe=o(t=>Npe(t,t.children()),"sortNodesByHierarchy")});var Ppe={};ur(Ppe,{render:()=>$Ke});var Ope,$Ke,Bpe=P(()=>{"use strict";YO();jO();$l();NM();zt();Mpe();B5();A5();RM();bt();Nb();Ut();Ope=o(async(t,e,r,i,n,a)=>{Q.warn("Graph in recursive render:XAX",zl(e),n);let s=e.graph().rankdir;Q.trace("Dir in recursive render - dir:",s);let l=t.insert("g").attr("class","root");e.nodes()?Q.info("Recursive render XXX",e.nodes()):Q.info("No nodes found for",e),e.edges().length>0&&Q.info("Recursive edges",e.edge(e.edges()[0]));let u=l.insert("g").attr("class","clusters"),h=l.insert("g").attr("class","edgePaths"),f=l.insert("g").attr("class","edgeLabels"),d=l.insert("g").attr("class","nodes");await Promise.all(e.nodes().map(async function(y){let v=e.node(y);if(n!==void 0){let x=JSON.parse(JSON.stringify(n.clusterData));Q.trace(`Setting data for parent cluster XXX + Node.id = `,y,` + data=`,x.height,` +Parent cluster`,n.height),e.setNode(n.id,x),e.parent(y)||(Q.trace("Setting parent",y,n.id),e.setParent(y,n.id,x))}if(Q.info("(Insert) Node XXX"+y+": "+JSON.stringify(e.node(y))),v?.clusterNode){Q.info("Cluster identified XBX",y,v.width,e.node(y));let{ranksep:x,nodesep:b}=e.graph();v.graph.setGraph({...v.graph.graph(),ranksep:x+25,nodesep:b});let T=await Ope(d,v.graph,r,i,e.node(y),a),w=T.elem;at(v,w),v.diff=T.diff||0,Q.info("New compound node after recursive render XAX",y,"width",v.width,"height",v.height),ece(w,v)}else e.children(y).length>0?(Q.trace("Cluster - the non recursive path XBX",y,v.id,v,v.width,"Graph:",e),Q.trace(J1(v.id,e)),Wr.set(v.id,{id:J1(v.id,e),node:v})):(Q.trace("Node - the non recursive path XAX",y,d,e.node(y),s),await I1(d,e.node(y),{config:a,dir:s}))})),await o(async()=>{let y=e.edges().map(async function(v){let x=e.edge(v.v,v.w,v.name);Q.info("Edge "+v.v+" -> "+v.w+": "+JSON.stringify(v)),Q.info("Edge "+v.v+" -> "+v.w+": ",v," ",JSON.stringify(e.edge(v))),Q.info("Fix",Wr,"ids:",v.v,v.w,"Translating: ",Wr.get(v.v),Wr.get(v.w)),await N5(f,x)});await Promise.all(y)},"processEdges")(),Q.info("Graph before layout:",JSON.stringify(zl(e))),Q.info("############################################# XXX"),Q.info("### Layout ### XXX"),Q.info("############################################# XXX"),Vb(e),Q.info("Graph after layout:",JSON.stringify(zl(e)));let m=0,{subGraphTitleTotalMargin:g}=Uh(a);return await Promise.all(Ipe(e).map(async function(y){let v=e.node(y);if(Q.info("Position XBX => "+y+": ("+v.x,","+v.y,") width: ",v.width," height: ",v.height),v?.clusterNode)v.y+=g,Q.info("A tainted cluster node XBX1",y,v.id,v.width,v.height,v.x,v.y,e.parent(y)),Wr.get(v.id).node=v,Mb(v);else if(e.children(y).length>0){Q.info("A pure cluster node XBX1",y,v.id,v.x,v.y,v.width,v.height,e.parent(y)),v.height+=g,e.node(v.parentId);let x=v?.padding/2||0,b=v?.labelBBox?.height||0,T=b-x||0;Q.debug("OffsetY",T,"labelHeight",b,"halfPadding",x),await N1(u,v),Wr.get(v.id).node=v}else{let x=e.node(v.parentId);v.y+=g/2,Q.info("A regular node XBX1 - using the padding",v.id,"parent",v.parentId,v.width,v.height,v.x,v.y,"offsetY",v.offsetY,"parent",x,x?.offsetY,v),Mb(v)}})),e.edges().forEach(function(y){let v=e.edge(y);Q.info("Edge "+y.v+" -> "+y.w+": "+JSON.stringify(v),v),v.points.forEach(w=>w.y+=g/2);let x=e.node(y.v);var b=e.node(y.w);let T=M5(h,v,Wr,r,x,b,i);I5(v,T)}),e.nodes().forEach(function(y){let v=e.node(y);Q.info(y,v.type,v.diff),v.isGroup&&(m=v.diff)}),Q.warn("Returning from recursive render XAX",l,m),{elem:l,diff:m}},"recursiveRender"),$Ke=o(async(t,e)=>{let r=new Ai({multigraph:!0,compound:!0}).setGraph({rankdir:t.direction,nodesep:t.config?.nodeSpacing||t.config?.flowchart?.nodeSpacing||t.nodeSpacing,ranksep:t.config?.rankSpacing||t.config?.flowchart?.rankSpacing||t.rankSpacing,marginx:8,marginy:8}).setDefaultEdgeLabel(function(){return{}}),i=e.select("g");O5(i,t.markers,t.type,t.diagramId),tce(),Jle(),Hle(),Ape(),t.nodes.forEach(a=>{r.setNode(a.id,{...a}),a.parentId&&r.setParent(a.id,a.parentId)}),Q.debug("Edges:",t.edges),t.edges.forEach(a=>{if(a.start===a.end){let s=a.start,l=s+"---"+s+"---1",u=s+"---"+s+"---2",h=r.node(s);r.setNode(l,{domId:l,id:l,parentId:h.parentId,labelStyle:"",label:"",padding:0,shape:"labelRect",style:"",width:10,height:10}),r.setParent(l,h.parentId),r.setNode(u,{domId:u,id:u,parentId:h.parentId,labelStyle:"",padding:0,shape:"labelRect",label:"",style:"",width:10,height:10}),r.setParent(u,h.parentId);let f=structuredClone(a),d=structuredClone(a),p=structuredClone(a);f.label="",f.arrowTypeEnd="none",f.id=s+"-cyclic-special-1",d.arrowTypeStart="none",d.arrowTypeEnd="none",d.id=s+"-cyclic-special-mid",p.label="",h.isGroup&&(f.fromCluster=s,p.toCluster=s),p.id=s+"-cyclic-special-2",p.arrowTypeStart="none",r.setEdge(s,l,f,s+"-cyclic-special-0"),r.setEdge(l,u,d,s+"-cyclic-special-1"),r.setEdge(u,s,p,s+"-cyct.length)&&(e=t.length);for(var r=0,i=Array(e);r=t.length?{done:!0}:{done:!1,value:t[i++]}},"n"),e:o(function(u){throw u},"e"),f:n}}throw new TypeError(`Invalid attempt to iterate non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var a,s=!0,l=!1;return{s:o(function(){r=r.call(t)},"s"),n:o(function(){var u=r.next();return s=u.done,u},"n"),e:o(function(u){l=!0,a=u},"e"),f:o(function(){try{s||r.return==null||r.return()}finally{if(l)throw a}},"f")}}function fge(t,e,r){return(e=dge(e))in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function qKe(t){if(typeof Symbol<"u"&&t[Symbol.iterator]!=null||t["@@iterator"]!=null)return Array.from(t)}function WKe(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var i,n,a,s,l=[],u=!0,h=!1;try{if(a=(r=r.call(t)).next,e===0){if(Object(r)!==r)return;u=!1}else for(;!(u=(i=a.call(r)).done)&&(l.push(i.value),l.length!==e);u=!0);}catch(f){h=!0,n=f}finally{try{if(!u&&r.return!=null&&(s=r.return(),Object(s)!==s))return}finally{if(h)throw n}}return l}}function UKe(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function HKe(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function ea(t,e){return zKe(t)||WKe(t,e)||UB(t,e)||UKe()}function hS(t){return GKe(t)||qKe(t)||UB(t)||HKe()}function YKe(t,e){if(typeof t!="object"||!t)return t;var r=t[Symbol.toPrimitive];if(r!==void 0){var i=r.call(t,e);if(typeof i!="object")return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(t)}function dge(t){var e=YKe(t,"string");return typeof e=="symbol"?e:e+""}function pa(t){"@babel/helpers - typeof";return pa=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(e){return typeof e}:function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},pa(t)}function UB(t,e){if(t){if(typeof t=="string")return EB(t,e);var r={}.toString.call(t).slice(8,-1);return r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set"?Array.from(t):r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?EB(t,e):void 0}}function pT(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function mT(){if(zpe)return XO;zpe=1;function t(e){var r=typeof e;return e!=null&&(r=="object"||r=="function")}return o(t,"isObject"),XO=t,XO}function gQe(){if(Gpe)return KO;Gpe=1;var t=typeof GE=="object"&&GE&&GE.Object===Object&&GE;return KO=t,KO}function SS(){if(Vpe)return QO;Vpe=1;var t=gQe(),e=typeof self=="object"&&self&&self.Object===Object&&self,r=t||e||Function("return this")();return QO=r,QO}function yQe(){if(qpe)return ZO;qpe=1;var t=SS(),e=o(function(){return t.Date.now()},"now");return ZO=e,ZO}function vQe(){if(Wpe)return JO;Wpe=1;var t=/\s/;function e(r){for(var i=r.length;i--&&t.test(r.charAt(i)););return i}return o(e,"trimmedEndIndex"),JO=e,JO}function xQe(){if(Upe)return eP;Upe=1;var t=vQe(),e=/^\s+/;function r(i){return i&&i.slice(0,t(i)+1).replace(e,"")}return o(r,"baseTrim"),eP=r,eP}function jB(){if(Hpe)return tP;Hpe=1;var t=SS(),e=t.Symbol;return tP=e,tP}function bQe(){if(Ype)return rP;Ype=1;var t=jB(),e=Object.prototype,r=e.hasOwnProperty,i=e.toString,n=t?t.toStringTag:void 0;function a(s){var l=r.call(s,n),u=s[n];try{s[n]=void 0;var h=!0}catch{}var f=i.call(s);return h&&(l?s[n]=u:delete s[n]),f}return o(a,"getRawTag"),rP=a,rP}function TQe(){if(jpe)return iP;jpe=1;var t=Object.prototype,e=t.toString;function r(i){return e.call(i)}return o(r,"objectToString"),iP=r,iP}function kge(){if(Xpe)return nP;Xpe=1;var t=jB(),e=bQe(),r=TQe(),i="[object Null]",n="[object Undefined]",a=t?t.toStringTag:void 0;function s(l){return l==null?l===void 0?n:i:a&&a in Object(l)?e(l):r(l)}return o(s,"baseGetTag"),nP=s,nP}function kQe(){if(Kpe)return aP;Kpe=1;function t(e){return e!=null&&typeof e=="object"}return o(t,"isObjectLike"),aP=t,aP}function gT(){if(Qpe)return sP;Qpe=1;var t=kge(),e=kQe(),r="[object Symbol]";function i(n){return typeof n=="symbol"||e(n)&&t(n)==r}return o(i,"isSymbol"),sP=i,sP}function CQe(){if(Zpe)return oP;Zpe=1;var t=xQe(),e=mT(),r=gT(),i=NaN,n=/^[-+]0x[0-9a-f]+$/i,a=/^0b[01]+$/i,s=/^0o[0-7]+$/i,l=parseInt;function u(h){if(typeof h=="number")return h;if(r(h))return i;if(e(h)){var f=typeof h.valueOf=="function"?h.valueOf():h;h=e(f)?f+"":f}if(typeof h!="string")return h===0?h:+h;h=t(h);var d=a.test(h);return d||s.test(h)?l(h.slice(2),d?2:8):n.test(h)?i:+h}return o(u,"toNumber"),oP=u,oP}function wQe(){if(Jpe)return lP;Jpe=1;var t=mT(),e=yQe(),r=CQe(),i="Expected a function",n=Math.max,a=Math.min;function s(l,u,h){var f,d,p,m,g,y,v=0,x=!1,b=!1,T=!0;if(typeof l!="function")throw new TypeError(i);u=r(u)||0,t(h)&&(x=!!h.leading,b="maxWait"in h,p=b?n(r(h.maxWait)||0,u):p,T="trailing"in h?!!h.trailing:T);function w(_){var D=f,N=d;return f=d=void 0,v=_,m=l.apply(N,D),m}o(w,"invokeFunc");function k(_){return v=_,g=setTimeout(S,u),x?w(_):m}o(k,"leadingEdge");function C(_){var D=_-y,N=_-v,R=u-D;return b?a(R,p-N):R}o(C,"remainingWait");function E(_){var D=_-y,N=_-v;return y===void 0||D>=u||D<0||b&&N>=p}o(E,"shouldInvoke");function S(){var _=e();if(E(_))return L(_);g=setTimeout(S,C(_))}o(S,"timerExpired");function L(_){return g=void 0,T&&f?w(_):(f=d=void 0,m)}o(L,"trailingEdge");function M(){g!==void 0&&clearTimeout(g),v=0,f=y=d=g=void 0}o(M,"cancel");function I(){return g===void 0?m:L(e())}o(I,"flush");function A(){var _=e(),D=E(_);if(f=arguments,d=this,y=_,D){if(g===void 0)return k(y);if(b)return clearTimeout(g),g=setTimeout(S,u),w(y)}return g===void 0&&(g=setTimeout(S,u)),m}return o(A,"debounced"),A.cancel=M,A.flush=I,A}return o(s,"debounce"),lP=s,lP}function DQe(t,e,r,i,n){var a=n*Math.PI/180,s=Math.cos(a)*(t-r)-Math.sin(a)*(e-i)+r,l=Math.sin(a)*(t-r)+Math.cos(a)*(e-i)+i;return{x:s,y:l}}function RQe(t,e,r){if(r===0)return t;var i=(e.x1+e.x2)/2,n=(e.y1+e.y2)/2,a=e.w/e.h,s=1/a,l=DQe(t.x,t.y,i,n,r),u=LQe(l.x,l.y,i,n,a,s);return{x:u.x,y:u.y}}function VQe(){return n0e||(n0e=1,(function(t,e){(function(){var r,i,n,a,s,l,u,h,f,d,p,m,g,y,v;n=Math.floor,d=Math.min,i=o(function(x,b){return xb?1:0},"defaultCmp"),f=o(function(x,b,T,w,k){var C;if(T==null&&(T=0),k==null&&(k=i),T<0)throw new Error("lo must be non-negative");for(w==null&&(w=x.length);TM;0<=M?L++:L--)S.push(L);return S}).apply(this).reverse(),E=[],w=0,k=C.length;wI;0<=I?++S:--S)A.push(s(x,T));return A},"nsmallest"),y=o(function(x,b,T,w){var k,C,E;for(w==null&&(w=i),k=x[T];T>b;){if(E=T-1>>1,C=x[E],w(k,C)<0){x[T]=C,T=E;continue}break}return x[T]=k},"_siftdown"),v=o(function(x,b,T){var w,k,C,E,S;for(T==null&&(T=i),k=x.length,S=b,C=x[b],w=2*b+1;w-1}return o(e,"listCacheHas"),BP=e,BP}function OJe(){if(U0e)return FP;U0e=1;var t=NS();function e(r,i){var n=this.__data__,a=t(n,r);return a<0?(++this.size,n.push([r,i])):n[a][1]=i,this}return o(e,"listCacheSet"),FP=e,FP}function PJe(){if(H0e)return $P;H0e=1;var t=RJe(),e=NJe(),r=IJe(),i=MJe(),n=OJe();function a(s){var l=-1,u=s==null?0:s.length;for(this.clear();++l-1&&i%1==0&&i0;){var f=n.shift();e(f),a.add(f.id()),l&&i(n,a,f)}return t}function Jge(t,e,r){if(r.isParent())for(var i=r._private.children,n=0;n0&&arguments[0]!==void 0?arguments[0]:jet,e=arguments.length>1?arguments[1]:void 0,r=0;r0?A=D:I=D;while(Math.abs(_)>s&&++N=a?b(M,N):R===0?N:w(M,I,I+h)}o(k,"getTForX");var C=!1;function E(){C=!0,(t!==e||r!==i)&&T()}o(E,"precompute");var S=o(function(I){return C||E(),t===e&&r===i?I:I===0?0:I===1?1:v(k(I),e,i)},"f");S.getControlPoints=function(){return[{x:t,y:e},{x:r,y:i}]};var L="generateBezier("+[t,e,r,i]+")";return S.toString=function(){return L},S}function Ome(t,e,r,i,n){if(i===1||e===r)return r;var a=n(e,r,i);return t==null||((t.roundValue||t.color)&&(a=Math.round(a)),t.min!==void 0&&(a=Math.max(a,t.min)),t.max!==void 0&&(a=Math.min(a,t.max))),a}function Pme(t,e){return t.pfValue!=null||t.value!=null?t.pfValue!=null&&(e==null||e.type.units!=="%")?t.pfValue:t.value:t}function ry(t,e,r,i,n){var a=n!=null?n.type:null;r<0?r=0:r>1&&(r=1);var s=Pme(t,n),l=Pme(e,n);if(Mt(s)&&Mt(l))return Ome(a,s,l,r,i);if(qi(s)&&qi(l)){for(var u=[],h=0;h0?(m==="spring"&&g.push(s.duration),s.easingImpl=aS[m].apply(null,g)):s.easingImpl=aS[m]}var y=s.easingImpl,v;if(s.duration===0?v=1:v=(r-u)/s.duration,s.applying&&(v=s.progress),v<0?v=0:v>1&&(v=1),s.delay==null){var x=s.startPosition,b=s.position;if(b&&n&&!t.locked()){var T={};Hb(x.x,b.x)&&(T.x=ry(x.x,b.x,v,y)),Hb(x.y,b.y)&&(T.y=ry(x.y,b.y,v,y)),t.position(T)}var w=s.startPan,k=s.pan,C=a.pan,E=k!=null&&i;E&&(Hb(w.x,k.x)&&(C.x=ry(w.x,k.x,v,y)),Hb(w.y,k.y)&&(C.y=ry(w.y,k.y,v,y)),t.emit("pan"));var S=s.startZoom,L=s.zoom,M=L!=null&&i;M&&(Hb(S,L)&&(a.zoom=aT(a.minZoom,ry(S,L,v,y),a.maxZoom)),t.emit("zoom")),(E||M)&&t.emit("viewport");var I=s.style;if(I&&I.length>0&&n){for(var A=0;A=0;E--){var S=C[E];S()}C.splice(0,C.length)},"callbacks"),b=m.length-1;b>=0;b--){var T=m[b],w=T._private;if(w.stopped){m.splice(b,1),w.hooked=!1,w.playing=!1,w.started=!1,x(w.frames);continue}!w.playing&&!w.applying||(w.playing&&w.applying&&(w.applying=!1),w.started||ltt(f,T,t),ott(f,T,t,d),w.applying&&(w.applying=!1),x(w.frames),w.step!=null&&w.step(t),T.completed()&&(m.splice(b,1),w.hooked=!1,w.playing=!1,w.started=!1,x(w.completes)),y=!0)}return!d&&m.length===0&&g.length===0&&i.push(f),y}o(n,"stepOne");for(var a=!1,s=0;s0?e.notify("draw",r):e.notify("draw")),r.unmerge(i),e.emit("step")}function y1e(t){this.options=yr({},gtt,ytt,t)}function v1e(t){this.options=yr({},vtt,t)}function x1e(t){this.options=yr({},xtt,t)}function zS(t){this.options=yr({},btt,t),this.options.layout=this;var e=this.options.eles.nodes(),r=this.options.eles.edges(),i=r.filter(function(n){var a=n.source().data("id"),s=n.target().data("id"),l=e.some(function(h){return h.data("id")===a}),u=e.some(function(h){return h.data("id")===s});return!l||!u});this.options.eles=this.options.eles.not(i)}function C1e(t){this.options=yr({},Ott,t)}function uF(t){this.options=yr({},Ptt,t)}function w1e(t){this.options=yr({},Btt,t)}function E1e(t){this.options=yr({},Ftt,t)}function S1e(t){this.options=t,this.notifications=0}function D1e(t,e){e.radius===0?t.lineTo(e.cx,e.cy):t.arc(e.cx,e.cy,e.radius,e.startAngle,e.endAngle,e.counterClockwise)}function fF(t,e,r,i){var n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0;return i===0||e.radius===0?{cx:e.x,cy:e.y,radius:0,startX:e.x,startY:e.y,stopX:e.x,stopY:e.y,startAngle:void 0,endAngle:void 0,counterClockwise:void 0}:(Gtt(t,e,r,i,n),{cx:PB,cy:BB,radius:X0,startX:A1e,startY:_1e,stopX:FB,stopY:$B,startAngle:Bu.ang+Math.PI/2*Q0,endAngle:Gl.ang-Math.PI/2*Q0,counterClockwise:lS})}function L1e(t){var e=[];if(t!=null){for(var r=0;r5&&arguments[5]!==void 0?arguments[5]:5,s=Math.min(a,i/2,n/2);t.beginPath(),t.moveTo(e+s,r),t.lineTo(e+i-s,r),t.quadraticCurveTo(e+i,r,e+i,r+s),t.lineTo(e+i,r+n-s),t.quadraticCurveTo(e+i,r+n,e+i-s,r+n),t.lineTo(e+s,r+n),t.quadraticCurveTo(e,r+n,e,r+n-s),t.lineTo(e,r+s),t.quadraticCurveTo(e,r,e+s,r),t.closePath()}function ige(t,e,r){var i=t.createShader(e);if(t.shaderSource(i,r),t.compileShader(i),!t.getShaderParameter(i,t.COMPILE_STATUS))throw new Error(t.getShaderInfoLog(i));return i}function Lrt(t,e,r){var i=ige(t,t.VERTEX_SHADER,e),n=ige(t,t.FRAGMENT_SHADER,r),a=t.createProgram();if(t.attachShader(a,i),t.attachShader(a,n),t.linkProgram(a),!t.getProgramParameter(a,t.LINK_STATUS))throw new Error("Could not initialize shaders");return a}function Rrt(t,e,r){r===void 0&&(r=e);var i=t.makeOffscreenCanvas(e,r),n=i.context=i.getContext("2d");return i.clear=function(){return n.clearRect(0,0,i.width,i.height)},i.clear(),i}function mF(t){var e=t.pixelRatio,r=t.cy.zoom(),i=t.cy.pan();return{zoom:r*e,pan:{x:i.x*e,y:i.y*e}}}function Nrt(t){var e=t.pixelRatio,r=t.cy.zoom();return r*e}function Irt(t,e,r,i,n){var a=i*r+e.x,s=n*r+e.y;return s=Math.round(t.canvasHeight-s),[a,s]}function Mrt(t){return t.pstyle("background-fill").value!=="solid"||t.pstyle("background-image").strValue!=="none"?!1:t.pstyle("border-width").value===0||t.pstyle("border-opacity").value===0?!0:t.pstyle("border-style").value==="solid"}function Ort(t,e){if(t.length!==e.length)return!1;for(var r=0;r>0&255)/255,r[1]=(t>>8&255)/255,r[2]=(t>>16&255)/255,r[3]=(t>>24&255)/255,r}function Prt(t){return t[0]+(t[1]<<8)+(t[2]<<16)+(t[3]<<24)}function Brt(t,e){var r=t.createTexture();return r.buffer=function(i){t.bindTexture(t.TEXTURE_2D,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR_MIPMAP_NEAREST),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,i),t.generateMipmap(t.TEXTURE_2D),t.bindTexture(t.TEXTURE_2D,null)},r.deleteTexture=function(){t.deleteTexture(r)},r}function q1e(t,e){switch(e){case"float":return[1,t.FLOAT,4];case"vec2":return[2,t.FLOAT,4];case"vec3":return[3,t.FLOAT,4];case"vec4":return[4,t.FLOAT,4];case"int":return[1,t.INT,4];case"ivec2":return[2,t.INT,4]}}function W1e(t,e,r){switch(e){case t.FLOAT:return new Float32Array(r);case t.INT:return new Int32Array(r)}}function Frt(t,e,r,i,n,a){switch(e){case t.FLOAT:return new Float32Array(r.buffer,a*i,n);case t.INT:return new Int32Array(r.buffer,a*i,n)}}function $rt(t,e,r,i){var n=q1e(t,e),a=ea(n,2),s=a[0],l=a[1],u=W1e(t,l,i),h=t.createBuffer();return t.bindBuffer(t.ARRAY_BUFFER,h),t.bufferData(t.ARRAY_BUFFER,u,t.STATIC_DRAW),l===t.FLOAT?t.vertexAttribPointer(r,s,l,!1,0,0):l===t.INT&&t.vertexAttribIPointer(r,s,l,0,0),t.enableVertexAttribArray(r),t.bindBuffer(t.ARRAY_BUFFER,null),h}function Pu(t,e,r,i){var n=q1e(t,r),a=ea(n,3),s=a[0],l=a[1],u=a[2],h=W1e(t,l,e*s),f=s*u,d=t.createBuffer();t.bindBuffer(t.ARRAY_BUFFER,d),t.bufferData(t.ARRAY_BUFFER,e*f,t.DYNAMIC_DRAW),t.enableVertexAttribArray(i),l===t.FLOAT?t.vertexAttribPointer(i,s,l,!1,f,0):l===t.INT&&t.vertexAttribIPointer(i,s,l,f,0),t.vertexAttribDivisor(i,1),t.bindBuffer(t.ARRAY_BUFFER,null);for(var p=new Array(e),m=0;mF1e?(rit(t),e.call(t,a)):(iit(t),j1e(t,a,tT.SCREEN)))}}{var r=t.matchCanvasSize;t.matchCanvasSize=function(a){r.call(t,a),t.pickingFrameBuffer.setFramebufferAttachmentSizes(t.canvasWidth,t.canvasHeight),t.pickingFrameBuffer.needsDraw=!0}}t.findNearestElements=function(a,s,l,u){return cit(t,a,s)};{var i=t.invalidateCachedZSortedEles;t.invalidateCachedZSortedEles=function(){i.call(t),t.pickingFrameBuffer.needsDraw=!0}}{var n=t.notify;t.notify=function(a,s){n.call(t,a,s),a==="viewport"||a==="bounds"?t.pickingFrameBuffer.needsDraw=!0:a==="background"&&t.drawing.invalidate(s,{type:"node-body"})}}}function rit(t){var e=t.data.contexts[t.WEBGL];e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}function iit(t){var e=o(function(i){i.save(),i.setTransform(1,0,0,1,0,0),i.clearRect(0,0,t.canvasWidth,t.canvasHeight),i.restore()},"clear");e(t.data.contexts[t.NODE]),e(t.data.contexts[t.DRAG])}function nit(t){var e=t.canvasWidth,r=t.canvasHeight,i=mF(t),n=i.pan,a=i.zoom,s=xB();uS(s,s,[n.x,n.y]),GB(s,s,[a,a]);var l=xB();qrt(l,e,r);var u=xB();return Vrt(u,l,s),u}function Y1e(t,e){var r=t.canvasWidth,i=t.canvasHeight,n=mF(t),a=n.pan,s=n.zoom;e.setTransform(1,0,0,1,0,0),e.clearRect(0,0,r,i),e.translate(a.x,a.y),e.scale(s,s)}function ait(t,e){t.drawSelectionRectangle(e,function(r){return Y1e(t,r)})}function sit(t){var e=t.data.contexts[t.NODE];e.save(),Y1e(t,e),e.strokeStyle="rgba(0, 0, 0, 0.3)",e.beginPath(),e.moveTo(-1e3,0),e.lineTo(1e3,0),e.stroke(),e.beginPath(),e.moveTo(0,-1e3),e.lineTo(0,1e3),e.stroke(),e.restore()}function oit(t){var e=o(function(n,a,s){for(var l=n.atlasManager.getAtlasCollection(a),u=t.data.contexts[t.NODE],h=l.atlases,f=0;f=0&&w.add(E)}return w}function cit(t,e,r){var i=lit(t,e,r),n=t.getCachedZSortedEles(),a,s,l=Lo(i),u;try{for(l.s();!(u=l.n()).done;){var h=u.value,f=n[h];if(!a&&f.isNode()&&(a=f),!s&&f.isEdge()&&(s=f),a&&s)break}}catch(d){l.e(d)}finally{l.f()}return[a,s].filter(Boolean)}function wB(t,e,r){var i=t.drawing;e+=1,r.isNode()?(i.drawNode(r,e,"node-underlay"),i.drawNode(r,e,"node-body"),i.drawTexture(r,e,"label"),i.drawNode(r,e,"node-overlay")):(i.drawEdgeLine(r,e),i.drawEdgeArrow(r,e,"source"),i.drawEdgeArrow(r,e,"target"),i.drawTexture(r,e,"label"),i.drawTexture(r,e,"edge-source-label"),i.drawTexture(r,e,"edge-target-label"))}function j1e(t,e,r){var i;t.webglDebug&&(i=performance.now());var n=t.drawing,a=0;if(r.screen&&t.data.canvasNeedsRedraw[t.SELECT_BOX]&&ait(t,e),t.data.canvasNeedsRedraw[t.NODE]||r.picking){var s=t.data.contexts[t.WEBGL];r.screen?(s.clearColor(0,0,0,0),s.enable(s.BLEND),s.blendFunc(s.ONE,s.ONE_MINUS_SRC_ALPHA)):s.disable(s.BLEND),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),s.viewport(0,0,s.canvas.width,s.canvas.height);var l=nit(t),u=t.getCachedZSortedEles();if(a=u.length,n.startFrame(l,r),r.screen){for(var h=0;h{"use strict";o(EB,"_arrayLikeToArray");o(zKe,"_arrayWithHoles");o(GKe,"_arrayWithoutHoles");o($d,"_classCallCheck");o(VKe,"_defineProperties");o(zd,"_createClass");o(Lo,"_createForOfIteratorHelper");o(fge,"_defineProperty$1");o(qKe,"_iterableToArray");o(WKe,"_iterableToArrayLimit");o(UKe,"_nonIterableRest");o(HKe,"_nonIterableSpread");o(ea,"_slicedToArray");o(hS,"_toConsumableArray");o(YKe,"_toPrimitive");o(dge,"_toPropertyKey");o(pa,"_typeof");o(UB,"_unsupportedIterableToArray");fa=typeof window>"u"?null:window,Fpe=fa?fa.navigator:null;fa&&fa.document;jKe=pa(""),pge=pa({}),XKe=pa(function(){}),KKe=typeof HTMLElement>"u"?"undefined":pa(HTMLElement),fT=o(function(e){return e&&e.instanceString&&An(e.instanceString)?e.instanceString():null},"instanceStr"),lr=o(function(e){return e!=null&&pa(e)==jKe},"string"),An=o(function(e){return e!=null&&pa(e)===XKe},"fn"),qi=o(function(e){return!il(e)&&(Array.isArray?Array.isArray(e):e!=null&&e instanceof Array)},"array"),si=o(function(e){return e!=null&&pa(e)===pge&&!qi(e)&&e.constructor===Object},"plainObject"),QKe=o(function(e){return e!=null&&pa(e)===pge},"object"),Mt=o(function(e){return e!=null&&pa(e)===pa(1)&&!isNaN(e)},"number"),ZKe=o(function(e){return Mt(e)&&Math.floor(e)===e},"integer"),fS=o(function(e){if(KKe!=="undefined")return e!=null&&e instanceof HTMLElement},"htmlElement"),il=o(function(e){return dT(e)||mge(e)},"elementOrCollection"),dT=o(function(e){return fT(e)==="collection"&&e._private.single},"element"),mge=o(function(e){return fT(e)==="collection"&&!e._private.single},"collection"),HB=o(function(e){return fT(e)==="core"},"core"),gge=o(function(e){return fT(e)==="stylesheet"},"stylesheet"),JKe=o(function(e){return fT(e)==="event"},"event"),Id=o(function(e){return e==null?!0:!!(e===""||e.match(/^\s+$/))},"emptyString"),eQe=o(function(e){return typeof HTMLElement>"u"?!1:e instanceof HTMLElement},"domElement"),tQe=o(function(e){return si(e)&&Mt(e.x1)&&Mt(e.x2)&&Mt(e.y1)&&Mt(e.y2)},"boundingBox"),rQe=o(function(e){return QKe(e)&&An(e.then)},"promise"),iQe=o(function(){return Fpe&&Fpe.userAgent.match(/msie|trident|edge/i)},"ms"),my=o(function(e,r){r||(r=o(function(){if(arguments.length===1)return arguments[0];if(arguments.length===0)return"undefined";for(var a=[],s=0;sr?1:0},"ascending"),uQe=o(function(e,r){return-1*vge(e,r)},"descending"),yr=Object.assign!=null?Object.assign.bind(Object):function(t){for(var e=arguments,r=1;r1&&(v-=1),v<1/6?g+(y-g)*6*v:v<1/2?y:v<2/3?g+(y-g)*(2/3-v)*6:g}o(f,"hue2rgb");var d=new RegExp("^"+sQe+"$").exec(e);if(d){if(i=parseInt(d[1]),i<0?i=(360- -1*i%360)%360:i>360&&(i=i%360),i/=360,n=parseFloat(d[2]),n<0||n>100||(n=n/100,a=parseFloat(d[3]),a<0||a>100)||(a=a/100,s=d[4],s!==void 0&&(s=parseFloat(s),s<0||s>1)))return;if(n===0)l=u=h=Math.round(a*255);else{var p=a<.5?a*(1+n):a+n-a*n,m=2*a-p;l=Math.round(255*f(m,p,i+1/3)),u=Math.round(255*f(m,p,i)),h=Math.round(255*f(m,p,i-1/3))}r=[l,u,h,s]}return r},"hsl2tuple"),dQe=o(function(e){var r,i=new RegExp("^"+nQe+"$").exec(e);if(i){r=[];for(var n=[],a=1;a<=3;a++){var s=i[a];if(s[s.length-1]==="%"&&(n[a]=!0),s=parseFloat(s),n[a]&&(s=s/100*255),s<0||s>255)return;r.push(Math.floor(s))}var l=n[1]||n[2]||n[3],u=n[1]&&n[2]&&n[3];if(l&&!u)return;var h=i[4];if(h!==void 0){if(h=parseFloat(h),h<0||h>1)return;r.push(h)}}return r},"rgb2tuple"),pQe=o(function(e){return mQe[e.toLowerCase()]},"colorname2tuple"),xge=o(function(e){return(qi(e)?e:null)||pQe(e)||hQe(e)||dQe(e)||fQe(e)},"color2tuple"),mQe={transparent:[0,0,0,0],aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],grey:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},bge=o(function(e){for(var r=e.map,i=e.keys,n=i.length,a=0;a1&&arguments[1]!==void 0?arguments[1]:K0,i=r,n;n=e.next(),!n.done;)i=i*wge+n.value|0;return i},"hashIterableInts"),rT=o(function(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:K0;return r*wge+e|0},"hashInt"),iT=o(function(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:oy;return(r<<5)+r+e|0},"hashIntAlt"),AQe=o(function(e,r){return e*2097152+r},"combineHashes"),Ed=o(function(e){return e[0]*2097152+e[1]},"combineHashesArray"),VE=o(function(e,r){return[rT(e[0],r[0]),iT(e[1],r[1])]},"hashArrays"),e0e=o(function(e,r){var i={value:0,done:!1},n=0,a=e.length,s={next:o(function(){return n=0;n--)e[n]===r&&e.splice(n,1)},"removeFromArray"),QB=o(function(e){e.splice(0,e.length)},"clearArray"),BQe=o(function(e,r){for(var i=0;i"u"?"undefined":pa(Set))!==$Qe?Set:zQe,AS=o(function(e,r){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(e===void 0||r===void 0||!HB(e)){mn("An element must have a core reference and parameters set");return}var n=r.group;if(n==null&&(r.data&&r.data.source!=null&&r.data.target!=null?n="edges":n="nodes"),n!=="nodes"&&n!=="edges"){mn("An element must be of type `nodes` or `edges`; you specified `"+n+"`");return}this.length=1,this[0]=this;var a=this._private={cy:e,single:!0,data:r.data||{},position:r.position||{x:0,y:0},autoWidth:void 0,autoHeight:void 0,autoPadding:void 0,compoundBoundsClean:!1,listeners:[],group:n,style:{},rstyle:{},styleCxts:[],styleKeys:{},removed:!0,selected:!!r.selected,selectable:r.selectable===void 0?!0:!!r.selectable,locked:!!r.locked,grabbed:!1,grabbable:r.grabbable===void 0?!0:!!r.grabbable,pannable:r.pannable===void 0?n==="edges":!!r.pannable,active:!1,classes:new vy,animation:{current:[],queue:[]},rscratch:{},scratch:r.scratch||{},edges:[],children:[],parent:r.parent&&r.parent.isNode()?r.parent:null,traversalCache:{},backgrounding:!1,bbCache:null,bbCacheShift:{x:0,y:0},bodyBounds:null,overlayBounds:null,labelBounds:{all:null,source:null,target:null,main:null},arrowBounds:{source:null,target:null,"mid-source":null,"mid-target":null}};if(a.position.x==null&&(a.position.x=0),a.position.y==null&&(a.position.y=0),r.renderedPosition){var s=r.renderedPosition,l=e.pan(),u=e.zoom();a.position={x:(s.x-l.x)/u,y:(s.y-l.y)/u}}var h=[];qi(r.classes)?h=r.classes:lr(r.classes)&&(h=r.classes.split(/\s+/));for(var f=0,d=h.length;f0;){var C=b.pop(),E=v(C),S=C.id();if(p[S]=E,E!==1/0)for(var L=C.neighborhood().intersect(g),M=0;M0)for(O.unshift(B);d[z];){var F=d[z];O.unshift(F.edge),O.unshift(F.node),$=F.node,z=$.id()}return l.spawn(O)},"pathTo")}},"dijkstra")},YQe={kruskal:o(function(e){e=e||function(T){return 1};for(var r=this.byGroup(),i=r.nodes,n=r.edges,a=i.length,s=new Array(a),l=i,u=o(function(w){for(var k=0;k0;){if(k(),E++,w===f){for(var S=[],L=a,M=f,I=x[M];S.unshift(L),I!=null&&S.unshift(I),L=v[M],L!=null;)M=L.id(),I=x[M];return{found:!0,distance:d[w],path:this.spawn(S),steps:E}}m[w]=!0;for(var A=T._private.edges,_=0;_I&&(g[M]=I,b[M]=L,T[M]=k),!a){var A=L*f+S;!a&&g[A]>I&&(g[A]=I,b[A]=S,T[A]=k)}}}for(var _=0;_1&&arguments[1]!==void 0?arguments[1]:s,$e=T(Te),pe=[],Je=$e;;){if(Je==null)return r.spawn();var Ce=b(Je),Fe=Ce.edge,Ue=Ce.pred;if(pe.unshift(Je[0]),Je.same(De)&&pe.length>0)break;Fe!=null&&pe.unshift(Fe),Je=Ue}return u.spawn(pe)},"pathTo"),C=0;C=0;f--){var d=h[f],p=d[1],m=d[2];(r[p]===l&&r[m]===u||r[p]===u&&r[m]===l)&&h.splice(f,1)}for(var g=0;gn;){var a=Math.floor(Math.random()*r.length);r=tZe(a,e,r),i--}return r},"contractUntil"),rZe={kargerStein:o(function(){var e=this,r=this.byGroup(),i=r.nodes,n=r.edges;n.unmergeBy(function(O){return O.isLoop()});var a=i.length,s=n.length,l=Math.ceil(Math.pow(Math.log(a)/Math.LN2,2)),u=Math.floor(a/eZe);if(a<2){mn("At least 2 nodes are required for Karger-Stein algorithm");return}for(var h=[],f=0;f1&&arguments[1]!==void 0?arguments[1]:0,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length,n=1/0,a=r;a1&&arguments[1]!==void 0?arguments[1]:0,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length,n=-1/0,a=r;a1&&arguments[1]!==void 0?arguments[1]:0,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length,n=0,a=0,s=r;s1&&arguments[1]!==void 0?arguments[1]:0,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:e.length,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,s=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!0;n?e=e.slice(r,i):(i0&&e.splice(0,r));for(var l=0,u=e.length-1;u>=0;u--){var h=e[u];s?isFinite(h)||(e[u]=-1/0,l++):e.splice(u,1)}a&&e.sort(function(p,m){return p-m});var f=e.length,d=Math.floor(f/2);return f%2!==0?e[d+1+l]:(e[d-1+l]+e[d+l])/2},"median"),lZe=o(function(e){return Math.PI*e/180},"deg2rad"),qE=o(function(e,r){return Math.atan2(r,e)-Math.PI/2},"getAngleFromDisp"),ZB=Math.log2||function(t){return Math.log(t)/Math.log(2)},JB=o(function(e){return e>0?1:e<0?-1:0},"signum"),em=o(function(e,r){return Math.sqrt(j0(e,r))},"dist"),j0=o(function(e,r){var i=r.x-e.x,n=r.y-e.y;return i*i+n*n},"sqdist"),cZe=o(function(e){for(var r=e.length,i=0,n=0;n=e.x1&&e.y2>=e.y1)return{x1:e.x1,y1:e.y1,x2:e.x2,y2:e.y2,w:e.x2-e.x1,h:e.y2-e.y1};if(e.w!=null&&e.h!=null&&e.w>=0&&e.h>=0)return{x1:e.x1,y1:e.y1,x2:e.x1+e.w,y2:e.y1+e.h,w:e.w,h:e.h}}},"makeBoundingBox"),hZe=o(function(e){return{x1:e.x1,x2:e.x2,w:e.w,y1:e.y1,y2:e.y2,h:e.h}},"copyBoundingBox"),fZe=o(function(e){e.x1=1/0,e.y1=1/0,e.x2=-1/0,e.y2=-1/0,e.w=0,e.h=0},"clearBoundingBox"),dZe=o(function(e,r){e.x1=Math.min(e.x1,r.x1),e.x2=Math.max(e.x2,r.x2),e.w=e.x2-e.x1,e.y1=Math.min(e.y1,r.y1),e.y2=Math.max(e.y2,r.y2),e.h=e.y2-e.y1},"updateBoundingBox"),Nge=o(function(e,r,i){e.x1=Math.min(e.x1,r),e.x2=Math.max(e.x2,r),e.w=e.x2-e.x1,e.y1=Math.min(e.y1,i),e.y2=Math.max(e.y2,i),e.h=e.y2-e.y1},"expandBoundingBoxByPoint"),tS=o(function(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return e.x1-=r,e.x2+=r,e.y1-=r,e.y2+=r,e.w=e.x2-e.x1,e.h=e.y2-e.y1,e},"expandBoundingBox"),rS=o(function(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[0],i,n,a,s;if(r.length===1)i=n=a=s=r[0];else if(r.length===2)i=a=r[0],s=n=r[1];else if(r.length===4){var l=ea(r,4);i=l[0],n=l[1],a=l[2],s=l[3]}return e.x1-=s,e.x2+=n,e.y1-=i,e.y2+=a,e.w=e.x2-e.x1,e.h=e.y2-e.y1,e},"expandBoundingBoxSides"),s0e=o(function(e,r){e.x1=r.x1,e.y1=r.y1,e.x2=r.x2,e.y2=r.y2,e.w=e.x2-e.x1,e.h=e.y2-e.y1},"assignBoundingBox"),eF=o(function(e,r){return!(e.x1>r.x2||r.x1>e.x2||e.x2r.y2||r.y1>e.y2)},"boundingBoxesIntersect"),Dd=o(function(e,r,i){return e.x1<=r&&r<=e.x2&&e.y1<=i&&i<=e.y2},"inBoundingBox"),o0e=o(function(e,r){return Dd(e,r.x,r.y)},"pointInBoundingBox"),Ige=o(function(e,r){return Dd(e,r.x1,r.y1)&&Dd(e,r.x2,r.y2)},"boundingBoxInBoundingBox"),pZe=(fP=Math.hypot)!==null&&fP!==void 0?fP:function(t,e){return Math.sqrt(t*t+e*e)};o(mZe,"inflatePolygon");o(gZe,"miterBox");Mge=o(function(e,r,i,n,a,s,l){var u=arguments.length>7&&arguments[7]!==void 0?arguments[7]:"auto",h=u==="auto"?Od(a,s):u,f=a/2,d=s/2;h=Math.min(h,f,d);var p=h!==f,m=h!==d,g;if(p){var y=i-f+h-l,v=n-d-l,x=i+f-h+l,b=v;if(g=Ld(e,r,i,n,y,v,x,b,!1),g.length>0)return g}if(m){var T=i+f+l,w=n-d+h-l,k=T,C=n+d-h+l;if(g=Ld(e,r,i,n,T,w,k,C,!1),g.length>0)return g}if(p){var E=i-f+h-l,S=n+d+l,L=i+f-h+l,M=S;if(g=Ld(e,r,i,n,E,S,L,M,!1),g.length>0)return g}if(m){var I=i-f-l,A=n-d+h-l,_=I,D=n+d-h+l;if(g=Ld(e,r,i,n,I,A,_,D,!1),g.length>0)return g}var N;{var R=i-f+h,B=n-d+h;if(N=Kb(e,r,i,n,R,B,h+l),N.length>0&&N[0]<=R&&N[1]<=B)return[N[0],N[1]]}{var O=i+f-h,$=n-d+h;if(N=Kb(e,r,i,n,O,$,h+l),N.length>0&&N[0]>=O&&N[1]<=$)return[N[0],N[1]]}{var z=i+f-h,F=n+d-h;if(N=Kb(e,r,i,n,z,F,h+l),N.length>0&&N[0]>=z&&N[1]>=F)return[N[0],N[1]]}{var V=i-f+h,H=n+d-h;if(N=Kb(e,r,i,n,V,H,h+l),N.length>0&&N[0]<=V&&N[1]>=H)return[N[0],N[1]]}return[]},"roundRectangleIntersectLine"),yZe=o(function(e,r,i,n,a,s,l){var u=l,h=Math.min(i,a),f=Math.max(i,a),d=Math.min(n,s),p=Math.max(n,s);return h-u<=e&&e<=f+u&&d-u<=r&&r<=p+u},"inLineVicinity"),vZe=o(function(e,r,i,n,a,s,l,u,h){var f={x1:Math.min(i,l,a)-h,x2:Math.max(i,l,a)+h,y1:Math.min(n,u,s)-h,y2:Math.max(n,u,s)+h};return!(ef.x2||rf.y2)},"inBezierVicinity"),xZe=o(function(e,r,i,n){i-=n;var a=r*r-4*e*i;if(a<0)return[];var s=Math.sqrt(a),l=2*e,u=(-r+s)/l,h=(-r-s)/l;return[u,h]},"solveQuadratic"),bZe=o(function(e,r,i,n,a){var s=1e-5;e===0&&(e=s),r/=e,i/=e,n/=e;var l,u,h,f,d,p,m,g;if(u=(3*i-r*r)/9,h=-(27*n)+r*(9*i-2*(r*r)),h/=54,l=u*u*u+h*h,a[1]=0,m=r/3,l>0){d=h+Math.sqrt(l),d=d<0?-Math.pow(-d,1/3):Math.pow(d,1/3),p=h-Math.sqrt(l),p=p<0?-Math.pow(-p,1/3):Math.pow(p,1/3),a[0]=-m+d+p,m+=(d+p)/2,a[4]=a[2]=-m,m=Math.sqrt(3)*(-p+d)/2,a[3]=m,a[5]=-m;return}if(a[5]=a[3]=0,l===0){g=h<0?-Math.pow(-h,1/3):Math.pow(h,1/3),a[0]=-m+2*g,a[4]=a[2]=-(g+m);return}u=-u,f=u*u*u,f=Math.acos(h/Math.sqrt(f)),g=2*Math.sqrt(u),a[0]=-m+g*Math.cos(f/3),a[2]=-m+g*Math.cos((f+2*Math.PI)/3),a[4]=-m+g*Math.cos((f+4*Math.PI)/3)},"solveCubic"),TZe=o(function(e,r,i,n,a,s,l,u){var h=1*i*i-4*i*a+2*i*l+4*a*a-4*a*l+l*l+n*n-4*n*s+2*n*u+4*s*s-4*s*u+u*u,f=9*i*a-3*i*i-3*i*l-6*a*a+3*a*l+9*n*s-3*n*n-3*n*u-6*s*s+3*s*u,d=3*i*i-6*i*a+i*l-i*e+2*a*a+2*a*e-l*e+3*n*n-6*n*s+n*u-n*r+2*s*s+2*s*r-u*r,p=1*i*a-i*i+i*e-a*e+n*s-n*n+n*r-s*r,m=[];bZe(h,f,d,p,m);for(var g=1e-7,y=[],v=0;v<6;v+=2)Math.abs(m[v+1])=0&&m[v]<=1&&y.push(m[v]);y.push(1),y.push(0);for(var x=-1,b,T,w,k=0;k=0?wh?(e-a)*(e-a)+(r-s)*(r-s):f-p},"sqdistToFiniteLine"),Do=o(function(e,r,i){for(var n,a,s,l,u,h=0,f=0;f=e&&e>=s||n<=e&&e<=s)u=(e-n)/(s-n)*(l-a)+a,u>r&&h++;else continue;return h%2!==0},"pointInsidePolygonPoints"),Qh=o(function(e,r,i,n,a,s,l,u,h){var f=new Array(i.length),d;u[0]!=null?(d=Math.atan(u[1]/u[0]),u[0]<0?d=d+Math.PI/2:d=-d-Math.PI/2):d=u;for(var p=Math.cos(-d),m=Math.sin(-d),g=0;g0){var v=gS(f,-h);y=mS(v)}else y=f;return Do(e,r,y)},"pointInsidePolygon"),CZe=o(function(e,r,i,n,a,s,l,u){for(var h=new Array(i.length*2),f=0;f=0&&v<=1&&b.push(v),x>=0&&x<=1&&b.push(x),b.length===0)return[];var T=b[0]*u[0]+e,w=b[0]*u[1]+r;if(b.length>1){if(b[0]==b[1])return[T,w];var k=b[1]*u[0]+e,C=b[1]*u[1]+r;return[T,w,k,C]}else return[T,w]},"intersectLineCircle"),dP=o(function(e,r,i){return r<=e&&e<=i||i<=e&&e<=r?e:e<=r&&r<=i||i<=r&&r<=e?r:i},"midOfThree"),Ld=o(function(e,r,i,n,a,s,l,u,h){var f=e-a,d=i-e,p=l-a,m=r-s,g=n-r,y=u-s,v=p*m-y*f,x=d*m-g*f,b=y*d-p*g;if(b!==0){var T=v/b,w=x/b,k=.001,C=0-k,E=1+k;return C<=T&&T<=E&&C<=w&&w<=E?[e+T*d,r+T*g]:h?[e+T*d,r+T*g]:[]}else return v===0||x===0?dP(e,i,l)===l?[l,u]:dP(e,i,a)===a?[a,s]:dP(a,l,i)===i?[i,n]:[]:[]},"finiteLinesIntersect"),EZe=o(function(e,r,i,n,a){var s=[],l=n/2,u=a/2,h=r,f=i;s.push({x:h+l*e[0],y:f+u*e[1]});for(var d=1;d0){var y=gS(d,-u);m=mS(y)}else m=d}else m=i;for(var v,x,b,T,w=0;w2){for(var g=[f[0],f[1]],y=Math.pow(g[0]-e,2)+Math.pow(g[1]-r,2),v=1;vf&&(f=w)},"set"),get:o(function(T){return h[T]},"get")},p=0;p0?N=D.edgesTo(_)[0]:N=_.edgesTo(D)[0];var R=n(N);_=_.id(),E[_]>E[I]+R&&(E[_]=E[I]+R,S.nodes.indexOf(_)<0?S.push(_):S.updateItem(_),C[_]=0,k[_]=[]),E[_]==E[I]+R&&(C[_]=C[_]+C[I],k[_].push(I))}else for(var B=0;B0;){for(var F=w.pop(),V=0;V0&&l.push(i[u]);l.length!==0&&a.push(n.collection(l))}return a},"assign"),zZe=o(function(e,r){for(var i=0;i5&&arguments[5]!==void 0?arguments[5]:qZe,l=n,u,h,f=0;f=2?qb(e,r,i,0,f0e,WZe):qb(e,r,i,0,h0e)},"euclidean"),squaredEuclidean:o(function(e,r,i){return qb(e,r,i,0,f0e)},"squaredEuclidean"),manhattan:o(function(e,r,i){return qb(e,r,i,0,h0e)},"manhattan"),max:o(function(e,r,i){return qb(e,r,i,-1/0,UZe)},"max")};gy["squared-euclidean"]=gy.squaredEuclidean;gy.squaredeuclidean=gy.squaredEuclidean;o(DS,"clusteringDistance");HZe=rs({k:2,m:2,sensitivityThreshold:1e-4,distance:"euclidean",maxIterations:10,attributes:[],testMode:!1,testCentroids:null}),rF=o(function(e){return HZe(e)},"setOptions"),yS=o(function(e,r,i,n,a){var s=a!=="kMedoids",l=s?function(d){return i[d]}:function(d){return n[d](i)},u=o(function(p){return n[p](r)},"getQ"),h=i,f=r;return DS(e,n.length,l,u,h,f)},"getDist"),mP=o(function(e,r,i){for(var n=i.length,a=new Array(n),s=new Array(n),l=new Array(r),u=null,h=0;hi)return!1}return!0},"haveMatricesConverged"),XZe=o(function(e,r,i){for(var n=0;nl&&(l=r[h][f],u=f);a[u].push(e[h])}for(var d=0;d=a.threshold||a.mode==="dendrogram"&&e.length===1)return!1;var g=r[s],y=r[n[s]],v;a.mode==="dendrogram"?v={left:g,right:y,key:g.key}:v={value:g.value.concat(y.value),key:g.key},e[g.index]=v,e.splice(y.index,1),r[g.key]=v;for(var x=0;xi[y.key][b.key]&&(u=i[y.key][b.key])):a.linkage==="max"?(u=i[g.key][b.key],i[g.key][b.key]0&&n.push(a);return n},"findExemplars"),v0e=o(function(e,r,i){for(var n=[],a=0;al&&(s=h,l=r[a*e+h])}s>0&&n.push(s)}for(var f=0;fh&&(u=f,h=d)}i[a]=s[u]}return n=v0e(e,r,i),n},"assign"),x0e=o(function(e){for(var r=this.cy(),i=this.nodes(),n=oJe(e),a={},s=0;s=I?(A=I,I=D,_=N):D>A&&(A=D);for(var R=0;R0?1:0;E[L%n.minIterations*l+V]=H,F+=H}if(F>0&&(L>=n.minIterations-1||L==n.maxIterations-1)){for(var X=0,W=0;W1||C>1)&&(l=!0),d[T]=[],b.outgoers().forEach(function(S){S.isEdge()&&d[T].push(S.id())})}else p[T]=[void 0,b.target().id()]}):s.forEach(function(b){var T=b.id();if(b.isNode()){var w=b.degree(!0);w%2&&(u?h?l=!0:h=T:u=T),d[T]=[],b.connectedEdges().forEach(function(k){return d[T].push(k.id())})}else p[T]=[b.source().id(),b.target().id()]});var m={found:!1,trail:void 0};if(l)return m;if(h&&u)if(a){if(f&&h!=f)return m;f=h}else{if(f&&h!=f&&u!=f)return m;f||(f=h)}else f||(f=s[0].id());var g=o(function(T){for(var w=T,k=[T],C,E,S;d[w].length;)C=d[w].shift(),E=p[C][0],S=p[C][1],w!=S?(d[S]=d[S].filter(function(L){return L!=C}),w=S):!a&&w!=E&&(d[E]=d[E].filter(function(L){return L!=C}),w=E),k.unshift(C),k.unshift(w);return k},"walk"),y=[],v=[];for(v=g(f);v.length!=1;)d[v[0]].length==0?(y.unshift(s.getElementById(v.shift())),y.unshift(s.getElementById(v.shift()))):v=g(v.shift()).concat(v);y.unshift(s.getElementById(v.shift()));for(var x in d)if(d[x].length)return m;return m.found=!0,m.trail=this.spawn(y,!0),m},"hierholzer")},UE=o(function(){var e=this,r={},i=0,n=0,a=[],s=[],l={},u=o(function(p,m){for(var g=s.length-1,y=[],v=e.spawn();s[g].x!=p||s[g].y!=m;)y.push(s.pop().edge),g--;y.push(s.pop().edge),y.forEach(function(x){var b=x.connectedNodes().intersection(e);v.merge(x),b.forEach(function(T){var w=T.id(),k=T.connectedEdges().intersection(e);v.merge(T),r[w].cutVertex?v.merge(k.filter(function(C){return C.isLoop()})):v.merge(k)})}),a.push(v)},"buildComponent"),h=o(function(p,m,g){p===g&&(n+=1),r[m]={id:i,low:i++,cutVertex:!1};var y=e.getElementById(m).connectedEdges().intersection(e);if(y.size()===0)a.push(e.spawn(e.getElementById(m)));else{var v,x,b,T;y.forEach(function(w){v=w.source().id(),x=w.target().id(),b=v===m?x:v,b!==g&&(T=w.id(),l[T]||(l[T]=!0,s.push({x:m,y:b,edge:w})),b in r?r[m].low=Math.min(r[m].low,r[b].id):(h(p,b,m),r[m].low=Math.min(r[m].low,r[b].low),r[m].id<=r[b].low&&(r[m].cutVertex=!0,u(m,b))))})}},"biconnectedSearch");e.forEach(function(d){if(d.isNode()){var p=d.id();p in r||(n=0,h(p,p),r[p].cutVertex=n>1)}});var f=Object.keys(r).filter(function(d){return r[d].cutVertex}).map(function(d){return e.getElementById(d)});return{cut:e.spawn(f),components:a}},"hopcroftTarjanBiconnected"),mJe={hopcroftTarjanBiconnected:UE,htbc:UE,htb:UE,hopcroftTarjanBiconnectedComponents:UE},HE=o(function(){var e=this,r={},i=0,n=[],a=[],s=e.spawn(e),l=o(function(h){a.push(h),r[h]={index:i,low:i++,explored:!1};var f=e.getElementById(h).connectedEdges().intersection(e);if(f.forEach(function(y){var v=y.target().id();v!==h&&(v in r||l(v),r[v].explored||(r[h].low=Math.min(r[h].low,r[v].low)))}),r[h].index===r[h].low){for(var d=e.spawn();;){var p=a.pop();if(d.merge(e.getElementById(p)),r[p].low=r[h].index,r[p].explored=!0,p===h)break}var m=d.edgesWith(d),g=d.merge(m);n.push(g),s=s.difference(g)}},"stronglyConnectedSearch");return e.forEach(function(u){if(u.isNode()){var h=u.id();h in r||l(h)}}),{cut:s,components:n}},"tarjanStronglyConnected"),gJe={tarjanStronglyConnected:HE,tsc:HE,tscc:HE,tarjanStronglyConnectedComponents:HE},Gge={};[nT,HQe,YQe,XQe,QQe,JQe,rZe,DZe,fy,dy,_B,VZe,tJe,aJe,fJe,pJe,mJe,gJe].forEach(function(t){yr(Gge,t)});Vge=0,qge=1,Wge=2,Ic=o(function(e){if(!(this instanceof Ic))return new Ic(e);this.id="Thenable/1.0.7",this.state=Vge,this.fulfillValue=void 0,this.rejectReason=void 0,this.onFulfilled=[],this.onRejected=[],this.proxy={then:this.then.bind(this)},typeof e=="function"&&e.call(this,this.fulfill.bind(this),this.reject.bind(this))},"api");Ic.prototype={fulfill:o(function(e){return b0e(this,qge,"fulfillValue",e)},"fulfill"),reject:o(function(e){return b0e(this,Wge,"rejectReason",e)},"reject"),then:o(function(e,r){var i=this,n=new Ic;return i.onFulfilled.push(k0e(e,n,"fulfill")),i.onRejected.push(k0e(r,n,"reject")),Uge(i),n.proxy},"then")};b0e=o(function(e,r,i,n){return e.state===Vge&&(e.state=r,e[i]=n,Uge(e)),e},"deliver"),Uge=o(function(e){e.state===qge?T0e(e,"onFulfilled",e.fulfillValue):e.state===Wge&&T0e(e,"onRejected",e.rejectReason)},"execute"),T0e=o(function(e,r,i){if(e[r].length!==0){var n=e[r];e[r]=[];var a=o(function(){for(var l=0;l0},"animatedImpl")},"animated"),clearQueue:o(function(){return o(function(){var r=this,i=r.length!==void 0,n=i?r:[r],a=this._private.cy||this;if(!a.styleEnabled())return this;for(var s=0;s0&&this.spawn(n).updateStyle().emit("class"),r},"classes"),addClass:o(function(e){return this.toggleClass(e,!0)},"addClass"),hasClass:o(function(e){var r=this[0];return r!=null&&r._private.classes.has(e)},"hasClass"),toggleClass:o(function(e,r){qi(e)||(e=e.match(/\S+/g)||[]);for(var i=this,n=r===void 0,a=[],s=0,l=i.length;s0&&this.spawn(a).updateStyle().emit("class"),i},"toggleClass"),removeClass:o(function(e){return this.toggleClass(e,!1)},"removeClass"),flashClass:o(function(e,r){var i=this;if(r==null)r=250;else if(r===0)return i;return i.addClass(e),setTimeout(function(){i.removeClass(e)},r),i},"flashClass")};iS.className=iS.classNames=iS.classes;ai={metaChar:"[\\!\\\"\\#\\$\\%\\&\\'\\(\\)\\*\\+\\,\\.\\/\\:\\;\\<\\=\\>\\?\\@\\[\\]\\^\\`\\{\\|\\}\\~]",comparatorOp:"=|\\!=|>|>=|<|<=|\\$=|\\^=|\\*=",boolOp:"\\?|\\!|\\^",string:`"(?:\\\\"|[^"])*"|'(?:\\\\'|[^'])*'`,number:da,meta:"degree|indegree|outdegree",separator:"\\s*,\\s*",descendant:"\\s+",child:"\\s+>\\s+",subject:"\\$",group:"node|edge|\\*",directedEdge:"\\s+->\\s+",undirectedEdge:"\\s+<->\\s+"};ai.variable="(?:[\\w-.]|(?:\\\\"+ai.metaChar+"))+";ai.className="(?:[\\w-]|(?:\\\\"+ai.metaChar+"))+";ai.value=ai.string+"|"+ai.number;ai.id=ai.variable;(function(){var t,e,r;for(t=ai.comparatorOp.split("|"),r=0;r=0)&&e!=="="&&(ai.comparatorOp+="|\\!"+e)})();Bi=o(function(){return{checks:[]}},"newQuery"),Wt={GROUP:0,COLLECTION:1,FILTER:2,DATA_COMPARE:3,DATA_EXIST:4,DATA_BOOL:5,META_COMPARE:6,STATE:7,ID:8,CLASS:9,UNDIRECTED_EDGE:10,DIRECTED_EDGE:11,NODE_SOURCE:12,NODE_TARGET:13,NODE_NEIGHBOR:14,CHILD:15,DESCENDANT:16,PARENT:17,ANCESTOR:18,COMPOUND_SPLIT:19,TRUE:20},NB=[{selector:":selected",matches:o(function(e){return e.selected()},"matches")},{selector:":unselected",matches:o(function(e){return!e.selected()},"matches")},{selector:":selectable",matches:o(function(e){return e.selectable()},"matches")},{selector:":unselectable",matches:o(function(e){return!e.selectable()},"matches")},{selector:":locked",matches:o(function(e){return e.locked()},"matches")},{selector:":unlocked",matches:o(function(e){return!e.locked()},"matches")},{selector:":visible",matches:o(function(e){return e.visible()},"matches")},{selector:":hidden",matches:o(function(e){return!e.visible()},"matches")},{selector:":transparent",matches:o(function(e){return e.transparent()},"matches")},{selector:":grabbed",matches:o(function(e){return e.grabbed()},"matches")},{selector:":free",matches:o(function(e){return!e.grabbed()},"matches")},{selector:":removed",matches:o(function(e){return e.removed()},"matches")},{selector:":inside",matches:o(function(e){return!e.removed()},"matches")},{selector:":grabbable",matches:o(function(e){return e.grabbable()},"matches")},{selector:":ungrabbable",matches:o(function(e){return!e.grabbable()},"matches")},{selector:":animated",matches:o(function(e){return e.animated()},"matches")},{selector:":unanimated",matches:o(function(e){return!e.animated()},"matches")},{selector:":parent",matches:o(function(e){return e.isParent()},"matches")},{selector:":childless",matches:o(function(e){return e.isChildless()},"matches")},{selector:":child",matches:o(function(e){return e.isChild()},"matches")},{selector:":orphan",matches:o(function(e){return e.isOrphan()},"matches")},{selector:":nonorphan",matches:o(function(e){return e.isChild()},"matches")},{selector:":compound",matches:o(function(e){return e.isNode()?e.isParent():e.source().isParent()||e.target().isParent()},"matches")},{selector:":loop",matches:o(function(e){return e.isLoop()},"matches")},{selector:":simple",matches:o(function(e){return e.isSimple()},"matches")},{selector:":active",matches:o(function(e){return e.active()},"matches")},{selector:":inactive",matches:o(function(e){return!e.active()},"matches")},{selector:":backgrounding",matches:o(function(e){return e.backgrounding()},"matches")},{selector:":nonbackgrounding",matches:o(function(e){return!e.backgrounding()},"matches")}].sort(function(t,e){return uQe(t.selector,e.selector)}),pet=(function(){for(var t={},e,r=0;r0&&f.edgeCount>0)return Di("The selector `"+e+"` is invalid because it uses both a compound selector and an edge selector"),!1;if(f.edgeCount>1)return Di("The selector `"+e+"` is invalid because it uses multiple edge selectors"),!1;f.edgeCount===1&&Di("The selector `"+e+"` is deprecated. Edge selectors do not take effect on changes to source and target nodes after an edge is added, for performance reasons. Use a class or data selector on edges instead, updating the class or data of an edge when your app detects a change in source or target nodes.")}return!0},"parse"),bet=o(function(){if(this.toStringCache!=null)return this.toStringCache;for(var e=o(function(f){return f??""},"clean"),r=o(function(f){return lr(f)?'"'+f+'"':e(f)},"cleanVal"),i=o(function(f){return" "+f+" "},"space"),n=o(function(f,d){var p=f.type,m=f.value;switch(p){case Wt.GROUP:{var g=e(m);return g.substring(0,g.length-1)}case Wt.DATA_COMPARE:{var y=f.field,v=f.operator;return"["+y+i(e(v))+r(m)+"]"}case Wt.DATA_BOOL:{var x=f.operator,b=f.field;return"["+e(x)+b+"]"}case Wt.DATA_EXIST:{var T=f.field;return"["+T+"]"}case Wt.META_COMPARE:{var w=f.operator,k=f.field;return"[["+k+i(e(w))+r(m)+"]]"}case Wt.STATE:return m;case Wt.ID:return"#"+m;case Wt.CLASS:return"."+m;case Wt.PARENT:case Wt.CHILD:return a(f.parent,d)+i(">")+a(f.child,d);case Wt.ANCESTOR:case Wt.DESCENDANT:return a(f.ancestor,d)+" "+a(f.descendant,d);case Wt.COMPOUND_SPLIT:{var C=a(f.left,d),E=a(f.subject,d),S=a(f.right,d);return C+(C.length>0?" ":"")+E+S}case Wt.TRUE:return""}},"checkToString"),a=o(function(f,d){return f.checks.reduce(function(p,m,g){return p+(d===f&&g===0?"$":"")+n(m,d)},"")},"queryToString"),s="",l=0;l1&&l=0&&(r=r.replace("!",""),d=!0),r.indexOf("@")>=0&&(r=r.replace("@",""),f=!0),(a||l||f)&&(u=!a&&!s?"":""+e,h=""+i),f&&(e=u=u.toLowerCase(),i=h=h.toLowerCase()),r){case"*=":n=u.indexOf(h)>=0;break;case"$=":n=u.indexOf(h,u.length-h.length)>=0;break;case"^=":n=u.indexOf(h)===0;break;case"=":n=e===i;break;case">":p=!0,n=e>i;break;case">=":p=!0,n=e>=i;break;case"<":p=!0,n=e1&&arguments[1]!==void 0?arguments[1]:!0;return sF(this,t,e,Jge)};o(e1e,"addParent");yy.forEachUp=function(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return sF(this,t,e,e1e)};o(Det,"addParentAndChildren");yy.forEachUpAndDown=function(t){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return sF(this,t,e,Det)};yy.ancestors=yy.parents;oT=t1e={data:_i.data({field:"data",bindingEvent:"data",allowBinding:!0,allowSetting:!0,settingEvent:"data",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,immutableKeys:{id:!0,source:!0,target:!0,parent:!0},updateStyle:!0}),removeData:_i.removeData({field:"data",event:"data",triggerFnName:"trigger",triggerEvent:!0,immutableKeys:{id:!0,source:!0,target:!0,parent:!0},updateStyle:!0}),scratch:_i.data({field:"scratch",bindingEvent:"scratch",allowBinding:!0,allowSetting:!0,settingEvent:"scratch",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeScratch:_i.removeData({field:"scratch",event:"scratch",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0}),rscratch:_i.data({field:"rscratch",allowBinding:!1,allowSetting:!0,settingTriggersEvent:!1,allowGetting:!0}),removeRscratch:_i.removeData({field:"rscratch",triggerEvent:!1}),id:o(function(){var e=this[0];if(e)return e._private.data.id},"id")};oT.attr=oT.data;oT.removeAttr=oT.removeData;Let=t1e,MS={};o(dB,"defineDegreeFunction");yr(MS,{degree:dB(function(t,e){return e.source().same(e.target())?2:1}),indegree:dB(function(t,e){return e.target().same(t)?1:0}),outdegree:dB(function(t,e){return e.source().same(t)?1:0})});o(ty,"defineDegreeBoundsFunction");yr(MS,{minDegree:ty("degree",function(t,e){return te}),minIndegree:ty("indegree",function(t,e){return te}),minOutdegree:ty("outdegree",function(t,e){return te})});yr(MS,{totalDegree:o(function(e){for(var r=0,i=this.nodes(),n=0;n0,p=d;d&&(f=f[0]);var m=p?f.position():{x:0,y:0};r!==void 0?h.position(e,r+m[e]):a!==void 0&&h.position({x:a.x+m.x,y:a.y+m.y})}else{var g=i.position(),y=l?i.parent():null,v=y&&y.length>0,x=v;v&&(y=y[0]);var b=x?y.position():{x:0,y:0};return a={x:g.x-b.x,y:g.y-b.y},e===void 0?a:a[e]}else if(!s)return;return this},"relativePosition")};Nc.modelPosition=Nc.point=Nc.position;Nc.modelPositions=Nc.points=Nc.positions;Nc.renderedPoint=Nc.renderedPosition;Nc.relativePoint=Nc.relativePosition;Ret=r1e;py=Gd={};Gd.renderedBoundingBox=function(t){var e=this.boundingBox(t),r=this.cy(),i=r.zoom(),n=r.pan(),a=e.x1*i+n.x,s=e.x2*i+n.x,l=e.y1*i+n.y,u=e.y2*i+n.y;return{x1:a,x2:s,y1:l,y2:u,w:s-a,h:u-l}};Gd.dirtyCompoundBoundsCache=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,e=this.cy();return!e.styleEnabled()||!e.hasCompoundNodes()?this:(this.forEachUp(function(r){if(r.isParent()){var i=r._private;i.compoundBoundsClean=!1,i.bbCache=null,t||r.emitAndNotify("bounds")}}),this)};Gd.updateCompoundBounds=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,e=this.cy();if(!e.styleEnabled()||!e.hasCompoundNodes())return this;if(!t&&e.batching())return this;function r(s){if(!s.isParent())return;var l=s._private,u=s.children(),h=s.pstyle("compound-sizing-wrt-labels").value==="include",f={width:{val:s.pstyle("min-width").pfValue,left:s.pstyle("min-width-bias-left"),right:s.pstyle("min-width-bias-right")},height:{val:s.pstyle("min-height").pfValue,top:s.pstyle("min-height-bias-top"),bottom:s.pstyle("min-height-bias-bottom")}},d=u.boundingBox({includeLabels:h,includeOverlays:!1,useCache:!1}),p=l.position;(d.w===0||d.h===0)&&(d={w:s.pstyle("width").pfValue,h:s.pstyle("height").pfValue},d.x1=p.x-d.w/2,d.x2=p.x+d.w/2,d.y1=p.y-d.h/2,d.y2=p.y+d.h/2);function m(L,M,I){var A=0,_=0,D=M+I;return L>0&&D>0&&(A=M/D*L,_=I/D*L),{biasDiff:A,biasComplementDiff:_}}o(m,"computeBiasValues");function g(L,M,I,A){if(I.units==="%")switch(A){case"width":return L>0?I.pfValue*L:0;case"height":return M>0?I.pfValue*M:0;case"average":return L>0&&M>0?I.pfValue*(L+M)/2:0;case"min":return L>0&&M>0?L>M?I.pfValue*M:I.pfValue*L:0;case"max":return L>0&&M>0?L>M?I.pfValue*L:I.pfValue*M:0;default:return 0}else return I.units==="px"?I.pfValue:0}o(g,"computePaddingValues");var y=f.width.left.value;f.width.left.units==="px"&&f.width.val>0&&(y=y*100/f.width.val);var v=f.width.right.value;f.width.right.units==="px"&&f.width.val>0&&(v=v*100/f.width.val);var x=f.height.top.value;f.height.top.units==="px"&&f.height.val>0&&(x=x*100/f.height.val);var b=f.height.bottom.value;f.height.bottom.units==="px"&&f.height.val>0&&(b=b*100/f.height.val);var T=m(f.width.val-d.w,y,v),w=T.biasDiff,k=T.biasComplementDiff,C=m(f.height.val-d.h,x,b),E=C.biasDiff,S=C.biasComplementDiff;l.autoPadding=g(d.w,d.h,s.pstyle("padding"),s.pstyle("padding-relative-to").value),l.autoWidth=Math.max(d.w,f.width.val),p.x=(-w+d.x1+d.x2+k)/2,l.autoHeight=Math.max(d.h,f.height.val),p.y=(-E+d.y1+d.y2+S)/2}o(r,"update");for(var i=0;ie.x2?n:e.x2,e.y1=ie.y2?a:e.y2,e.w=e.x2-e.x1,e.h=e.y2-e.y1)},"updateBounds"),Ad=o(function(e,r){return r==null?e:Rc(e,r.x1,r.y1,r.x2,r.y2)},"updateBoundsFromBox"),Wb=o(function(e,r,i){return _o(e,r,i)},"prefixedProperty"),YE=o(function(e,r,i){if(!r.cy().headless()){var n=r._private,a=n.rstyle,s=a.arrowWidth/2,l=r.pstyle(i+"-arrow-shape").value,u,h;if(l!=="none"){i==="source"?(u=a.srcX,h=a.srcY):i==="target"?(u=a.tgtX,h=a.tgtY):(u=a.midX,h=a.midY);var f=n.arrowBounds=n.arrowBounds||{},d=f[i]=f[i]||{};d.x1=u-s,d.y1=h-s,d.x2=u+s,d.y2=h+s,d.w=d.x2-d.x1,d.h=d.y2-d.y1,tS(d,1),Rc(e,d.x1,d.y1,d.x2,d.y2)}}},"updateBoundsFromArrow"),pB=o(function(e,r,i){if(!r.cy().headless()){var n;i?n=i+"-":n="";var a=r._private,s=a.rstyle,l=r.pstyle(n+"label").strValue;if(l){var u=r.pstyle("text-halign"),h=r.pstyle("text-valign"),f=Wb(s,"labelWidth",i),d=Wb(s,"labelHeight",i),p=Wb(s,"labelX",i),m=Wb(s,"labelY",i),g=r.pstyle(n+"text-margin-x").pfValue,y=r.pstyle(n+"text-margin-y").pfValue,v=r.isEdge(),x=r.pstyle(n+"text-rotation"),b=r.pstyle("text-outline-width").pfValue,T=r.pstyle("text-border-width").pfValue,w=T/2,k=r.pstyle("text-background-padding").pfValue,C=2,E=d,S=f,L=S/2,M=E/2,I,A,_,D;if(v)I=p-L,A=p+L,_=m-M,D=m+M;else{switch(u.value){case"left":I=p-S,A=p;break;case"center":I=p-L,A=p+L;break;case"right":I=p,A=p+S;break}switch(h.value){case"top":_=m-E,D=m;break;case"center":_=m-M,D=m+M;break;case"bottom":_=m,D=m+E;break}}var N=g-Math.max(b,w)-k-C,R=g+Math.max(b,w)+k+C,B=y-Math.max(b,w)-k-C,O=y+Math.max(b,w)+k+C;I+=N,A+=R,_+=B,D+=O;var $=i||"main",z=a.labelBounds,F=z[$]=z[$]||{};F.x1=I,F.y1=_,F.x2=A,F.y2=D,F.w=A-I,F.h=D-_,F.leftPad=N,F.rightPad=R,F.topPad=B,F.botPad=O;var V=v&&x.strValue==="autorotate",H=x.pfValue!=null&&x.pfValue!==0;if(V||H){var X=V?Wb(a.rstyle,"labelAngle",i):x.pfValue,W=Math.cos(X),Z=Math.sin(X),Y=(I+A)/2,ae=(_+D)/2;if(!v){switch(u.value){case"left":Y=A;break;case"right":Y=I;break}switch(h.value){case"top":ae=D;break;case"bottom":ae=_;break}}var J=o(function(we,Te){return we=we-Y,Te=Te-ae,{x:we*W-Te*Z+Y,y:we*Z+Te*W+ae}},"rotate"),ee=J(I,_),re=J(I,D),te=J(A,_),be=J(A,D);I=Math.min(ee.x,re.x,te.x,be.x),A=Math.max(ee.x,re.x,te.x,be.x),_=Math.min(ee.y,re.y,te.y,be.y),D=Math.max(ee.y,re.y,te.y,be.y)}var de=$+"Rot",Ee=z[de]=z[de]||{};Ee.x1=I,Ee.y1=_,Ee.x2=A,Ee.y2=D,Ee.w=A-I,Ee.h=D-_,Rc(e,I,_,A,D),Rc(a.labelBounds.all,I,_,A,D)}return e}},"updateBoundsFromLabel"),Tme=o(function(e,r){if(!r.cy().headless()){var i=r.pstyle("outline-opacity").value,n=r.pstyle("outline-width").value,a=r.pstyle("outline-offset").value,s=n+a;n1e(e,r,i,s,"outside",s/2)}},"updateBoundsFromOutline"),n1e=o(function(e,r,i,n,a,s){if(!(i===0||n<=0||a==="inside")){var l=r.cy(),u=r.pstyle("shape").value,h=l.renderer().nodeShapes[u],f=r.position(),d=f.x,p=f.y,m=r.width(),g=r.height();if(h.hasMiterBounds){a==="center"&&(n/=2);var y=h.miterBounds(d,p,m,g,n);Ad(e,y)}else s!=null&&s>0&&rS(e,[s,s,s,s])}},"updateBoundsFromMiter"),Net=o(function(e,r){if(!r.cy().headless()){var i=r.pstyle("border-opacity").value,n=r.pstyle("border-width").pfValue,a=r.pstyle("border-position").value;n1e(e,r,i,n,a)}},"updateBoundsFromMiterBorder"),Iet=o(function(e,r){var i=e._private.cy,n=i.styleEnabled(),a=i.headless(),s=Us(),l=e._private,u=e.isNode(),h=e.isEdge(),f,d,p,m,g,y,v=l.rstyle,x=u&&n?e.pstyle("bounds-expansion").pfValue:[0],b=o(function(Ne){return Ne.pstyle("display").value!=="none"},"isDisplayed"),T=!n||b(e)&&(!h||b(e.source())&&b(e.target()));if(T){var w=0,k=0;n&&r.includeOverlays&&(w=e.pstyle("overlay-opacity").value,w!==0&&(k=e.pstyle("overlay-padding").value));var C=0,E=0;n&&r.includeUnderlays&&(C=e.pstyle("underlay-opacity").value,C!==0&&(E=e.pstyle("underlay-padding").value));var S=Math.max(k,E),L=0,M=0;if(n&&(L=e.pstyle("width").pfValue,M=L/2),u&&r.includeNodes){var I=e.position();g=I.x,y=I.y;var A=e.outerWidth(),_=A/2,D=e.outerHeight(),N=D/2;f=g-_,d=g+_,p=y-N,m=y+N,Rc(s,f,p,d,m),n&&Tme(s,e),n&&r.includeOutlines&&!a&&Tme(s,e),n&&Net(s,e)}else if(h&&r.includeEdges)if(n&&!a){var R=e.pstyle("curve-style").strValue;if(f=Math.min(v.srcX,v.midX,v.tgtX),d=Math.max(v.srcX,v.midX,v.tgtX),p=Math.min(v.srcY,v.midY,v.tgtY),m=Math.max(v.srcY,v.midY,v.tgtY),f-=M,d+=M,p-=M,m+=M,Rc(s,f,p,d,m),R==="haystack"){var B=v.haystackPts;if(B&&B.length===2){if(f=B[0].x,p=B[0].y,d=B[1].x,m=B[1].y,f>d){var O=f;f=d,d=O}if(p>m){var $=p;p=m,m=$}Rc(s,f-M,p-M,d+M,m+M)}}else if(R==="bezier"||R==="unbundled-bezier"||_d(R,"segments")||_d(R,"taxi")){var z;switch(R){case"bezier":case"unbundled-bezier":z=v.bezierPts;break;case"segments":case"taxi":case"round-segments":case"round-taxi":z=v.linePts;break}if(z!=null)for(var F=0;Fd){var Y=f;f=d,d=Y}if(p>m){var ae=p;p=m,m=ae}f-=M,d+=M,p-=M,m+=M,Rc(s,f,p,d,m)}if(n&&r.includeEdges&&h&&(YE(s,e,"mid-source"),YE(s,e,"mid-target"),YE(s,e,"source"),YE(s,e,"target")),n){var J=e.pstyle("ghost").value==="yes";if(J){var ee=e.pstyle("ghost-offset-x").pfValue,re=e.pstyle("ghost-offset-y").pfValue;Rc(s,s.x1+ee,s.y1+re,s.x2+ee,s.y2+re)}}var te=l.bodyBounds=l.bodyBounds||{};s0e(te,s),rS(te,x),tS(te,1),n&&(f=s.x1,d=s.x2,p=s.y1,m=s.y2,Rc(s,f-S,p-S,d+S,m+S));var be=l.overlayBounds=l.overlayBounds||{};s0e(be,s),rS(be,x),tS(be,1);var de=l.labelBounds=l.labelBounds||{};de.all!=null?fZe(de.all):de.all=Us(),n&&r.includeLabels&&(r.includeMainLabels&&pB(s,e,null),h&&(r.includeSourceLabels&&pB(s,e,"source"),r.includeTargetLabels&&pB(s,e,"target")))}return s.x1=Vl(s.x1),s.y1=Vl(s.y1),s.x2=Vl(s.x2),s.y2=Vl(s.y2),s.w=Vl(s.x2-s.x1),s.h=Vl(s.y2-s.y1),s.w>0&&s.h>0&&T&&(rS(s,x),tS(s,1)),s},"boundingBoxImpl"),a1e=o(function(e){var r=0,i=o(function(s){return(s?1:0)<=0;l--)s(l);return this};Fd.removeAllListeners=function(){return this.removeListener("*")};Fd.emit=Fd.trigger=function(t,e,r){var i=this.listeners,n=i.length;return this.emitting++,qi(e)||(e=[e]),Xet(this,function(a,s){r!=null&&(i=[{event:s.event,type:s.type,namespace:s.namespace,callback:r}],n=i.length);for(var l=o(function(){var f=i[u];if(f.type===s.type&&(!f.namespace||f.namespace===s.namespace||f.namespace===Yet)&&a.eventMatches(a.context,f,s)){var d=[s];e!=null&&BQe(d,e),a.beforeEmit(a.context,f,s),f.conf&&f.conf.one&&(a.listeners=a.listeners.filter(function(g){return g!==f}));var p=a.callbackContext(a.context,f,s),m=f.callback.apply(p,d);a.afterEmit(a.context,f,s),m===!1&&(s.stopPropagation(),s.preventDefault())}},"_loop2"),u=0;u1&&!s){var l=this.length-1,u=this[l],h=u._private.data.id;this[l]=void 0,this[e]=u,a.set(h,{ele:u,index:e})}return this.length--,this},"unmergeAt"),unmergeOne:o(function(e){e=e[0];var r=this._private,i=e._private.data.id,n=r.map,a=n.get(i);if(!a)return this;var s=a.index;return this.unmergeAt(s),this},"unmergeOne"),unmerge:o(function(e){var r=this._private.cy;if(!e)return this;if(e&&lr(e)){var i=e;e=r.mutableElements().filter(i)}for(var n=0;n=0;r--){var i=this[r];e(i)&&this.unmergeAt(r)}return this},"unmergeBy"),map:o(function(e,r){for(var i=[],n=this,a=0;ai&&(i=u,n=l)}return{value:i,ele:n}},"max"),min:o(function(e,r){for(var i=1/0,n,a=this,s=0;s=0&&a"u"?"undefined":pa(Symbol))!=e&&pa(Symbol.iterator)!=e;r&&(vS[Symbol.iterator]=function(){var i=this,n={value:void 0,done:!1},a=0,s=this.length;return fge({next:o(function(){return a1&&arguments[1]!==void 0?arguments[1]:!0,i=this[0],n=i.cy();if(n.styleEnabled()&&i){i._private.styleDirty&&(i._private.styleDirty=!1,n.style().apply(i));var a=i._private.style[e];return a??(r?n.style().getDefaultProperty(e):null)}},"parsedStyle"),numericStyle:o(function(e){var r=this[0];if(r.cy().styleEnabled()&&r){var i=r.pstyle(e);return i.pfValue!==void 0?i.pfValue:i.value}},"numericStyle"),numericStyleUnits:o(function(e){var r=this[0];if(r.cy().styleEnabled()&&r)return r.pstyle(e).units},"numericStyleUnits"),renderedStyle:o(function(e){var r=this.cy();if(!r.styleEnabled())return this;var i=this[0];if(i)return r.style().getRenderedStyle(i,e)},"renderedStyle"),style:o(function(e,r){var i=this.cy();if(!i.styleEnabled())return this;var n=!1,a=i.style();if(si(e)){var s=e;a.applyBypass(this,s,n),this.emitAndNotify("style")}else if(lr(e))if(r===void 0){var l=this[0];return l?a.getStylePropertyValue(l,e):void 0}else a.applyBypass(this,e,r,n),this.emitAndNotify("style");else if(e===void 0){var u=this[0];return u?a.getRawStyle(u):void 0}return this},"style"),removeStyle:o(function(e){var r=this.cy();if(!r.styleEnabled())return this;var i=!1,n=r.style(),a=this;if(e===void 0)for(var s=0;s0&&e.push(f[0]),e.push(l[0])}return this.spawn(e,!0).filter(t)},"neighborhood"),closedNeighborhood:o(function(e){return this.neighborhood().add(this).filter(e)},"closedNeighborhood"),openNeighborhood:o(function(e){return this.neighborhood(e)},"openNeighborhood")});gs.neighbourhood=gs.neighborhood;gs.closedNeighbourhood=gs.closedNeighborhood;gs.openNeighbourhood=gs.openNeighborhood;yr(gs,{source:ql(o(function(e){var r=this[0],i;return r&&(i=r._private.source||r.cy().collection()),i&&e?i.filter(e):i},"sourceImpl"),"source"),target:ql(o(function(e){var r=this[0],i;return r&&(i=r._private.target||r.cy().collection()),i&&e?i.filter(e):i},"targetImpl"),"target"),sources:Nme({attr:"source"}),targets:Nme({attr:"target"})});o(Nme,"defineSourceFunction");yr(gs,{edgesWith:ql(Ime(),"edgesWith"),edgesTo:ql(Ime({thisIsSrc:!0}),"edgesTo")});o(Ime,"defineEdgesWithFunction");yr(gs,{connectedEdges:ql(function(t){for(var e=[],r=this,i=0;i0);return s},"components"),component:o(function(){var e=this[0];return e.cy().mutableElements().components(e)[0]},"component")});gs.componentsOf=gs.components;ts=o(function(e,r){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!1,n=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(e===void 0){mn("A collection must have a reference to the core");return}var a=new Xh,s=!1;if(!r)r=[];else if(r.length>0&&si(r[0])&&!dT(r[0])){s=!0;for(var l=[],u=new vy,h=0,f=r.length;h0&&arguments[0]!==void 0?arguments[0]:!0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,r=this,i=r.cy(),n=i._private,a=[],s=[],l,u=0,h=r.length;u0){for(var $=l.length===r.length?r:new ts(i,l),z=0;z<$.length;z++){var F=$[z];F.isNode()||(F.parallelEdges().clearTraversalCache(),F.source().clearTraversalCache(),F.target().clearTraversalCache())}var V;n.hasCompoundNodes?V=i.collection().merge($).merge($.connectedNodes()).merge($.parent()):V=$,V.dirtyCompoundBoundsCache().dirtyBoundingBoxCache().updateStyle(t),t?$.emitAndNotify("add"):e&&$.emit("add")}return r};Ji.removed=function(){var t=this[0];return t&&t._private.removed};Ji.inside=function(){var t=this[0];return t&&!t._private.removed};Ji.remove=function(){var t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,r=this,i=[],n={},a=r._private.cy;function s(D){for(var N=D._private.edges,R=0;R0&&(t?I.emitAndNotify("remove"):e&&I.emit("remove"));for(var A=0;Af&&Math.abs(g.v)>f;);return p?function(y){return u[y*(u.length-1)|0]}:h},"springRK4Factory")})(),Zi=o(function(e,r,i,n){var a=att(e,r,i,n);return function(s,l,u){return s+(l-s)*a(u)}},"cubicBezier"),aS={linear:o(function(e,r,i){return e+(r-e)*i},"linear"),ease:Zi(.25,.1,.25,1),"ease-in":Zi(.42,0,1,1),"ease-out":Zi(0,0,.58,1),"ease-in-out":Zi(.42,0,.58,1),"ease-in-sine":Zi(.47,0,.745,.715),"ease-out-sine":Zi(.39,.575,.565,1),"ease-in-out-sine":Zi(.445,.05,.55,.95),"ease-in-quad":Zi(.55,.085,.68,.53),"ease-out-quad":Zi(.25,.46,.45,.94),"ease-in-out-quad":Zi(.455,.03,.515,.955),"ease-in-cubic":Zi(.55,.055,.675,.19),"ease-out-cubic":Zi(.215,.61,.355,1),"ease-in-out-cubic":Zi(.645,.045,.355,1),"ease-in-quart":Zi(.895,.03,.685,.22),"ease-out-quart":Zi(.165,.84,.44,1),"ease-in-out-quart":Zi(.77,0,.175,1),"ease-in-quint":Zi(.755,.05,.855,.06),"ease-out-quint":Zi(.23,1,.32,1),"ease-in-out-quint":Zi(.86,0,.07,1),"ease-in-expo":Zi(.95,.05,.795,.035),"ease-out-expo":Zi(.19,1,.22,1),"ease-in-out-expo":Zi(1,0,0,1),"ease-in-circ":Zi(.6,.04,.98,.335),"ease-out-circ":Zi(.075,.82,.165,1),"ease-in-out-circ":Zi(.785,.135,.15,.86),spring:o(function(e,r,i){if(i===0)return aS.linear;var n=stt(e,r,i);return function(a,s,l){return a+(s-a)*n(l)}},"spring"),"cubic-bezier":Zi};o(Ome,"getEasedValue");o(Pme,"getValue");o(ry,"ease");o(ott,"step$1");o(Hb,"valid");o(ltt,"startAnimation");o(Bme,"stepAll");ctt={animate:_i.animate(),animation:_i.animation(),animated:_i.animated(),clearQueue:_i.clearQueue(),delay:_i.delay(),delayAnimation:_i.delayAnimation(),stop:_i.stop(),addToAnimationPool:o(function(e){var r=this;r.styleEnabled()&&r._private.aniEles.merge(e)},"addToAnimationPool"),stopAnimationLoop:o(function(){this._private.animationsRunning=!1},"stopAnimationLoop"),startAnimationLoop:o(function(){var e=this;if(e._private.animationsRunning=!0,!e.styleEnabled())return;function r(){e._private.animationsRunning&&dS(o(function(a){Bme(a,e),r()},"animationStep"))}o(r,"headlessStep");var i=e.renderer();i&&i.beforeRender?i.beforeRender(o(function(a,s){Bme(s,e)},"rendererAnimationStep"),i.beforeRenderPriorities.animations):r()},"startAnimationLoop")},utt={qualifierCompare:o(function(e,r){return e==null||r==null?e==null&&r==null:e.sameText(r)},"qualifierCompare"),eventMatches:o(function(e,r,i){var n=r.qualifier;return n!=null?e!==i.target&&dT(i.target)&&n.matches(i.target):!0},"eventMatches"),addEventFields:o(function(e,r){r.cy=e,r.target=e},"addEventFields"),callbackContext:o(function(e,r,i){return r.qualifier!=null?i.target:e},"callbackContext")},KE=o(function(e){return lr(e)?new Pd(e):e},"argSelector"),g1e={createEmitter:o(function(){var e=this._private;return e.emitter||(e.emitter=new OS(utt,this)),this},"createEmitter"),emitter:o(function(){return this._private.emitter},"emitter"),on:o(function(e,r,i){return this.emitter().on(e,KE(r),i),this},"on"),removeListener:o(function(e,r,i){return this.emitter().removeListener(e,KE(r),i),this},"removeListener"),removeAllListeners:o(function(){return this.emitter().removeAllListeners(),this},"removeAllListeners"),one:o(function(e,r,i){return this.emitter().one(e,KE(r),i),this},"one"),once:o(function(e,r,i){return this.emitter().one(e,KE(r),i),this},"once"),emit:o(function(e,r){return this.emitter().emit(e,r),this},"emit"),emitAndNotify:o(function(e,r){return this.emit(e),this.notify(e,r),this},"emitAndNotify")};_i.eventAliasesOn(g1e);MB={png:o(function(e){var r=this._private.renderer;return e=e||{},r.png(e)},"png"),jpg:o(function(e){var r=this._private.renderer;return e=e||{},e.bg=e.bg||"#fff",r.jpg(e)},"jpg")};MB.jpeg=MB.jpg;sS={layout:o(function(e){var r=this;if(e==null){mn("Layout options must be specified to make a layout");return}if(e.name==null){mn("A `name` must be specified to make a layout");return}var i=e.name,n=r.extension("layout",i);if(n==null){mn("No such layout `"+i+"` found. Did you forget to import it and `cytoscape.use()` it?");return}var a;lr(e.eles)?a=r.$(e.eles):a=e.eles!=null?e.eles:r.$();var s=new n(yr({},e,{cy:r,eles:a}));return s},"layout")};sS.createLayout=sS.makeLayout=sS.layout;htt={notify:o(function(e,r){var i=this._private;if(this.batching()){i.batchNotifications=i.batchNotifications||{};var n=i.batchNotifications[e]=i.batchNotifications[e]||this.collection();r!=null&&n.merge(r);return}if(i.notificationsEnabled){var a=this.renderer();this.destroyed()||!a||a.notify(e,r)}},"notify"),notifications:o(function(e){var r=this._private;return e===void 0?r.notificationsEnabled:(r.notificationsEnabled=!!e,this)},"notifications"),noNotifications:o(function(e){this.notifications(!1),e(),this.notifications(!0)},"noNotifications"),batching:o(function(){return this._private.batchCount>0},"batching"),startBatch:o(function(){var e=this._private;return e.batchCount==null&&(e.batchCount=0),e.batchCount===0&&(e.batchStyleEles=this.collection(),e.batchNotifications={}),e.batchCount++,this},"startBatch"),endBatch:o(function(){var e=this._private;if(e.batchCount===0)return this;if(e.batchCount--,e.batchCount===0){e.batchStyleEles.updateStyle();var r=this.renderer();Object.keys(e.batchNotifications).forEach(function(i){var n=e.batchNotifications[i];n.empty()?r.notify(i):r.notify(i,n)})}return this},"endBatch"),batch:o(function(e){return this.startBatch(),e(),this.endBatch(),this},"batch"),batchData:o(function(e){var r=this;return this.batch(function(){for(var i=Object.keys(e),n=0;n0;)r.removeChild(r.childNodes[0]);e._private.renderer=null,e.mutableElements().forEach(function(i){var n=i._private;n.rscratch={},n.rstyle={},n.animation.current=[],n.animation.queue=[]})},"destroyRenderer"),onRender:o(function(e){return this.on("render",e)},"onRender"),offRender:o(function(e){return this.off("render",e)},"offRender")};OB.invalidateDimensions=OB.resize;oS={collection:o(function(e,r){return lr(e)?this.$(e):il(e)?e.collection():qi(e)?(r||(r={}),new ts(this,e,r.unique,r.removed)):new ts(this)},"collection"),nodes:o(function(e){var r=this.$(function(i){return i.isNode()});return e?r.filter(e):r},"nodes"),edges:o(function(e){var r=this.$(function(i){return i.isEdge()});return e?r.filter(e):r},"edges"),$:o(function(e){var r=this._private.elements;return e?r.filter(e):r.spawnSelf()},"$"),mutableElements:o(function(){return this._private.elements},"mutableElements")};oS.elements=oS.filter=oS.$;Pa={},Jb="t",dtt="f";Pa.apply=function(t){for(var e=this,r=e._private,i=r.cy,n=i.collection(),a=0;a0;if(p||d&&m){var g=void 0;p&&m||p?g=h.properties:m&&(g=h.mappedProperties);for(var y=0;y1&&(w=1),l.color){var C=i.valueMin[0],E=i.valueMax[0],S=i.valueMin[1],L=i.valueMax[1],M=i.valueMin[2],I=i.valueMax[2],A=i.valueMin[3]==null?1:i.valueMin[3],_=i.valueMax[3]==null?1:i.valueMax[3],D=[Math.round(C+(E-C)*w),Math.round(S+(L-S)*w),Math.round(M+(I-M)*w),Math.round(A+(_-A)*w)];a={bypass:i.bypass,name:i.name,value:D,strValue:"rgb("+D[0]+", "+D[1]+", "+D[2]+")"}}else if(l.number){var N=i.valueMin+(i.valueMax-i.valueMin)*w;a=this.parse(i.name,N,i.bypass,p)}else return!1;if(!a)return y(),!1;a.mapping=i,i=a;break}case s.data:{for(var R=i.field.split("."),B=d.data,O=0;O0&&a>0){for(var l={},u=!1,h=0;h0?t.delayAnimation(s).play().promise().then(T):T()}).then(function(){return t.animation({style:l,duration:a,easing:t.pstyle("transition-timing-function").value,queue:!1}).play().promise()}).then(function(){r.removeBypasses(t,n),t.emitAndNotify("style"),i.transitioning=!1})}else i.transitioning&&(this.removeBypasses(t,n),t.emitAndNotify("style"),i.transitioning=!1)};Pa.checkTrigger=function(t,e,r,i,n,a){var s=this.properties[e],l=n(s);t.removed()||l!=null&&l(r,i,t)&&a(s)};Pa.checkZOrderTrigger=function(t,e,r,i){var n=this;this.checkTrigger(t,e,r,i,function(a){return a.triggersZOrder},function(){n._private.cy.notify("zorder",t)})};Pa.checkBoundsTrigger=function(t,e,r,i){this.checkTrigger(t,e,r,i,function(n){return n.triggersBounds},function(n){t.dirtyCompoundBoundsCache(),t.dirtyBoundingBoxCache()})};Pa.checkConnectedEdgesBoundsTrigger=function(t,e,r,i){this.checkTrigger(t,e,r,i,function(n){return n.triggersBoundsOfConnectedEdges},function(n){t.connectedEdges().forEach(function(a){a.dirtyBoundingBoxCache()})})};Pa.checkParallelEdgesBoundsTrigger=function(t,e,r,i){this.checkTrigger(t,e,r,i,function(n){return n.triggersBoundsOfParallelEdges},function(n){t.parallelEdges().forEach(function(a){a.dirtyBoundingBoxCache()})})};Pa.checkTriggers=function(t,e,r,i){t.dirtyStyleCache(),this.checkZOrderTrigger(t,e,r,i),this.checkBoundsTrigger(t,e,r,i),this.checkConnectedEdgesBoundsTrigger(t,e,r,i),this.checkParallelEdgesBoundsTrigger(t,e,r,i)};bT={};bT.applyBypass=function(t,e,r,i){var n=this,a=[],s=!0;if(e==="*"||e==="**"){if(r!==void 0)for(var l=0;ln.length?i=i.substr(n.length):i=""}o(l,"removeSelAndBlockFromRemaining");function u(){a.length>s.length?a=a.substr(s.length):a=""}for(o(u,"removePropAndValFromRem");;){var h=i.match(/^\s*$/);if(h)break;var f=i.match(/^\s*((?:.|\s)+?)\s*\{((?:.|\s)+?)\}/);if(!f){Di("Halting stylesheet parsing: String stylesheet contains more to parse but no selector and block found in: "+i);break}n=f[0];var d=f[1];if(d!=="core"){var p=new Pd(d);if(p.invalid){Di("Skipping parsing of block: Invalid selector found in string stylesheet: "+d),l();continue}}var m=f[2],g=!1;a=m;for(var y=[];;){var v=a.match(/^\s*$/);if(v)break;var x=a.match(/^\s*(.+?)\s*:\s*(.+?)(?:\s*;|\s*$)/);if(!x){Di("Skipping parsing of block: Invalid formatting of style property and value definitions found in:"+m),g=!0;break}s=x[0];var b=x[1],T=x[2],w=e.properties[b];if(!w){Di("Skipping property: Invalid property name in: "+s),u();continue}var k=r.parse(b,T);if(!k){Di("Skipping property: Invalid property definition in: "+s),u();continue}y.push({name:b,val:T}),u()}if(g){l();break}r.selector(d);for(var C=0;C=7&&e[0]==="d"&&(f=new RegExp(l.data.regex).exec(e))){if(r)return!1;var p=l.data;return{name:t,value:f,strValue:""+e,mapped:p,field:f[1],bypass:r}}else if(e.length>=10&&e[0]==="m"&&(d=new RegExp(l.mapData.regex).exec(e))){if(r||h.multiple)return!1;var m=l.mapData;if(!(h.color||h.number))return!1;var g=this.parse(t,d[4]);if(!g||g.mapped)return!1;var y=this.parse(t,d[5]);if(!y||y.mapped)return!1;if(g.pfValue===y.pfValue||g.strValue===y.strValue)return Di("`"+t+": "+e+"` is not a valid mapper because the output range is zero; converting to `"+t+": "+g.strValue+"`"),this.parse(t,g.strValue);if(h.color){var v=g.value,x=y.value,b=v[0]===x[0]&&v[1]===x[1]&&v[2]===x[2]&&(v[3]===x[3]||(v[3]==null||v[3]===1)&&(x[3]==null||x[3]===1));if(b)return!1}return{name:t,value:d,strValue:""+e,mapped:m,field:d[1],fieldMin:parseFloat(d[2]),fieldMax:parseFloat(d[3]),valueMin:g.value,valueMax:y.value,bypass:r}}}if(h.multiple&&i!=="multiple"){var T;if(u?T=e.split(/\s+/):qi(e)?T=e:T=[e],h.evenMultiple&&T.length%2!==0)return null;for(var w=[],k=[],C=[],E="",S=!1,L=0;L0?" ":"")+M.strValue}return h.validate&&!h.validate(w,k)?null:h.singleEnum&&S?w.length===1&&lr(w[0])?{name:t,value:w[0],strValue:w[0],bypass:r}:null:{name:t,value:w,pfValue:C,strValue:E,bypass:r,units:k}}var I=o(function(){for(var J=0;Jh.max||h.strictMax&&e===h.max))return null;var R={name:t,value:e,strValue:""+e+(A||""),units:A,bypass:r};return h.unitless||A!=="px"&&A!=="em"?R.pfValue=e:R.pfValue=A==="px"||!A?e:this.getEmSizeInPixels()*e,(A==="ms"||A==="s")&&(R.pfValue=A==="ms"?e:1e3*e),(A==="deg"||A==="rad")&&(R.pfValue=A==="rad"?e:lZe(e)),A==="%"&&(R.pfValue=e/100),R}else if(h.propList){var B=[],O=""+e;if(O!=="none"){for(var $=O.split(/\s*,\s*|\s+/),z=0;z<$.length;z++){var F=$[z].trim();n.properties[F]?B.push(F):Di("`"+F+"` is not a valid property name")}if(B.length===0)return null}return{name:t,value:B,strValue:B.length===0?"none":B.join(" "),bypass:r}}else if(h.color){var V=xge(e);return V?{name:t,value:V,pfValue:V,strValue:"rgb("+V[0]+","+V[1]+","+V[2]+")",bypass:r}:null}else if(h.regex||h.regexes){if(h.enums){var H=I();if(H)return H}for(var X=h.regexes?h.regexes:[h.regex],W=0;W0&&l>0&&!isNaN(i.w)&&!isNaN(i.h)&&i.w>0&&i.h>0){u=Math.min((s-2*r)/i.w,(l-2*r)/i.h),u=u>this._private.maxZoom?this._private.maxZoom:u,u=u=i.minZoom&&(i.maxZoom=r),this},"zoomRange"),minZoom:o(function(e){return e===void 0?this._private.minZoom:this.zoomRange({min:e})},"minZoom"),maxZoom:o(function(e){return e===void 0?this._private.maxZoom:this.zoomRange({max:e})},"maxZoom"),getZoomedViewport:o(function(e){var r=this._private,i=r.pan,n=r.zoom,a,s,l=!1;if(r.zoomingEnabled||(l=!0),Mt(e)?s=e:si(e)&&(s=e.level,e.position!=null?a=_S(e.position,n,i):e.renderedPosition!=null&&(a=e.renderedPosition),a!=null&&!r.panningEnabled&&(l=!0)),s=s>r.maxZoom?r.maxZoom:s,s=sr.maxZoom||!r.zoomingEnabled?s=!0:(r.zoom=u,a.push("zoom"))}if(n&&(!s||!e.cancelOnFailedZoom)&&r.panningEnabled){var h=e.pan;Mt(h.x)&&(r.pan.x=h.x,l=!1),Mt(h.y)&&(r.pan.y=h.y,l=!1),l||a.push("pan")}return a.length>0&&(a.push("viewport"),this.emit(a.join(" ")),this.notify("viewport")),this},"viewport"),center:o(function(e){var r=this.getCenterPan(e);return r&&(this._private.pan=r,this.emit("pan viewport"),this.notify("viewport")),this},"center"),getCenterPan:o(function(e,r){if(this._private.panningEnabled){if(lr(e)){var i=e;e=this.mutableElements().filter(i)}else il(e)||(e=this.mutableElements());if(e.length!==0){var n=e.boundingBox(),a=this.width(),s=this.height();r=r===void 0?this._private.zoom:r;var l={x:(a-r*(n.x1+n.x2))/2,y:(s-r*(n.y1+n.y2))/2};return l}}},"getCenterPan"),reset:o(function(){return!this._private.panningEnabled||!this._private.zoomingEnabled?this:(this.viewport({pan:{x:0,y:0},zoom:1}),this)},"reset"),invalidateSize:o(function(){this._private.sizeCache=null},"invalidateSize"),size:o(function(){var e=this._private,r=e.container,i=this;return e.sizeCache=e.sizeCache||(r?(function(){var n=i.window().getComputedStyle(r),a=o(function(l){return parseFloat(n.getPropertyValue(l))},"val");return{width:r.clientWidth-a("padding-left")-a("padding-right"),height:r.clientHeight-a("padding-top")-a("padding-bottom")}})():{width:1,height:1})},"size"),width:o(function(){return this.size().width},"width"),height:o(function(){return this.size().height},"height"),extent:o(function(){var e=this._private.pan,r=this._private.zoom,i=this.renderedExtent(),n={x1:(i.x1-e.x)/r,x2:(i.x2-e.x)/r,y1:(i.y1-e.y)/r,y2:(i.y2-e.y)/r};return n.w=n.x2-n.x1,n.h=n.y2-n.y1,n},"extent"),renderedExtent:o(function(){var e=this.width(),r=this.height();return{x1:0,y1:0,x2:e,y2:r,w:e,h:r}},"renderedExtent"),multiClickDebounceTime:o(function(e){if(e)this._private.multiClickDebounceTime=e;else return this._private.multiClickDebounceTime;return this},"multiClickDebounceTime")};rm.centre=rm.center;rm.autolockNodes=rm.autolock;rm.autoungrabifyNodes=rm.autoungrabify;cT={data:_i.data({field:"data",bindingEvent:"data",allowBinding:!0,allowSetting:!0,settingEvent:"data",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeData:_i.removeData({field:"data",event:"data",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0}),scratch:_i.data({field:"scratch",bindingEvent:"scratch",allowBinding:!0,allowSetting:!0,settingEvent:"scratch",settingTriggersEvent:!0,triggerFnName:"trigger",allowGetting:!0,updateStyle:!0}),removeScratch:_i.removeData({field:"scratch",event:"scratch",triggerFnName:"trigger",triggerEvent:!0,updateStyle:!0})};cT.attr=cT.data;cT.removeAttr=cT.removeData;uT=o(function(e){var r=this;e=yr({},e);var i=e.container;i&&!fS(i)&&fS(i[0])&&(i=i[0]);var n=i?i._cyreg:null;n=n||{},n&&n.cy&&(n.cy.destroy(),n={});var a=n.readies=n.readies||[];i&&(i._cyreg=n),n.cy=r;var s=fa!==void 0&&i!==void 0&&!e.headless,l=e;l.layout=yr({name:s?"grid":"null"},l.layout),l.renderer=yr({name:s?"canvas":"null"},l.renderer);var u=o(function(g,y,v){return y!==void 0?y:v!==void 0?v:g},"defVal"),h=this._private={container:i,ready:!1,options:l,elements:new ts(this),listeners:[],aniEles:new ts(this),data:l.data||{},scratch:{},layout:null,renderer:null,destroyed:!1,notificationsEnabled:!0,minZoom:1e-50,maxZoom:1e50,zoomingEnabled:u(!0,l.zoomingEnabled),userZoomingEnabled:u(!0,l.userZoomingEnabled),panningEnabled:u(!0,l.panningEnabled),userPanningEnabled:u(!0,l.userPanningEnabled),boxSelectionEnabled:u(!0,l.boxSelectionEnabled),autolock:u(!1,l.autolock,l.autolockNodes),autoungrabify:u(!1,l.autoungrabify,l.autoungrabifyNodes),autounselectify:u(!1,l.autounselectify),styleEnabled:l.styleEnabled===void 0?s:l.styleEnabled,zoom:Mt(l.zoom)?l.zoom:1,pan:{x:si(l.pan)&&Mt(l.pan.x)?l.pan.x:0,y:si(l.pan)&&Mt(l.pan.y)?l.pan.y:0},animation:{current:[],queue:[]},hasCompoundNodes:!1,multiClickDebounceTime:u(250,l.multiClickDebounceTime)};this.createEmitter(),this.selectionType(l.selectionType),this.zoomRange({min:l.minZoom,max:l.maxZoom});var f=o(function(g,y){var v=g.some(rQe);if(v)return xy.all(g).then(y);y(g)},"loadExtData");h.styleEnabled&&r.setStyle([]);var d=yr({},l,l.renderer);r.initRenderer(d);var p=o(function(g,y,v){r.notifications(!1);var x=r.mutableElements();x.length>0&&x.remove(),g!=null&&(si(g)||qi(g))&&r.add(g),r.one("layoutready",function(T){r.notifications(!0),r.emit(T),r.one("load",y),r.emitAndNotify("load")}).one("layoutstop",function(){r.one("done",v),r.emit("done")});var b=yr({},r._private.options.layout);b.eles=r.elements(),r.layout(b).run()},"setElesAndLayout");f([l.style,l.elements],function(m){var g=m[0],y=m[1];h.styleEnabled&&r.style().append(g),p(y,function(){r.startAnimationLoop(),h.ready=!0,An(l.ready)&&r.on("ready",l.ready);for(var v=0;v0,l=!!t.boundingBox,u=Us(l?t.boundingBox:structuredClone(e.extent())),h;if(il(t.roots))h=t.roots;else if(qi(t.roots)){for(var f=[],d=0;d0;){var D=_(),N=L(D,I);if(N)D.outgoers().filter(function(De){return De.isNode()&&r.has(De)}).forEach(A);else if(N===null){Di("Detected double maximal shift for node `"+D.id()+"`. Bailing maximal adjustment due to cycle. Use `options.maximal: true` only on DAGs.");break}}}var R=0;if(t.avoidOverlap)for(var B=0;B0&&x[0].length<=3?Fe/2:0),qe=2*Math.PI/x[Je].length*Ce;return Je===0&&x[0].length===1&&(Ue=1),{x:te.x+Ue*Math.cos(qe),y:te.y+Ue*Math.sin(qe)}}else{var Me=x[Je].length,He=Math.max(Me===1?0:l?(u.w-t.padding*2-be.w)/((t.grid?Ee:Me)-1):(u.w-t.padding*2-be.w)/((t.grid?Ee:Me)+1),R),K={x:te.x+(Ce+1-(Me+1)/2)*He,y:te.y+(Je+1-(W+1)/2)*de};return K}},"getPositionTopBottom"),we={downward:0,leftward:90,upward:180,rightward:-90};Object.keys(we).indexOf(t.direction)===-1&&mn("Invalid direction '".concat(t.direction,"' specified for breadthfirst layout. Valid values are: ").concat(Object.keys(we).join(", ")));var Te=o(function($e){return RQe(Ne($e),u,we[t.direction])},"getPosition");return r.nodes().layoutPositions(this,t,Te),this};vtt={fit:!0,padding:30,boundingBox:void 0,avoidOverlap:!0,nodeDimensionsIncludeLabels:!1,spacingFactor:void 0,radius:void 0,startAngle:3/2*Math.PI,sweep:void 0,clockwise:!0,sort:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:o(function(e,r){return!0},"animateFilter"),ready:void 0,stop:void 0,transform:o(function(e,r){return r},"transform")};o(v1e,"CircleLayout");v1e.prototype.run=function(){var t=this.options,e=t,r=t.cy,i=e.eles,n=e.counterclockwise!==void 0?!e.counterclockwise:e.clockwise,a=i.nodes().not(":parent");e.sort&&(a=a.sort(e.sort));for(var s=Us(e.boundingBox?e.boundingBox:{x1:0,y1:0,w:r.width(),h:r.height()}),l={x:s.x1+s.w/2,y:s.y1+s.h/2},u=e.sweep===void 0?2*Math.PI-2*Math.PI/a.length:e.sweep,h=u/Math.max(1,a.length-1),f,d=0,p=0;p1&&e.avoidOverlap){d*=1.75;var x=Math.cos(h)-Math.cos(0),b=Math.sin(h)-Math.sin(0),T=Math.sqrt(d*d/(x*x+b*b));f=Math.max(T,f)}var w=o(function(C,E){var S=e.startAngle+E*h*(n?1:-1),L=f*Math.cos(S),M=f*Math.sin(S),I={x:l.x+L,y:l.y+M};return I},"getPos");return i.nodes().layoutPositions(this,e,w),this};xtt={fit:!0,padding:30,startAngle:3/2*Math.PI,sweep:void 0,clockwise:!0,equidistant:!1,minNodeSpacing:10,boundingBox:void 0,avoidOverlap:!0,nodeDimensionsIncludeLabels:!1,height:void 0,width:void 0,spacingFactor:void 0,concentric:o(function(e){return e.degree()},"concentric"),levelWidth:o(function(e){return e.maxDegree()/4},"levelWidth"),animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:o(function(e,r){return!0},"animateFilter"),ready:void 0,stop:void 0,transform:o(function(e,r){return r},"transform")};o(x1e,"ConcentricLayout");x1e.prototype.run=function(){for(var t=this.options,e=t,r=e.counterclockwise!==void 0?!e.counterclockwise:e.clockwise,i=t.cy,n=e.eles,a=n.nodes().not(":parent"),s=Us(e.boundingBox?e.boundingBox:{x1:0,y1:0,w:i.width(),h:i.height()}),l={x:s.x1+s.w/2,y:s.y1+s.h/2},u=[],h=0,f=0;f0){var k=Math.abs(b[0].value-w.value);k>=v&&(b=[],x.push(b))}b.push(w)}var C=h+e.minNodeSpacing;if(!e.avoidOverlap){var E=x.length>0&&x[0].length>1,S=Math.min(s.w,s.h)/2-C,L=S/(x.length+E?1:0);C=Math.min(C,L)}for(var M=0,I=0;I1&&e.avoidOverlap){var N=Math.cos(D)-Math.cos(0),R=Math.sin(D)-Math.sin(0),B=Math.sqrt(C*C/(N*N+R*R));M=Math.max(B,M)}A.r=M,M+=C}if(e.equidistant){for(var O=0,$=0,z=0;z=t.numIter||(Stt(i,t),i.temperature=i.temperature*t.coolingFactor,i.temperature=t.animationThreshold&&a(),dS(f)}},"frame");f()}else{for(;h;)h=s(u),u++;zme(i,t),l()}return this};zS.prototype.stop=function(){return this.stopped=!0,this.thread&&this.thread.stop(),this.emit("layoutstop"),this};zS.prototype.destroy=function(){return this.thread&&this.thread.stop(),this};Ttt=o(function(e,r,i){for(var n=i.eles.edges(),a=i.eles.nodes(),s=Us(i.boundingBox?i.boundingBox:{x1:0,y1:0,w:e.width(),h:e.height()}),l={isCompound:e.hasCompoundNodes(),layoutNodes:[],idToIndex:{},nodeSize:a.size(),graphSet:[],indexToGraph:[],layoutEdges:[],edgeSize:n.size(),temperature:i.initialTemp,clientWidth:s.w,clientHeight:s.h,boundingBox:s},u=i.eles.components(),h={},f=0;f0){l.graphSet.push(S);for(var f=0;fn.count?0:n.graph},"findLCA"),b1e=o(function(e,r,i,n){var a=n.graphSet[i];if(-10)var d=n.nodeOverlap*f,p=Math.sqrt(l*l+u*u),m=d*l/p,g=d*u/p;else var y=bS(e,l,u),v=bS(r,-1*l,-1*u),x=v.x-y.x,b=v.y-y.y,T=x*x+b*b,p=Math.sqrt(T),d=(e.nodeRepulsion+r.nodeRepulsion)/T,m=d*x/p,g=d*b/p;e.isLocked||(e.offsetX-=m,e.offsetY-=g),r.isLocked||(r.offsetX+=m,r.offsetY+=g)}},"nodeRepulsion"),Dtt=o(function(e,r,i,n){if(i>0)var a=e.maxX-r.minX;else var a=r.maxX-e.minX;if(n>0)var s=e.maxY-r.minY;else var s=r.maxY-e.minY;return a>=0&&s>=0?Math.sqrt(a*a+s*s):0},"nodesOverlap"),bS=o(function(e,r,i){var n=e.positionX,a=e.positionY,s=e.height||1,l=e.width||1,u=i/r,h=s/l,f={};return r===0&&0i?(f.x=n,f.y=a+s/2,f):0r&&-1*h<=u&&u<=h?(f.x=n-l/2,f.y=a-l*i/2/r,f):0=h)?(f.x=n+s*r/2/i,f.y=a+s/2,f):(0>i&&(u<=-1*h||u>=h)&&(f.x=n-s*r/2/i,f.y=a-s/2),f)},"findClippingPoint"),Ltt=o(function(e,r){for(var i=0;ii){var v=r.gravity*m/y,x=r.gravity*g/y;p.offsetX+=v,p.offsetY+=x}}}}},"calculateGravityForces"),Ntt=o(function(e,r){var i=[],n=0,a=-1;for(i.push.apply(i,e.graphSet[0]),a+=e.graphSet[0].length;n<=a;){var s=i[n++],l=e.idToIndex[s],u=e.layoutNodes[l],h=u.children;if(0i)var a={x:i*e/n,y:i*r/n};else var a={x:e,y:r};return a},"limitForce"),k1e=o(function(e,r){var i=e.parentId;if(i!=null){var n=r.layoutNodes[r.idToIndex[i]],a=!1;if((n.maxX==null||e.maxX+n.padRight>n.maxX)&&(n.maxX=e.maxX+n.padRight,a=!0),(n.minX==null||e.minX-n.padLeftn.maxY)&&(n.maxY=e.maxY+n.padBottom,a=!0),(n.minY==null||e.minY-n.padTopx&&(g+=v+r.componentSpacing,m=0,y=0,v=0)}}},"separateComponents"),Ott={fit:!0,padding:30,boundingBox:void 0,avoidOverlap:!0,avoidOverlapPadding:10,nodeDimensionsIncludeLabels:!1,spacingFactor:void 0,condense:!1,rows:void 0,cols:void 0,position:o(function(e){},"position"),sort:void 0,animate:!1,animationDuration:500,animationEasing:void 0,animateFilter:o(function(e,r){return!0},"animateFilter"),ready:void 0,stop:void 0,transform:o(function(e,r){return r},"transform")};o(C1e,"GridLayout");C1e.prototype.run=function(){var t=this.options,e=t,r=t.cy,i=e.eles,n=i.nodes().not(":parent");e.sort&&(n=n.sort(e.sort));var a=Us(e.boundingBox?e.boundingBox:{x1:0,y1:0,w:r.width(),h:r.height()});if(a.h===0||a.w===0)i.nodes().layoutPositions(this,e,function(H){return{x:a.x1,y:a.y1}});else{var s=n.size(),l=Math.sqrt(s*a.h/a.w),u=Math.round(l),h=Math.round(a.w/a.h*l),f=o(function(X){if(X==null)return Math.min(u,h);var W=Math.min(u,h);W==u?u=X:h=X},"small"),d=o(function(X){if(X==null)return Math.max(u,h);var W=Math.max(u,h);W==u?u=X:h=X},"large"),p=e.rows,m=e.cols!=null?e.cols:e.columns;if(p!=null&&m!=null)u=p,h=m;else if(p!=null&&m==null)u=p,h=Math.ceil(s/u);else if(p==null&&m!=null)h=m,u=Math.ceil(s/h);else if(h*u>s){var g=f(),y=d();(g-1)*y>=s?f(g-1):(y-1)*g>=s&&d(y-1)}else for(;h*u=s?d(x+1):f(v+1)}var b=a.w/h,T=a.h/u;if(e.condense&&(b=0,T=0),e.avoidOverlap)for(var w=0;w=h&&(N=0,D++)},"moveToNextCell"),B={},O=0;O(N=kZe(t,e,R[B],R[B+1],R[B+2],R[B+3])))return v(E,N),!0}else if(L.edgeType==="bezier"||L.edgeType==="multibezier"||L.edgeType==="self"||L.edgeType==="compound"){for(var R=L.allpts,B=0;B+5(N=TZe(t,e,R[B],R[B+1],R[B+2],R[B+3],R[B+4],R[B+5])))return v(E,N),!0}for(var O=O||S.source,$=$||S.target,z=n.getArrowWidth(M,I),F=[{name:"source",x:L.arrowStartX,y:L.arrowStartY,angle:L.srcArrowAngle},{name:"target",x:L.arrowEndX,y:L.arrowEndY,angle:L.tgtArrowAngle},{name:"mid-source",x:L.midX,y:L.midY,angle:L.midsrcArrowAngle},{name:"mid-target",x:L.midX,y:L.midY,angle:L.midtgtArrowAngle}],B=0;B0&&(x(O),x($))}o(b,"checkEdge");function T(E,S,L){return _o(E,S,L)}o(T,"preprop");function w(E,S){var L=E._private,M=p,I;S?I=S+"-":I="",E.boundingBox();var A=L.labelBounds[S||"main"],_=E.pstyle(I+"label").value,D=E.pstyle("text-events").strValue==="yes";if(!(!D||!_)){var N=T(L.rscratch,"labelX",S),R=T(L.rscratch,"labelY",S),B=T(L.rscratch,"labelAngle",S),O=E.pstyle(I+"text-margin-x").pfValue,$=E.pstyle(I+"text-margin-y").pfValue,z=A.x1-M-O,F=A.x2+M-O,V=A.y1-M-$,H=A.y2+M-$;if(B){var X=Math.cos(B),W=Math.sin(B),Z=o(function(be,de){return be=be-N,de=de-R,{x:be*X-de*W+N,y:be*W+de*X+R}},"rotate"),Y=Z(z,V),ae=Z(z,H),J=Z(F,V),ee=Z(F,H),re=[Y.x+O,Y.y+$,J.x+O,J.y+$,ee.x+O,ee.y+$,ae.x+O,ae.y+$];if(Do(t,e,re))return v(E),!0}else if(Dd(A,t,e))return v(E),!0}}o(w,"checkLabel");for(var k=s.length-1;k>=0;k--){var C=s[k];C.isNode()?x(C)||w(C):b(C)||w(C)||w(C,"source")||w(C,"target")}return l};nm.getAllInBox=function(t,e,r,i){var n=this.getCachedZSortedEles().interactive,a=this.cy.zoom(),s=2/a,l=[],u=Math.min(t,r),h=Math.max(t,r),f=Math.min(e,i),d=Math.max(e,i);t=u,r=h,e=f,i=d;var p=Us({x1:t,y1:e,x2:r,y2:i}),m=[{x:p.x1,y:p.y1},{x:p.x2,y:p.y1},{x:p.x2,y:p.y2},{x:p.x1,y:p.y2}],g=[[m[0],m[1]],[m[1],m[2]],[m[2],m[3]],[m[3],m[0]]];function y(be,de,Ee){return _o(be,de,Ee)}o(y,"preprop");function v(be,de){var Ee=be._private,Ne=s,we="";be.boundingBox();var Te=Ee.labelBounds.main;if(!Te)return null;var De=y(Ee.rscratch,"labelX",de),$e=y(Ee.rscratch,"labelY",de),pe=y(Ee.rscratch,"labelAngle",de),Je=be.pstyle(we+"text-margin-x").pfValue,Ce=be.pstyle(we+"text-margin-y").pfValue,Fe=Te.x1-Ne-Je,Ue=Te.x2+Ne-Je,qe=Te.y1-Ne-Ce,Me=Te.y2+Ne-Ce;if(pe){var He=Math.cos(pe),K=Math.sin(pe),oe=o(function(ue,G){return ue=ue-De,G=G-$e,{x:ue*He-G*K+De,y:ue*K+G*He+$e}},"rotate");return[oe(Fe,qe),oe(Ue,qe),oe(Ue,Me),oe(Fe,Me)]}else return[{x:Fe,y:qe},{x:Ue,y:qe},{x:Ue,y:Me},{x:Fe,y:Me}]}o(v,"getRotatedLabelBox");function x(be,de,Ee,Ne){function we(Te,De,$e){return($e.y-Te.y)*(De.x-Te.x)>(De.y-Te.y)*($e.x-Te.x)}return o(we,"ccw"),we(be,Ee,Ne)!==we(de,Ee,Ne)&&we(be,de,Ee)!==we(be,de,Ne)}o(x,"doLinesIntersect");for(var b=0;b0?-(Math.PI-e.ang):Math.PI+e.ang},"invertVec"),Gtt=o(function(e,r,i,n,a){if(e!==Ume?Hme(r,e,Bu):ztt(Gl,Bu),Hme(r,i,Gl),qme=Bu.nx*Gl.ny-Bu.ny*Gl.nx,Wme=Bu.nx*Gl.nx-Bu.ny*-Gl.ny,Yh=Math.asin(Math.max(-1,Math.min(1,qme))),Math.abs(Yh)<1e-6){PB=r.x,BB=r.y,X0=ny=0;return}Q0=1,lS=!1,Wme<0?Yh<0?Yh=Math.PI+Yh:(Yh=Math.PI-Yh,Q0=-1,lS=!0):Yh>0&&(Q0=-1,lS=!0),r.radius!==void 0?ny=r.radius:ny=n,U0=Yh/2,QE=Math.min(Bu.len/2,Gl.len/2),a?(Ou=Math.abs(Math.cos(U0)*ny/Math.sin(U0)),Ou>QE?(Ou=QE,X0=Math.abs(Ou*Math.sin(U0)/Math.cos(U0))):X0=ny):(Ou=Math.min(QE,ny),X0=Math.abs(Ou*Math.sin(U0)/Math.cos(U0))),FB=r.x+Gl.nx*Ou,$B=r.y+Gl.ny*Ou,PB=FB-Gl.ny*X0*Q0,BB=$B+Gl.nx*X0*Q0,A1e=r.x+Bu.nx*Ou,_1e=r.y+Bu.ny*Ou,Ume=r},"calcCornerArc");o(D1e,"drawPreparedRoundCorner");o(fF,"getRoundCorner");hT=.01,Vtt=Math.sqrt(2*hT),vs={};vs.findMidptPtsEtc=function(t,e){var r=e.posPts,i=e.intersectionPts,n=e.vectorNormInverse,a,s=t.pstyle("source-endpoint"),l=t.pstyle("target-endpoint"),u=s.units!=null&&l.units!=null,h=o(function(k,C,E,S){var L=S-C,M=E-k,I=Math.sqrt(M*M+L*L);return{x:-L/I,y:M/I}},"recalcVectorNormInverse"),f=t.pstyle("edge-distances").value;switch(f){case"node-position":a=r;break;case"intersection":a=i;break;case"endpoints":{if(u){var d=this.manualEndptToPx(t.source()[0],s),p=ea(d,2),m=p[0],g=p[1],y=this.manualEndptToPx(t.target()[0],l),v=ea(y,2),x=v[0],b=v[1],T={x1:m,y1:g,x2:x,y2:b};n=h(m,g,x,b),a=T}else Di("Edge ".concat(t.id()," has edge-distances:endpoints specified without manual endpoints specified via source-endpoint and target-endpoint. Falling back on edge-distances:intersection (default).")),a=i;break}}return{midptPts:a,vectorNormInverse:n}};vs.findHaystackPoints=function(t){for(var e=0;e0?Math.max(G-se,0):Math.min(G+se,0)},"subDWH"),_=A(M,S),D=A(I,L),N=!1;b===h?x=Math.abs(_)>Math.abs(D)?n:i:b===u||b===l?(x=i,N=!0):(b===a||b===s)&&(x=n,N=!0);var R=x===i,B=R?D:_,O=R?I:M,$=JB(O),z=!1;!(N&&(w||C))&&(b===l&&O<0||b===u&&O>0||b===a&&O>0||b===s&&O<0)&&($*=-1,B=$*Math.abs(B),z=!0);var F;if(w){var V=k<0?1+k:k;F=V*B}else{var H=k<0?B:0;F=H+k*$}var X=o(function(G){return Math.abs(G)=Math.abs(B)},"getIsTooClose"),W=X(F),Z=X(Math.abs(B)-Math.abs(F)),Y=W||Z;if(Y&&!z)if(R){var ae=Math.abs(O)<=p/2,J=Math.abs(M)<=m/2;if(ae){var ee=(f.x1+f.x2)/2,re=f.y1,te=f.y2;r.segpts=[ee,re,ee,te]}else if(J){var be=(f.y1+f.y2)/2,de=f.x1,Ee=f.x2;r.segpts=[de,be,Ee,be]}else r.segpts=[f.x1,f.y2]}else{var Ne=Math.abs(O)<=d/2,we=Math.abs(I)<=g/2;if(Ne){var Te=(f.y1+f.y2)/2,De=f.x1,$e=f.x2;r.segpts=[De,Te,$e,Te]}else if(we){var pe=(f.x1+f.x2)/2,Je=f.y1,Ce=f.y2;r.segpts=[pe,Je,pe,Ce]}else r.segpts=[f.x2,f.y1]}else if(R){var Fe=f.y1+F+(v?p/2*$:0),Ue=f.x1,qe=f.x2;r.segpts=[Ue,Fe,qe,Fe]}else{var Me=f.x1+F+(v?d/2*$:0),He=f.y1,K=f.y2;r.segpts=[Me,He,Me,K]}if(r.isRound){var oe=t.pstyle("taxi-radius").value,U=t.pstyle("radius-type").value[0]==="arc-radius";r.radii=new Array(r.segpts.length/2).fill(oe),r.isArcRadius=new Array(r.segpts.length/2).fill(U)}};vs.tryToCorrectInvalidPoints=function(t,e){var r=t._private.rscratch;if(r.edgeType==="bezier"){var i=e.srcPos,n=e.tgtPos,a=e.srcW,s=e.srcH,l=e.tgtW,u=e.tgtH,h=e.srcShape,f=e.tgtShape,d=e.srcCornerRadius,p=e.tgtCornerRadius,m=e.srcRs,g=e.tgtRs,y=!Mt(r.startX)||!Mt(r.startY),v=!Mt(r.arrowStartX)||!Mt(r.arrowStartY),x=!Mt(r.endX)||!Mt(r.endY),b=!Mt(r.arrowEndX)||!Mt(r.arrowEndY),T=3,w=this.getArrowWidth(t.pstyle("width").pfValue,t.pstyle("arrow-scale").value)*this.arrowShapeWidth,k=T*w,C=em({x:r.ctrlpts[0],y:r.ctrlpts[1]},{x:r.startX,y:r.startY}),E=CO.poolIndex()){var $=B;B=O,O=$}var z=_.srcPos=B.position(),F=_.tgtPos=O.position(),V=_.srcW=B.outerWidth(),H=_.srcH=B.outerHeight(),X=_.tgtW=O.outerWidth(),W=_.tgtH=O.outerHeight(),Z=_.srcShape=r.nodeShapes[e.getNodeShape(B)],Y=_.tgtShape=r.nodeShapes[e.getNodeShape(O)],ae=_.srcCornerRadius=B.pstyle("corner-radius").value==="auto"?"auto":B.pstyle("corner-radius").pfValue,J=_.tgtCornerRadius=O.pstyle("corner-radius").value==="auto"?"auto":O.pstyle("corner-radius").pfValue,ee=_.tgtRs=O._private.rscratch,re=_.srcRs=B._private.rscratch;_.dirCounts={north:0,west:0,south:0,east:0,northwest:0,southwest:0,northeast:0,southeast:0};for(var te=0;te<_.eles.length;te++){var be=_.eles[te],de=be[0]._private.rscratch,Ee=be.pstyle("curve-style").value,Ne=Ee==="unbundled-bezier"||_d(Ee,"segments")||_d(Ee,"taxi"),we=!B.same(be.source());if(!_.calculatedIntersection&&B!==O&&(_.hasBezier||_.hasUnbundled)){_.calculatedIntersection=!0;var Te=Z.intersectLine(z.x,z.y,V,H,F.x,F.y,0,ae,re),De=_.srcIntn=Te,$e=Y.intersectLine(F.x,F.y,X,W,z.x,z.y,0,J,ee),pe=_.tgtIntn=$e,Je=_.intersectionPts={x1:Te[0],x2:$e[0],y1:Te[1],y2:$e[1]},Ce=_.posPts={x1:z.x,x2:F.x,y1:z.y,y2:F.y},Fe=$e[1]-Te[1],Ue=$e[0]-Te[0],qe=Math.sqrt(Ue*Ue+Fe*Fe);Mt(qe)&&qe>=Vtt||(qe=Math.sqrt(Math.max(Ue*Ue,hT)+Math.max(Fe*Fe,hT)));var Me=_.vector={x:Ue,y:Fe},He=_.vectorNorm={x:Me.x/qe,y:Me.y/qe},K={x:-He.y,y:He.x};_.nodesOverlap=!Mt(qe)||Y.checkPoint(Te[0],Te[1],0,X,W,F.x,F.y,J,ee)||Z.checkPoint($e[0],$e[1],0,V,H,z.x,z.y,ae,re),_.vectorNormInverse=K,D={nodesOverlap:_.nodesOverlap,dirCounts:_.dirCounts,calculatedIntersection:!0,hasBezier:_.hasBezier,hasUnbundled:_.hasUnbundled,eles:_.eles,srcPos:F,srcRs:ee,tgtPos:z,tgtRs:re,srcW:X,srcH:W,tgtW:V,tgtH:H,srcIntn:pe,tgtIntn:De,srcShape:Y,tgtShape:Z,posPts:{x1:Ce.x2,y1:Ce.y2,x2:Ce.x1,y2:Ce.y1},intersectionPts:{x1:Je.x2,y1:Je.y2,x2:Je.x1,y2:Je.y1},vector:{x:-Me.x,y:-Me.y},vectorNorm:{x:-He.x,y:-He.y},vectorNormInverse:{x:-K.x,y:-K.y}}}var oe=we?D:_;de.nodesOverlap=oe.nodesOverlap,de.srcIntn=oe.srcIntn,de.tgtIntn=oe.tgtIntn,de.isRound=Ee.startsWith("round"),n&&(B.isParent()||B.isChild()||O.isParent()||O.isChild())&&(B.parents().anySame(O)||O.parents().anySame(B)||B.same(O)&&B.isParent())?e.findCompoundLoopPoints(be,oe,te,Ne):B===O?e.findLoopPoints(be,oe,te,Ne):Ee.endsWith("segments")?e.findSegmentsPoints(be,oe):Ee.endsWith("taxi")?e.findTaxiPoints(be,oe):Ee==="straight"||!Ne&&_.eles.length%2===1&&te===Math.floor(_.eles.length/2)?e.findStraightEdgePoints(be):e.findBezierPoints(be,oe,te,Ne,we),e.findEndpoints(be),e.tryToCorrectInvalidPoints(be,oe),e.checkForInvalidEdgeWarning(be),e.storeAllpts(be),e.storeEdgeProjections(be),e.calculateArrowAngles(be),e.recalculateEdgeLabelProjections(be),e.calculateLabelAngles(be)}},"_loop"),E=0;E0){var Te=h,De=j0(Te,ly(s)),$e=j0(Te,ly(we)),pe=De;if($e2){var Je=j0(Te,{x:we[2],y:we[3]});Je0){var le=f,ke=j0(le,ly(s)),me=j0(le,ly(se)),ye=ke;if(me2){var Re=j0(le,{x:se[2],y:se[3]});Re=g||E){v={cp:w,segment:C};break}}if(v)break}var S=v.cp,L=v.segment,M=(g-x)/L.length,I=L.t1-L.t0,A=m?L.t0+I*M:L.t1-I*M;A=aT(0,A,1),e=hy(S.p0,S.p1,S.p2,A),p=Wtt(S.p0,S.p1,S.p2,A);break}case"straight":case"segments":case"haystack":{for(var _=0,D,N,R,B,O=i.allpts.length,$=0;$+3=g));$+=2);var z=g-N,F=z/D;F=aT(0,F,1),e=uZe(R,B,F),p=N1e(R,B);break}}s("labelX",d,e.x),s("labelY",d,e.y),s("labelAutoAngle",d,p)}},"calculateEndProjection");h("source"),h("target"),this.applyLabelDimensions(t)}};zu.applyLabelDimensions=function(t){this.applyPrefixedLabelDimensions(t),t.isEdge()&&(this.applyPrefixedLabelDimensions(t,"source"),this.applyPrefixedLabelDimensions(t,"target"))};zu.applyPrefixedLabelDimensions=function(t,e){var r=t._private,i=this.getLabelText(t,e),n=J0(i,t._private.labelDimsKey);if(_o(r.rscratch,"prefixedLabelDimsKey",e)!==n){jh(r.rscratch,"prefixedLabelDimsKey",e,n);var a=this.calculateLabelDimensions(t,i),s=t.pstyle("line-height").pfValue,l=t.pstyle("text-wrap").strValue,u=_o(r.rscratch,"labelWrapCachedLines",e)||[],h=l!=="wrap"?1:Math.max(u.length,1),f=a.height/h,d=f*s,p=a.width,m=a.height+(h-1)*(s-1)*f;jh(r.rstyle,"labelWidth",e,p),jh(r.rscratch,"labelWidth",e,p),jh(r.rstyle,"labelHeight",e,m),jh(r.rscratch,"labelHeight",e,m),jh(r.rscratch,"labelLineHeight",e,d)}};zu.getLabelText=function(t,e){var r=t._private,i=e?e+"-":"",n=t.pstyle(i+"label").strValue,a=t.pstyle("text-transform").value,s=o(function(H,X){return X?(jh(r.rscratch,H,e,X),X):_o(r.rscratch,H,e)},"rscratch");if(!n)return"";a=="none"||(a=="uppercase"?n=n.toUpperCase():a=="lowercase"&&(n=n.toLowerCase()));var l=t.pstyle("text-wrap").value;if(l==="wrap"){var u=s("labelKey");if(u!=null&&s("labelWrapKey")===u)return s("labelWrapCachedText");for(var h="\u200B",f=n.split(` +`),d=t.pstyle("text-max-width").pfValue,p=t.pstyle("text-overflow-wrap").value,m=p==="anywhere",g=[],y=/[\s\u200b]+|$/g,v=0;vd){var k=x.matchAll(y),C="",E=0,S=Lo(k),L;try{for(S.s();!(L=S.n()).done;){var M=L.value,I=M[0],A=x.substring(E,M.index);E=M.index+I.length;var _=C.length===0?A:C+A+I,D=this.calculateLabelDimensions(t,_),N=D.width;N<=d?C+=A+I:(C&&g.push(C),C=A+I)}}catch(V){S.e(V)}finally{S.f()}C.match(/^[\s\u200b]+$/)||g.push(C)}else g.push(x)}s("labelWrapCachedLines",g),n=s("labelWrapCachedText",g.join(` +`)),s("labelWrapKey",u)}else if(l==="ellipsis"){var R=t.pstyle("text-max-width").pfValue,B="",O="\u2026",$=!1;if(this.calculateLabelDimensions(t,n).widthR)break;B+=n[z],z===n.length-1&&($=!0)}return $||(B+=O),B}return n};zu.getLabelJustification=function(t){var e=t.pstyle("text-justification").strValue,r=t.pstyle("text-halign").strValue;if(e==="auto")if(t.isNode())switch(r){case"left":return"right";case"right":return"left";default:return"center"}else return"center";else return e};zu.calculateLabelDimensions=function(t,e){var r=this,i=r.cy.window(),n=i.document,a=0,s=t.pstyle("font-style").strValue,l=t.pstyle("font-size").pfValue,u=t.pstyle("font-family").strValue,h=t.pstyle("font-weight").strValue,f=this.labelCalcCanvas,d=this.labelCalcCanvasContext;if(!f){f=this.labelCalcCanvas=n.createElement("canvas"),d=this.labelCalcCanvasContext=f.getContext("2d");var p=f.style;p.position="absolute",p.left="-9999px",p.top="-9999px",p.zIndex="-1",p.visibility="hidden",p.pointerEvents="none"}d.font="".concat(s," ").concat(h," ").concat(l,"px ").concat(u);for(var m=0,g=0,y=e.split(` +`),v=0;v1&&arguments[1]!==void 0?arguments[1]:!0;if(e.merge(s),l)for(var u=0;u=t.desktopTapThreshold2}var ct=a(G);ut&&(t.hoverData.tapholdCancelled=!0);var Dt=o(function(){var xt=t.hoverData.dragDelta=t.hoverData.dragDelta||[];xt.length===0?(xt.push(it[0]),xt.push(it[1])):(xt[0]+=it[0],xt[1]+=it[1])},"updateDragDelta");le=!0,n(Be,["mousemove","vmousemove","tapdrag"],G,{x:Re[0],y:Re[1]});var kt=o(function(xt){return{originalEvent:G,type:xt,position:{x:Re[0],y:Re[1]}}},"makeEvent"),yt=o(function(){t.data.bgActivePosistion=void 0,t.hoverData.selecting||ke.emit(kt("boxstart")),We[4]=1,t.hoverData.selecting=!0,t.redrawHint("select",!0),t.redraw()},"goIntoBoxMode");if(t.hoverData.which===3){if(ut){var jt=kt("cxtdrag");ce?ce.emit(jt):ke.emit(jt),t.hoverData.cxtDragged=!0,(!t.hoverData.cxtOver||Be!==t.hoverData.cxtOver)&&(t.hoverData.cxtOver&&t.hoverData.cxtOver.emit(kt("cxtdragout")),t.hoverData.cxtOver=Be,Be&&Be.emit(kt("cxtdragover")))}}else if(t.hoverData.dragging){if(le=!0,ke.panningEnabled()&&ke.userPanningEnabled()){var hr;if(t.hoverData.justStartedPan){var Qt=t.hoverData.mdownPos;hr={x:(Re[0]-Qt[0])*me,y:(Re[1]-Qt[1])*me},t.hoverData.justStartedPan=!1}else hr={x:it[0]*me,y:it[1]*me};ke.panBy(hr),ke.emit(kt("dragpan")),t.hoverData.dragged=!0}Re=t.projectIntoViewport(G.clientX,G.clientY)}else if(We[4]==1&&(ce==null||ce.pannable())){if(ut){if(!t.hoverData.dragging&&ke.boxSelectionEnabled()&&(ct||!ke.panningEnabled()||!ke.userPanningEnabled()))yt();else if(!t.hoverData.selecting&&ke.panningEnabled()&&ke.userPanningEnabled()){var Er=s(ce,t.hoverData.downs);Er&&(t.hoverData.dragging=!0,t.hoverData.justStartedPan=!0,We[4]=0,t.data.bgActivePosistion=ly(ve),t.redrawHint("select",!0),t.redraw())}ce&&ce.pannable()&&ce.active()&&ce.unactivate()}}else{if(ce&&ce.pannable()&&ce.active()&&ce.unactivate(),(!ce||!ce.grabbed())&&Be!=Qe&&(Qe&&n(Qe,["mouseout","tapdragout"],G,{x:Re[0],y:Re[1]}),Be&&n(Be,["mouseover","tapdragover"],G,{x:Re[0],y:Re[1]}),t.hoverData.last=Be),ce)if(ut){if(ke.boxSelectionEnabled()&&ct)ce&&ce.grabbed()&&(x(fe),ce.emit(kt("freeon")),fe.emit(kt("free")),t.dragData.didDrag&&(ce.emit(kt("dragfreeon")),fe.emit(kt("dragfree")))),yt();else if(ce&&ce.grabbed()&&t.nodeIsDraggable(ce)){var dr=!t.dragData.didDrag;dr&&t.redrawHint("eles",!0),t.dragData.didDrag=!0,t.hoverData.draggingEles||y(fe,{inDragLayer:!0});var ir={x:0,y:0};if(Mt(it[0])&&Mt(it[1])&&(ir.x+=it[0],ir.y+=it[1],dr)){var pr=t.hoverData.dragDelta;pr&&Mt(pr[0])&&Mt(pr[1])&&(ir.x+=pr[0],ir.y+=pr[1])}t.hoverData.draggingEles=!0,fe.silentShift(ir).emit(kt("position")).emit(kt("drag")),t.redrawHint("drag",!0),t.redraw()}}else Dt();le=!0}if(We[2]=Re[0],We[3]=Re[1],le)return G.stopPropagation&&G.stopPropagation(),G.preventDefault&&G.preventDefault(),!1}},"mousemoveHandler"),!1);var A,_,D;t.registerBinding(e,"mouseup",o(function(G){if(!(t.hoverData.which===1&&G.which!==1&&t.hoverData.capture)){var se=t.hoverData.capture;if(se){t.hoverData.capture=!1;var le=t.cy,ke=t.projectIntoViewport(G.clientX,G.clientY),me=t.selection,ye=t.findNearestElement(ke[0],ke[1],!0,!1),Re=t.dragData.possibleDragElements,ve=t.hoverData.down,Oe=a(G);t.data.bgActivePosistion&&(t.redrawHint("select",!0),t.redraw()),t.hoverData.tapholdCancelled=!0,t.data.bgActivePosistion=void 0,ve&&ve.unactivate();var We=o(function(Nt){return{originalEvent:G,type:Nt,position:{x:ke[0],y:ke[1]}}},"makeEvent");if(t.hoverData.which===3){var Be=We("cxttapend");if(ve?ve.emit(Be):le.emit(Be),!t.hoverData.cxtDragged){var Qe=We("cxttap");ve?ve.emit(Qe):le.emit(Qe)}t.hoverData.cxtDragged=!1,t.hoverData.which=null}else if(t.hoverData.which===1){if(n(ye,["mouseup","tapend","vmouseup"],G,{x:ke[0],y:ke[1]}),!t.dragData.didDrag&&!t.hoverData.dragged&&!t.hoverData.selecting&&!t.hoverData.isOverThresholdDrag&&(n(ve,["click","tap","vclick"],G,{x:ke[0],y:ke[1]}),_=!1,G.timeStamp-D<=le.multiClickDebounceTime()?(A&&clearTimeout(A),_=!0,D=null,n(ve,["dblclick","dbltap","vdblclick"],G,{x:ke[0],y:ke[1]})):(A=setTimeout(function(){_||n(ve,["oneclick","onetap","voneclick"],G,{x:ke[0],y:ke[1]})},le.multiClickDebounceTime()),D=G.timeStamp)),ve==null&&!t.dragData.didDrag&&!t.hoverData.selecting&&!t.hoverData.dragged&&!a(G)&&(le.$(r).unselect(["tapunselect"]),Re.length>0&&t.redrawHint("eles",!0),t.dragData.possibleDragElements=Re=le.collection()),ye==ve&&!t.dragData.didDrag&&!t.hoverData.selecting&&ye!=null&&ye._private.selectable&&(t.hoverData.dragging||(le.selectionType()==="additive"||Oe?ye.selected()?ye.unselect(["tapunselect"]):ye.select(["tapselect"]):Oe||(le.$(r).unmerge(ye).unselect(["tapunselect"]),ye.select(["tapselect"]))),t.redrawHint("eles",!0)),t.hoverData.selecting){var ce=le.collection(t.getAllInBox(me[0],me[1],me[2],me[3]));t.redrawHint("select",!0),ce.length>0&&t.redrawHint("eles",!0),le.emit(We("boxend"));var it=o(function(Nt){return Nt.selectable()&&!Nt.selected()},"eleWouldBeSelected");le.selectionType()==="additive"||Oe||le.$(r).unmerge(ce).unselect(),ce.emit(We("box")).stdFilter(it).select().emit(We("boxselect")),t.redraw()}if(t.hoverData.dragging&&(t.hoverData.dragging=!1,t.redrawHint("select",!0),t.redrawHint("eles",!0),t.redraw()),!me[4]){t.redrawHint("drag",!0),t.redrawHint("eles",!0);var fe=ve&&ve.grabbed();x(Re),fe&&(ve.emit(We("freeon")),Re.emit(We("free")),t.dragData.didDrag&&(ve.emit(We("dragfreeon")),Re.emit(We("dragfree"))))}}me[4]=0,t.hoverData.down=null,t.hoverData.cxtStarted=!1,t.hoverData.draggingEles=!1,t.hoverData.selecting=!1,t.hoverData.isOverThresholdDrag=!1,t.dragData.didDrag=!1,t.hoverData.dragged=!1,t.hoverData.dragDelta=[],t.hoverData.mdownPos=null,t.hoverData.mdownGPos=null,t.hoverData.which=null}}},"mouseupHandler"),!1);var N=[],R=4,B,O=1e5,$=o(function(G,se){for(var le=0;le=R){var ke=N;if(B=$(ke,5),!B){var me=Math.abs(ke[0]);B=z(ke)&&me>5}if(B)for(var ye=0;ye5&&(le=JB(le)*5),Qe=le/-250,B&&(Qe/=O,Qe*=3),Qe=Qe*t.wheelSensitivity;var ce=G.deltaMode===1;ce&&(Qe*=33);var it=Re.zoom()*Math.pow(10,Qe);G.type==="gesturechange"&&(it=t.gestureStartZoom*G.scale),Re.zoom({level:it,renderedPosition:{x:Be[0],y:Be[1]}}),Re.emit({type:G.type==="gesturechange"?"pinchzoom":"scrollzoom",originalEvent:G,position:{x:We[0],y:We[1]}})}}}},"wheelHandler");t.registerBinding(t.container,"wheel",F,!0),t.registerBinding(e,"scroll",o(function(G){t.scrollingPage=!0,clearTimeout(t.scrollingPageTimeout),t.scrollingPageTimeout=setTimeout(function(){t.scrollingPage=!1},250)},"scrollHandler"),!0),t.registerBinding(t.container,"gesturestart",o(function(G){t.gestureStartZoom=t.cy.zoom(),t.hasTouchStarted||G.preventDefault()},"gestureStartHandler"),!0),t.registerBinding(t.container,"gesturechange",function(ue){t.hasTouchStarted||F(ue)},!0),t.registerBinding(t.container,"mouseout",o(function(G){var se=t.projectIntoViewport(G.clientX,G.clientY);t.cy.emit({originalEvent:G,type:"mouseout",position:{x:se[0],y:se[1]}})},"mouseOutHandler"),!1),t.registerBinding(t.container,"mouseover",o(function(G){var se=t.projectIntoViewport(G.clientX,G.clientY);t.cy.emit({originalEvent:G,type:"mouseover",position:{x:se[0],y:se[1]}})},"mouseOverHandler"),!1);var V,H,X,W,Z,Y,ae,J,ee,re,te,be,de,Ee=o(function(G,se,le,ke){return Math.sqrt((le-G)*(le-G)+(ke-se)*(ke-se))},"distance"),Ne=o(function(G,se,le,ke){return(le-G)*(le-G)+(ke-se)*(ke-se)},"distanceSq"),we;t.registerBinding(t.container,"touchstart",we=o(function(G){if(t.hasTouchStarted=!0,!!M(G)){T(),t.touchData.capture=!0,t.data.bgActivePosistion=void 0;var se=t.cy,le=t.touchData.now,ke=t.touchData.earlier;if(G.touches[0]){var me=t.projectIntoViewport(G.touches[0].clientX,G.touches[0].clientY);le[0]=me[0],le[1]=me[1]}if(G.touches[1]){var me=t.projectIntoViewport(G.touches[1].clientX,G.touches[1].clientY);le[2]=me[0],le[3]=me[1]}if(G.touches[2]){var me=t.projectIntoViewport(G.touches[2].clientX,G.touches[2].clientY);le[4]=me[0],le[5]=me[1]}var ye=o(function(ct){return{originalEvent:G,type:ct,position:{x:le[0],y:le[1]}}},"makeEvent");if(G.touches[1]){t.touchData.singleTouchMoved=!0,x(t.dragData.touchDragEles);var Re=t.findContainerClientCoords();ee=Re[0],re=Re[1],te=Re[2],be=Re[3],V=G.touches[0].clientX-ee,H=G.touches[0].clientY-re,X=G.touches[1].clientX-ee,W=G.touches[1].clientY-re,de=0<=V&&V<=te&&0<=X&&X<=te&&0<=H&&H<=be&&0<=W&&W<=be;var ve=se.pan(),Oe=se.zoom();Z=Ee(V,H,X,W),Y=Ne(V,H,X,W),ae=[(V+X)/2,(H+W)/2],J=[(ae[0]-ve.x)/Oe,(ae[1]-ve.y)/Oe];var We=200,Be=We*We;if(Y=1){for(var Pt=t.touchData.startPosition=[null,null,null,null,null,null],St=0;St=t.touchTapThreshold2}if(se&&t.touchData.cxt){G.preventDefault();var St=G.touches[0].clientX-ee,It=G.touches[0].clientY-re,ot=G.touches[1].clientX-ee,ct=G.touches[1].clientY-re,Dt=Ne(St,It,ot,ct),kt=Dt/Y,yt=150,jt=yt*yt,hr=1.5,Qt=hr*hr;if(kt>=Qt||Dt>=jt){t.touchData.cxt=!1,t.data.bgActivePosistion=void 0,t.redrawHint("select",!0);var Er=Oe("cxttapend");t.touchData.start?(t.touchData.start.unactivate().emit(Er),t.touchData.start=null):ke.emit(Er)}}if(se&&t.touchData.cxt){var Er=Oe("cxtdrag");t.data.bgActivePosistion=void 0,t.redrawHint("select",!0),t.touchData.start?t.touchData.start.emit(Er):ke.emit(Er),t.touchData.start&&(t.touchData.start._private.grabbed=!1),t.touchData.cxtDragged=!0;var dr=t.findNearestElement(me[0],me[1],!0,!0);(!t.touchData.cxtOver||dr!==t.touchData.cxtOver)&&(t.touchData.cxtOver&&t.touchData.cxtOver.emit(Oe("cxtdragout")),t.touchData.cxtOver=dr,dr&&dr.emit(Oe("cxtdragover")))}else if(se&&G.touches[2]&&ke.boxSelectionEnabled())G.preventDefault(),t.data.bgActivePosistion=void 0,this.lastThreeTouch=+new Date,t.touchData.selecting||ke.emit(Oe("boxstart")),t.touchData.selecting=!0,t.touchData.didSelect=!0,le[4]=1,!le||le.length===0||le[0]===void 0?(le[0]=(me[0]+me[2]+me[4])/3,le[1]=(me[1]+me[3]+me[5])/3,le[2]=(me[0]+me[2]+me[4])/3+1,le[3]=(me[1]+me[3]+me[5])/3+1):(le[2]=(me[0]+me[2]+me[4])/3,le[3]=(me[1]+me[3]+me[5])/3),t.redrawHint("select",!0),t.redraw();else if(se&&G.touches[1]&&!t.touchData.didSelect&&ke.zoomingEnabled()&&ke.panningEnabled()&&ke.userZoomingEnabled()&&ke.userPanningEnabled()){G.preventDefault(),t.data.bgActivePosistion=void 0,t.redrawHint("select",!0);var ir=t.dragData.touchDragEles;if(ir){t.redrawHint("drag",!0);for(var pr=0;pr0&&!t.hoverData.draggingEles&&!t.swipePanning&&t.data.bgActivePosistion!=null&&(t.data.bgActivePosistion=void 0,t.redrawHint("select",!0),t.redraw())}},"touchmoveHandler"),!1);var De;t.registerBinding(e,"touchcancel",De=o(function(G){var se=t.touchData.start;t.touchData.capture=!1,se&&se.unactivate()},"touchcancelHandler"));var $e,pe,Je,Ce;if(t.registerBinding(e,"touchend",$e=o(function(G){var se=t.touchData.start,le=t.touchData.capture;if(le)G.touches.length===0&&(t.touchData.capture=!1),G.preventDefault();else return;var ke=t.selection;t.swipePanning=!1,t.hoverData.draggingEles=!1;var me=t.cy,ye=me.zoom(),Re=t.touchData.now,ve=t.touchData.earlier;if(G.touches[0]){var Oe=t.projectIntoViewport(G.touches[0].clientX,G.touches[0].clientY);Re[0]=Oe[0],Re[1]=Oe[1]}if(G.touches[1]){var Oe=t.projectIntoViewport(G.touches[1].clientX,G.touches[1].clientY);Re[2]=Oe[0],Re[3]=Oe[1]}if(G.touches[2]){var Oe=t.projectIntoViewport(G.touches[2].clientX,G.touches[2].clientY);Re[4]=Oe[0],Re[5]=Oe[1]}var We=o(function(jt){return{originalEvent:G,type:jt,position:{x:Re[0],y:Re[1]}}},"makeEvent");se&&se.unactivate();var Be;if(t.touchData.cxt){if(Be=We("cxttapend"),se?se.emit(Be):me.emit(Be),!t.touchData.cxtDragged){var Qe=We("cxttap");se?se.emit(Qe):me.emit(Qe)}t.touchData.start&&(t.touchData.start._private.grabbed=!1),t.touchData.cxt=!1,t.touchData.start=null,t.redraw();return}if(!G.touches[2]&&me.boxSelectionEnabled()&&t.touchData.selecting){t.touchData.selecting=!1;var ce=me.collection(t.getAllInBox(ke[0],ke[1],ke[2],ke[3]));ke[0]=void 0,ke[1]=void 0,ke[2]=void 0,ke[3]=void 0,ke[4]=0,t.redrawHint("select",!0),me.emit(We("boxend"));var it=o(function(jt){return jt.selectable()&&!jt.selected()},"eleWouldBeSelected");ce.emit(We("box")).stdFilter(it).select().emit(We("boxselect")),ce.nonempty()&&t.redrawHint("eles",!0),t.redraw()}if(se?.unactivate(),G.touches[2])t.data.bgActivePosistion=void 0,t.redrawHint("select",!0);else if(!G.touches[1]){if(!G.touches[0]){if(!G.touches[0]){t.data.bgActivePosistion=void 0,t.redrawHint("select",!0);var fe=t.dragData.touchDragEles;if(se!=null){var ut=se._private.grabbed;x(fe),t.redrawHint("drag",!0),t.redrawHint("eles",!0),ut&&(se.emit(We("freeon")),fe.emit(We("free")),t.dragData.didDrag&&(se.emit(We("dragfreeon")),fe.emit(We("dragfree")))),n(se,["touchend","tapend","vmouseup","tapdragout"],G,{x:Re[0],y:Re[1]}),se.unactivate(),t.touchData.start=null}else{var Nt=t.findNearestElement(Re[0],Re[1],!0,!0);n(Nt,["touchend","tapend","vmouseup","tapdragout"],G,{x:Re[0],y:Re[1]})}var Pt=t.touchData.startPosition[0]-Re[0],St=Pt*Pt,It=t.touchData.startPosition[1]-Re[1],ot=It*It,ct=St+ot,Dt=ct*ye*ye;t.touchData.singleTouchMoved||(se||me.$(":selected").unselect(["tapunselect"]),n(se,["tap","vclick"],G,{x:Re[0],y:Re[1]}),pe=!1,G.timeStamp-Ce<=me.multiClickDebounceTime()?(Je&&clearTimeout(Je),pe=!0,Ce=null,n(se,["dbltap","vdblclick"],G,{x:Re[0],y:Re[1]})):(Je=setTimeout(function(){pe||n(se,["onetap","voneclick"],G,{x:Re[0],y:Re[1]})},me.multiClickDebounceTime()),Ce=G.timeStamp)),se!=null&&!t.dragData.didDrag&&se._private.selectable&&Dt"u"){var Fe=[],Ue=o(function(G){return{clientX:G.clientX,clientY:G.clientY,force:1,identifier:G.pointerId,pageX:G.pageX,pageY:G.pageY,radiusX:G.width/2,radiusY:G.height/2,screenX:G.screenX,screenY:G.screenY,target:G.target}},"makeTouch"),qe=o(function(G){return{event:G,touch:Ue(G)}},"makePointer"),Me=o(function(G){Fe.push(qe(G))},"addPointer"),He=o(function(G){for(var se=0;se0)return V[0]}return null},"getCurveT"),g=Object.keys(p),y=0;y0?m:Mge(a,s,e,r,i,n,l,u)},"intersectLine"),checkPoint:o(function(e,r,i,n,a,s,l,u){u=u==="auto"?Od(n,a):u;var h=2*u;if(Qh(e,r,this.points,s,l,n,a-h,[0,-1],i)||Qh(e,r,this.points,s,l,n-h,a,[0,-1],i))return!0;var f=n/2+2*i,d=a/2+2*i,p=[s-f,l-d,s-f,l,s+f,l,s+f,l-d];return!!(Do(e,r,p)||Z0(e,r,h,h,s+n/2-u,l+a/2-u,i)||Z0(e,r,h,h,s-n/2+u,l+a/2-u,i))},"checkPoint")}};Zh.registerNodeShapes=function(){var t=this.nodeShapes={},e=this;this.generateEllipse(),this.generatePolygon("triangle",Ws(3,0)),this.generateRoundPolygon("round-triangle",Ws(3,0)),this.generatePolygon("rectangle",Ws(4,0)),t.square=t.rectangle,this.generateRoundRectangle(),this.generateCutRectangle(),this.generateBarrel(),this.generateBottomRoundrectangle();{var r=[0,1,1,0,0,-1,-1,0];this.generatePolygon("diamond",r),this.generateRoundPolygon("round-diamond",r)}this.generatePolygon("pentagon",Ws(5,0)),this.generateRoundPolygon("round-pentagon",Ws(5,0)),this.generatePolygon("hexagon",Ws(6,0)),this.generateRoundPolygon("round-hexagon",Ws(6,0)),this.generatePolygon("heptagon",Ws(7,0)),this.generateRoundPolygon("round-heptagon",Ws(7,0)),this.generatePolygon("octagon",Ws(8,0)),this.generateRoundPolygon("round-octagon",Ws(8,0));var i=new Array(20);{var n=SB(5,0),a=SB(5,Math.PI/5),s=.5*(3-Math.sqrt(5));s*=1.57;for(var l=0;l=e.deqFastCost*w)break}else if(h){if(b>=e.deqCost*m||b>=e.deqAvgCost*p)break}else if(T>=e.deqNoDrawCost*yB)break;var k=e.deq(i,v,y);if(k.length>0)for(var C=0;C0&&(e.onDeqd(i,g),!h&&e.shouldRedraw(i,g,v,y)&&a())},"dequeue"),l=e.priority||KB;n.beforeRender(s,l(i))}},"setupDequeueingImpl")},"setupDequeueing")},Htt=(function(){function t(e){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:pS;$d(this,t),this.idsByKey=new Xh,this.keyForId=new Xh,this.cachesByLvl=new Xh,this.lvls=[],this.getKey=e,this.doesEleInvalidateKey=r}return o(t,"ElementTextureCacheLookup"),zd(t,[{key:"getIdsFor",value:o(function(r){r==null&&mn("Can not get id list for null key");var i=this.idsByKey,n=this.idsByKey.get(r);return n||(n=new vy,i.set(r,n)),n},"getIdsFor")},{key:"addIdForKey",value:o(function(r,i){r!=null&&this.getIdsFor(r).add(i)},"addIdForKey")},{key:"deleteIdForKey",value:o(function(r,i){r!=null&&this.getIdsFor(r).delete(i)},"deleteIdForKey")},{key:"getNumberOfIdsForKey",value:o(function(r){return r==null?0:this.getIdsFor(r).size},"getNumberOfIdsForKey")},{key:"updateKeyMappingFor",value:o(function(r){var i=r.id(),n=this.keyForId.get(i),a=this.getKey(r);this.deleteIdForKey(n,i),this.addIdForKey(a,i),this.keyForId.set(i,a)},"updateKeyMappingFor")},{key:"deleteKeyMappingFor",value:o(function(r){var i=r.id(),n=this.keyForId.get(i);this.deleteIdForKey(n,i),this.keyForId.delete(i)},"deleteKeyMappingFor")},{key:"keyHasChangedFor",value:o(function(r){var i=r.id(),n=this.keyForId.get(i),a=this.getKey(r);return n!==a},"keyHasChangedFor")},{key:"isInvalid",value:o(function(r){return this.keyHasChangedFor(r)||this.doesEleInvalidateKey(r)},"isInvalid")},{key:"getCachesAt",value:o(function(r){var i=this.cachesByLvl,n=this.lvls,a=i.get(r);return a||(a=new Xh,i.set(r,a),n.push(r)),a},"getCachesAt")},{key:"getCache",value:o(function(r,i){return this.getCachesAt(i).get(r)},"getCache")},{key:"get",value:o(function(r,i){var n=this.getKey(r),a=this.getCache(n,i);return a!=null&&this.updateKeyMappingFor(r),a},"get")},{key:"getForCachedKey",value:o(function(r,i){var n=this.keyForId.get(r.id()),a=this.getCache(n,i);return a},"getForCachedKey")},{key:"hasCache",value:o(function(r,i){return this.getCachesAt(i).has(r)},"hasCache")},{key:"has",value:o(function(r,i){var n=this.getKey(r);return this.hasCache(n,i)},"has")},{key:"setCache",value:o(function(r,i,n){n.key=r,this.getCachesAt(i).set(r,n)},"setCache")},{key:"set",value:o(function(r,i,n){var a=this.getKey(r);this.setCache(a,i,n),this.updateKeyMappingFor(r)},"set")},{key:"deleteCache",value:o(function(r,i){this.getCachesAt(i).delete(r)},"deleteCache")},{key:"delete",value:o(function(r,i){var n=this.getKey(r);this.deleteCache(n,i)},"_delete")},{key:"invalidateKey",value:o(function(r){var i=this;this.lvls.forEach(function(n){return i.deleteCache(r,n)})},"invalidateKey")},{key:"invalidate",value:o(function(r){var i=r.id(),n=this.keyForId.get(i);this.deleteKeyMappingFor(r);var a=this.doesEleInvalidateKey(r);return a&&this.invalidateKey(n),a||this.getNumberOfIdsForKey(n)===0},"invalidate")}])})(),Kme=25,ZE=50,cS=-4,zB=3,F1e=7.99,Ytt=8,jtt=1024,Xtt=1024,Ktt=1024,Qtt=.2,Ztt=.8,Jtt=10,ert=.15,trt=.1,rrt=.9,irt=.9,nrt=100,art=1,uy={dequeue:"dequeue",downscale:"downscale",highQuality:"highQuality"},srt=rs({getKey:null,doesEleInvalidateKey:pS,drawElement:null,getBoundingBox:null,getRotationPoint:null,getRotationOffset:null,isVisible:Age,allowEdgeTxrCaching:!0,allowParentTxrCaching:!0}),Zb=o(function(e,r){var i=this;i.renderer=e,i.onDequeues=[];var n=srt(r);yr(i,n),i.lookup=new Htt(n.getKey,n.doesEleInvalidateKey),i.setupDequeueing()},"ElementTextureCache"),ma=Zb.prototype;ma.reasons=uy;ma.getTextureQueue=function(t){var e=this;return e.eleImgCaches=e.eleImgCaches||{},e.eleImgCaches[t]=e.eleImgCaches[t]||[]};ma.getRetiredTextureQueue=function(t){var e=this,r=e.eleImgCaches.retired=e.eleImgCaches.retired||{},i=r[t]=r[t]||[];return i};ma.getElementQueue=function(){var t=this,e=t.eleCacheQueue=t.eleCacheQueue||new vT(function(r,i){return i.reqs-r.reqs});return e};ma.getElementKeyToQueue=function(){var t=this,e=t.eleKeyToCacheQueue=t.eleKeyToCacheQueue||{};return e};ma.getElement=function(t,e,r,i,n){var a=this,s=this.renderer,l=s.cy.zoom(),u=this.lookup;if(!e||e.w===0||e.h===0||isNaN(e.w)||isNaN(e.h)||!t.visible()||t.removed()||!a.allowEdgeTxrCaching&&t.isEdge()||!a.allowParentTxrCaching&&t.isParent())return null;if(i==null&&(i=Math.ceil(ZB(l*r))),i=F1e||i>zB)return null;var h=Math.pow(2,i),f=e.h*h,d=e.w*h,p=s.eleTextBiggerThanMin(t,h);if(!this.isVisible(t,p))return null;var m=u.get(t,i);if(m&&m.invalidated&&(m.invalidated=!1,m.texture.invalidatedWidth-=m.width),m)return m;var g;if(f<=Kme?g=Kme:f<=ZE?g=ZE:g=Math.ceil(f/ZE)*ZE,f>Ktt||d>Xtt)return null;var y=a.getTextureQueue(g),v=y[y.length-2],x=o(function(){return a.recycleTexture(g,d)||a.addTexture(g,d)},"addNewTxr");v||(v=y[y.length-1]),v||(v=x()),v.width-v.usedWidthi;I--)L=a.getElement(t,e,r,I,uy.downscale);M()}else return a.queueElement(t,C.level-1),C;else{var A;if(!T&&!w&&!k)for(var _=i-1;_>=cS;_--){var D=u.get(t,_);if(D){A=D;break}}if(b(A))return a.queueElement(t,i),A;v.context.translate(v.usedWidth,0),v.context.scale(h,h),this.drawElement(v.context,t,e,p,!1),v.context.scale(1/h,1/h),v.context.translate(-v.usedWidth,0)}return m={x:v.usedWidth,texture:v,level:i,scale:h,width:d,height:f,scaledLabelShown:p},v.usedWidth+=Math.ceil(d+Ytt),v.eleCaches.push(m),u.set(t,i,m),a.checkTextureFullness(v),m};ma.invalidateElements=function(t){for(var e=0;e=Qtt*t.width&&this.retireTexture(t)};ma.checkTextureFullness=function(t){var e=this,r=e.getTextureQueue(t.height);t.usedWidth/t.width>Ztt&&t.fullnessChecks>=Jtt?Md(r,t):t.fullnessChecks++};ma.retireTexture=function(t){var e=this,r=t.height,i=e.getTextureQueue(r),n=this.lookup;Md(i,t),t.retired=!0;for(var a=t.eleCaches,s=0;s=e)return s.retired=!1,s.usedWidth=0,s.invalidatedWidth=0,s.fullnessChecks=0,QB(s.eleCaches),s.context.setTransform(1,0,0,1,0,0),s.context.clearRect(0,0,s.width,s.height),Md(n,s),i.push(s),s}};ma.queueElement=function(t,e){var r=this,i=r.getElementQueue(),n=r.getElementKeyToQueue(),a=this.getKey(t),s=n[a];if(s)s.level=Math.max(s.level,e),s.eles.merge(t),s.reqs++,i.updateItem(s);else{var l={eles:t.spawn().merge(t),level:e,reqs:1,key:a};i.push(l),n[a]=l}};ma.dequeue=function(t){for(var e=this,r=e.getElementQueue(),i=e.getElementKeyToQueue(),n=[],a=e.lookup,s=0;s0;s++){var l=r.pop(),u=l.key,h=l.eles[0],f=a.hasCache(h,l.level);if(i[u]=null,f)continue;n.push(l);var d=e.getBoundingBox(h);e.getElement(h,d,t,l.level,uy.dequeue)}return n};ma.removeFromQueue=function(t){var e=this,r=e.getElementQueue(),i=e.getElementKeyToQueue(),n=this.getKey(t),a=i[n];a!=null&&(a.eles.length===1?(a.reqs=XB,r.updateItem(a),r.pop(),i[n]=null):a.eles.unmerge(t))};ma.onDequeue=function(t){this.onDequeues.push(t)};ma.offDequeue=function(t){Md(this.onDequeues,t)};ma.setupDequeueing=B1e.setupDequeueing({deqRedrawThreshold:nrt,deqCost:ert,deqAvgCost:trt,deqNoDrawCost:rrt,deqFastCost:irt,deq:o(function(e,r,i){return e.dequeue(r,i)},"deq"),onDeqd:o(function(e,r){for(var i=0;i=lrt||r>kS)return null}i.validateLayersElesOrdering(r,t);var u=i.layersByLevel,h=Math.pow(2,r),f=u[r]=u[r]||[],d,p=i.levelIsComplete(r,t),m,g=o(function(){var M=o(function(N){if(i.validateLayersElesOrdering(N,t),i.levelIsComplete(N,t))return m=u[N],!0},"canUseAsTmpLvl"),I=o(function(N){if(!m)for(var R=r+N;eT<=R&&R<=kS&&!M(R);R+=N);},"checkLvls");I(1),I(-1);for(var A=f.length-1;A>=0;A--){var _=f[A];_.invalid&&Md(f,_)}},"checkTempLevels");if(!p)g();else return f;var y=o(function(){if(!d){d=Us();for(var M=0;MZme||_>Zme)return null;var D=A*_;if(D>grt)return null;var N=i.makeLayer(d,r);if(I!=null){var R=f.indexOf(I)+1;f.splice(R,0,N)}else(M.insert===void 0||M.insert)&&f.unshift(N);return N},"makeLayer");if(i.skipping&&!l)return null;for(var x=null,b=t.length/ort,T=!l,w=0;w=b||!Ige(x.bb,k.boundingBox()))&&(x=v({insert:!0,after:x}),!x))return null;m||T?i.queueLayer(x,k):i.drawEleInLayer(x,k,r,e),x.eles.push(k),E[r]=x}return m||(T?null:f)};is.getEleLevelForLayerLevel=function(t,e){return t};is.drawEleInLayer=function(t,e,r,i){var n=this,a=this.renderer,s=t.context,l=e.boundingBox();l.w===0||l.h===0||!e.visible()||(r=n.getEleLevelForLayerLevel(r,i),a.setImgSmoothing(s,!1),a.drawCachedElement(s,e,null,null,r,yrt),a.setImgSmoothing(s,!0))};is.levelIsComplete=function(t,e){var r=this,i=r.layersByLevel[t];if(!i||i.length===0)return!1;for(var n=0,a=0;a0||s.invalid)return!1;n+=s.eles.length}return n===e.length};is.validateLayersElesOrdering=function(t,e){var r=this.layersByLevel[t];if(r)for(var i=0;i0){e=!0;break}}return e};is.invalidateElements=function(t){var e=this;t.length!==0&&(e.lastInvalidationTime=Kh(),!(t.length===0||!e.haveLayers())&&e.updateElementsInLayers(t,o(function(i,n,a){e.invalidateLayer(i)},"invalAssocLayers")))};is.invalidateLayer=function(t){if(this.lastInvalidationTime=Kh(),!t.invalid){var e=t.level,r=t.eles,i=this.layersByLevel[e];Md(i,t),t.elesQueue=[],t.invalid=!0,t.replacement&&(t.replacement.invalid=!0);for(var n=0;n3&&arguments[3]!==void 0?arguments[3]:!0,n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!0,s=this,l=e._private.rscratch;if(!(a&&!e.visible())&&!(l.badLine||l.allpts==null||isNaN(l.allpts[0]))){var u;r&&(u=r,t.translate(-u.x1,-u.y1));var h=a?e.pstyle("opacity").value:1,f=a?e.pstyle("line-opacity").value:1,d=e.pstyle("curve-style").value,p=e.pstyle("line-style").value,m=e.pstyle("width").pfValue,g=e.pstyle("line-cap").value,y=e.pstyle("line-outline-width").value,v=e.pstyle("line-outline-color").value,x=h*f,b=h*f,T=o(function(){var N=arguments.length>0&&arguments[0]!==void 0?arguments[0]:x;d==="straight-triangle"?(s.eleStrokeStyle(t,e,N),s.drawEdgeTrianglePath(e,t,l.allpts)):(t.lineWidth=m,t.lineCap=g,s.eleStrokeStyle(t,e,N),s.drawEdgePath(e,t,l.allpts,p),t.lineCap="butt")},"drawLine"),w=o(function(){var N=arguments.length>0&&arguments[0]!==void 0?arguments[0]:x;if(t.lineWidth=m+y,t.lineCap=g,y>0)s.colorStrokeStyle(t,v[0],v[1],v[2],N);else{t.lineCap="butt";return}d==="straight-triangle"?s.drawEdgeTrianglePath(e,t,l.allpts):(s.drawEdgePath(e,t,l.allpts,p),t.lineCap="butt")},"drawLineOutline"),k=o(function(){n&&s.drawEdgeOverlay(t,e)},"drawOverlay"),C=o(function(){n&&s.drawEdgeUnderlay(t,e)},"drawUnderlay"),E=o(function(){var N=arguments.length>0&&arguments[0]!==void 0?arguments[0]:b;s.drawArrowheads(t,e,N)},"drawArrows"),S=o(function(){s.drawElementText(t,e,null,i)},"drawText");t.lineJoin="round";var L=e.pstyle("ghost").value==="yes";if(L){var M=e.pstyle("ghost-offset-x").pfValue,I=e.pstyle("ghost-offset-y").pfValue,A=e.pstyle("ghost-opacity").value,_=x*A;t.translate(M,I),T(_),E(_),t.translate(-M,-I)}else w();C(),T(),E(),k(),S(),r&&t.translate(u.x1,u.y1)}};G1e=o(function(e){if(!["overlay","underlay"].includes(e))throw new Error("Invalid state");return function(r,i){if(i.visible()){var n=i.pstyle("".concat(e,"-opacity")).value;if(n!==0){var a=this,s=a.usePaths(),l=i._private.rscratch,u=i.pstyle("".concat(e,"-padding")).pfValue,h=2*u,f=i.pstyle("".concat(e,"-color")).value;r.lineWidth=h,l.edgeType==="self"&&!s?r.lineCap="butt":r.lineCap="round",a.colorStrokeStyle(r,f[0],f[1],f[2],n),a.drawEdgePath(i,r,l.allpts,"solid")}}}},"drawEdgeOverlayUnderlay");Jh.drawEdgeOverlay=G1e("overlay");Jh.drawEdgeUnderlay=G1e("underlay");Jh.drawEdgePath=function(t,e,r,i){var n=t._private.rscratch,a=e,s,l=!1,u=this.usePaths(),h=t.pstyle("line-dash-pattern").pfValue,f=t.pstyle("line-dash-offset").pfValue;if(u){var d=r.join("$"),p=n.pathCacheKey&&n.pathCacheKey===d;p?(s=e=n.pathCache,l=!0):(s=e=new Path2D,n.pathCacheKey=d,n.pathCache=s)}if(a.setLineDash)switch(i){case"dotted":a.setLineDash([1,1]);break;case"dashed":a.setLineDash(h),a.lineDashOffset=f;break;case"solid":a.setLineDash([]);break}if(!l&&!n.badLine)switch(e.beginPath&&e.beginPath(),e.moveTo(r[0],r[1]),n.edgeType){case"bezier":case"self":case"compound":case"multibezier":for(var m=2;m+35&&arguments[5]!==void 0?arguments[5]:!0,s=this;if(i==null){if(a&&!s.eleTextBiggerThanMin(e))return}else if(i===!1)return;if(e.isNode()){var l=e.pstyle("label");if(!l||!l.value)return;var u=s.getLabelJustification(e);t.textAlign=u,t.textBaseline="bottom"}else{var h=e.element()._private.rscratch.badLine,f=e.pstyle("label"),d=e.pstyle("source-label"),p=e.pstyle("target-label");if(h||(!f||!f.value)&&(!d||!d.value)&&(!p||!p.value))return;t.textAlign="center",t.textBaseline="bottom"}var m=!r,g;r&&(g=r,t.translate(-g.x1,-g.y1)),n==null?(s.drawText(t,e,null,m,a),e.isEdge()&&(s.drawText(t,e,"source",m,a),s.drawText(t,e,"target",m,a))):s.drawText(t,e,n,m,a),r&&t.translate(g.x1,g.y1)};am.getFontCache=function(t){var e;this.fontCaches=this.fontCaches||[];for(var r=0;r2&&arguments[2]!==void 0?arguments[2]:!0,i=e.pstyle("font-style").strValue,n=e.pstyle("font-size").pfValue+"px",a=e.pstyle("font-family").strValue,s=e.pstyle("font-weight").strValue,l=r?e.effectiveOpacity()*e.pstyle("text-opacity").value:1,u=e.pstyle("text-outline-opacity").value*l,h=e.pstyle("color").value,f=e.pstyle("text-outline-color").value;t.font=i+" "+s+" "+n+" "+a,t.lineJoin="round",this.colorFillStyle(t,h[0],h[1],h[2],l),this.colorStrokeStyle(t,f[0],f[1],f[2],u)};o(_rt,"circle");o(rge,"roundRect");am.getTextAngle=function(t,e){var r,i=t._private,n=i.rscratch,a=e?e+"-":"",s=t.pstyle(a+"text-rotation");if(s.strValue==="autorotate"){var l=_o(n,"labelAngle",e);r=t.isEdge()?l:0}else s.strValue==="none"?r=0:r=s.pfValue;return r};am.drawText=function(t,e,r){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,a=e._private,s=a.rscratch,l=n?e.effectiveOpacity():1;if(!(n&&(l===0||e.pstyle("text-opacity").value===0))){r==="main"&&(r=null);var u=_o(s,"labelX",r),h=_o(s,"labelY",r),f,d,p=this.getLabelText(e,r);if(p!=null&&p!==""&&!isNaN(u)&&!isNaN(h)){this.setupTextStyle(t,e,n);var m=r?r+"-":"",g=_o(s,"labelWidth",r),y=_o(s,"labelHeight",r),v=e.pstyle(m+"text-margin-x").pfValue,x=e.pstyle(m+"text-margin-y").pfValue,b=e.isEdge(),T=e.pstyle("text-halign").value,w=e.pstyle("text-valign").value;b&&(T="center",w="center"),u+=v,h+=x;var k;switch(i?k=this.getTextAngle(e,r):k=0,k!==0&&(f=u,d=h,t.translate(f,d),t.rotate(k),u=0,h=0),w){case"top":break;case"center":h+=y/2;break;case"bottom":h+=y;break}var C=e.pstyle("text-background-opacity").value,E=e.pstyle("text-border-opacity").value,S=e.pstyle("text-border-width").pfValue,L=e.pstyle("text-background-padding").pfValue,M=e.pstyle("text-background-shape").strValue,I=M==="round-rectangle"||M==="roundrectangle",A=M==="circle",_=2;if(C>0||S>0&&E>0){var D=t.fillStyle,N=t.strokeStyle,R=t.lineWidth,B=e.pstyle("text-background-color").value,O=e.pstyle("text-border-color").value,$=e.pstyle("text-border-style").value,z=C>0,F=S>0&&E>0,V=u-L;switch(T){case"left":V-=g;break;case"center":V-=g/2;break}var H=h-y-L,X=g+2*L,W=y+2*L;if(z&&(t.fillStyle="rgba(".concat(B[0],",").concat(B[1],",").concat(B[2],",").concat(C*l,")")),F&&(t.strokeStyle="rgba(".concat(O[0],",").concat(O[1],",").concat(O[2],",").concat(E*l,")"),t.lineWidth=S,t.setLineDash))switch($){case"dotted":t.setLineDash([1,1]);break;case"dashed":t.setLineDash([4,2]);break;case"double":t.lineWidth=S/4,t.setLineDash([]);break;case"solid":default:t.setLineDash([]);break}if(I?(t.beginPath(),rge(t,V,H,X,W,_)):A?(t.beginPath(),_rt(t,V,H,X,W)):(t.beginPath(),t.rect(V,H,X,W)),z&&t.fill(),F&&t.stroke(),F&&$==="double"){var Z=S/2;t.beginPath(),I?rge(t,V+Z,H+Z,X-2*Z,W-2*Z,_):t.rect(V+Z,H+Z,X-2*Z,W-2*Z),t.stroke()}t.fillStyle=D,t.strokeStyle=N,t.lineWidth=R,t.setLineDash&&t.setLineDash([])}var Y=2*e.pstyle("text-outline-width").pfValue;if(Y>0&&(t.lineWidth=Y),e.pstyle("text-wrap").value==="wrap"){var ae=_o(s,"labelWrapCachedLines",r),J=_o(s,"labelLineHeight",r),ee=g/2,re=this.getLabelJustification(e);switch(re==="auto"||(T==="left"?re==="left"?u+=-g:re==="center"&&(u+=-ee):T==="center"?re==="left"?u+=-ee:re==="right"&&(u+=ee):T==="right"&&(re==="center"?u+=ee:re==="right"&&(u+=g))),w){case"top":h-=(ae.length-1)*J;break;case"center":case"bottom":h-=(ae.length-1)*J;break}for(var te=0;te0&&t.strokeText(ae[te],u,h),t.fillText(ae[te],u,h),h+=J}else Y>0&&t.strokeText(p,u,h),t.fillText(p,u,h);k!==0&&(t.rotate(-k),t.translate(-f,-d))}}};Vd={};Vd.drawNode=function(t,e,r){var i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!0,n=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,a=arguments.length>5&&arguments[5]!==void 0?arguments[5]:!0,s=this,l,u,h=e._private,f=h.rscratch,d=e.position();if(!(!Mt(d.x)||!Mt(d.y))&&!(a&&!e.visible())){var p=a?e.effectiveOpacity():1,m=s.usePaths(),g,y=!1,v=e.padding();l=e.width()+2*v,u=e.height()+2*v;var x;r&&(x=r,t.translate(-x.x1,-x.y1));for(var b=e.pstyle("background-image"),T=b.value,w=new Array(T.length),k=new Array(T.length),C=0,E=0;E0&&arguments[0]!==void 0?arguments[0]:_;s.eleFillStyle(t,e,U)},"setupShapeColor"),J=o(function(){var U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:F;s.colorStrokeStyle(t,D[0],D[1],D[2],U)},"setupBorderColor"),ee=o(function(){var U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:W;s.colorStrokeStyle(t,H[0],H[1],H[2],U)},"setupOutlineColor"),re=o(function(U,ue,G,se){var le=s.nodePathCache=s.nodePathCache||[],ke=Sge(G==="polygon"?G+","+se.join(","):G,""+ue,""+U,""+Y),me=le[ke],ye,Re=!1;return me!=null?(ye=me,Re=!0,f.pathCache=ye):(ye=new Path2D,le[ke]=f.pathCache=ye),{path:ye,cacheHit:Re}},"getPath"),te=e.pstyle("shape").strValue,be=e.pstyle("shape-polygon-points").pfValue;if(m){t.translate(d.x,d.y);var de=re(l,u,te,be);g=de.path,y=de.cacheHit}var Ee=o(function(){if(!y){var U=d;m&&(U={x:0,y:0}),s.nodeShapes[s.getNodeShape(e)].draw(g||t,U.x,U.y,l,u,Y,f)}m?t.fill(g):t.fill()},"drawShape"),Ne=o(function(){for(var U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:p,ue=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,G=h.backgrounding,se=0,le=0;le0&&arguments[0]!==void 0?arguments[0]:!1,ue=arguments.length>1&&arguments[1]!==void 0?arguments[1]:p;s.hasPie(e)&&(s.drawPie(t,e,ue),U&&(m||s.nodeShapes[s.getNodeShape(e)].draw(t,d.x,d.y,l,u,Y,f)))},"drawPie"),Te=o(function(){var U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!1,ue=arguments.length>1&&arguments[1]!==void 0?arguments[1]:p;s.hasStripe(e)&&(t.save(),m?t.clip(f.pathCache):(s.nodeShapes[s.getNodeShape(e)].draw(t,d.x,d.y,l,u,Y,f),t.clip()),s.drawStripe(t,e,ue),t.restore(),U&&(m||s.nodeShapes[s.getNodeShape(e)].draw(t,d.x,d.y,l,u,Y,f)))},"drawStripe"),De=o(function(){var U=arguments.length>0&&arguments[0]!==void 0?arguments[0]:p,ue=(I>0?I:-I)*U,G=I>0?0:255;I!==0&&(s.colorFillStyle(t,G,G,G,ue),m?t.fill(g):t.fill())},"darken"),$e=o(function(){if(A>0){if(t.lineWidth=A,t.lineCap=B,t.lineJoin=R,t.setLineDash)switch(N){case"dotted":t.setLineDash([1,1]);break;case"dashed":t.setLineDash($),t.lineDashOffset=z;break;case"solid":case"double":t.setLineDash([]);break}if(O!=="center"){if(t.save(),t.lineWidth*=2,O==="inside")m?t.clip(g):t.clip();else{var U=new Path2D;U.rect(-l/2-A,-u/2-A,l+2*A,u+2*A),U.addPath(g),t.clip(U,"evenodd")}m?t.stroke(g):t.stroke(),t.restore()}else m?t.stroke(g):t.stroke();if(N==="double"){t.lineWidth=A/3;var ue=t.globalCompositeOperation;t.globalCompositeOperation="destination-out",m?t.stroke(g):t.stroke(),t.globalCompositeOperation=ue}t.setLineDash&&t.setLineDash([])}},"drawBorder"),pe=o(function(){if(V>0){if(t.lineWidth=V,t.lineCap="butt",t.setLineDash)switch(X){case"dotted":t.setLineDash([1,1]);break;case"dashed":t.setLineDash([4,2]);break;case"solid":case"double":t.setLineDash([]);break}var U=d;m&&(U={x:0,y:0});var ue=s.getNodeShape(e),G=A;O==="inside"&&(G=0),O==="outside"&&(G*=2);var se=(l+G+(V+Z))/l,le=(u+G+(V+Z))/u,ke=l*se,me=u*le,ye=s.nodeShapes[ue].points,Re;if(m){var ve=re(ke,me,ue,ye);Re=ve.path}if(ue==="ellipse")s.drawEllipsePath(Re||t,U.x,U.y,ke,me);else if(["round-diamond","round-heptagon","round-hexagon","round-octagon","round-pentagon","round-polygon","round-triangle","round-tag"].includes(ue)){var Oe=0,We=0,Be=0;ue==="round-diamond"?Oe=(G+Z+V)*1.4:ue==="round-heptagon"?(Oe=(G+Z+V)*1.075,Be=-(G/2+Z+V)/35):ue==="round-hexagon"?Oe=(G+Z+V)*1.12:ue==="round-pentagon"?(Oe=(G+Z+V)*1.13,Be=-(G/2+Z+V)/15):ue==="round-tag"?(Oe=(G+Z+V)*1.12,We=(G/2+V+Z)*.07):ue==="round-triangle"&&(Oe=(G+Z+V)*(Math.PI/2),Be=-(G+Z/2+V)/Math.PI),Oe!==0&&(se=(l+Oe)/l,ke=l*se,["round-hexagon","round-tag"].includes(ue)||(le=(u+Oe)/u,me=u*le)),Y=Y==="auto"?Pge(ke,me):Y;for(var Qe=ke/2,ce=me/2,it=Y+(G+V+Z)/2,fe=new Array(ye.length/2),ut=new Array(ye.length/2),Nt=0;Nt0){if(n=n||i.position(),a==null||s==null){var m=i.padding();a=i.width()+2*m,s=i.height()+2*m}l.colorFillStyle(r,f[0],f[1],f[2],h),l.nodeShapes[d].draw(r,n.x,n.y,a+u*2,s+u*2,p),r.fill()}}}},"drawNodeOverlayUnderlay");Vd.drawNodeOverlay=V1e("overlay");Vd.drawNodeUnderlay=V1e("underlay");Vd.hasPie=function(t){return t=t[0],t._private.hasPie};Vd.hasStripe=function(t){return t=t[0],t._private.hasStripe};Vd.drawPie=function(t,e,r,i){e=e[0],i=i||e.position();var n=e.cy().style(),a=e.pstyle("pie-size"),s=e.pstyle("pie-hole"),l=e.pstyle("pie-start-angle").pfValue,u=i.x,h=i.y,f=e.width(),d=e.height(),p=Math.min(f,d)/2,m,g=0,y=this.usePaths();if(y&&(u=0,h=0),a.units==="%"?p=p*a.pfValue:a.pfValue!==void 0&&(p=a.pfValue/2),s.units==="%"?m=p*s.pfValue:s.pfValue!==void 0&&(m=s.pfValue/2),!(m>=p))for(var v=1;v<=n.pieBackgroundN;v++){var x=e.pstyle("pie-"+v+"-background-size").value,b=e.pstyle("pie-"+v+"-background-color").value,T=e.pstyle("pie-"+v+"-background-opacity").value*r,w=x/100;w+g>1&&(w=1-g);var k=1.5*Math.PI+2*Math.PI*g;k+=l;var C=2*Math.PI*w,E=k+C;x===0||g>=1||g+w>1||(m===0?(t.beginPath(),t.moveTo(u,h),t.arc(u,h,p,k,E),t.closePath()):(t.beginPath(),t.arc(u,h,p,k,E),t.arc(u,h,m,E,k,!0),t.closePath()),this.colorFillStyle(t,b[0],b[1],b[2],T),t.fill(),g+=w)}};Vd.drawStripe=function(t,e,r,i){e=e[0],i=i||e.position();var n=e.cy().style(),a=i.x,s=i.y,l=e.width(),u=e.height(),h=0,f=this.usePaths();t.save();var d=e.pstyle("stripe-direction").value,p=e.pstyle("stripe-size");switch(d){case"vertical":break;case"righward":t.rotate(-Math.PI/2);break}var m=l,g=u;p.units==="%"?(m=m*p.pfValue,g=g*p.pfValue):p.pfValue!==void 0&&(m=p.pfValue,g=p.pfValue),f&&(a=0,s=0),s-=m/2,a-=g/2;for(var y=1;y<=n.stripeBackgroundN;y++){var v=e.pstyle("stripe-"+y+"-background-size").value,x=e.pstyle("stripe-"+y+"-background-color").value,b=e.pstyle("stripe-"+y+"-background-opacity").value*r,T=v/100;T+h>1&&(T=1-h),!(v===0||h>=1||h+T>1)&&(t.beginPath(),t.rect(a,s+g*h,m,g*T),t.closePath(),this.colorFillStyle(t,x[0],x[1],x[2],b),t.fill(),h+=T)}t.restore()};Hs={},Drt=100;Hs.getPixelRatio=function(){var t=this.data.contexts[0];if(this.forcedPixelRatio!=null)return this.forcedPixelRatio;var e=this.cy.window(),r=t.backingStorePixelRatio||t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1;return(e.devicePixelRatio||1)/r};Hs.paintCache=function(t){for(var e=this.paintCaches=this.paintCaches||[],r=!0,i,n=0;ne.minMbLowQualFrames&&(e.motionBlurPxRatio=e.mbPxRBlurry)),e.clearingMotionBlur&&(e.motionBlurPxRatio=1),e.textureDrawLastFrame&&!d&&(f[e.NODE]=!0,f[e.SELECT_BOX]=!0);var b=r.style(),T=r.zoom(),w=s!==void 0?s:T,k=r.pan(),C={x:k.x,y:k.y},E={zoom:T,pan:{x:k.x,y:k.y}},S=e.prevViewport,L=S===void 0||E.zoom!==S.zoom||E.pan.x!==S.pan.x||E.pan.y!==S.pan.y;!L&&!(y&&!g)&&(e.motionBlurPxRatio=1),l&&(C=l),w*=u,C.x*=u,C.y*=u;var M=e.getCachedZSortedEles();function I(J,ee,re,te,be){var de=J.globalCompositeOperation;J.globalCompositeOperation="destination-out",e.colorFillStyle(J,255,255,255,e.motionBlurTransparency),J.fillRect(ee,re,te,be),J.globalCompositeOperation=de}o(I,"mbclear");function A(J,ee){var re,te,be,de;!e.clearingMotionBlur&&(J===h.bufferContexts[e.MOTIONBLUR_BUFFER_NODE]||J===h.bufferContexts[e.MOTIONBLUR_BUFFER_DRAG])?(re={x:k.x*m,y:k.y*m},te=T*m,be=e.canvasWidth*m,de=e.canvasHeight*m):(re=C,te=w,be=e.canvasWidth,de=e.canvasHeight),J.setTransform(1,0,0,1,0,0),ee==="motionBlur"?I(J,0,0,be,de):!i&&(ee===void 0||ee)&&J.clearRect(0,0,be,de),n||(J.translate(re.x,re.y),J.scale(te,te)),l&&J.translate(l.x,l.y),s&&J.scale(s,s)}if(o(A,"setContextTransform"),d||(e.textureDrawLastFrame=!1),d){if(e.textureDrawLastFrame=!0,!e.textureCache){e.textureCache={},e.textureCache.bb=r.mutableElements().boundingBox(),e.textureCache.texture=e.data.bufferCanvases[e.TEXTURE_BUFFER];var _=e.data.bufferContexts[e.TEXTURE_BUFFER];_.setTransform(1,0,0,1,0,0),_.clearRect(0,0,e.canvasWidth*e.textureMult,e.canvasHeight*e.textureMult),e.render({forcedContext:_,drawOnlyNodeLayer:!0,forcedPxRatio:u*e.textureMult});var E=e.textureCache.viewport={zoom:r.zoom(),pan:r.pan(),width:e.canvasWidth,height:e.canvasHeight};E.mpan={x:(0-E.pan.x)/E.zoom,y:(0-E.pan.y)/E.zoom}}f[e.DRAG]=!1,f[e.NODE]=!1;var D=h.contexts[e.NODE],N=e.textureCache.texture,E=e.textureCache.viewport;D.setTransform(1,0,0,1,0,0),p?I(D,0,0,E.width,E.height):D.clearRect(0,0,E.width,E.height);var R=b.core("outside-texture-bg-color").value,B=b.core("outside-texture-bg-opacity").value;e.colorFillStyle(D,R[0],R[1],R[2],B),D.fillRect(0,0,E.width,E.height);var T=r.zoom();A(D,!1),D.clearRect(E.mpan.x,E.mpan.y,E.width/E.zoom/u,E.height/E.zoom/u),D.drawImage(N,E.mpan.x,E.mpan.y,E.width/E.zoom/u,E.height/E.zoom/u)}else e.textureOnViewport&&!i&&(e.textureCache=null);var O=r.extent(),$=e.pinching||e.hoverData.dragging||e.swipePanning||e.data.wheelZooming||e.hoverData.draggingEles||e.cy.animated(),z=e.hideEdgesOnViewport&&$,F=[];if(F[e.NODE]=!f[e.NODE]&&p&&!e.clearedForMotionBlur[e.NODE]||e.clearingMotionBlur,F[e.NODE]&&(e.clearedForMotionBlur[e.NODE]=!0),F[e.DRAG]=!f[e.DRAG]&&p&&!e.clearedForMotionBlur[e.DRAG]||e.clearingMotionBlur,F[e.DRAG]&&(e.clearedForMotionBlur[e.DRAG]=!0),f[e.NODE]||n||a||F[e.NODE]){var V=p&&!F[e.NODE]&&m!==1,D=i||(V?e.data.bufferContexts[e.MOTIONBLUR_BUFFER_NODE]:h.contexts[e.NODE]),H=p&&!V?"motionBlur":void 0;A(D,H),z?e.drawCachedNodes(D,M.nondrag,u,O):e.drawLayeredElements(D,M.nondrag,u,O),e.debug&&e.drawDebugPoints(D,M.nondrag),!n&&!p&&(f[e.NODE]=!1)}if(!a&&(f[e.DRAG]||n||F[e.DRAG])){var V=p&&!F[e.DRAG]&&m!==1,D=i||(V?e.data.bufferContexts[e.MOTIONBLUR_BUFFER_DRAG]:h.contexts[e.DRAG]);A(D,p&&!V?"motionBlur":void 0),z?e.drawCachedNodes(D,M.drag,u,O):e.drawCachedElements(D,M.drag,u,O),e.debug&&e.drawDebugPoints(D,M.drag),!n&&!p&&(f[e.DRAG]=!1)}if(this.drawSelectionRectangle(t,A),p&&m!==1){var X=h.contexts[e.NODE],W=e.data.bufferCanvases[e.MOTIONBLUR_BUFFER_NODE],Z=h.contexts[e.DRAG],Y=e.data.bufferCanvases[e.MOTIONBLUR_BUFFER_DRAG],ae=o(function(ee,re,te){ee.setTransform(1,0,0,1,0,0),te||!x?ee.clearRect(0,0,e.canvasWidth,e.canvasHeight):I(ee,0,0,e.canvasWidth,e.canvasHeight);var be=m;ee.drawImage(re,0,0,e.canvasWidth*be,e.canvasHeight*be,0,0,e.canvasWidth,e.canvasHeight)},"drawMotionBlur");(f[e.NODE]||F[e.NODE])&&(ae(X,W,F[e.NODE]),f[e.NODE]=!1),(f[e.DRAG]||F[e.DRAG])&&(ae(Z,Y,F[e.DRAG]),f[e.DRAG]=!1)}e.prevViewport=E,e.clearingMotionBlur&&(e.clearingMotionBlur=!1,e.motionBlurCleared=!0,e.motionBlur=!0),p&&(e.motionBlurTimeout=setTimeout(function(){e.motionBlurTimeout=null,e.clearedForMotionBlur[e.NODE]=!1,e.clearedForMotionBlur[e.DRAG]=!1,e.motionBlur=!1,e.clearingMotionBlur=!d,e.mbFrames=0,f[e.NODE]=!0,f[e.DRAG]=!0,e.redraw()},Drt)),i||r.emit("render")};Hs.drawSelectionRectangle=function(t,e){var r=this,i=r.cy,n=r.data,a=i.style(),s=t.drawOnlyNodeLayer,l=t.drawAllLayers,u=n.canvasNeedsRedraw,h=t.forcedContext;if(r.showFps||!s&&u[r.SELECT_BOX]&&!l){var f=h||n.contexts[r.SELECT_BOX];if(e(f),r.selection[4]==1&&(r.hoverData.selecting||r.touchData.selecting)){var d=r.cy.zoom(),p=a.core("selection-box-border-width").value/d;f.lineWidth=p,f.fillStyle="rgba("+a.core("selection-box-color").value[0]+","+a.core("selection-box-color").value[1]+","+a.core("selection-box-color").value[2]+","+a.core("selection-box-opacity").value+")",f.fillRect(r.selection[0],r.selection[1],r.selection[2]-r.selection[0],r.selection[3]-r.selection[1]),p>0&&(f.strokeStyle="rgba("+a.core("selection-box-border-color").value[0]+","+a.core("selection-box-border-color").value[1]+","+a.core("selection-box-border-color").value[2]+","+a.core("selection-box-opacity").value+")",f.strokeRect(r.selection[0],r.selection[1],r.selection[2]-r.selection[0],r.selection[3]-r.selection[1]))}if(n.bgActivePosistion&&!r.hoverData.selecting){var d=r.cy.zoom(),m=n.bgActivePosistion;f.fillStyle="rgba("+a.core("active-bg-color").value[0]+","+a.core("active-bg-color").value[1]+","+a.core("active-bg-color").value[2]+","+a.core("active-bg-opacity").value+")",f.beginPath(),f.arc(m.x,m.y,a.core("active-bg-size").pfValue/d,0,2*Math.PI),f.fill()}var g=r.lastRedrawTime;if(r.showFps&&g){g=Math.round(g);var y=Math.round(1e3/g),v="1 frame = "+g+" ms = "+y+" fps";if(f.setTransform(1,0,0,1,0,0),f.fillStyle="rgba(255, 0, 0, 0.75)",f.strokeStyle="rgba(255, 0, 0, 0.75)",f.font="30px Arial",!Yb){var x=f.measureText(v);Yb=x.actualBoundingBoxAscent}f.fillText(v,0,Yb);var b=60;f.strokeRect(0,Yb+10,250,20),f.fillRect(0,Yb+10,250*Math.min(y/b,1),20)}l||(u[r.SELECT_BOX]=!1)}};o(ige,"compileShader");o(Lrt,"createProgram");o(Rrt,"createTextureCanvas");o(mF,"getEffectivePanZoom");o(Nrt,"getEffectiveZoom");o(Irt,"modelToRenderedPosition");o(Mrt,"isSimpleShape");o(Ort,"arrayEqual");o(H0,"toWebGLColor");o(ay,"indexToVec4");o(Prt,"vec4ToIndex");o(Brt,"createTexture");o(q1e,"getTypeInfo");o(W1e,"createTypedArray");o(Frt,"createTypedArrayView");o($rt,"createBufferStaticDraw");o(Pu,"createBufferDynamicDraw");o(zrt,"create3x3MatrixBufferDynamicDraw");o(Grt,"createPickingFrameBuffer");nge=typeof Float32Array<"u"?Float32Array:Array;Math.hypot||(Math.hypot=function(){for(var t=0,e=arguments.length;e--;)t+=arguments[e]*arguments[e];return Math.sqrt(t)});o(xB,"create");o(age,"identity");o(Vrt,"multiply");o(uS,"translate");o(sge,"rotate");o(GB,"scale");o(qrt,"projection");Wrt=(function(){function t(e,r,i,n){$d(this,t),this.debugID=Math.floor(Math.random()*1e4),this.r=e,this.texSize=r,this.texRows=i,this.texHeight=Math.floor(r/i),this.enableWrapping=!0,this.locked=!1,this.texture=null,this.needsBuffer=!0,this.freePointer={x:0,row:0},this.keyToLocation=new Map,this.canvas=n(e,r,r),this.scratch=n(e,r,this.texHeight,"scratch")}return o(t,"Atlas"),zd(t,[{key:"lock",value:o(function(){this.locked=!0},"lock")},{key:"getKeys",value:o(function(){return new Set(this.keyToLocation.keys())},"getKeys")},{key:"getScale",value:o(function(r){var i=r.w,n=r.h,a=this.texHeight,s=this.texSize,l=a/n,u=i*l,h=n*l;return u>s&&(l=s/i,u=i*l,h=n*l),{scale:l,texW:u,texH:h}},"getScale")},{key:"draw",value:o(function(r,i,n){var a=this;if(this.locked)throw new Error("can't draw, atlas is locked");var s=this.texSize,l=this.texRows,u=this.texHeight,h=this.getScale(i),f=h.scale,d=h.texW,p=h.texH,m=o(function(T,w){if(n&&w){var k=w.context,C=T.x,E=T.row,S=C,L=u*E;k.save(),k.translate(S,L),k.scale(f,f),n(k,i),k.restore()}},"drawAt"),g=[null,null],y=o(function(){m(a.freePointer,a.canvas),g[0]={x:a.freePointer.x,y:a.freePointer.row*u,w:d,h:p},g[1]={x:a.freePointer.x+d,y:a.freePointer.row*u,w:0,h:p},a.freePointer.x+=d,a.freePointer.x==s&&(a.freePointer.x=0,a.freePointer.row++)},"drawNormal"),v=o(function(){var T=a.scratch,w=a.canvas;T.clear(),m({x:0,row:0},T);var k=s-a.freePointer.x,C=d-k,E=u;{var S=a.freePointer.x,L=a.freePointer.row*u,M=k;w.context.drawImage(T,0,0,M,E,S,L,M,E),g[0]={x:S,y:L,w:M,h:p}}{var I=k,A=(a.freePointer.row+1)*u,_=C;w&&w.context.drawImage(T,I,0,_,E,0,A,_,E),g[1]={x:0,y:A,w:_,h:p}}a.freePointer.x=C,a.freePointer.row++},"drawWrapped"),x=o(function(){a.freePointer.x=0,a.freePointer.row++},"moveToStartOfNextRow");if(this.freePointer.x+d<=s)y();else{if(this.freePointer.row>=l-1)return!1;this.freePointer.x===s?(x(),y()):this.enableWrapping?v():(x(),y())}return this.keyToLocation.set(r,g),this.needsBuffer=!0,g},"draw")},{key:"getOffsets",value:o(function(r){return this.keyToLocation.get(r)},"getOffsets")},{key:"isEmpty",value:o(function(){return this.freePointer.x===0&&this.freePointer.row===0},"isEmpty")},{key:"canFit",value:o(function(r){if(this.locked)return!1;var i=this.texSize,n=this.texRows,a=this.getScale(r),s=a.texW;return this.freePointer.x+s>i?this.freePointer.row1&&arguments[1]!==void 0?arguments[1]:{},a=n.forceRedraw,s=a===void 0?!1:a,l=n.filterEle,u=l===void 0?function(){return!0}:l,h=n.filterType,f=h===void 0?function(){return!0}:h,d=!1,p=!1,m=Lo(r),g;try{for(m.s();!(g=m.n()).done;){var y=g.value;if(u(y)){var v=Lo(this.renderTypes.values()),x;try{var b=o(function(){var w=x.value,k=w.type;if(f(k)){var C=i.collections.get(w.collection),E=w.getKey(y),S=Array.isArray(E)?E:[E];if(s)S.forEach(function(A){return C.markKeyForGC(A)}),p=!0;else{var L=w.getID?w.getID(y):y.id(),M=i._key(k,L),I=i.typeAndIdToKey.get(M);I!==void 0&&!Ort(S,I)&&(d=!0,i.typeAndIdToKey.delete(M),I.forEach(function(A){return C.markKeyForGC(A)}))}}},"_loop2");for(v.s();!(x=v.n()).done;)b()}catch(T){v.e(T)}finally{v.f()}}}}catch(T){m.e(T)}finally{m.f()}return p&&(this.gc(),d=!1),d},"invalidate")},{key:"gc",value:o(function(){var r=Lo(this.collections.values()),i;try{for(r.s();!(i=r.n()).done;){var n=i.value;n.gc()}}catch(a){r.e(a)}finally{r.f()}},"gc")},{key:"getOrCreateAtlas",value:o(function(r,i,n,a){var s=this.renderTypes.get(i),l=this.collections.get(s.collection),u=!1,h=l.draw(a,n,function(p){s.drawClipped?(p.save(),p.beginPath(),p.rect(0,0,n.w,n.h),p.clip(),s.drawElement(p,r,n,!0,!0),p.restore()):s.drawElement(p,r,n,!0,!0),u=!0});if(u){var f=s.getID?s.getID(r):r.id(),d=this._key(i,f);this.typeAndIdToKey.has(d)?this.typeAndIdToKey.get(d).push(a):this.typeAndIdToKey.set(d,[a])}return h},"getOrCreateAtlas")},{key:"getAtlasInfo",value:o(function(r,i){var n=this,a=this.renderTypes.get(i),s=a.getKey(r),l=Array.isArray(s)?s:[s];return l.map(function(u){var h=a.getBoundingBox(r,u),f=n.getOrCreateAtlas(r,i,h,u),d=f.getOffsets(u),p=ea(d,2),m=p[0],g=p[1];return{atlas:f,tex:m,tex1:m,tex2:g,bb:h}})},"getAtlasInfo")},{key:"getDebugInfo",value:o(function(){var r=[],i=Lo(this.collections),n;try{for(i.s();!(n=i.n()).done;){var a=ea(n.value,2),s=a[0],l=a[1],u=l.getCounts(),h=u.keyCount,f=u.atlasCount;r.push({type:s,keyCount:h,atlasCount:f})}}catch(d){i.e(d)}finally{i.f()}return r},"getDebugInfo")}])})(),jrt=(function(){function t(e){$d(this,t),this.globalOptions=e,this.atlasSize=e.webglTexSize,this.maxAtlasesPerBatch=e.webglTexPerBatch,this.batchAtlases=[]}return o(t,"AtlasBatchManager"),zd(t,[{key:"getMaxAtlasesPerBatch",value:o(function(){return this.maxAtlasesPerBatch},"getMaxAtlasesPerBatch")},{key:"getAtlasSize",value:o(function(){return this.atlasSize},"getAtlasSize")},{key:"getIndexArray",value:o(function(){return Array.from({length:this.maxAtlasesPerBatch},function(r,i){return i})},"getIndexArray")},{key:"startBatch",value:o(function(){this.batchAtlases=[]},"startBatch")},{key:"getAtlasCount",value:o(function(){return this.batchAtlases.length},"getAtlasCount")},{key:"getAtlases",value:o(function(){return this.batchAtlases},"getAtlases")},{key:"canAddToCurrentBatch",value:o(function(r){return this.batchAtlases.length===this.maxAtlasesPerBatch?this.batchAtlases.includes(r):!0},"canAddToCurrentBatch")},{key:"getAtlasIndexForBatch",value:o(function(r){var i=this.batchAtlases.indexOf(r);if(i<0){if(this.batchAtlases.length===this.maxAtlasesPerBatch)throw new Error("cannot add more atlases to batch");this.batchAtlases.push(r),i=this.batchAtlases.length-1}return i},"getAtlasIndexForBatch")}])})(),Xrt=` + float circleSD(vec2 p, float r) { + return distance(vec2(0), p) - r; // signed distance + } +`,Krt=` + float rectangleSD(vec2 p, vec2 b) { + vec2 d = abs(p)-b; + return distance(vec2(0),max(d,0.0)) + min(max(d.x,d.y),0.0); + } +`,Qrt=` + float roundRectangleSD(vec2 p, vec2 b, vec4 cr) { + cr.xy = (p.x > 0.0) ? cr.xy : cr.zw; + cr.x = (p.y > 0.0) ? cr.x : cr.y; + vec2 q = abs(p) - b + cr.x; + return min(max(q.x, q.y), 0.0) + distance(vec2(0), max(q, 0.0)) - cr.x; + } +`,Zrt=` + float ellipseSD(vec2 p, vec2 ab) { + p = abs( p ); // symmetry + + // find root with Newton solver + vec2 q = ab*(p-ab); + float w = (q.x1.0) ? d : -d; + } +`,tT={SCREEN:{name:"screen",screen:!0},PICKING:{name:"picking",picking:!0}},CS={IGNORE:1,USE_BB:2},bB=0,oge=1,lge=2,TB=3,sy=4,JE=5,jb=6,Xb=7,Jrt=(function(){function t(e,r,i){$d(this,t),this.r=e,this.gl=r,this.maxInstances=i.webglBatchSize,this.atlasSize=i.webglTexSize,this.bgColor=i.bgColor,this.debug=i.webglDebug,this.batchDebugInfo=[],i.enableWrapping=!0,i.createTextureCanvas=Rrt,this.atlasManager=new Yrt(e,i),this.batchManager=new jrt(i),this.simpleShapeOptions=new Map,this.program=this._createShaderProgram(tT.SCREEN),this.pickingProgram=this._createShaderProgram(tT.PICKING),this.vao=this._createVAO()}return o(t,"ElementDrawingWebGL"),zd(t,[{key:"addAtlasCollection",value:o(function(r,i){this.atlasManager.addAtlasCollection(r,i)},"addAtlasCollection")},{key:"addTextureAtlasRenderType",value:o(function(r,i){this.atlasManager.addRenderType(r,i)},"addTextureAtlasRenderType")},{key:"addSimpleShapeRenderType",value:o(function(r,i){this.simpleShapeOptions.set(r,i)},"addSimpleShapeRenderType")},{key:"invalidate",value:o(function(r){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=i.type,a=this.atlasManager;return n?a.invalidate(r,{filterType:o(function(l){return l===n},"filterType"),forceRedraw:!0}):a.invalidate(r)},"invalidate")},{key:"gc",value:o(function(){this.atlasManager.gc()},"gc")},{key:"_createShaderProgram",value:o(function(r){var i=this.gl,n=`#version 300 es + precision highp float; + + uniform mat3 uPanZoomMatrix; + uniform int uAtlasSize; + + // instanced + in vec2 aPosition; // a vertex from the unit square + + in mat3 aTransform; // used to transform verticies, eg into a bounding box + in int aVertType; // the type of thing we are rendering + + // the z-index that is output when using picking mode + in vec4 aIndex; + + // For textures + in int aAtlasId; // which shader unit/atlas to use + in vec4 aTex; // x/y/w/h of texture in atlas + + // for edges + in vec4 aPointAPointB; + in vec4 aPointCPointD; + in vec2 aLineWidth; // also used for node border width + + // simple shapes + in vec4 aCornerRadius; // for round-rectangle [top-right, bottom-right, top-left, bottom-left] + in vec4 aColor; // also used for edges + in vec4 aBorderColor; // aLineWidth is used for border width + + // output values passed to the fragment shader + out vec2 vTexCoord; + out vec4 vColor; + out vec2 vPosition; + // flat values are not interpolated + flat out int vAtlasId; + flat out int vVertType; + flat out vec2 vTopRight; + flat out vec2 vBotLeft; + flat out vec4 vCornerRadius; + flat out vec4 vBorderColor; + flat out vec2 vBorderWidth; + flat out vec4 vIndex; + + void main(void) { + int vid = gl_VertexID; + vec2 position = aPosition; // TODO make this a vec3, simplifies some code below + + if(aVertType == `.concat(bB,`) { + float texX = aTex.x; // texture coordinates + float texY = aTex.y; + float texW = aTex.z; + float texH = aTex.w; + + if(vid == 1 || vid == 2 || vid == 4) { + texX += texW; + } + if(vid == 2 || vid == 4 || vid == 5) { + texY += texH; + } + + float d = float(uAtlasSize); + vTexCoord = vec2(texX / d, texY / d); // tex coords must be between 0 and 1 + + gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0); + } + else if(aVertType == `).concat(sy," || aVertType == ").concat(Xb,` + || aVertType == `).concat(JE," || aVertType == ").concat(jb,`) { // simple shapes + + // the bounding box is needed by the fragment shader + vBotLeft = (aTransform * vec3(0, 0, 1)).xy; // flat + vTopRight = (aTransform * vec3(1, 1, 1)).xy; // flat + vPosition = (aTransform * vec3(position, 1)).xy; // will be interpolated + + // calculations are done in the fragment shader, just pass these along + vColor = aColor; + vCornerRadius = aCornerRadius; + vBorderColor = aBorderColor; + vBorderWidth = aLineWidth; + + gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0); + } + else if(aVertType == `).concat(oge,`) { + vec2 source = aPointAPointB.xy; + vec2 target = aPointAPointB.zw; + + // adjust the geometry so that the line is centered on the edge + position.y = position.y - 0.5; + + // stretch the unit square into a long skinny rectangle + vec2 xBasis = target - source; + vec2 yBasis = normalize(vec2(-xBasis.y, xBasis.x)); + vec2 point = source + xBasis * position.x + yBasis * aLineWidth[0] * position.y; + + gl_Position = vec4(uPanZoomMatrix * vec3(point, 1.0), 1.0); + vColor = aColor; + } + else if(aVertType == `).concat(lge,`) { + vec2 pointA = aPointAPointB.xy; + vec2 pointB = aPointAPointB.zw; + vec2 pointC = aPointCPointD.xy; + vec2 pointD = aPointCPointD.zw; + + // adjust the geometry so that the line is centered on the edge + position.y = position.y - 0.5; + + vec2 p0, p1, p2, pos; + if(position.x == 0.0) { // The left side of the unit square + p0 = pointA; + p1 = pointB; + p2 = pointC; + pos = position; + } else { // The right side of the unit square, use same approach but flip the geometry upside down + p0 = pointD; + p1 = pointC; + p2 = pointB; + pos = vec2(0.0, -position.y); + } + + vec2 p01 = p1 - p0; + vec2 p12 = p2 - p1; + vec2 p21 = p1 - p2; + + // Find the normal vector. + vec2 tangent = normalize(normalize(p12) + normalize(p01)); + vec2 normal = vec2(-tangent.y, tangent.x); + + // Find the vector perpendicular to p0 -> p1. + vec2 p01Norm = normalize(vec2(-p01.y, p01.x)); + + // Determine the bend direction. + float sigma = sign(dot(p01 + p21, normal)); + float width = aLineWidth[0]; + + if(sign(pos.y) == -sigma) { + // This is an intersecting vertex. Adjust the position so that there's no overlap. + vec2 point = 0.5 * width * normal * -sigma / dot(normal, p01Norm); + gl_Position = vec4(uPanZoomMatrix * vec3(p1 + point, 1.0), 1.0); + } else { + // This is a non-intersecting vertex. Treat it like a mitre join. + vec2 point = 0.5 * width * normal * sigma * dot(normal, p01Norm); + gl_Position = vec4(uPanZoomMatrix * vec3(p1 + point, 1.0), 1.0); + } + + vColor = aColor; + } + else if(aVertType == `).concat(TB,` && vid < 3) { + // massage the first triangle into an edge arrow + if(vid == 0) + position = vec2(-0.15, -0.3); + if(vid == 1) + position = vec2( 0.0, 0.0); + if(vid == 2) + position = vec2( 0.15, -0.3); + + gl_Position = vec4(uPanZoomMatrix * aTransform * vec3(position, 1.0), 1.0); + vColor = aColor; + } + else { + gl_Position = vec4(2.0, 0.0, 0.0, 1.0); // discard vertex by putting it outside webgl clip space + } + + vAtlasId = aAtlasId; + vVertType = aVertType; + vIndex = aIndex; + } + `),a=this.batchManager.getIndexArray(),s=`#version 300 es + precision highp float; + + // declare texture unit for each texture atlas in the batch + `.concat(a.map(function(h){return"uniform sampler2D uTexture".concat(h,";")}).join(` + `),` + + uniform vec4 uBGColor; + uniform float uZoom; + + in vec2 vTexCoord; + in vec4 vColor; + in vec2 vPosition; // model coordinates + + flat in int vAtlasId; + flat in vec4 vIndex; + flat in int vVertType; + flat in vec2 vTopRight; + flat in vec2 vBotLeft; + flat in vec4 vCornerRadius; + flat in vec4 vBorderColor; + flat in vec2 vBorderWidth; + + out vec4 outColor; + + `).concat(Xrt,` + `).concat(Krt,` + `).concat(Qrt,` + `).concat(Zrt,` + + vec4 blend(vec4 top, vec4 bot) { // blend colors with premultiplied alpha + return vec4( + top.rgb + (bot.rgb * (1.0 - top.a)), + top.a + (bot.a * (1.0 - top.a)) + ); + } + + vec4 distInterp(vec4 cA, vec4 cB, float d) { // interpolate color using Signed Distance + // scale to the zoom level so that borders don't look blurry when zoomed in + // note 1.5 is an aribitrary value chosen because it looks good + return mix(cA, cB, 1.0 - smoothstep(0.0, 1.5 / uZoom, abs(d))); + } + + void main(void) { + if(vVertType == `).concat(bB,`) { + // look up the texel from the texture unit + `).concat(a.map(function(h){return"if(vAtlasId == ".concat(h,") outColor = texture(uTexture").concat(h,", vTexCoord);")}).join(` + else `),` + } + else if(vVertType == `).concat(TB,`) { + // mimics how canvas renderer uses context.globalCompositeOperation = 'destination-out'; + outColor = blend(vColor, uBGColor); + outColor.a = 1.0; // make opaque, masks out line under arrow + } + else if(vVertType == `).concat(sy,` && vBorderWidth == vec2(0.0)) { // simple rectangle with no border + outColor = vColor; // unit square is already transformed to the rectangle, nothing else needs to be done + } + else if(vVertType == `).concat(sy," || vVertType == ").concat(Xb,` + || vVertType == `).concat(JE," || vVertType == ").concat(jb,`) { // use SDF + + float outerBorder = vBorderWidth[0]; + float innerBorder = vBorderWidth[1]; + float borderPadding = outerBorder * 2.0; + float w = vTopRight.x - vBotLeft.x - borderPadding; + float h = vTopRight.y - vBotLeft.y - borderPadding; + vec2 b = vec2(w/2.0, h/2.0); // half width, half height + vec2 p = vPosition - vec2(vTopRight.x - b[0] - outerBorder, vTopRight.y - b[1] - outerBorder); // translate to center + + float d; // signed distance + if(vVertType == `).concat(sy,`) { + d = rectangleSD(p, b); + } else if(vVertType == `).concat(Xb,` && w == h) { + d = circleSD(p, b.x); // faster than ellipse + } else if(vVertType == `).concat(Xb,`) { + d = ellipseSD(p, b); + } else { + d = roundRectangleSD(p, b, vCornerRadius.wzyx); + } + + // use the distance to interpolate a color to smooth the edges of the shape, doesn't need multisampling + // we must smooth colors inwards, because we can't change pixels outside the shape's bounding box + if(d > 0.0) { + if(d > outerBorder) { + discard; + } else { + outColor = distInterp(vBorderColor, vec4(0), d - outerBorder); + } + } else { + if(d > innerBorder) { + vec4 outerColor = outerBorder == 0.0 ? vec4(0) : vBorderColor; + vec4 innerBorderColor = blend(vBorderColor, vColor); + outColor = distInterp(innerBorderColor, outerColor, d); + } + else { + vec4 outerColor; + if(innerBorder == 0.0 && outerBorder == 0.0) { + outerColor = vec4(0); + } else if(innerBorder == 0.0) { + outerColor = vBorderColor; + } else { + outerColor = blend(vBorderColor, vColor); + } + outColor = distInterp(vColor, outerColor, d - innerBorder); + } + } + } + else { + outColor = vColor; + } + + `).concat(r.picking?`if(outColor.a == 0.0) discard; + else outColor = vIndex;`:"",` + } + `),l=Lrt(i,n,s);l.aPosition=i.getAttribLocation(l,"aPosition"),l.aIndex=i.getAttribLocation(l,"aIndex"),l.aVertType=i.getAttribLocation(l,"aVertType"),l.aTransform=i.getAttribLocation(l,"aTransform"),l.aAtlasId=i.getAttribLocation(l,"aAtlasId"),l.aTex=i.getAttribLocation(l,"aTex"),l.aPointAPointB=i.getAttribLocation(l,"aPointAPointB"),l.aPointCPointD=i.getAttribLocation(l,"aPointCPointD"),l.aLineWidth=i.getAttribLocation(l,"aLineWidth"),l.aColor=i.getAttribLocation(l,"aColor"),l.aCornerRadius=i.getAttribLocation(l,"aCornerRadius"),l.aBorderColor=i.getAttribLocation(l,"aBorderColor"),l.uPanZoomMatrix=i.getUniformLocation(l,"uPanZoomMatrix"),l.uAtlasSize=i.getUniformLocation(l,"uAtlasSize"),l.uBGColor=i.getUniformLocation(l,"uBGColor"),l.uZoom=i.getUniformLocation(l,"uZoom"),l.uTextures=[];for(var u=0;u1&&arguments[1]!==void 0?arguments[1]:tT.SCREEN;this.panZoomMatrix=r,this.renderTarget=i,this.batchDebugInfo=[],this.wrappedCount=0,this.simpleCount=0,this.startBatch()},"startFrame")},{key:"startBatch",value:o(function(){this.instanceCount=0,this.batchManager.startBatch()},"startBatch")},{key:"endFrame",value:o(function(){this.endBatch()},"endFrame")},{key:"_isVisible",value:o(function(r,i){return r.visible()?i&&i.isVisible?i.isVisible(r):!0:!1},"_isVisible")},{key:"drawTexture",value:o(function(r,i,n){var a=this.atlasManager,s=this.batchManager,l=a.getRenderTypeOpts(n);if(this._isVisible(r,l)&&!(r.isEdge()&&!this._isValidEdge(r))){if(this.renderTarget.picking&&l.getTexPickingMode){var u=l.getTexPickingMode(r);if(u===CS.IGNORE)return;if(u==CS.USE_BB){this.drawPickingRectangle(r,i,n);return}}var h=a.getAtlasInfo(r,n),f=Lo(h),d;try{for(f.s();!(d=f.n()).done;){var p=d.value,m=p.atlas,g=p.tex1,y=p.tex2;s.canAddToCurrentBatch(m)||this.endBatch();for(var v=s.getAtlasIndexForBatch(m),x=0,b=[[g,!0],[y,!1]];x=this.maxInstances&&this.endBatch()}}}}catch(I){f.e(I)}finally{f.f()}}},"drawTexture")},{key:"setTransformMatrix",value:o(function(r,i,n,a){var s=arguments.length>4&&arguments[4]!==void 0?arguments[4]:!0,l=0;if(n.shapeProps&&n.shapeProps.padding&&(l=r.pstyle(n.shapeProps.padding).pfValue),a){var u=a.bb,h=a.tex1,f=a.tex2,d=h.w/(h.w+f.w);s||(d=1-d);var p=this._getAdjustedBB(u,l,s,d);this._applyTransformMatrix(i,p,n,r)}else{var m=n.getBoundingBox(r),g=this._getAdjustedBB(m,l,!0,1);this._applyTransformMatrix(i,g,n,r)}},"setTransformMatrix")},{key:"_applyTransformMatrix",value:o(function(r,i,n,a){var s,l;age(r);var u=n.getRotation?n.getRotation(a):0;if(u!==0){var h=n.getRotationPoint(a),f=h.x,d=h.y;uS(r,r,[f,d]),sge(r,r,u);var p=n.getRotationOffset(a);s=p.x+(i.xOffset||0),l=p.y+(i.yOffset||0)}else s=i.x1,l=i.y1;uS(r,r,[s,l]),GB(r,r,[i.w,i.h])},"_applyTransformMatrix")},{key:"_getAdjustedBB",value:o(function(r,i,n,a){var s=r.x1,l=r.y1,u=r.w,h=r.h,f=r.yOffset;i&&(s-=i,l-=i,u+=2*i,h+=2*i);var d=0,p=u*a;return n&&a<1?u=p:!n&&a<1&&(d=u-p,s+=d,u=p),{x1:s,y1:l,w:u,h,xOffset:d,yOffset:f}},"_getAdjustedBB")},{key:"drawPickingRectangle",value:o(function(r,i,n){var a=this.atlasManager.getRenderTypeOpts(n),s=this.instanceCount;this.vertTypeBuffer.getView(s)[0]=sy;var l=this.indexBuffer.getView(s);ay(i,l);var u=this.colorBuffer.getView(s);H0([0,0,0],1,u);var h=this.transformBuffer.getMatrixView(s);this.setTransformMatrix(r,h,a),this.simpleCount++,this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()},"drawPickingRectangle")},{key:"drawNode",value:o(function(r,i,n){var a=this.simpleShapeOptions.get(n);if(this._isVisible(r,a)){var s=a.shapeProps,l=this._getVertTypeForShape(r,s.shape);if(l===void 0||a.isSimple&&!a.isSimple(r)){this.drawTexture(r,i,n);return}var u=this.instanceCount;if(this.vertTypeBuffer.getView(u)[0]=l,l===JE||l===jb){var h=a.getBoundingBox(r),f=this._getCornerRadius(r,s.radius,h),d=this.cornerRadiusBuffer.getView(u);d[0]=f,d[1]=f,d[2]=f,d[3]=f,l===jb&&(d[0]=0,d[2]=0)}var p=this.indexBuffer.getView(u);ay(i,p);var m=r.pstyle(s.color).value,g=r.pstyle(s.opacity).value,y=this.colorBuffer.getView(u);H0(m,g,y);var v=this.lineWidthBuffer.getView(u);if(v[0]=0,v[1]=0,s.border){var x=r.pstyle("border-width").value;if(x>0){var b=r.pstyle("border-color").value,T=r.pstyle("border-opacity").value,w=this.borderColorBuffer.getView(u);H0(b,T,w);var k=r.pstyle("border-position").value;if(k==="inside")v[0]=0,v[1]=-x;else if(k==="outside")v[0]=x,v[1]=0;else{var C=x/2;v[0]=C,v[1]=-C}}}var E=this.transformBuffer.getMatrixView(u);this.setTransformMatrix(r,E,a),this.simpleCount++,this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}},"drawNode")},{key:"_getVertTypeForShape",value:o(function(r,i){var n=r.pstyle(i).value;switch(n){case"rectangle":return sy;case"ellipse":return Xb;case"roundrectangle":case"round-rectangle":return JE;case"bottom-round-rectangle":return jb;default:return}},"_getVertTypeForShape")},{key:"_getCornerRadius",value:o(function(r,i,n){var a=n.w,s=n.h;if(r.pstyle(i).value==="auto")return Od(a,s);var l=r.pstyle(i).pfValue,u=a/2,h=s/2;return Math.min(l,h,u)},"_getCornerRadius")},{key:"drawEdgeArrow",value:o(function(r,i,n){if(r.visible()){var a=r._private.rscratch,s,l,u;if(n==="source"?(s=a.arrowStartX,l=a.arrowStartY,u=a.srcArrowAngle):(s=a.arrowEndX,l=a.arrowEndY,u=a.tgtArrowAngle),!(isNaN(s)||s==null||isNaN(l)||l==null||isNaN(u)||u==null)){var h=r.pstyle(n+"-arrow-shape").value;if(h!=="none"){var f=r.pstyle(n+"-arrow-color").value,d=r.pstyle("opacity").value,p=r.pstyle("line-opacity").value,m=d*p,g=r.pstyle("width").pfValue,y=r.pstyle("arrow-scale").value,v=this.r.getArrowWidth(g,y),x=this.instanceCount,b=this.transformBuffer.getMatrixView(x);age(b),uS(b,b,[s,l]),GB(b,b,[v,v]),sge(b,b,u),this.vertTypeBuffer.getView(x)[0]=TB;var T=this.indexBuffer.getView(x);ay(i,T);var w=this.colorBuffer.getView(x);H0(f,m,w),this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}}}},"drawEdgeArrow")},{key:"drawEdgeLine",value:o(function(r,i){if(r.visible()){var n=this._getEdgePoints(r);if(n){var a=r.pstyle("opacity").value,s=r.pstyle("line-opacity").value,l=r.pstyle("width").pfValue,u=r.pstyle("line-color").value,h=a*s;if(n.length/2+this.instanceCount>this.maxInstances&&this.endBatch(),n.length==4){var f=this.instanceCount;this.vertTypeBuffer.getView(f)[0]=oge;var d=this.indexBuffer.getView(f);ay(i,d);var p=this.colorBuffer.getView(f);H0(u,h,p);var m=this.lineWidthBuffer.getView(f);m[0]=l;var g=this.pointAPointBBuffer.getView(f);g[0]=n[0],g[1]=n[1],g[2]=n[2],g[3]=n[3],this.instanceCount++,this.instanceCount>=this.maxInstances&&this.endBatch()}else for(var y=0;y=this.maxInstances&&this.endBatch()}}}},"drawEdgeLine")},{key:"_isValidEdge",value:o(function(r){var i=r._private.rscratch;return!(i.badLine||i.allpts==null||isNaN(i.allpts[0]))},"_isValidEdge")},{key:"_getEdgePoints",value:o(function(r){var i=r._private.rscratch;if(this._isValidEdge(r)){var n=i.allpts;if(n.length==4)return n;var a=this._getNumSegments(r);return this._getCurveSegmentPoints(n,a)}},"_getEdgePoints")},{key:"_getNumSegments",value:o(function(r){var i=15;return Math.min(Math.max(i,5),this.maxInstances)},"_getNumSegments")},{key:"_getCurveSegmentPoints",value:o(function(r,i){if(r.length==4)return r;for(var n=Array((i+1)*2),a=0;a<=i;a++)if(a==0)n[0]=r[0],n[1]=r[1];else if(a==i)n[a*2]=r[r.length-2],n[a*2+1]=r[r.length-1];else{var s=a/i;this._setCurvePoint(r,s,n,a*2)}return n},"_getCurveSegmentPoints")},{key:"_setCurvePoint",value:o(function(r,i,n,a){if(r.length<=2)n[a]=r[0],n[a+1]=r[1];else{for(var s=Array(r.length-2),l=0;l0}},"isLayerVisible"),l=o(function(d){var p=d.pstyle("text-events").strValue==="yes";return p?CS.USE_BB:CS.IGNORE},"getTexPickingMode"),u=o(function(d){var p=d.position(),m=p.x,g=p.y,y=d.outerWidth(),v=d.outerHeight();return{w:y,h:v,x1:m-y/2,y1:g-v/2}},"getBBForSimpleShape");r.drawing.addAtlasCollection("node",{texRows:t.webglTexRowsNodes}),r.drawing.addAtlasCollection("label",{texRows:t.webglTexRows}),r.drawing.addTextureAtlasRenderType("node-body",{collection:"node",getKey:e.getStyleKey,getBoundingBox:e.getElementBox,drawElement:e.drawElement}),r.drawing.addSimpleShapeRenderType("node-body",{getBoundingBox:u,isSimple:Mrt,shapeProps:{shape:"shape",color:"background-color",opacity:"background-opacity",radius:"corner-radius",border:!0}}),r.drawing.addSimpleShapeRenderType("node-overlay",{getBoundingBox:u,isVisible:s("overlay"),shapeProps:{shape:"overlay-shape",color:"overlay-color",opacity:"overlay-opacity",padding:"overlay-padding",radius:"overlay-corner-radius"}}),r.drawing.addSimpleShapeRenderType("node-underlay",{getBoundingBox:u,isVisible:s("underlay"),shapeProps:{shape:"underlay-shape",color:"underlay-color",opacity:"underlay-opacity",padding:"underlay-padding",radius:"underlay-corner-radius"}}),r.drawing.addTextureAtlasRenderType("label",{collection:"label",getTexPickingMode:l,getKey:kB(e.getLabelKey,null),getBoundingBox:CB(e.getLabelBox,null),drawClipped:!0,drawElement:e.drawLabel,getRotation:n(null),getRotationPoint:e.getLabelRotationPoint,getRotationOffset:e.getLabelRotationOffset,isVisible:a("label")}),r.drawing.addTextureAtlasRenderType("edge-source-label",{collection:"label",getTexPickingMode:l,getKey:kB(e.getSourceLabelKey,"source"),getBoundingBox:CB(e.getSourceLabelBox,"source"),drawClipped:!0,drawElement:e.drawSourceLabel,getRotation:n("source"),getRotationPoint:e.getSourceLabelRotationPoint,getRotationOffset:e.getSourceLabelRotationOffset,isVisible:a("source-label")}),r.drawing.addTextureAtlasRenderType("edge-target-label",{collection:"label",getTexPickingMode:l,getKey:kB(e.getTargetLabelKey,"target"),getBoundingBox:CB(e.getTargetLabelBox,"target"),drawClipped:!0,drawElement:e.drawTargetLabel,getRotation:n("target"),getRotationPoint:e.getTargetLabelRotationPoint,getRotationOffset:e.getTargetLabelRotationOffset,isVisible:a("target-label")});var h=yT(function(){console.log("garbage collect flag set"),r.data.gc=!0},1e4);r.onUpdateEleCalcs(function(f,d){var p=!1;d&&d.length>0&&(p|=r.drawing.invalidate(d)),p&&h()}),tit(r)};o(eit,"getBGColor");o(H1e,"getLabelLines");kB=o(function(e,r){return function(i){var n=e(i),a=H1e(i,r);return a.length>1?a.map(function(s,l){return"".concat(n,"_").concat(l)}):n}},"getStyleKeysForLabel"),CB=o(function(e,r){return function(i,n){var a=e(i);if(typeof n=="string"){var s=n.indexOf("_");if(s>0){var l=Number(n.substring(s+1)),u=H1e(i,r),h=a.h/u.length,f=h*l,d=a.y1+f;return{x1:a.x1,w:a.w,y1:d,h,yOffset:f}}}return a}},"getBoundingBoxForLabel");o(tit,"overrideCanvasRendererFunctions");o(rit,"clearWebgl");o(iit,"clearCanvas");o(nit,"createPanZoomMatrix");o(Y1e,"setContextTransform");o(ait,"drawSelectionRectangle");o(sit,"drawAxes");o(oit,"drawAtlases");o(lit,"getPickingIndexes");o(cit,"findNearestElementsWebgl");o(wB,"drawEle");o(j1e,"renderWebgl");qd={};qd.drawPolygonPath=function(t,e,r,i,n,a){var s=i/2,l=n/2;t.beginPath&&t.beginPath(),t.moveTo(e+s*a[0],r+l*a[1]);for(var u=1;u0&&s>0){m.clearRect(0,0,a,s),m.globalCompositeOperation="source-over";var g=this.getCachedZSortedEles();if(t.full)m.translate(-i.x1*h,-i.y1*h),m.scale(h,h),this.drawElements(m,g),m.scale(1/h,1/h),m.translate(i.x1*h,i.y1*h);else{var y=e.pan(),v={x:y.x*h,y:y.y*h};h*=e.zoom(),m.translate(v.x,v.y),m.scale(h,h),this.drawElements(m,g),m.scale(1/h,1/h),m.translate(-v.x,-v.y)}t.bg&&(m.globalCompositeOperation="destination-over",m.fillStyle=t.bg,m.rect(0,0,a,s),m.fill())}return p};o(uit,"b64ToBlob");o(hge,"b64UriToB64");o(K1e,"output");CT.png=function(t){return K1e(t,this.bufferCanvasImage(t),"image/png")};CT.jpg=function(t){return K1e(t,this.bufferCanvasImage(t),"image/jpeg")};Q1e={};Q1e.nodeShapeImpl=function(t,e,r,i,n,a,s,l){switch(t){case"ellipse":return this.drawEllipsePath(e,r,i,n,a);case"polygon":return this.drawPolygonPath(e,r,i,n,a,s);case"round-polygon":return this.drawRoundPolygonPath(e,r,i,n,a,s,l);case"roundrectangle":case"round-rectangle":return this.drawRoundRectanglePath(e,r,i,n,a,l);case"cutrectangle":case"cut-rectangle":return this.drawCutRectanglePath(e,r,i,n,a,s,l);case"bottomroundrectangle":case"bottom-round-rectangle":return this.drawBottomRoundRectanglePath(e,r,i,n,a,l);case"barrel":return this.drawBarrelPath(e,r,i,n,a)}};hit=Z1e,Yr=Z1e.prototype;Yr.CANVAS_LAYERS=3;Yr.SELECT_BOX=0;Yr.DRAG=1;Yr.NODE=2;Yr.WEBGL=3;Yr.CANVAS_TYPES=["2d","2d","2d","webgl2"];Yr.BUFFER_COUNT=3;Yr.TEXTURE_BUFFER=0;Yr.MOTIONBLUR_BUFFER_NODE=1;Yr.MOTIONBLUR_BUFFER_DRAG=2;o(Z1e,"CanvasRenderer");Yr.redrawHint=function(t,e){var r=this;switch(t){case"eles":r.data.canvasNeedsRedraw[Yr.NODE]=e;break;case"drag":r.data.canvasNeedsRedraw[Yr.DRAG]=e;break;case"select":r.data.canvasNeedsRedraw[Yr.SELECT_BOX]=e;break;case"gc":r.data.gc=!0;break}};fit=typeof Path2D<"u";Yr.path2dEnabled=function(t){if(t===void 0)return this.pathsEnabled;this.pathsEnabled=!!t};Yr.usePaths=function(){return fit&&this.pathsEnabled};Yr.setImgSmoothing=function(t,e){t.imageSmoothingEnabled!=null?t.imageSmoothingEnabled=e:(t.webkitImageSmoothingEnabled=e,t.mozImageSmoothingEnabled=e,t.msImageSmoothingEnabled=e)};Yr.getImgSmoothing=function(t){return t.imageSmoothingEnabled!=null?t.imageSmoothingEnabled:t.webkitImageSmoothingEnabled||t.mozImageSmoothingEnabled||t.msImageSmoothingEnabled};Yr.makeOffscreenCanvas=function(t,e){var r;if((typeof OffscreenCanvas>"u"?"undefined":pa(OffscreenCanvas))!=="undefined")r=new OffscreenCanvas(t,e);else{var i=this.cy.window(),n=i.document;r=n.createElement("canvas"),r.width=t,r.height=e}return r};[z1e,Gu,Jh,pF,am,Vd,Hs,U1e,qd,CT,Q1e].forEach(function(t){yr(Yr,t)});dit=[{name:"null",impl:S1e},{name:"base",impl:P1e},{name:"canvas",impl:hit}],pit=[{type:"layout",extensions:$tt},{type:"renderer",extensions:dit}],J1e={},eye={};o(tye,"setExtension");o(rye,"getExtension");o(mit,"setModule");o(git,"getModule");WB=o(function(){if(arguments.length===2)return rye.apply(null,arguments);if(arguments.length===3)return tye.apply(null,arguments);if(arguments.length===4)return git.apply(null,arguments);if(arguments.length===5)return mit.apply(null,arguments);mn("Invalid extension access syntax")},"extension");uT.prototype.extension=WB;pit.forEach(function(t){t.extensions.forEach(function(e){tye(t.type,e.name,e.impl)})});wS=o(function(){if(!(this instanceof wS))return new wS;this.length=0},"Stylesheet"),im=wS.prototype;im.instanceString=function(){return"stylesheet"};im.selector=function(t){var e=this.length++;return this[e]={selector:t,properties:[]},this};im.css=function(t,e){var r=this.length-1;if(lr(t))this[r].properties.push({name:t,value:e});else if(si(t))for(var i=t,n=Object.keys(i),a=0;a{"use strict";o((function(e,r){typeof wT=="object"&&typeof yF=="object"?yF.exports=r():typeof define=="function"&&define.amd?define([],r):typeof wT=="object"?wT.layoutBase=r():e.layoutBase=r()}),"webpackUniversalModuleDefinition")(wT,function(){return(function(t){var e={};function r(i){if(e[i])return e[i].exports;var n=e[i]={i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return o(r,"__webpack_require__"),r.m=t,r.c=e,r.i=function(i){return i},r.d=function(i,n,a){r.o(i,n)||Object.defineProperty(i,n,{configurable:!1,enumerable:!0,get:a})},r.n=function(i){var n=i&&i.__esModule?o(function(){return i.default},"getDefault"):o(function(){return i},"getModuleExports");return r.d(n,"a",n),n},r.o=function(i,n){return Object.prototype.hasOwnProperty.call(i,n)},r.p="",r(r.s=26)})([(function(t,e,r){"use strict";function i(){}o(i,"LayoutConstants"),i.QUALITY=1,i.DEFAULT_CREATE_BENDS_AS_NEEDED=!1,i.DEFAULT_INCREMENTAL=!1,i.DEFAULT_ANIMATION_ON_LAYOUT=!0,i.DEFAULT_ANIMATION_DURING_LAYOUT=!1,i.DEFAULT_ANIMATION_PERIOD=50,i.DEFAULT_UNIFORM_LEAF_NODE_SIZES=!1,i.DEFAULT_GRAPH_MARGIN=15,i.NODE_DIMENSIONS_INCLUDE_LABELS=!1,i.SIMPLE_NODE_SIZE=40,i.SIMPLE_NODE_HALF_SIZE=i.SIMPLE_NODE_SIZE/2,i.EMPTY_COMPOUND_NODE_SIZE=40,i.MIN_EDGE_LENGTH=1,i.WORLD_BOUNDARY=1e6,i.INITIAL_WORLD_BOUNDARY=i.WORLD_BOUNDARY/1e3,i.WORLD_CENTER_X=1200,i.WORLD_CENTER_Y=900,t.exports=i}),(function(t,e,r){"use strict";var i=r(2),n=r(8),a=r(9);function s(u,h,f){i.call(this,f),this.isOverlapingSourceAndTarget=!1,this.vGraphObject=f,this.bendpoints=[],this.source=u,this.target=h}o(s,"LEdge"),s.prototype=Object.create(i.prototype);for(var l in i)s[l]=i[l];s.prototype.getSource=function(){return this.source},s.prototype.getTarget=function(){return this.target},s.prototype.isInterGraph=function(){return this.isInterGraph},s.prototype.getLength=function(){return this.length},s.prototype.isOverlapingSourceAndTarget=function(){return this.isOverlapingSourceAndTarget},s.prototype.getBendpoints=function(){return this.bendpoints},s.prototype.getLca=function(){return this.lca},s.prototype.getSourceInLca=function(){return this.sourceInLca},s.prototype.getTargetInLca=function(){return this.targetInLca},s.prototype.getOtherEnd=function(u){if(this.source===u)return this.target;if(this.target===u)return this.source;throw"Node is not incident with this edge"},s.prototype.getOtherEndInGraph=function(u,h){for(var f=this.getOtherEnd(u),d=h.getGraphManager().getRoot();;){if(f.getOwner()==h)return f;if(f.getOwner()==d)break;f=f.getOwner().getParent()}return null},s.prototype.updateLength=function(){var u=new Array(4);this.isOverlapingSourceAndTarget=n.getIntersection(this.target.getRect(),this.source.getRect(),u),this.isOverlapingSourceAndTarget||(this.lengthX=u[0]-u[2],this.lengthY=u[1]-u[3],Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY))},s.prototype.updateLengthSimple=function(){this.lengthX=this.target.getCenterX()-this.source.getCenterX(),this.lengthY=this.target.getCenterY()-this.source.getCenterY(),Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY)},t.exports=s}),(function(t,e,r){"use strict";function i(n){this.vGraphObject=n}o(i,"LGraphObject"),t.exports=i}),(function(t,e,r){"use strict";var i=r(2),n=r(10),a=r(13),s=r(0),l=r(16),u=r(4);function h(d,p,m,g){m==null&&g==null&&(g=p),i.call(this,g),d.graphManager!=null&&(d=d.graphManager),this.estimatedSize=n.MIN_VALUE,this.inclusionTreeDepth=n.MAX_VALUE,this.vGraphObject=g,this.edges=[],this.graphManager=d,m!=null&&p!=null?this.rect=new a(p.x,p.y,m.width,m.height):this.rect=new a}o(h,"LNode"),h.prototype=Object.create(i.prototype);for(var f in i)h[f]=i[f];h.prototype.getEdges=function(){return this.edges},h.prototype.getChild=function(){return this.child},h.prototype.getOwner=function(){return this.owner},h.prototype.getWidth=function(){return this.rect.width},h.prototype.setWidth=function(d){this.rect.width=d},h.prototype.getHeight=function(){return this.rect.height},h.prototype.setHeight=function(d){this.rect.height=d},h.prototype.getCenterX=function(){return this.rect.x+this.rect.width/2},h.prototype.getCenterY=function(){return this.rect.y+this.rect.height/2},h.prototype.getCenter=function(){return new u(this.rect.x+this.rect.width/2,this.rect.y+this.rect.height/2)},h.prototype.getLocation=function(){return new u(this.rect.x,this.rect.y)},h.prototype.getRect=function(){return this.rect},h.prototype.getDiagonal=function(){return Math.sqrt(this.rect.width*this.rect.width+this.rect.height*this.rect.height)},h.prototype.getHalfTheDiagonal=function(){return Math.sqrt(this.rect.height*this.rect.height+this.rect.width*this.rect.width)/2},h.prototype.setRect=function(d,p){this.rect.x=d.x,this.rect.y=d.y,this.rect.width=p.width,this.rect.height=p.height},h.prototype.setCenter=function(d,p){this.rect.x=d-this.rect.width/2,this.rect.y=p-this.rect.height/2},h.prototype.setLocation=function(d,p){this.rect.x=d,this.rect.y=p},h.prototype.moveBy=function(d,p){this.rect.x+=d,this.rect.y+=p},h.prototype.getEdgeListToNode=function(d){var p=[],m,g=this;return g.edges.forEach(function(y){if(y.target==d){if(y.source!=g)throw"Incorrect edge source!";p.push(y)}}),p},h.prototype.getEdgesBetween=function(d){var p=[],m,g=this;return g.edges.forEach(function(y){if(!(y.source==g||y.target==g))throw"Incorrect edge source and/or target";(y.target==d||y.source==d)&&p.push(y)}),p},h.prototype.getNeighborsList=function(){var d=new Set,p=this;return p.edges.forEach(function(m){if(m.source==p)d.add(m.target);else{if(m.target!=p)throw"Incorrect incidency!";d.add(m.source)}}),d},h.prototype.withChildren=function(){var d=new Set,p,m;if(d.add(this),this.child!=null)for(var g=this.child.getNodes(),y=0;yp&&(this.rect.x-=(this.labelWidth-p)/2,this.setWidth(this.labelWidth)),this.labelHeight>m&&(this.labelPos=="center"?this.rect.y-=(this.labelHeight-m)/2:this.labelPos=="top"&&(this.rect.y-=this.labelHeight-m),this.setHeight(this.labelHeight))}}},h.prototype.getInclusionTreeDepth=function(){if(this.inclusionTreeDepth==n.MAX_VALUE)throw"assert failed";return this.inclusionTreeDepth},h.prototype.transform=function(d){var p=this.rect.x;p>s.WORLD_BOUNDARY?p=s.WORLD_BOUNDARY:p<-s.WORLD_BOUNDARY&&(p=-s.WORLD_BOUNDARY);var m=this.rect.y;m>s.WORLD_BOUNDARY?m=s.WORLD_BOUNDARY:m<-s.WORLD_BOUNDARY&&(m=-s.WORLD_BOUNDARY);var g=new u(p,m),y=d.inverseTransformPoint(g);this.setLocation(y.x,y.y)},h.prototype.getLeft=function(){return this.rect.x},h.prototype.getRight=function(){return this.rect.x+this.rect.width},h.prototype.getTop=function(){return this.rect.y},h.prototype.getBottom=function(){return this.rect.y+this.rect.height},h.prototype.getParent=function(){return this.owner==null?null:this.owner.getParent()},t.exports=h}),(function(t,e,r){"use strict";function i(n,a){n==null&&a==null?(this.x=0,this.y=0):(this.x=n,this.y=a)}o(i,"PointD"),i.prototype.getX=function(){return this.x},i.prototype.getY=function(){return this.y},i.prototype.setX=function(n){this.x=n},i.prototype.setY=function(n){this.y=n},i.prototype.getDifference=function(n){return new DimensionD(this.x-n.x,this.y-n.y)},i.prototype.getCopy=function(){return new i(this.x,this.y)},i.prototype.translate=function(n){return this.x+=n.width,this.y+=n.height,this},t.exports=i}),(function(t,e,r){"use strict";var i=r(2),n=r(10),a=r(0),s=r(6),l=r(3),u=r(1),h=r(13),f=r(12),d=r(11);function p(g,y,v){i.call(this,v),this.estimatedSize=n.MIN_VALUE,this.margin=a.DEFAULT_GRAPH_MARGIN,this.edges=[],this.nodes=[],this.isConnected=!1,this.parent=g,y!=null&&y instanceof s?this.graphManager=y:y!=null&&y instanceof Layout&&(this.graphManager=y.graphManager)}o(p,"LGraph"),p.prototype=Object.create(i.prototype);for(var m in i)p[m]=i[m];p.prototype.getNodes=function(){return this.nodes},p.prototype.getEdges=function(){return this.edges},p.prototype.getGraphManager=function(){return this.graphManager},p.prototype.getParent=function(){return this.parent},p.prototype.getLeft=function(){return this.left},p.prototype.getRight=function(){return this.right},p.prototype.getTop=function(){return this.top},p.prototype.getBottom=function(){return this.bottom},p.prototype.isConnected=function(){return this.isConnected},p.prototype.add=function(g,y,v){if(y==null&&v==null){var x=g;if(this.graphManager==null)throw"Graph has no graph mgr!";if(this.getNodes().indexOf(x)>-1)throw"Node already in graph!";return x.owner=this,this.getNodes().push(x),x}else{var b=g;if(!(this.getNodes().indexOf(y)>-1&&this.getNodes().indexOf(v)>-1))throw"Source or target not in graph!";if(!(y.owner==v.owner&&y.owner==this))throw"Both owners must be this graph!";return y.owner!=v.owner?null:(b.source=y,b.target=v,b.isInterGraph=!1,this.getEdges().push(b),y.edges.push(b),v!=y&&v.edges.push(b),b)}},p.prototype.remove=function(g){var y=g;if(g instanceof l){if(y==null)throw"Node is null!";if(!(y.owner!=null&&y.owner==this))throw"Owner graph is invalid!";if(this.graphManager==null)throw"Owner graph manager is invalid!";for(var v=y.edges.slice(),x,b=v.length,T=0;T-1&&C>-1))throw"Source and/or target doesn't know this edge!";x.source.edges.splice(k,1),x.target!=x.source&&x.target.edges.splice(C,1);var w=x.source.owner.getEdges().indexOf(x);if(w==-1)throw"Not in owner's edge list!";x.source.owner.getEdges().splice(w,1)}},p.prototype.updateLeftTop=function(){for(var g=n.MAX_VALUE,y=n.MAX_VALUE,v,x,b,T=this.getNodes(),w=T.length,k=0;kv&&(g=v),y>x&&(y=x)}return g==n.MAX_VALUE?null:(T[0].getParent().paddingLeft!=null?b=T[0].getParent().paddingLeft:b=this.margin,this.left=y-b,this.top=g-b,new f(this.left,this.top))},p.prototype.updateBounds=function(g){for(var y=n.MAX_VALUE,v=-n.MAX_VALUE,x=n.MAX_VALUE,b=-n.MAX_VALUE,T,w,k,C,E,S=this.nodes,L=S.length,M=0;MT&&(y=T),vk&&(x=k),bT&&(y=T),vk&&(x=k),b=this.nodes.length){var L=0;v.forEach(function(M){M.owner==g&&L++}),L==this.nodes.length&&(this.isConnected=!0)}},t.exports=p}),(function(t,e,r){"use strict";var i,n=r(1);function a(s){i=r(5),this.layout=s,this.graphs=[],this.edges=[]}o(a,"LGraphManager"),a.prototype.addRoot=function(){var s=this.layout.newGraph(),l=this.layout.newNode(null),u=this.add(s,l);return this.setRootGraph(u),this.rootGraph},a.prototype.add=function(s,l,u,h,f){if(u==null&&h==null&&f==null){if(s==null)throw"Graph is null!";if(l==null)throw"Parent node is null!";if(this.graphs.indexOf(s)>-1)throw"Graph already in this graph mgr!";if(this.graphs.push(s),s.parent!=null)throw"Already has a parent!";if(l.child!=null)throw"Already has a child!";return s.parent=l,l.child=s,s}else{f=u,h=l,u=s;var d=h.getOwner(),p=f.getOwner();if(!(d!=null&&d.getGraphManager()==this))throw"Source not in this graph mgr!";if(!(p!=null&&p.getGraphManager()==this))throw"Target not in this graph mgr!";if(d==p)return u.isInterGraph=!1,d.add(u,h,f);if(u.isInterGraph=!0,u.source=h,u.target=f,this.edges.indexOf(u)>-1)throw"Edge already in inter-graph edge list!";if(this.edges.push(u),!(u.source!=null&&u.target!=null))throw"Edge source and/or target is null!";if(!(u.source.edges.indexOf(u)==-1&&u.target.edges.indexOf(u)==-1))throw"Edge already in source and/or target incidency list!";return u.source.edges.push(u),u.target.edges.push(u),u}},a.prototype.remove=function(s){if(s instanceof i){var l=s;if(l.getGraphManager()!=this)throw"Graph not in this graph mgr";if(!(l==this.rootGraph||l.parent!=null&&l.parent.graphManager==this))throw"Invalid parent node!";var u=[];u=u.concat(l.getEdges());for(var h,f=u.length,d=0;d=s.getRight()?l[0]+=Math.min(s.getX()-a.getX(),a.getRight()-s.getRight()):s.getX()<=a.getX()&&s.getRight()>=a.getRight()&&(l[0]+=Math.min(a.getX()-s.getX(),s.getRight()-a.getRight())),a.getY()<=s.getY()&&a.getBottom()>=s.getBottom()?l[1]+=Math.min(s.getY()-a.getY(),a.getBottom()-s.getBottom()):s.getY()<=a.getY()&&s.getBottom()>=a.getBottom()&&(l[1]+=Math.min(a.getY()-s.getY(),s.getBottom()-a.getBottom()));var f=Math.abs((s.getCenterY()-a.getCenterY())/(s.getCenterX()-a.getCenterX()));s.getCenterY()===a.getCenterY()&&s.getCenterX()===a.getCenterX()&&(f=1);var d=f*l[0],p=l[1]/f;l[0]d)return l[0]=u,l[1]=m,l[2]=f,l[3]=S,!1;if(hf)return l[0]=p,l[1]=h,l[2]=C,l[3]=d,!1;if(uf?(l[0]=y,l[1]=v,A=!0):(l[0]=g,l[1]=m,A=!0):D===R&&(u>f?(l[0]=p,l[1]=m,A=!0):(l[0]=x,l[1]=v,A=!0)),-N===R?f>u?(l[2]=E,l[3]=S,_=!0):(l[2]=C,l[3]=k,_=!0):N===R&&(f>u?(l[2]=w,l[3]=k,_=!0):(l[2]=L,l[3]=S,_=!0)),A&&_)return!1;if(u>f?h>d?(B=this.getCardinalDirection(D,R,4),O=this.getCardinalDirection(N,R,2)):(B=this.getCardinalDirection(-D,R,3),O=this.getCardinalDirection(-N,R,1)):h>d?(B=this.getCardinalDirection(-D,R,1),O=this.getCardinalDirection(-N,R,3)):(B=this.getCardinalDirection(D,R,2),O=this.getCardinalDirection(N,R,4)),!A)switch(B){case 1:z=m,$=u+-T/R,l[0]=$,l[1]=z;break;case 2:$=x,z=h+b*R,l[0]=$,l[1]=z;break;case 3:z=v,$=u+T/R,l[0]=$,l[1]=z;break;case 4:$=y,z=h+-b*R,l[0]=$,l[1]=z;break}if(!_)switch(O){case 1:V=k,F=f+-I/R,l[2]=F,l[3]=V;break;case 2:F=L,V=d+M*R,l[2]=F,l[3]=V;break;case 3:V=S,F=f+I/R,l[2]=F,l[3]=V;break;case 4:F=E,V=d+-M*R,l[2]=F,l[3]=V;break}}return!1},n.getCardinalDirection=function(a,s,l){return a>s?l:1+l%4},n.getIntersection=function(a,s,l,u){if(u==null)return this.getIntersection2(a,s,l);var h=a.x,f=a.y,d=s.x,p=s.y,m=l.x,g=l.y,y=u.x,v=u.y,x=void 0,b=void 0,T=void 0,w=void 0,k=void 0,C=void 0,E=void 0,S=void 0,L=void 0;return T=p-f,k=h-d,E=d*f-h*p,w=v-g,C=m-y,S=y*g-m*v,L=T*C-w*k,L===0?null:(x=(k*S-C*E)/L,b=(w*E-T*S)/L,new i(x,b))},n.angleOfVector=function(a,s,l,u){var h=void 0;return a!==l?(h=Math.atan((u-s)/(l-a)),l0?1:n<0?-1:0},i.floor=function(n){return n<0?Math.ceil(n):Math.floor(n)},i.ceil=function(n){return n<0?Math.floor(n):Math.ceil(n)},t.exports=i}),(function(t,e,r){"use strict";function i(){}o(i,"Integer"),i.MAX_VALUE=2147483647,i.MIN_VALUE=-2147483648,t.exports=i}),(function(t,e,r){"use strict";var i=(function(){function h(f,d){for(var p=0;p"u"?"undefined":i(a);return a==null||s!="object"&&s!="function"},t.exports=n}),(function(t,e,r){"use strict";function i(m){if(Array.isArray(m)){for(var g=0,y=Array(m.length);g0&&g;){for(T.push(k[0]);T.length>0&&g;){var C=T[0];T.splice(0,1),b.add(C);for(var E=C.getEdges(),x=0;x-1&&k.splice(I,1)}b=new Set,w=new Map}}return m},p.prototype.createDummyNodesForBendpoints=function(m){for(var g=[],y=m.source,v=this.graphManager.calcLowestCommonAncestor(m.source,m.target),x=0;x0){for(var v=this.edgeToDummyNodes.get(y),x=0;x=0&&g.splice(S,1);var L=w.getNeighborsList();L.forEach(function(A){if(y.indexOf(A)<0){var _=v.get(A),D=_-1;D==1&&C.push(A),v.set(A,D)}})}y=y.concat(C),(g.length==1||g.length==2)&&(x=!0,b=g[0])}return b},p.prototype.setGraphManager=function(m){this.graphManager=m},t.exports=p}),(function(t,e,r){"use strict";function i(){}o(i,"RandomSeed"),i.seed=1,i.x=0,i.nextDouble=function(){return i.x=Math.sin(i.seed++)*1e4,i.x-Math.floor(i.x)},t.exports=i}),(function(t,e,r){"use strict";var i=r(4);function n(a,s){this.lworldOrgX=0,this.lworldOrgY=0,this.ldeviceOrgX=0,this.ldeviceOrgY=0,this.lworldExtX=1,this.lworldExtY=1,this.ldeviceExtX=1,this.ldeviceExtY=1}o(n,"Transform"),n.prototype.getWorldOrgX=function(){return this.lworldOrgX},n.prototype.setWorldOrgX=function(a){this.lworldOrgX=a},n.prototype.getWorldOrgY=function(){return this.lworldOrgY},n.prototype.setWorldOrgY=function(a){this.lworldOrgY=a},n.prototype.getWorldExtX=function(){return this.lworldExtX},n.prototype.setWorldExtX=function(a){this.lworldExtX=a},n.prototype.getWorldExtY=function(){return this.lworldExtY},n.prototype.setWorldExtY=function(a){this.lworldExtY=a},n.prototype.getDeviceOrgX=function(){return this.ldeviceOrgX},n.prototype.setDeviceOrgX=function(a){this.ldeviceOrgX=a},n.prototype.getDeviceOrgY=function(){return this.ldeviceOrgY},n.prototype.setDeviceOrgY=function(a){this.ldeviceOrgY=a},n.prototype.getDeviceExtX=function(){return this.ldeviceExtX},n.prototype.setDeviceExtX=function(a){this.ldeviceExtX=a},n.prototype.getDeviceExtY=function(){return this.ldeviceExtY},n.prototype.setDeviceExtY=function(a){this.ldeviceExtY=a},n.prototype.transformX=function(a){var s=0,l=this.lworldExtX;return l!=0&&(s=this.ldeviceOrgX+(a-this.lworldOrgX)*this.ldeviceExtX/l),s},n.prototype.transformY=function(a){var s=0,l=this.lworldExtY;return l!=0&&(s=this.ldeviceOrgY+(a-this.lworldOrgY)*this.ldeviceExtY/l),s},n.prototype.inverseTransformX=function(a){var s=0,l=this.ldeviceExtX;return l!=0&&(s=this.lworldOrgX+(a-this.ldeviceOrgX)*this.lworldExtX/l),s},n.prototype.inverseTransformY=function(a){var s=0,l=this.ldeviceExtY;return l!=0&&(s=this.lworldOrgY+(a-this.ldeviceOrgY)*this.lworldExtY/l),s},n.prototype.inverseTransformPoint=function(a){var s=new i(this.inverseTransformX(a.x),this.inverseTransformY(a.y));return s},t.exports=n}),(function(t,e,r){"use strict";function i(d){if(Array.isArray(d)){for(var p=0,m=Array(d.length);pa.ADAPTATION_LOWER_NODE_LIMIT&&(this.coolingFactor=Math.max(this.coolingFactor*a.COOLING_ADAPTATION_FACTOR,this.coolingFactor-(d-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*this.coolingFactor*(1-a.COOLING_ADAPTATION_FACTOR))),this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT_INCREMENTAL):(d>a.ADAPTATION_LOWER_NODE_LIMIT?this.coolingFactor=Math.max(a.COOLING_ADAPTATION_FACTOR,1-(d-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*(1-a.COOLING_ADAPTATION_FACTOR)):this.coolingFactor=1,this.initialCoolingFactor=this.coolingFactor,this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT),this.maxIterations=Math.max(this.getAllNodes().length*5,this.maxIterations),this.totalDisplacementThreshold=this.displacementThresholdPerNode*this.getAllNodes().length,this.repulsionRange=this.calcRepulsionRange()},h.prototype.calcSpringForces=function(){for(var d=this.getAllEdges(),p,m=0;m0&&arguments[0]!==void 0?arguments[0]:!0,p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,m,g,y,v,x=this.getAllNodes(),b;if(this.useFRGridVariant)for(this.totalIterations%a.GRID_CALCULATION_CHECK_PERIOD==1&&d&&this.updateGrid(),b=new Set,m=0;mT||b>T)&&(d.gravitationForceX=-this.gravityConstant*y,d.gravitationForceY=-this.gravityConstant*v)):(T=p.getEstimatedSize()*this.compoundGravityRangeFactor,(x>T||b>T)&&(d.gravitationForceX=-this.gravityConstant*y*this.compoundGravityConstant,d.gravitationForceY=-this.gravityConstant*v*this.compoundGravityConstant))},h.prototype.isConverged=function(){var d,p=!1;return this.totalIterations>this.maxIterations/3&&(p=Math.abs(this.totalDisplacement-this.oldTotalDisplacement)<2),d=this.totalDisplacement=x.length||T>=x[0].length)){for(var w=0;wh},"_defaultCompareFunction")}]),l})();t.exports=s}),(function(t,e,r){"use strict";var i=(function(){function s(l,u){for(var h=0;h2&&arguments[2]!==void 0?arguments[2]:1,f=arguments.length>3&&arguments[3]!==void 0?arguments[3]:-1,d=arguments.length>4&&arguments[4]!==void 0?arguments[4]:-1;n(this,s),this.sequence1=l,this.sequence2=u,this.match_score=h,this.mismatch_penalty=f,this.gap_penalty=d,this.iMax=l.length+1,this.jMax=u.length+1,this.grid=new Array(this.iMax);for(var p=0;p=0;l--){var u=this.listeners[l];u.event===a&&u.callback===s&&this.listeners.splice(l,1)}},n.emit=function(a,s){for(var l=0;l{"use strict";o((function(e,r){typeof ET=="object"&&typeof xF=="object"?xF.exports=r(vF()):typeof define=="function"&&define.amd?define(["layout-base"],r):typeof ET=="object"?ET.coseBase=r(vF()):e.coseBase=r(e.layoutBase)}),"webpackUniversalModuleDefinition")(ET,function(t){return(function(e){var r={};function i(n){if(r[n])return r[n].exports;var a=r[n]={i:n,l:!1,exports:{}};return e[n].call(a.exports,a,a.exports,i),a.l=!0,a.exports}return o(i,"__webpack_require__"),i.m=e,i.c=r,i.i=function(n){return n},i.d=function(n,a,s){i.o(n,a)||Object.defineProperty(n,a,{configurable:!1,enumerable:!0,get:s})},i.n=function(n){var a=n&&n.__esModule?o(function(){return n.default},"getDefault"):o(function(){return n},"getModuleExports");return i.d(a,"a",a),a},i.o=function(n,a){return Object.prototype.hasOwnProperty.call(n,a)},i.p="",i(i.s=7)})([(function(e,r){e.exports=t}),(function(e,r,i){"use strict";var n=i(0).FDLayoutConstants;function a(){}o(a,"CoSEConstants");for(var s in n)a[s]=n[s];a.DEFAULT_USE_MULTI_LEVEL_SCALING=!1,a.DEFAULT_RADIAL_SEPARATION=n.DEFAULT_EDGE_LENGTH,a.DEFAULT_COMPONENT_SEPERATION=60,a.TILE=!0,a.TILING_PADDING_VERTICAL=10,a.TILING_PADDING_HORIZONTAL=10,a.TREE_REDUCTION_ON_INCREMENTAL=!1,e.exports=a}),(function(e,r,i){"use strict";var n=i(0).FDLayoutEdge;function a(l,u,h){n.call(this,l,u,h)}o(a,"CoSEEdge"),a.prototype=Object.create(n.prototype);for(var s in n)a[s]=n[s];e.exports=a}),(function(e,r,i){"use strict";var n=i(0).LGraph;function a(l,u,h){n.call(this,l,u,h)}o(a,"CoSEGraph"),a.prototype=Object.create(n.prototype);for(var s in n)a[s]=n[s];e.exports=a}),(function(e,r,i){"use strict";var n=i(0).LGraphManager;function a(l){n.call(this,l)}o(a,"CoSEGraphManager"),a.prototype=Object.create(n.prototype);for(var s in n)a[s]=n[s];e.exports=a}),(function(e,r,i){"use strict";var n=i(0).FDLayoutNode,a=i(0).IMath;function s(u,h,f,d){n.call(this,u,h,f,d)}o(s,"CoSENode"),s.prototype=Object.create(n.prototype);for(var l in n)s[l]=n[l];s.prototype.move=function(){var u=this.graphManager.getLayout();this.displacementX=u.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.noOfChildren,this.displacementY=u.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.noOfChildren,Math.abs(this.displacementX)>u.coolingFactor*u.maxNodeDisplacement&&(this.displacementX=u.coolingFactor*u.maxNodeDisplacement*a.sign(this.displacementX)),Math.abs(this.displacementY)>u.coolingFactor*u.maxNodeDisplacement&&(this.displacementY=u.coolingFactor*u.maxNodeDisplacement*a.sign(this.displacementY)),this.child==null?this.moveBy(this.displacementX,this.displacementY):this.child.getNodes().length==0?this.moveBy(this.displacementX,this.displacementY):this.propogateDisplacementToChildren(this.displacementX,this.displacementY),u.totalDisplacement+=Math.abs(this.displacementX)+Math.abs(this.displacementY),this.springForceX=0,this.springForceY=0,this.repulsionForceX=0,this.repulsionForceY=0,this.gravitationForceX=0,this.gravitationForceY=0,this.displacementX=0,this.displacementY=0},s.prototype.propogateDisplacementToChildren=function(u,h){for(var f=this.getChild().getNodes(),d,p=0;p0)this.positionNodesRadially(k);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var C=new Set(this.getAllNodes()),E=this.nodesWithGravity.filter(function(S){return C.has(S)});this.graphManager.setAllNodesToApplyGravitation(E),this.positionNodesRandomly()}}return this.initSpringEmbedder(),this.runSpringEmbedder(),!0},T.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished)if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;if(this.totalIterations%f.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged())if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;this.coolingCycle++,this.layoutQuality==0?this.coolingAdjuster=this.coolingCycle:this.layoutQuality==1&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-Math.pow(this.coolingCycle,Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var k=new Set(this.getAllNodes()),C=this.nodesWithGravity.filter(function(L){return k.has(L)});this.graphManager.setAllNodesToApplyGravitation(C),this.graphManager.updateBounds(),this.updateGrid(),this.coolingFactor=f.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),this.coolingFactor=f.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var E=!this.isTreeGrowing&&!this.isGrowthFinished,S=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(E,S),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},T.prototype.getPositionsData=function(){for(var k=this.graphManager.getAllNodes(),C={},E=0;E1){var A;for(A=0;AS&&(S=Math.floor(I.y)),M=Math.floor(I.x+h.DEFAULT_COMPONENT_SEPERATION)}this.transform(new m(d.WORLD_CENTER_X-I.x/2,d.WORLD_CENTER_Y-I.y/2))},T.radialLayout=function(k,C,E){var S=Math.max(this.maxDiagonalInTree(k),h.DEFAULT_RADIAL_SEPARATION);T.branchRadialLayout(C,null,0,359,0,S);var L=x.calculateBounds(k),M=new b;M.setDeviceOrgX(L.getMinX()),M.setDeviceOrgY(L.getMinY()),M.setWorldOrgX(E.x),M.setWorldOrgY(E.y);for(var I=0;I1;){var H=V[0];V.splice(0,1);var X=B.indexOf(H);X>=0&&B.splice(X,1),z--,O--}C!=null?F=(B.indexOf(V[0])+1)%z:F=0;for(var W=Math.abs(S-E)/O,Z=F;$!=O;Z=++Z%z){var Y=B[Z].getOtherEnd(k);if(Y!=C){var ae=(E+$*W)%360,J=(ae+W)%360;T.branchRadialLayout(Y,k,ae,J,L+M,M),$++}}},T.maxDiagonalInTree=function(k){for(var C=y.MIN_VALUE,E=0;EC&&(C=L)}return C},T.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},T.prototype.groupZeroDegreeMembers=function(){var k=this,C={};this.memberGroups={},this.idToDummyNode={};for(var E=[],S=this.graphManager.getAllNodes(),L=0;L"u"&&(C[A]=[]),C[A]=C[A].concat(M)}Object.keys(C).forEach(function(_){if(C[_].length>1){var D="DummyCompound_"+_;k.memberGroups[D]=C[_];var N=C[_][0].getParent(),R=new l(k.graphManager);R.id=D,R.paddingLeft=N.paddingLeft||0,R.paddingRight=N.paddingRight||0,R.paddingBottom=N.paddingBottom||0,R.paddingTop=N.paddingTop||0,k.idToDummyNode[D]=R;var B=k.getGraphManager().add(k.newGraph(),R),O=N.getChild();O.add(R);for(var $=0;$=0;k--){var C=this.compoundOrder[k],E=C.id,S=C.paddingLeft,L=C.paddingTop;this.adjustLocations(this.tiledMemberPack[E],C.rect.x,C.rect.y,S,L)}},T.prototype.repopulateZeroDegreeMembers=function(){var k=this,C=this.tiledZeroDegreePack;Object.keys(C).forEach(function(E){var S=k.idToDummyNode[E],L=S.paddingLeft,M=S.paddingTop;k.adjustLocations(C[E],S.rect.x,S.rect.y,L,M)})},T.prototype.getToBeTiled=function(k){var C=k.id;if(this.toBeTiled[C]!=null)return this.toBeTiled[C];var E=k.getChild();if(E==null)return this.toBeTiled[C]=!1,!1;for(var S=E.getNodes(),L=0;L0)return this.toBeTiled[C]=!1,!1;if(M.getChild()==null){this.toBeTiled[M.id]=!1;continue}if(!this.getToBeTiled(M))return this.toBeTiled[C]=!1,!1}return this.toBeTiled[C]=!0,!0},T.prototype.getNodeDegree=function(k){for(var C=k.id,E=k.getEdges(),S=0,L=0;L_&&(_=N.rect.height)}E+=_+k.verticalPadding}},T.prototype.tileCompoundMembers=function(k,C){var E=this;this.tiledMemberPack=[],Object.keys(k).forEach(function(S){var L=C[S];E.tiledMemberPack[S]=E.tileNodes(k[S],L.paddingLeft+L.paddingRight),L.rect.width=E.tiledMemberPack[S].width,L.rect.height=E.tiledMemberPack[S].height})},T.prototype.tileNodes=function(k,C){var E=h.TILING_PADDING_VERTICAL,S=h.TILING_PADDING_HORIZONTAL,L={rows:[],rowWidth:[],rowHeight:[],width:0,height:C,verticalPadding:E,horizontalPadding:S};k.sort(function(A,_){return A.rect.width*A.rect.height>_.rect.width*_.rect.height?-1:A.rect.width*A.rect.height<_.rect.width*_.rect.height?1:0});for(var M=0;M0&&(I+=k.horizontalPadding),k.rowWidth[E]=I,k.width0&&(A+=k.verticalPadding);var _=0;A>k.rowHeight[E]&&(_=k.rowHeight[E],k.rowHeight[E]=A,_=k.rowHeight[E]-_),k.height+=_,k.rows[E].push(C)},T.prototype.getShortestRowIndex=function(k){for(var C=-1,E=Number.MAX_VALUE,S=0;SE&&(C=S,E=k.rowWidth[S]);return C},T.prototype.canAddHorizontal=function(k,C,E){var S=this.getShortestRowIndex(k);if(S<0)return!0;var L=k.rowWidth[S];if(L+k.horizontalPadding+C<=k.width)return!0;var M=0;k.rowHeight[S]0&&(M=E+k.verticalPadding-k.rowHeight[S]);var I;k.width-L>=C+k.horizontalPadding?I=(k.height+M)/(L+C+k.horizontalPadding):I=(k.height+M)/k.width,M=E+k.verticalPadding;var A;return k.widthM&&C!=E){S.splice(-1,1),k.rows[E].push(L),k.rowWidth[C]=k.rowWidth[C]-M,k.rowWidth[E]=k.rowWidth[E]+M,k.width=k.rowWidth[instance.getLongestRowIndex(k)];for(var I=Number.MIN_VALUE,A=0;AI&&(I=S[A].height);C>0&&(I+=k.verticalPadding);var _=k.rowHeight[C]+k.rowHeight[E];k.rowHeight[C]=I,k.rowHeight[E]0)for(var O=L;O<=M;O++)B[0]+=this.grid[O][I-1].length+this.grid[O][I].length-1;if(M0)for(var O=I;O<=A;O++)B[3]+=this.grid[L-1][O].length+this.grid[L][O].length-1;for(var $=y.MAX_VALUE,z,F,V=0;V{"use strict";o((function(e,r){typeof ST=="object"&&typeof TF=="object"?TF.exports=r(bF()):typeof define=="function"&&define.amd?define(["cose-base"],r):typeof ST=="object"?ST.cytoscapeCoseBilkent=r(bF()):e.cytoscapeCoseBilkent=r(e.coseBase)}),"webpackUniversalModuleDefinition")(ST,function(t){return(function(e){var r={};function i(n){if(r[n])return r[n].exports;var a=r[n]={i:n,l:!1,exports:{}};return e[n].call(a.exports,a,a.exports,i),a.l=!0,a.exports}return o(i,"__webpack_require__"),i.m=e,i.c=r,i.i=function(n){return n},i.d=function(n,a,s){i.o(n,a)||Object.defineProperty(n,a,{configurable:!1,enumerable:!0,get:s})},i.n=function(n){var a=n&&n.__esModule?o(function(){return n.default},"getDefault"):o(function(){return n},"getModuleExports");return i.d(a,"a",a),a},i.o=function(n,a){return Object.prototype.hasOwnProperty.call(n,a)},i.p="",i(i.s=1)})([(function(e,r){e.exports=t}),(function(e,r,i){"use strict";var n=i(0).layoutBase.LayoutConstants,a=i(0).layoutBase.FDLayoutConstants,s=i(0).CoSEConstants,l=i(0).CoSELayout,u=i(0).CoSENode,h=i(0).layoutBase.PointD,f=i(0).layoutBase.DimensionD,d={ready:o(function(){},"ready"),stop:o(function(){},"stop"),quality:"default",nodeDimensionsIncludeLabels:!1,refresh:30,fit:!0,padding:10,randomize:!0,nodeRepulsion:4500,idealEdgeLength:50,edgeElasticity:.45,nestingFactor:.1,gravity:.25,numIter:2500,tile:!0,animate:"end",animationDuration:500,tilingPaddingVertical:10,tilingPaddingHorizontal:10,gravityRangeCompound:1.5,gravityCompound:1,gravityRange:3.8,initialEnergyOnIncremental:.5};function p(v,x){var b={};for(var T in v)b[T]=v[T];for(var T in x)b[T]=x[T];return b}o(p,"extend");function m(v){this.options=p(d,v),g(this.options)}o(m,"_CoSELayout");var g=o(function(x){x.nodeRepulsion!=null&&(s.DEFAULT_REPULSION_STRENGTH=a.DEFAULT_REPULSION_STRENGTH=x.nodeRepulsion),x.idealEdgeLength!=null&&(s.DEFAULT_EDGE_LENGTH=a.DEFAULT_EDGE_LENGTH=x.idealEdgeLength),x.edgeElasticity!=null&&(s.DEFAULT_SPRING_STRENGTH=a.DEFAULT_SPRING_STRENGTH=x.edgeElasticity),x.nestingFactor!=null&&(s.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=a.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=x.nestingFactor),x.gravity!=null&&(s.DEFAULT_GRAVITY_STRENGTH=a.DEFAULT_GRAVITY_STRENGTH=x.gravity),x.numIter!=null&&(s.MAX_ITERATIONS=a.MAX_ITERATIONS=x.numIter),x.gravityRange!=null&&(s.DEFAULT_GRAVITY_RANGE_FACTOR=a.DEFAULT_GRAVITY_RANGE_FACTOR=x.gravityRange),x.gravityCompound!=null&&(s.DEFAULT_COMPOUND_GRAVITY_STRENGTH=a.DEFAULT_COMPOUND_GRAVITY_STRENGTH=x.gravityCompound),x.gravityRangeCompound!=null&&(s.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=a.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=x.gravityRangeCompound),x.initialEnergyOnIncremental!=null&&(s.DEFAULT_COOLING_FACTOR_INCREMENTAL=a.DEFAULT_COOLING_FACTOR_INCREMENTAL=x.initialEnergyOnIncremental),x.quality=="draft"?n.QUALITY=0:x.quality=="proof"?n.QUALITY=2:n.QUALITY=1,s.NODE_DIMENSIONS_INCLUDE_LABELS=a.NODE_DIMENSIONS_INCLUDE_LABELS=n.NODE_DIMENSIONS_INCLUDE_LABELS=x.nodeDimensionsIncludeLabels,s.DEFAULT_INCREMENTAL=a.DEFAULT_INCREMENTAL=n.DEFAULT_INCREMENTAL=!x.randomize,s.ANIMATE=a.ANIMATE=n.ANIMATE=x.animate,s.TILE=x.tile,s.TILING_PADDING_VERTICAL=typeof x.tilingPaddingVertical=="function"?x.tilingPaddingVertical.call():x.tilingPaddingVertical,s.TILING_PADDING_HORIZONTAL=typeof x.tilingPaddingHorizontal=="function"?x.tilingPaddingHorizontal.call():x.tilingPaddingHorizontal},"getUserOptions");m.prototype.run=function(){var v,x,b=this.options,T=this.idToLNode={},w=this.layout=new l,k=this;k.stopped=!1,this.cy=this.options.cy,this.cy.trigger({type:"layoutstart",layout:this});var C=w.newGraphManager();this.gm=C;var E=this.options.eles.nodes(),S=this.options.eles.edges();this.root=C.addRoot(),this.processChildrenList(this.root,this.getTopMostNodes(E),w);for(var L=0;L0){var A;A=b.getGraphManager().add(b.newGraph(),E),this.processChildrenList(A,C,b)}}},m.prototype.stop=function(){return this.stopped=!0,this};var y=o(function(x){x("layout","cose-bilkent",m)},"register");typeof cytoscape<"u"&&y(cytoscape),e.exports=y})])})});function vit(t,e){t.forEach(r=>{let i={id:r.id,labelText:r.label,height:r.height,width:r.width,padding:r.padding??0};Object.keys(r).forEach(n=>{["id","label","height","width","padding","x","y"].includes(n)||(i[n]=r[n])}),e.add({group:"nodes",data:i,position:{x:r.x??0,y:r.y??0}})})}function xit(t,e){t.forEach(r=>{let i={id:r.id,source:r.start,target:r.end};Object.keys(r).forEach(n=>{["id","start","end"].includes(n)||(i[n]=r[n])}),e.add({group:"edges",data:i})})}function aye(t){return new Promise(e=>{let r=Ze("body").append("div").attr("id","cy").attr("style","display:none"),i=Wl({container:document.getElementById("cy"),style:[{selector:"edge",style:{"curve-style":"bezier"}}]});r.remove(),vit(t.nodes,i),xit(t.edges,i),i.nodes().forEach(function(a){a.layoutDimensions=()=>{let s=a.data();return{w:s.width,h:s.height}}});let n={name:"cose-bilkent",quality:"proof",styleEnabled:!1,animate:!1};i.layout(n).run(),i.ready(a=>{Q.info("Cytoscape ready",a),e(i)})})}function sye(t){return t.nodes().map(e=>{let r=e.data(),i=e.position(),n={id:r.id,x:i.x,y:i.y};return Object.keys(r).forEach(a=>{a!=="id"&&(n[a]=r[a])}),n})}function oye(t){return t.edges().map(e=>{let r=e.data(),i=e._private.rscratch,n={id:r.id,source:r.source,target:r.target,startX:i.startX,startY:i.startY,midX:i.midX,midY:i.midY,endX:i.endX,endY:i.endY};return Object.keys(r).forEach(a=>{["id","source","target"].includes(a)||(n[a]=r[a])}),n})}var nye,lye=P(()=>{"use strict";gF();nye=Wa(iye(),1);Pr();bt();Wl.use(nye.default);o(vit,"addNodes");o(xit,"addEdges");o(aye,"createCytoscapeInstance");o(sye,"extractPositionedNodes");o(oye,"extractPositionedEdges")});async function cye(t,e){Q.debug("Starting cose-bilkent layout algorithm");try{bit(t);let r=await aye(t),i=sye(r),n=oye(r);return Q.debug(`Layout completed: ${i.length} nodes, ${n.length} edges`),{nodes:i,edges:n}}catch(r){throw Q.error("Error in cose-bilkent layout algorithm:",r),r}}function bit(t){if(!t)throw new Error("Layout data is required");if(!t.config)throw new Error("Configuration is required in layout data");if(!t.rootNode)throw new Error("Root node is required");if(!t.nodes||!Array.isArray(t.nodes))throw new Error("No nodes found in layout data");if(!Array.isArray(t.edges))throw new Error("Edges array is required in layout data");return!0}var uye=P(()=>{"use strict";bt();lye();o(cye,"executeCoseBilkentLayout");o(bit,"validateLayoutData")});var hye,fye=P(()=>{"use strict";uye();hye=o(async(t,e,{insertCluster:r,insertEdge:i,insertEdgeLabel:n,insertMarkers:a,insertNode:s,log:l,positionEdgeLabel:u},{algorithm:h})=>{let f={},d={},p=e.select("g");a(p,t.markers,t.type,t.diagramId);let m=p.insert("g").attr("class","subgraphs"),g=p.insert("g").attr("class","edgePaths"),y=p.insert("g").attr("class","edgeLabels"),v=p.insert("g").attr("class","nodes");l.debug("Inserting nodes into DOM for dimension calculation"),await Promise.all(t.nodes.map(async T=>{if(T.isGroup){let w={...T};d[T.id]=w,f[T.id]=w,await r(m,T)}else{let w={...T};f[T.id]=w;let k=await s(v,T,{config:t.config,dir:t.direction||"TB"}),C=k.node().getBBox();w.width=C.width,w.height=C.height,w.domId=k,l.debug(`Node ${T.id} dimensions: ${C.width}x${C.height}`)}})),l.debug("Running cose-bilkent layout algorithm");let x={...t,nodes:t.nodes.map(T=>{let w=f[T.id];return{...T,width:w.width,height:w.height}})},b=await cye(x,t.config);l.debug("Positioning nodes based on layout results"),b.nodes.forEach(T=>{let w=f[T.id];w?.domId&&(w.domId.attr("transform",`translate(${T.x}, ${T.y})`),w.x=T.x,w.y=T.y,l.debug(`Positioned node ${w.id} at center (${T.x}, ${T.y})`))}),b.edges.forEach(T=>{let w=t.edges.find(k=>k.id===T.id);w&&(w.points=[{x:T.startX,y:T.startY},{x:T.midX,y:T.midY},{x:T.endX,y:T.endY}])}),l.debug("Inserting and positioning edges"),await Promise.all(t.edges.map(async T=>{let w=await n(y,T),k=f[T.start??""],C=f[T.end??""];if(k&&C){let E=b.edges.find(S=>S.id===T.id);if(E){l.debug("APA01 positionedEdge",E);let S={...T},L=i(g,S,d,t.type,k,C,t.diagramId);u(S,L)}else{let S={...T,points:[{x:k.x||0,y:k.y||0},{x:C.x||0,y:C.y||0}]},L=i(g,S,d,t.type,k,C,t.diagramId);u(S,L)}}})),l.debug("Cose-bilkent rendering completed")},"render")});var dye={};ur(dye,{render:()=>Tit});var Tit,pye=P(()=>{"use strict";fye();Tit=hye});var AT,kF,kit,Ul,Vu,Wd=P(()=>{"use strict";ice();bt();AT={},kF=o(t=>{for(let e of t)AT[e.name]=e},"registerLayoutLoaders"),kit=o(()=>{kF([{name:"dagre",loader:o(async()=>await Promise.resolve().then(()=>(Bpe(),Ppe)),"loader")},{name:"cose-bilkent",loader:o(async()=>await Promise.resolve().then(()=>(pye(),dye)),"loader")}])},"registerDefaultLayoutLoaders");kit();Ul=o(async(t,e)=>{if(!(t.layoutAlgorithm in AT))throw new Error(`Unknown layout algorithm: ${t.layoutAlgorithm}`);if(t.diagramId)for(let f of t.nodes){let d=f.domId||f.id;f.domId=`${t.diagramId}-${d}`}let r=AT[t.layoutAlgorithm],i=await r.loader(),{theme:n,themeVariables:a}=t.config,{useGradient:s,gradientStart:l,gradientStop:u}=a,h=e.attr("id");if(e.append("defs").append("filter").attr("id",`${h}-drop-shadow`).attr("height","130%").attr("width","130%").append("feDropShadow").attr("dx","4").attr("dy","4").attr("stdDeviation",0).attr("flood-opacity","0.06").attr("flood-color",`${n?.includes("dark")?"#FFFFFF":"#000000"}`),e.append("defs").append("filter").attr("id",`${h}-drop-shadow-small`).attr("height","150%").attr("width","150%").append("feDropShadow").attr("dx","2").attr("dy","2").attr("stdDeviation",0).attr("flood-opacity","0.06").attr("flood-color",`${n?.includes("dark")?"#FFFFFF":"#000000"}`),s){let f=e.append("linearGradient").attr("id",e.attr("id")+"-gradient").attr("gradientUnits","objectBoundingBox").attr("x1","0%").attr("y1","0%").attr("x2","100%").attr("y2","0%");f.append("svg:stop").attr("offset","0%").attr("stop-color",l).attr("stop-opacity",1),f.append("svg:stop").attr("offset","100%").attr("stop-color",u).attr("stop-opacity",1)}return i.render(t,e,rce,{algorithm:r.algorithm})},"render"),Vu=o((t="",{fallback:e="dagre"}={})=>{if(t in AT)return t;if(e in AT)return Q.warn(`Layout algorithm ${t} is not registered. Using ${e} as fallback.`),e;throw new Error(`Both layout algorithms ${t} and ${e} are not registered.`)},"getRegisteredLayoutAlgorithm")});var Ro,Cit,wit,Ud=P(()=>{"use strict";Xi();bt();Ro=o((t,e,r,i)=>{t.attr("class",r);let{width:n,height:a,x:s,y:l}=Cit(t,e);Hr(t,a,n,i);let u=wit(s,l,n,a,e);t.attr("viewBox",u),Q.debug(`viewBox configured: ${u} with padding: ${e}`)},"setupViewPortForSVG"),Cit=o((t,e)=>{let r=t.node()?.getBBox()||{width:0,height:0,x:0,y:0};return{width:r.width+e*2,height:r.height+e*2,x:r.x,y:r.y}},"calculateDimensionsWithPadding"),wit=o((t,e,r,i,n)=>`${t-n} ${e-n} ${r} ${i}`,"createViewBox")});var Eit,Sit,mye,gye=P(()=>{"use strict";Ut();bt();I0();Wd();Ud();er();Eit=o(function(t,e){return e.db.getClasses()},"getClasses"),Sit=o(async function(t,e,r,i){Q.info("REF0:"),Q.info("Drawing state diagram (v2)",e);let{securityLevel:n,flowchart:a,layout:s}=ge();i.db.setDiagramId(e),Q.debug("Before getData: ");let l=i.db.getData();Q.debug("Data: ",l);let u=Ol(e,n),h=i.db.getDirection();l.type=i.type,l.layoutAlgorithm=Vu(s),l.layoutAlgorithm==="dagre"&&s==="elk"&&Q.warn("flowchart-elk was moved to an external package in Mermaid v11. Please refer [release notes](https://github.com/mermaid-js/mermaid/releases/tag/v11.0.0) for more details. This diagram will be rendered using `dagre` layout as a fallback."),l.direction=h,l.nodeSpacing=a?.nodeSpacing||50,l.rankSpacing=a?.rankSpacing||50,l.markers=["point","circle","cross"],l.diagramId=e,Q.debug("REF1:",l),await Ul(l,u);let f=l.config.flowchart?.diagramPadding??8;Kt.insertTitle(u,"flowchartTitleText",a?.titleTopMargin||0,i.db.getDiagramTitle()),Ro(u,f,"flowchart",a?.useMaxWidth||!1)},"draw"),mye={getClasses:Eit,draw:Sit}});var CF,wF,yye=P(()=>{"use strict";CF=(function(){var t=o(function(Ft,Et,qt,Zt){for(qt=qt||{},Zt=Ft.length;Zt--;qt[Ft[Zt]]=Et);return qt},"o"),e=[1,4],r=[1,3],i=[1,5],n=[1,8,9,10,11,27,34,36,38,44,60,84,85,86,87,88,89,102,105,106,109,111,114,115,116,121,122,123,124,125],a=[2,2],s=[1,13],l=[1,14],u=[1,15],h=[1,16],f=[1,23],d=[1,25],p=[1,26],m=[1,27],g=[1,50],y=[1,49],v=[1,29],x=[1,30],b=[1,31],T=[1,32],w=[1,33],k=[1,45],C=[1,47],E=[1,43],S=[1,48],L=[1,44],M=[1,51],I=[1,46],A=[1,52],_=[1,53],D=[1,34],N=[1,35],R=[1,36],B=[1,37],O=[1,38],$=[1,58],z=[1,8,9,10,11,27,32,34,36,38,44,60,84,85,86,87,88,89,102,105,106,109,111,114,115,116,121,122,123,124,125],F=[1,62],V=[1,61],H=[1,63],X=[8,9,11,75,77,78],W=[1,79],Z=[1,92],Y=[1,97],ae=[1,96],J=[1,93],ee=[1,89],re=[1,95],te=[1,91],be=[1,98],de=[1,94],Ee=[1,99],Ne=[1,90],we=[8,9,10,11,40,75,77,78],Te=[8,9,10,11,40,46,75,77,78],De=[8,9,10,11,29,40,44,46,48,50,52,54,56,58,60,63,65,67,68,70,75,77,78,89,102,105,106,109,111,114,115,116],$e=[8,9,11,44,60,75,77,78,89,102,105,106,109,111,114,115,116],pe=[44,60,89,102,105,106,109,111,114,115,116],Je=[1,122],Ce=[1,123],Fe=[1,125],Ue=[1,124],qe=[44,60,62,74,89,102,105,106,109,111,114,115,116],Me=[1,134],He=[1,148],K=[1,149],oe=[1,150],U=[1,151],ue=[1,136],G=[1,138],se=[1,142],le=[1,143],ke=[1,144],me=[1,145],ye=[1,146],Re=[1,147],ve=[1,152],Oe=[1,153],We=[1,132],Be=[1,133],Qe=[1,140],ce=[1,135],it=[1,139],fe=[1,137],ut=[8,9,10,11,27,32,34,36,38,44,60,84,85,86,87,88,89,102,105,106,109,111,114,115,116,121,122,123,124,125],Nt=[1,155],Pt=[1,157],St=[8,9,11],It=[8,9,10,11,14,44,60,89,105,106,109,111,114,115,116],ot=[1,177],ct=[1,173],Dt=[1,174],kt=[1,178],yt=[1,175],jt=[1,176],hr=[77,116,119],Qt=[8,9,10,11,12,14,27,29,32,44,60,75,84,85,86,87,88,89,90,105,109,111,114,115,116],Er=[10,106],dr=[31,49,51,53,55,57,62,64,66,67,69,71,116,117,118],ir=[1,248],pr=[1,246],Ii=[1,250],xt=[1,244],Ie=[1,245],ft=[1,247],_t=[1,249],zr=[1,251],ri=[1,269],ci=[8,9,11,106],Ir=[8,9,10,11,60,84,105,106,109,110,111,112],sa={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,graphConfig:4,document:5,line:6,statement:7,SEMI:8,NEWLINE:9,SPACE:10,EOF:11,GRAPH:12,NODIR:13,DIR:14,FirstStmtSeparator:15,ending:16,endToken:17,spaceList:18,spaceListNewline:19,vertexStatement:20,separator:21,styleStatement:22,linkStyleStatement:23,classDefStatement:24,classStatement:25,clickStatement:26,subgraph:27,textNoTags:28,SQS:29,text:30,SQE:31,end:32,direction:33,acc_title:34,acc_title_value:35,acc_descr:36,acc_descr_value:37,acc_descr_multiline_value:38,shapeData:39,SHAPE_DATA:40,link:41,node:42,styledVertex:43,AMP:44,vertex:45,STYLE_SEPARATOR:46,idString:47,DOUBLECIRCLESTART:48,DOUBLECIRCLEEND:49,PS:50,PE:51,"(-":52,"-)":53,STADIUMSTART:54,STADIUMEND:55,SUBROUTINESTART:56,SUBROUTINEEND:57,VERTEX_WITH_PROPS_START:58,"NODE_STRING[field]":59,COLON:60,"NODE_STRING[value]":61,PIPE:62,CYLINDERSTART:63,CYLINDEREND:64,DIAMOND_START:65,DIAMOND_STOP:66,TAGEND:67,TRAPSTART:68,TRAPEND:69,INVTRAPSTART:70,INVTRAPEND:71,linkStatement:72,arrowText:73,TESTSTR:74,START_LINK:75,edgeText:76,LINK:77,LINK_ID:78,edgeTextToken:79,STR:80,MD_STR:81,textToken:82,keywords:83,STYLE:84,LINKSTYLE:85,CLASSDEF:86,CLASS:87,CLICK:88,DOWN:89,UP:90,textNoTagsToken:91,stylesOpt:92,"idString[vertex]":93,"idString[class]":94,CALLBACKNAME:95,CALLBACKARGS:96,HREF:97,LINK_TARGET:98,"STR[link]":99,"STR[tooltip]":100,alphaNum:101,DEFAULT:102,numList:103,INTERPOLATE:104,NUM:105,COMMA:106,style:107,styleComponent:108,NODE_STRING:109,UNIT:110,BRKT:111,PCT:112,idStringToken:113,MINUS:114,MULT:115,UNICODE_TEXT:116,TEXT:117,TAGSTART:118,EDGE_TEXT:119,alphaNumToken:120,direction_tb:121,direction_bt:122,direction_rl:123,direction_lr:124,direction_td:125,$accept:0,$end:1},terminals_:{2:"error",8:"SEMI",9:"NEWLINE",10:"SPACE",11:"EOF",12:"GRAPH",13:"NODIR",14:"DIR",27:"subgraph",29:"SQS",31:"SQE",32:"end",34:"acc_title",35:"acc_title_value",36:"acc_descr",37:"acc_descr_value",38:"acc_descr_multiline_value",40:"SHAPE_DATA",44:"AMP",46:"STYLE_SEPARATOR",48:"DOUBLECIRCLESTART",49:"DOUBLECIRCLEEND",50:"PS",51:"PE",52:"(-",53:"-)",54:"STADIUMSTART",55:"STADIUMEND",56:"SUBROUTINESTART",57:"SUBROUTINEEND",58:"VERTEX_WITH_PROPS_START",59:"NODE_STRING[field]",60:"COLON",61:"NODE_STRING[value]",62:"PIPE",63:"CYLINDERSTART",64:"CYLINDEREND",65:"DIAMOND_START",66:"DIAMOND_STOP",67:"TAGEND",68:"TRAPSTART",69:"TRAPEND",70:"INVTRAPSTART",71:"INVTRAPEND",74:"TESTSTR",75:"START_LINK",77:"LINK",78:"LINK_ID",80:"STR",81:"MD_STR",84:"STYLE",85:"LINKSTYLE",86:"CLASSDEF",87:"CLASS",88:"CLICK",89:"DOWN",90:"UP",93:"idString[vertex]",94:"idString[class]",95:"CALLBACKNAME",96:"CALLBACKARGS",97:"HREF",98:"LINK_TARGET",99:"STR[link]",100:"STR[tooltip]",102:"DEFAULT",104:"INTERPOLATE",105:"NUM",106:"COMMA",109:"NODE_STRING",110:"UNIT",111:"BRKT",112:"PCT",114:"MINUS",115:"MULT",116:"UNICODE_TEXT",117:"TEXT",118:"TAGSTART",119:"EDGE_TEXT",121:"direction_tb",122:"direction_bt",123:"direction_rl",124:"direction_lr",125:"direction_td"},productions_:[0,[3,2],[5,0],[5,2],[6,1],[6,1],[6,1],[6,1],[6,1],[4,2],[4,2],[4,2],[4,3],[16,2],[16,1],[17,1],[17,1],[17,1],[15,1],[15,1],[15,2],[19,2],[19,2],[19,1],[19,1],[18,2],[18,1],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[7,9],[7,6],[7,4],[7,1],[7,2],[7,2],[7,1],[21,1],[21,1],[21,1],[39,2],[39,1],[20,4],[20,3],[20,4],[20,2],[20,2],[20,1],[42,1],[42,6],[42,5],[43,1],[43,3],[45,4],[45,4],[45,6],[45,4],[45,4],[45,4],[45,8],[45,4],[45,4],[45,4],[45,6],[45,4],[45,4],[45,4],[45,4],[45,4],[45,1],[41,2],[41,3],[41,3],[41,1],[41,3],[41,4],[76,1],[76,2],[76,1],[76,1],[72,1],[72,2],[73,3],[30,1],[30,2],[30,1],[30,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[83,1],[28,1],[28,2],[28,1],[28,1],[24,5],[25,5],[26,2],[26,4],[26,3],[26,5],[26,3],[26,5],[26,5],[26,7],[26,2],[26,4],[26,2],[26,4],[26,4],[26,6],[22,5],[23,5],[23,5],[23,9],[23,9],[23,7],[23,7],[103,1],[103,3],[92,1],[92,3],[107,1],[107,2],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[108,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[113,1],[82,1],[82,1],[82,1],[82,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[91,1],[79,1],[79,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[120,1],[47,1],[47,2],[101,1],[101,2],[33,1],[33,1],[33,1],[33,1],[33,1]],performAction:o(function(Et,qt,Zt,Tt,wi,xe,Wo){var Se=xe.length-1;switch(wi){case 2:this.$=[];break;case 3:(!Array.isArray(xe[Se])||xe[Se].length>0)&&xe[Se-1].push(xe[Se]),this.$=xe[Se-1];break;case 4:case 183:this.$=xe[Se];break;case 11:Tt.setDirection("TB"),this.$="TB";break;case 12:Tt.setDirection(xe[Se-1]),this.$=xe[Se-1];break;case 27:this.$=xe[Se-1].nodes;break;case 28:case 29:case 30:case 31:case 32:this.$=[];break;case 33:this.$=Tt.addSubGraph(xe[Se-6],xe[Se-1],xe[Se-4]);break;case 34:this.$=Tt.addSubGraph(xe[Se-3],xe[Se-1],xe[Se-3]);break;case 35:this.$=Tt.addSubGraph(void 0,xe[Se-1],void 0);break;case 37:this.$=xe[Se].trim(),Tt.setAccTitle(this.$);break;case 38:case 39:this.$=xe[Se].trim(),Tt.setAccDescription(this.$);break;case 43:this.$=xe[Se-1]+xe[Se];break;case 44:this.$=xe[Se];break;case 45:Tt.addVertex(xe[Se-1][xe[Se-1].length-1],void 0,void 0,void 0,void 0,void 0,void 0,xe[Se]),Tt.addLink(xe[Se-3].stmt,xe[Se-1],xe[Se-2]),this.$={stmt:xe[Se-1],nodes:xe[Se-1].concat(xe[Se-3].nodes)};break;case 46:Tt.addLink(xe[Se-2].stmt,xe[Se],xe[Se-1]),this.$={stmt:xe[Se],nodes:xe[Se].concat(xe[Se-2].nodes)};break;case 47:Tt.addLink(xe[Se-3].stmt,xe[Se-1],xe[Se-2]),this.$={stmt:xe[Se-1],nodes:xe[Se-1].concat(xe[Se-3].nodes)};break;case 48:this.$={stmt:xe[Se-1],nodes:xe[Se-1]};break;case 49:Tt.addVertex(xe[Se-1][xe[Se-1].length-1],void 0,void 0,void 0,void 0,void 0,void 0,xe[Se]),this.$={stmt:xe[Se-1],nodes:xe[Se-1],shapeData:xe[Se]};break;case 50:this.$={stmt:xe[Se],nodes:xe[Se]};break;case 51:this.$=[xe[Se]];break;case 52:Tt.addVertex(xe[Se-5][xe[Se-5].length-1],void 0,void 0,void 0,void 0,void 0,void 0,xe[Se-4]),this.$=xe[Se-5].concat(xe[Se]);break;case 53:this.$=xe[Se-4].concat(xe[Se]);break;case 54:this.$=xe[Se];break;case 55:this.$=xe[Se-2],Tt.setClass(xe[Se-2],xe[Se]);break;case 56:this.$=xe[Se-3],Tt.addVertex(xe[Se-3],xe[Se-1],"square");break;case 57:this.$=xe[Se-3],Tt.addVertex(xe[Se-3],xe[Se-1],"doublecircle");break;case 58:this.$=xe[Se-5],Tt.addVertex(xe[Se-5],xe[Se-2],"circle");break;case 59:this.$=xe[Se-3],Tt.addVertex(xe[Se-3],xe[Se-1],"ellipse");break;case 60:this.$=xe[Se-3],Tt.addVertex(xe[Se-3],xe[Se-1],"stadium");break;case 61:this.$=xe[Se-3],Tt.addVertex(xe[Se-3],xe[Se-1],"subroutine");break;case 62:this.$=xe[Se-7],Tt.addVertex(xe[Se-7],xe[Se-1],"rect",void 0,void 0,void 0,Object.fromEntries([[xe[Se-5],xe[Se-3]]]));break;case 63:this.$=xe[Se-3],Tt.addVertex(xe[Se-3],xe[Se-1],"cylinder");break;case 64:this.$=xe[Se-3],Tt.addVertex(xe[Se-3],xe[Se-1],"round");break;case 65:this.$=xe[Se-3],Tt.addVertex(xe[Se-3],xe[Se-1],"diamond");break;case 66:this.$=xe[Se-5],Tt.addVertex(xe[Se-5],xe[Se-2],"hexagon");break;case 67:this.$=xe[Se-3],Tt.addVertex(xe[Se-3],xe[Se-1],"odd");break;case 68:this.$=xe[Se-3],Tt.addVertex(xe[Se-3],xe[Se-1],"trapezoid");break;case 69:this.$=xe[Se-3],Tt.addVertex(xe[Se-3],xe[Se-1],"inv_trapezoid");break;case 70:this.$=xe[Se-3],Tt.addVertex(xe[Se-3],xe[Se-1],"lean_right");break;case 71:this.$=xe[Se-3],Tt.addVertex(xe[Se-3],xe[Se-1],"lean_left");break;case 72:this.$=xe[Se],Tt.addVertex(xe[Se]);break;case 73:xe[Se-1].text=xe[Se],this.$=xe[Se-1];break;case 74:case 75:xe[Se-2].text=xe[Se-1],this.$=xe[Se-2];break;case 76:this.$=xe[Se];break;case 77:var Rn=Tt.destructLink(xe[Se],xe[Se-2]);this.$={type:Rn.type,stroke:Rn.stroke,length:Rn.length,text:xe[Se-1]};break;case 78:var Rn=Tt.destructLink(xe[Se],xe[Se-2]);this.$={type:Rn.type,stroke:Rn.stroke,length:Rn.length,text:xe[Se-1],id:xe[Se-3]};break;case 79:this.$={text:xe[Se],type:"text"};break;case 80:this.$={text:xe[Se-1].text+""+xe[Se],type:xe[Se-1].type};break;case 81:this.$={text:xe[Se],type:"string"};break;case 82:this.$={text:xe[Se],type:"markdown"};break;case 83:var Rn=Tt.destructLink(xe[Se]);this.$={type:Rn.type,stroke:Rn.stroke,length:Rn.length};break;case 84:var Rn=Tt.destructLink(xe[Se]);this.$={type:Rn.type,stroke:Rn.stroke,length:Rn.length,id:xe[Se-1]};break;case 85:this.$=xe[Se-1];break;case 86:this.$={text:xe[Se],type:"text"};break;case 87:this.$={text:xe[Se-1].text+""+xe[Se],type:xe[Se-1].type};break;case 88:this.$={text:xe[Se],type:"string"};break;case 89:case 104:this.$={text:xe[Se],type:"markdown"};break;case 101:this.$={text:xe[Se],type:"text"};break;case 102:this.$={text:xe[Se-1].text+""+xe[Se],type:xe[Se-1].type};break;case 103:this.$={text:xe[Se],type:"text"};break;case 105:this.$=xe[Se-4],Tt.addClass(xe[Se-2],xe[Se]);break;case 106:this.$=xe[Se-4],Tt.setClass(xe[Se-2],xe[Se]);break;case 107:case 115:this.$=xe[Se-1],Tt.setClickEvent(xe[Se-1],xe[Se]);break;case 108:case 116:this.$=xe[Se-3],Tt.setClickEvent(xe[Se-3],xe[Se-2]),Tt.setTooltip(xe[Se-3],xe[Se]);break;case 109:this.$=xe[Se-2],Tt.setClickEvent(xe[Se-2],xe[Se-1],xe[Se]);break;case 110:this.$=xe[Se-4],Tt.setClickEvent(xe[Se-4],xe[Se-3],xe[Se-2]),Tt.setTooltip(xe[Se-4],xe[Se]);break;case 111:this.$=xe[Se-2],Tt.setLink(xe[Se-2],xe[Se]);break;case 112:this.$=xe[Se-4],Tt.setLink(xe[Se-4],xe[Se-2]),Tt.setTooltip(xe[Se-4],xe[Se]);break;case 113:this.$=xe[Se-4],Tt.setLink(xe[Se-4],xe[Se-2],xe[Se]);break;case 114:this.$=xe[Se-6],Tt.setLink(xe[Se-6],xe[Se-4],xe[Se]),Tt.setTooltip(xe[Se-6],xe[Se-2]);break;case 117:this.$=xe[Se-1],Tt.setLink(xe[Se-1],xe[Se]);break;case 118:this.$=xe[Se-3],Tt.setLink(xe[Se-3],xe[Se-2]),Tt.setTooltip(xe[Se-3],xe[Se]);break;case 119:this.$=xe[Se-3],Tt.setLink(xe[Se-3],xe[Se-2],xe[Se]);break;case 120:this.$=xe[Se-5],Tt.setLink(xe[Se-5],xe[Se-4],xe[Se]),Tt.setTooltip(xe[Se-5],xe[Se-2]);break;case 121:this.$=xe[Se-4],Tt.addVertex(xe[Se-2],void 0,void 0,xe[Se]);break;case 122:this.$=xe[Se-4],Tt.updateLink([xe[Se-2]],xe[Se]);break;case 123:this.$=xe[Se-4],Tt.updateLink(xe[Se-2],xe[Se]);break;case 124:this.$=xe[Se-8],Tt.updateLinkInterpolate([xe[Se-6]],xe[Se-2]),Tt.updateLink([xe[Se-6]],xe[Se]);break;case 125:this.$=xe[Se-8],Tt.updateLinkInterpolate(xe[Se-6],xe[Se-2]),Tt.updateLink(xe[Se-6],xe[Se]);break;case 126:this.$=xe[Se-6],Tt.updateLinkInterpolate([xe[Se-4]],xe[Se]);break;case 127:this.$=xe[Se-6],Tt.updateLinkInterpolate(xe[Se-4],xe[Se]);break;case 128:case 130:this.$=[xe[Se]];break;case 129:case 131:xe[Se-2].push(xe[Se]),this.$=xe[Se-2];break;case 133:this.$=xe[Se-1]+xe[Se];break;case 181:this.$=xe[Se];break;case 182:this.$=xe[Se-1]+""+xe[Se];break;case 184:this.$=xe[Se-1]+""+xe[Se];break;case 185:this.$={stmt:"dir",value:"TB"};break;case 186:this.$={stmt:"dir",value:"BT"};break;case 187:this.$={stmt:"dir",value:"RL"};break;case 188:this.$={stmt:"dir",value:"LR"};break;case 189:this.$={stmt:"dir",value:"TD"};break}},"anonymous"),table:[{3:1,4:2,9:e,10:r,12:i},{1:[3]},t(n,a,{5:6}),{4:7,9:e,10:r,12:i},{4:8,9:e,10:r,12:i},{13:[1,9],14:[1,10]},{1:[2,1],6:11,7:12,8:s,9:l,10:u,11:h,20:17,22:18,23:19,24:20,25:21,26:22,27:f,33:24,34:d,36:p,38:m,42:28,43:39,44:g,45:40,47:41,60:y,84:v,85:x,86:b,87:T,88:w,89:k,102:C,105:E,106:S,109:L,111:M,113:42,114:I,115:A,116:_,121:D,122:N,123:R,124:B,125:O},t(n,[2,9]),t(n,[2,10]),t(n,[2,11]),{8:[1,55],9:[1,56],10:$,15:54,18:57},t(z,[2,3]),t(z,[2,4]),t(z,[2,5]),t(z,[2,6]),t(z,[2,7]),t(z,[2,8]),{8:F,9:V,11:H,21:59,41:60,72:64,75:[1,65],77:[1,67],78:[1,66]},{8:F,9:V,11:H,21:68},{8:F,9:V,11:H,21:69},{8:F,9:V,11:H,21:70},{8:F,9:V,11:H,21:71},{8:F,9:V,11:H,21:72},{8:F,9:V,10:[1,73],11:H,21:74},t(z,[2,36]),{35:[1,75]},{37:[1,76]},t(z,[2,39]),t(X,[2,50],{18:77,39:78,10:$,40:W}),{10:[1,80]},{10:[1,81]},{10:[1,82]},{10:[1,83]},{14:Z,44:Y,60:ae,80:[1,87],89:J,95:[1,84],97:[1,85],101:86,105:ee,106:re,109:te,111:be,114:de,115:Ee,116:Ne,120:88},t(z,[2,185]),t(z,[2,186]),t(z,[2,187]),t(z,[2,188]),t(z,[2,189]),t(we,[2,51]),t(we,[2,54],{46:[1,100]}),t(Te,[2,72],{113:113,29:[1,101],44:g,48:[1,102],50:[1,103],52:[1,104],54:[1,105],56:[1,106],58:[1,107],60:y,63:[1,108],65:[1,109],67:[1,110],68:[1,111],70:[1,112],89:k,102:C,105:E,106:S,109:L,111:M,114:I,115:A,116:_}),t(De,[2,181]),t(De,[2,142]),t(De,[2,143]),t(De,[2,144]),t(De,[2,145]),t(De,[2,146]),t(De,[2,147]),t(De,[2,148]),t(De,[2,149]),t(De,[2,150]),t(De,[2,151]),t(De,[2,152]),t(n,[2,12]),t(n,[2,18]),t(n,[2,19]),{9:[1,114]},t($e,[2,26],{18:115,10:$}),t(z,[2,27]),{42:116,43:39,44:g,45:40,47:41,60:y,89:k,102:C,105:E,106:S,109:L,111:M,113:42,114:I,115:A,116:_},t(z,[2,40]),t(z,[2,41]),t(z,[2,42]),t(pe,[2,76],{73:117,62:[1,119],74:[1,118]}),{76:120,79:121,80:Je,81:Ce,116:Fe,119:Ue},{75:[1,126],77:[1,127]},t(qe,[2,83]),t(z,[2,28]),t(z,[2,29]),t(z,[2,30]),t(z,[2,31]),t(z,[2,32]),{10:Me,12:He,14:K,27:oe,28:128,32:U,44:ue,60:G,75:se,80:[1,130],81:[1,131],83:141,84:le,85:ke,86:me,87:ye,88:Re,89:ve,90:Oe,91:129,105:We,109:Be,111:Qe,114:ce,115:it,116:fe},t(ut,a,{5:154}),t(z,[2,37]),t(z,[2,38]),t(X,[2,48],{44:Nt}),t(X,[2,49],{18:156,10:$,40:Pt}),t(we,[2,44]),{44:g,47:158,60:y,89:k,102:C,105:E,106:S,109:L,111:M,113:42,114:I,115:A,116:_},{102:[1,159],103:160,105:[1,161]},{44:g,47:162,60:y,89:k,102:C,105:E,106:S,109:L,111:M,113:42,114:I,115:A,116:_},{44:g,47:163,60:y,89:k,102:C,105:E,106:S,109:L,111:M,113:42,114:I,115:A,116:_},t(St,[2,107],{10:[1,164],96:[1,165]}),{80:[1,166]},t(St,[2,115],{120:168,10:[1,167],14:Z,44:Y,60:ae,89:J,105:ee,106:re,109:te,111:be,114:de,115:Ee,116:Ne}),t(St,[2,117],{10:[1,169]}),t(It,[2,183]),t(It,[2,170]),t(It,[2,171]),t(It,[2,172]),t(It,[2,173]),t(It,[2,174]),t(It,[2,175]),t(It,[2,176]),t(It,[2,177]),t(It,[2,178]),t(It,[2,179]),t(It,[2,180]),{44:g,47:170,60:y,89:k,102:C,105:E,106:S,109:L,111:M,113:42,114:I,115:A,116:_},{30:171,67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},{30:179,67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},{30:181,50:[1,180],67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},{30:182,67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},{30:183,67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},{30:184,67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},{109:[1,185]},{30:186,67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},{30:187,65:[1,188],67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},{30:189,67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},{30:190,67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},{30:191,67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},t(De,[2,182]),t(n,[2,20]),t($e,[2,25]),t(X,[2,46],{39:192,18:193,10:$,40:W}),t(pe,[2,73],{10:[1,194]}),{10:[1,195]},{30:196,67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},{77:[1,197],79:198,116:Fe,119:Ue},t(hr,[2,79]),t(hr,[2,81]),t(hr,[2,82]),t(hr,[2,168]),t(hr,[2,169]),{76:199,79:121,80:Je,81:Ce,116:Fe,119:Ue},t(qe,[2,84]),{8:F,9:V,10:Me,11:H,12:He,14:K,21:201,27:oe,29:[1,200],32:U,44:ue,60:G,75:se,83:141,84:le,85:ke,86:me,87:ye,88:Re,89:ve,90:Oe,91:202,105:We,109:Be,111:Qe,114:ce,115:it,116:fe},t(Qt,[2,101]),t(Qt,[2,103]),t(Qt,[2,104]),t(Qt,[2,157]),t(Qt,[2,158]),t(Qt,[2,159]),t(Qt,[2,160]),t(Qt,[2,161]),t(Qt,[2,162]),t(Qt,[2,163]),t(Qt,[2,164]),t(Qt,[2,165]),t(Qt,[2,166]),t(Qt,[2,167]),t(Qt,[2,90]),t(Qt,[2,91]),t(Qt,[2,92]),t(Qt,[2,93]),t(Qt,[2,94]),t(Qt,[2,95]),t(Qt,[2,96]),t(Qt,[2,97]),t(Qt,[2,98]),t(Qt,[2,99]),t(Qt,[2,100]),{6:11,7:12,8:s,9:l,10:u,11:h,20:17,22:18,23:19,24:20,25:21,26:22,27:f,32:[1,203],33:24,34:d,36:p,38:m,42:28,43:39,44:g,45:40,47:41,60:y,84:v,85:x,86:b,87:T,88:w,89:k,102:C,105:E,106:S,109:L,111:M,113:42,114:I,115:A,116:_,121:D,122:N,123:R,124:B,125:O},{10:$,18:204},{44:[1,205]},t(we,[2,43]),{10:[1,206],44:g,60:y,89:k,102:C,105:E,106:S,109:L,111:M,113:113,114:I,115:A,116:_},{10:[1,207]},{10:[1,208],106:[1,209]},t(Er,[2,128]),{10:[1,210],44:g,60:y,89:k,102:C,105:E,106:S,109:L,111:M,113:113,114:I,115:A,116:_},{10:[1,211],44:g,60:y,89:k,102:C,105:E,106:S,109:L,111:M,113:113,114:I,115:A,116:_},{80:[1,212]},t(St,[2,109],{10:[1,213]}),t(St,[2,111],{10:[1,214]}),{80:[1,215]},t(It,[2,184]),{80:[1,216],98:[1,217]},t(we,[2,55],{113:113,44:g,60:y,89:k,102:C,105:E,106:S,109:L,111:M,114:I,115:A,116:_}),{31:[1,218],67:ot,82:219,116:kt,117:yt,118:jt},t(dr,[2,86]),t(dr,[2,88]),t(dr,[2,89]),t(dr,[2,153]),t(dr,[2,154]),t(dr,[2,155]),t(dr,[2,156]),{49:[1,220],67:ot,82:219,116:kt,117:yt,118:jt},{30:221,67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},{51:[1,222],67:ot,82:219,116:kt,117:yt,118:jt},{53:[1,223],67:ot,82:219,116:kt,117:yt,118:jt},{55:[1,224],67:ot,82:219,116:kt,117:yt,118:jt},{57:[1,225],67:ot,82:219,116:kt,117:yt,118:jt},{60:[1,226]},{64:[1,227],67:ot,82:219,116:kt,117:yt,118:jt},{66:[1,228],67:ot,82:219,116:kt,117:yt,118:jt},{30:229,67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},{31:[1,230],67:ot,82:219,116:kt,117:yt,118:jt},{67:ot,69:[1,231],71:[1,232],82:219,116:kt,117:yt,118:jt},{67:ot,69:[1,234],71:[1,233],82:219,116:kt,117:yt,118:jt},t(X,[2,45],{18:156,10:$,40:Pt}),t(X,[2,47],{44:Nt}),t(pe,[2,75]),t(pe,[2,74]),{62:[1,235],67:ot,82:219,116:kt,117:yt,118:jt},t(pe,[2,77]),t(hr,[2,80]),{77:[1,236],79:198,116:Fe,119:Ue},{30:237,67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},t(ut,a,{5:238}),t(Qt,[2,102]),t(z,[2,35]),{43:239,44:g,45:40,47:41,60:y,89:k,102:C,105:E,106:S,109:L,111:M,113:42,114:I,115:A,116:_},{10:$,18:240},{10:ir,60:pr,84:Ii,92:241,105:xt,107:242,108:243,109:Ie,110:ft,111:_t,112:zr},{10:ir,60:pr,84:Ii,92:252,104:[1,253],105:xt,107:242,108:243,109:Ie,110:ft,111:_t,112:zr},{10:ir,60:pr,84:Ii,92:254,104:[1,255],105:xt,107:242,108:243,109:Ie,110:ft,111:_t,112:zr},{105:[1,256]},{10:ir,60:pr,84:Ii,92:257,105:xt,107:242,108:243,109:Ie,110:ft,111:_t,112:zr},{44:g,47:258,60:y,89:k,102:C,105:E,106:S,109:L,111:M,113:42,114:I,115:A,116:_},t(St,[2,108]),{80:[1,259]},{80:[1,260],98:[1,261]},t(St,[2,116]),t(St,[2,118],{10:[1,262]}),t(St,[2,119]),t(Te,[2,56]),t(dr,[2,87]),t(Te,[2,57]),{51:[1,263],67:ot,82:219,116:kt,117:yt,118:jt},t(Te,[2,64]),t(Te,[2,59]),t(Te,[2,60]),t(Te,[2,61]),{109:[1,264]},t(Te,[2,63]),t(Te,[2,65]),{66:[1,265],67:ot,82:219,116:kt,117:yt,118:jt},t(Te,[2,67]),t(Te,[2,68]),t(Te,[2,70]),t(Te,[2,69]),t(Te,[2,71]),t([10,44,60,89,102,105,106,109,111,114,115,116],[2,85]),t(pe,[2,78]),{31:[1,266],67:ot,82:219,116:kt,117:yt,118:jt},{6:11,7:12,8:s,9:l,10:u,11:h,20:17,22:18,23:19,24:20,25:21,26:22,27:f,32:[1,267],33:24,34:d,36:p,38:m,42:28,43:39,44:g,45:40,47:41,60:y,84:v,85:x,86:b,87:T,88:w,89:k,102:C,105:E,106:S,109:L,111:M,113:42,114:I,115:A,116:_,121:D,122:N,123:R,124:B,125:O},t(we,[2,53]),{43:268,44:g,45:40,47:41,60:y,89:k,102:C,105:E,106:S,109:L,111:M,113:42,114:I,115:A,116:_},t(St,[2,121],{106:ri}),t(ci,[2,130],{108:270,10:ir,60:pr,84:Ii,105:xt,109:Ie,110:ft,111:_t,112:zr}),t(Ir,[2,132]),t(Ir,[2,134]),t(Ir,[2,135]),t(Ir,[2,136]),t(Ir,[2,137]),t(Ir,[2,138]),t(Ir,[2,139]),t(Ir,[2,140]),t(Ir,[2,141]),t(St,[2,122],{106:ri}),{10:[1,271]},t(St,[2,123],{106:ri}),{10:[1,272]},t(Er,[2,129]),t(St,[2,105],{106:ri}),t(St,[2,106],{113:113,44:g,60:y,89:k,102:C,105:E,106:S,109:L,111:M,114:I,115:A,116:_}),t(St,[2,110]),t(St,[2,112],{10:[1,273]}),t(St,[2,113]),{98:[1,274]},{51:[1,275]},{62:[1,276]},{66:[1,277]},{8:F,9:V,11:H,21:278},t(z,[2,34]),t(we,[2,52]),{10:ir,60:pr,84:Ii,105:xt,107:279,108:243,109:Ie,110:ft,111:_t,112:zr},t(Ir,[2,133]),{14:Z,44:Y,60:ae,89:J,101:280,105:ee,106:re,109:te,111:be,114:de,115:Ee,116:Ne,120:88},{14:Z,44:Y,60:ae,89:J,101:281,105:ee,106:re,109:te,111:be,114:de,115:Ee,116:Ne,120:88},{98:[1,282]},t(St,[2,120]),t(Te,[2,58]),{30:283,67:ot,80:ct,81:Dt,82:172,116:kt,117:yt,118:jt},t(Te,[2,66]),t(ut,a,{5:284}),t(ci,[2,131],{108:270,10:ir,60:pr,84:Ii,105:xt,109:Ie,110:ft,111:_t,112:zr}),t(St,[2,126],{120:168,10:[1,285],14:Z,44:Y,60:ae,89:J,105:ee,106:re,109:te,111:be,114:de,115:Ee,116:Ne}),t(St,[2,127],{120:168,10:[1,286],14:Z,44:Y,60:ae,89:J,105:ee,106:re,109:te,111:be,114:de,115:Ee,116:Ne}),t(St,[2,114]),{31:[1,287],67:ot,82:219,116:kt,117:yt,118:jt},{6:11,7:12,8:s,9:l,10:u,11:h,20:17,22:18,23:19,24:20,25:21,26:22,27:f,32:[1,288],33:24,34:d,36:p,38:m,42:28,43:39,44:g,45:40,47:41,60:y,84:v,85:x,86:b,87:T,88:w,89:k,102:C,105:E,106:S,109:L,111:M,113:42,114:I,115:A,116:_,121:D,122:N,123:R,124:B,125:O},{10:ir,60:pr,84:Ii,92:289,105:xt,107:242,108:243,109:Ie,110:ft,111:_t,112:zr},{10:ir,60:pr,84:Ii,92:290,105:xt,107:242,108:243,109:Ie,110:ft,111:_t,112:zr},t(Te,[2,62]),t(z,[2,33]),t(St,[2,124],{106:ri}),t(St,[2,125],{106:ri})],defaultActions:{},parseError:o(function(Et,qt){if(qt.recoverable)this.trace(Et);else{var Zt=new Error(Et);throw Zt.hash=qt,Zt}},"parseError"),parse:o(function(Et){var qt=this,Zt=[0],Tt=[],wi=[null],xe=[],Wo=this.table,Se="",Rn=0,k8=0,r4=0,r8e=2,xY=1,i8e=xe.slice.call(arguments,1),Ca=Object.create(this.lexer),Bp={yy:{}};for(var C8 in this.yy)Object.prototype.hasOwnProperty.call(this.yy,C8)&&(Bp.yy[C8]=this.yy[C8]);Ca.setInput(Et,Bp.yy),Bp.yy.lexer=Ca,Bp.yy.parser=this,typeof Ca.yylloc>"u"&&(Ca.yylloc={});var w8=Ca.yylloc;xe.push(w8);var n8e=Ca.options&&Ca.options.ranges;typeof Bp.yy.parseError=="function"?this.parseError=Bp.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function Tvt(Uo){Zt.length=Zt.length-2*Uo,wi.length=wi.length-Uo,xe.length=xe.length-Uo}o(Tvt,"popStack");function a8e(){var Uo;return Uo=Tt.pop()||Ca.lex()||xY,typeof Uo!="number"&&(Uo instanceof Array&&(Tt=Uo,Uo=Tt.pop()),Uo=qt.symbols_[Uo]||Uo),Uo}o(a8e,"lex");for(var Ls,E8,Fp,gl,kvt,S8,bg={},i4,fh,bY,n4;;){if(Fp=Zt[Zt.length-1],this.defaultActions[Fp]?gl=this.defaultActions[Fp]:((Ls===null||typeof Ls>"u")&&(Ls=a8e()),gl=Wo[Fp]&&Wo[Fp][Ls]),typeof gl>"u"||!gl.length||!gl[0]){var A8="";n4=[];for(i4 in Wo[Fp])this.terminals_[i4]&&i4>r8e&&n4.push("'"+this.terminals_[i4]+"'");Ca.showPosition?A8="Parse error on line "+(Rn+1)+`: +`+Ca.showPosition()+` +Expecting `+n4.join(", ")+", got '"+(this.terminals_[Ls]||Ls)+"'":A8="Parse error on line "+(Rn+1)+": Unexpected "+(Ls==xY?"end of input":"'"+(this.terminals_[Ls]||Ls)+"'"),this.parseError(A8,{text:Ca.match,token:this.terminals_[Ls]||Ls,line:Ca.yylineno,loc:w8,expected:n4})}if(gl[0]instanceof Array&&gl.length>1)throw new Error("Parse Error: multiple actions possible at state: "+Fp+", token: "+Ls);switch(gl[0]){case 1:Zt.push(Ls),wi.push(Ca.yytext),xe.push(Ca.yylloc),Zt.push(gl[1]),Ls=null,E8?(Ls=E8,E8=null):(k8=Ca.yyleng,Se=Ca.yytext,Rn=Ca.yylineno,w8=Ca.yylloc,r4>0&&r4--);break;case 2:if(fh=this.productions_[gl[1]][1],bg.$=wi[wi.length-fh],bg._$={first_line:xe[xe.length-(fh||1)].first_line,last_line:xe[xe.length-1].last_line,first_column:xe[xe.length-(fh||1)].first_column,last_column:xe[xe.length-1].last_column},n8e&&(bg._$.range=[xe[xe.length-(fh||1)].range[0],xe[xe.length-1].range[1]]),S8=this.performAction.apply(bg,[Se,k8,Rn,Bp.yy,gl[1],wi,xe].concat(i8e)),typeof S8<"u")return S8;fh&&(Zt=Zt.slice(0,-1*fh*2),wi=wi.slice(0,-1*fh),xe=xe.slice(0,-1*fh)),Zt.push(this.productions_[gl[1]][0]),wi.push(bg.$),xe.push(bg._$),bY=Wo[Zt[Zt.length-2]][Zt[Zt.length-1]],Zt.push(bY);break;case 3:return!0}}return!0},"parse")},qa=(function(){var Ft={EOF:1,parseError:o(function(qt,Zt){if(this.yy.parser)this.yy.parser.parseError(qt,Zt);else throw new Error(qt)},"parseError"),setInput:o(function(Et,qt){return this.yy=qt||this.yy||{},this._input=Et,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var Et=this._input[0];this.yytext+=Et,this.yyleng++,this.offset++,this.match+=Et,this.matched+=Et;var qt=Et.match(/(?:\r\n?|\n).*/g);return qt?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),Et},"input"),unput:o(function(Et){var qt=Et.length,Zt=Et.split(/(?:\r\n?|\n)/g);this._input=Et+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-qt),this.offset-=qt;var Tt=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),Zt.length-1&&(this.yylineno-=Zt.length-1);var wi=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:Zt?(Zt.length===Tt.length?this.yylloc.first_column:0)+Tt[Tt.length-Zt.length].length-Zt[0].length:this.yylloc.first_column-qt},this.options.ranges&&(this.yylloc.range=[wi[0],wi[0]+this.yyleng-qt]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(Et){this.unput(this.match.slice(Et))},"less"),pastInput:o(function(){var Et=this.matched.substr(0,this.matched.length-this.match.length);return(Et.length>20?"...":"")+Et.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var Et=this.match;return Et.length<20&&(Et+=this._input.substr(0,20-Et.length)),(Et.substr(0,20)+(Et.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var Et=this.pastInput(),qt=new Array(Et.length+1).join("-");return Et+this.upcomingInput()+` +`+qt+"^"},"showPosition"),test_match:o(function(Et,qt){var Zt,Tt,wi;if(this.options.backtrack_lexer&&(wi={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(wi.yylloc.range=this.yylloc.range.slice(0))),Tt=Et[0].match(/(?:\r\n?|\n).*/g),Tt&&(this.yylineno+=Tt.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:Tt?Tt[Tt.length-1].length-Tt[Tt.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+Et[0].length},this.yytext+=Et[0],this.match+=Et[0],this.matches=Et,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(Et[0].length),this.matched+=Et[0],Zt=this.performAction.call(this,this.yy,this,qt,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),Zt)return Zt;if(this._backtrack){for(var xe in wi)this[xe]=wi[xe];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var Et,qt,Zt,Tt;this._more||(this.yytext="",this.match="");for(var wi=this._currentRules(),xe=0;xeqt[0].length)){if(qt=Zt,Tt=xe,this.options.backtrack_lexer){if(Et=this.test_match(Zt,wi[xe]),Et!==!1)return Et;if(this._backtrack){qt=!1;continue}else return!1}else if(!this.options.flex)break}return qt?(Et=this.test_match(qt,wi[Tt]),Et!==!1?Et:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var qt=this.next();return qt||this.lex()},"lex"),begin:o(function(qt){this.conditionStack.push(qt)},"begin"),popState:o(function(){var qt=this.conditionStack.length-1;return qt>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(qt){return qt=this.conditionStack.length-1-Math.abs(qt||0),qt>=0?this.conditionStack[qt]:"INITIAL"},"topState"),pushState:o(function(qt){this.begin(qt)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{},performAction:o(function(qt,Zt,Tt,wi){var xe=wi;switch(Tt){case 0:return this.begin("acc_title"),34;break;case 1:return this.popState(),"acc_title_value";break;case 2:return this.begin("acc_descr"),36;break;case 3:return this.popState(),"acc_descr_value";break;case 4:this.begin("acc_descr_multiline");break;case 5:this.popState();break;case 6:return"acc_descr_multiline_value";case 7:return this.pushState("shapeData"),Zt.yytext="",40;break;case 8:return this.pushState("shapeDataStr"),40;break;case 9:return this.popState(),40;break;case 10:let Wo=/\n\s*/g;return Zt.yytext=Zt.yytext.replace(Wo,"
    "),40;break;case 11:return 40;case 12:this.popState();break;case 13:this.begin("callbackname");break;case 14:this.popState();break;case 15:this.popState(),this.begin("callbackargs");break;case 16:return 95;case 17:this.popState();break;case 18:return 96;case 19:return"MD_STR";case 20:this.popState();break;case 21:this.begin("md_string");break;case 22:return"STR";case 23:this.popState();break;case 24:this.pushState("string");break;case 25:return 84;case 26:return 102;case 27:return 85;case 28:return 104;case 29:return 86;case 30:return 87;case 31:return 97;case 32:this.begin("click");break;case 33:this.popState();break;case 34:return 88;case 35:return qt.lex.firstGraph()&&this.begin("dir"),12;break;case 36:return qt.lex.firstGraph()&&this.begin("dir"),12;break;case 37:return qt.lex.firstGraph()&&this.begin("dir"),12;break;case 38:return 27;case 39:return 32;case 40:return 98;case 41:return 98;case 42:return 98;case 43:return 98;case 44:return this.popState(),13;break;case 45:return this.popState(),14;break;case 46:return this.popState(),14;break;case 47:return this.popState(),14;break;case 48:return this.popState(),14;break;case 49:return this.popState(),14;break;case 50:return this.popState(),14;break;case 51:return this.popState(),14;break;case 52:return this.popState(),14;break;case 53:return this.popState(),14;break;case 54:return this.popState(),14;break;case 55:return 121;case 56:return 122;case 57:return 123;case 58:return 124;case 59:return 125;case 60:return 78;case 61:return 105;case 62:return 111;case 63:return 46;case 64:return 60;case 65:return 44;case 66:return 8;case 67:return 106;case 68:return 115;case 69:return this.popState(),77;break;case 70:return this.pushState("edgeText"),75;break;case 71:return 119;case 72:return this.popState(),77;break;case 73:return this.pushState("thickEdgeText"),75;break;case 74:return 119;case 75:return this.popState(),77;break;case 76:return this.pushState("dottedEdgeText"),75;break;case 77:return 119;case 78:return 77;case 79:return this.popState(),53;break;case 80:return"TEXT";case 81:return this.pushState("ellipseText"),52;break;case 82:return this.popState(),55;break;case 83:return this.pushState("text"),54;break;case 84:return this.popState(),57;break;case 85:return this.pushState("text"),56;break;case 86:return 58;case 87:return this.pushState("text"),67;break;case 88:return this.popState(),64;break;case 89:return this.pushState("text"),63;break;case 90:return this.popState(),49;break;case 91:return this.pushState("text"),48;break;case 92:return this.popState(),69;break;case 93:return this.popState(),71;break;case 94:return 117;case 95:return this.pushState("trapText"),68;break;case 96:return this.pushState("trapText"),70;break;case 97:return 118;case 98:return 67;case 99:return 90;case 100:return"SEP";case 101:return 89;case 102:return 115;case 103:return 111;case 104:return 44;case 105:return 109;case 106:return 114;case 107:return 116;case 108:return this.popState(),62;break;case 109:return this.pushState("text"),62;break;case 110:return this.popState(),51;break;case 111:return this.pushState("text"),50;break;case 112:return this.popState(),31;break;case 113:return this.pushState("text"),29;break;case 114:return this.popState(),66;break;case 115:return this.pushState("text"),65;break;case 116:return"TEXT";case 117:return"QUOTE";case 118:return 9;case 119:return 10;case 120:return 11}},"anonymous"),rules:[/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:@\{)/,/^(?:["])/,/^(?:["])/,/^(?:[^\"]+)/,/^(?:[^}^"]+)/,/^(?:\})/,/^(?:call[\s]+)/,/^(?:\([\s]*\))/,/^(?:\()/,/^(?:[^(]*)/,/^(?:\))/,/^(?:[^)]*)/,/^(?:[^`"]+)/,/^(?:[`]["])/,/^(?:["][`])/,/^(?:[^"]+)/,/^(?:["])/,/^(?:["])/,/^(?:style\b)/,/^(?:default\b)/,/^(?:linkStyle\b)/,/^(?:interpolate\b)/,/^(?:classDef\b)/,/^(?:class\b)/,/^(?:href[\s])/,/^(?:click[\s]+)/,/^(?:[\s\n])/,/^(?:[^\s\n]*)/,/^(?:flowchart-elk\b)/,/^(?:graph\b)/,/^(?:flowchart\b)/,/^(?:subgraph\b)/,/^(?:end\b\s*)/,/^(?:_self\b)/,/^(?:_blank\b)/,/^(?:_parent\b)/,/^(?:_top\b)/,/^(?:(\r?\n)*\s*\n)/,/^(?:\s*LR\b)/,/^(?:\s*RL\b)/,/^(?:\s*TB\b)/,/^(?:\s*BT\b)/,/^(?:\s*TD\b)/,/^(?:\s*BR\b)/,/^(?:\s*<)/,/^(?:\s*>)/,/^(?:\s*\^)/,/^(?:\s*v\b)/,/^(?:.*direction\s+TB[^\n]*)/,/^(?:.*direction\s+BT[^\n]*)/,/^(?:.*direction\s+RL[^\n]*)/,/^(?:.*direction\s+LR[^\n]*)/,/^(?:.*direction\s+TD[^\n]*)/,/^(?:[^\s\"]+@(?=[^\{\"]))/,/^(?:[0-9]+)/,/^(?:#)/,/^(?::::)/,/^(?::)/,/^(?:&)/,/^(?:;)/,/^(?:,)/,/^(?:\*)/,/^(?:\s*[xo<]?--+[-xo>]\s*)/,/^(?:\s*[xo<]?--\s*)/,/^(?:[^-]|-(?!-)+)/,/^(?:\s*[xo<]?==+[=xo>]\s*)/,/^(?:\s*[xo<]?==\s*)/,/^(?:[^=]|=(?!))/,/^(?:\s*[xo<]?-?\.+-[xo>]?\s*)/,/^(?:\s*[xo<]?-\.\s*)/,/^(?:[^\.]|\.(?!))/,/^(?:\s*~~[\~]+\s*)/,/^(?:[-/\)][\)])/,/^(?:[^\(\)\[\]\{\}]|!\)+)/,/^(?:\(-)/,/^(?:\]\))/,/^(?:\(\[)/,/^(?:\]\])/,/^(?:\[\[)/,/^(?:\[\|)/,/^(?:>)/,/^(?:\)\])/,/^(?:\[\()/,/^(?:\)\)\))/,/^(?:\(\(\()/,/^(?:[\\(?=\])][\]])/,/^(?:\/(?=\])\])/,/^(?:\/(?!\])|\\(?!\])|[^\\\[\]\(\)\{\}\/]+)/,/^(?:\[\/)/,/^(?:\[\\)/,/^(?:<)/,/^(?:>)/,/^(?:\^)/,/^(?:\\\|)/,/^(?:v\b)/,/^(?:\*)/,/^(?:#)/,/^(?:&)/,/^(?:([A-Za-z0-9!"\#$%&'*+\.`?\\_\/]|-(?=[^\>\-\.])|(?!))+)/,/^(?:-)/,/^(?:[\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6]|[\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377]|[\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5]|[\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA]|[\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE]|[\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA]|[\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0]|[\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977]|[\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2]|[\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A]|[\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39]|[\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8]|[\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C]|[\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C]|[\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99]|[\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0]|[\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D]|[\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3]|[\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10]|[\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1]|[\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81]|[\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3]|[\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6]|[\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A]|[\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081]|[\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D]|[\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0]|[\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310]|[\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C]|[\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711]|[\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7]|[\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C]|[\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16]|[\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF]|[\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC]|[\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D]|[\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D]|[\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3]|[\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F]|[\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128]|[\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184]|[\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3]|[\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6]|[\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE]|[\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C]|[\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D]|[\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC]|[\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B]|[\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788]|[\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805]|[\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB]|[\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28]|[\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5]|[\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4]|[\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E]|[\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D]|[\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36]|[\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D]|[\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC]|[\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF]|[\uFFD2-\uFFD7\uFFDA-\uFFDC])/,/^(?:\|)/,/^(?:\|)/,/^(?:\))/,/^(?:\()/,/^(?:\])/,/^(?:\[)/,/^(?:(\}))/,/^(?:\{)/,/^(?:[^\[\]\(\)\{\}\|\"]+)/,/^(?:")/,/^(?:(\r?\n)+)/,/^(?:\s)/,/^(?:$)/],conditions:{shapeDataEndBracket:{rules:[21,24,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},shapeDataStr:{rules:[9,10,21,24,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},shapeData:{rules:[8,11,12,21,24,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},callbackargs:{rules:[17,18,21,24,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},callbackname:{rules:[14,15,16,21,24,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},href:{rules:[21,24,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},click:{rules:[21,24,33,34,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},dottedEdgeText:{rules:[21,24,75,77,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},thickEdgeText:{rules:[21,24,72,74,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},edgeText:{rules:[21,24,69,71,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},trapText:{rules:[21,24,78,81,83,85,89,91,92,93,94,95,96,109,111,113,115],inclusive:!1},ellipseText:{rules:[21,24,78,79,80,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},text:{rules:[21,24,78,81,82,83,84,85,88,89,90,91,95,96,108,109,110,111,112,113,114,115,116],inclusive:!1},vertex:{rules:[21,24,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},dir:{rules:[21,24,44,45,46,47,48,49,50,51,52,53,54,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},acc_descr_multiline:{rules:[5,6,21,24,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},acc_descr:{rules:[3,21,24,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},acc_title:{rules:[1,21,24,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},md_string:{rules:[19,20,21,24,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},string:{rules:[21,22,23,24,78,81,83,85,89,91,95,96,109,111,113,115],inclusive:!1},INITIAL:{rules:[0,2,4,7,13,21,24,25,26,27,28,29,30,31,32,35,36,37,38,39,40,41,42,43,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,72,73,75,76,78,81,83,85,86,87,89,91,95,96,97,98,99,100,101,102,103,104,105,106,107,109,111,113,115,117,118,119,120],inclusive:!0}}};return Ft})();sa.lexer=qa;function Mi(){this.yy={}}return o(Mi,"Parser"),Mi.prototype=sa,sa.Parser=Mi,new Mi})();CF.parser=CF;wF=CF});var vye,xye,bye=P(()=>{"use strict";yye();vye=Object.assign({},wF);vye.parse=t=>{let e=t.replace(/}\s*\n/g,`} +`);return wF.parse(e)};xye=vye});var qu,wy=P(()=>{"use strict";qu=o(()=>` + /* Font Awesome icon styling - consolidated */ + .label-icon { + display: inline-block; + height: 1em; + overflow: visible; + vertical-align: -0.125em; + } + + .node .label-icon path { + fill: currentColor; + stroke: revert; + stroke-width: revert; + } +`,"getIconStyles")});var Ait,_it,Tye,kye=P(()=>{"use strict";Yn();wy();Ait=o((t,e)=>{let r=zp,i=r(t,"r"),n=r(t,"g"),a=r(t,"b");return Fn(i,n,a,e)},"fade"),_it=o(t=>`.label { + font-family: ${t.fontFamily}; + color: ${t.nodeTextColor||t.textColor}; + } + .cluster-label text { + fill: ${t.titleColor}; + } + .cluster-label span { + color: ${t.titleColor}; + } + .cluster-label span p { + background-color: transparent; + } + + .label text,span { + fill: ${t.nodeTextColor||t.textColor}; + color: ${t.nodeTextColor||t.textColor}; + } + + .node rect, + .node circle, + .node ellipse, + .node polygon, + .node path { + fill: ${t.mainBkg}; + stroke: ${t.nodeBorder}; + stroke-width: ${t.strokeWidth??1}px; + } + .rough-node .label text , .node .label text, .image-shape .label, .icon-shape .label { + text-anchor: middle; + } + // .flowchart-label .text-outer-tspan { + // text-anchor: middle; + // } + // .flowchart-label .text-inner-tspan { + // text-anchor: start; + // } + + .node .katex path { + fill: #000; + stroke: #000; + stroke-width: 1px; + } + + .rough-node .label,.node .label, .image-shape .label, .icon-shape .label { + text-align: center; + } + .node.clickable { + cursor: pointer; + } + + + .root .anchor path { + fill: ${t.lineColor} !important; + stroke-width: 0; + stroke: ${t.lineColor}; + } + + .arrowheadPath { + fill: ${t.arrowheadColor}; + } + + .edgePath .path { + stroke: ${t.lineColor}; + stroke-width: ${t.strokeWidth??2}px; + } + + .flowchart-link { + stroke: ${t.lineColor}; + fill: none; + } + + .edgeLabel { + background-color: ${t.edgeLabelBackground}; + p { + background-color: ${t.edgeLabelBackground}; + } + rect { + opacity: 0.5; + background-color: ${t.edgeLabelBackground}; + fill: ${t.edgeLabelBackground}; + } + text-align: center; + } + + /* For html labels only */ + .labelBkg { + background-color: ${Ait(t.edgeLabelBackground,.5)}; + // background-color: + } + + .cluster rect { + fill: ${t.clusterBkg}; + stroke: ${t.clusterBorder}; + stroke-width: 1px; + } + + .cluster text { + fill: ${t.titleColor}; + } + + .cluster span { + color: ${t.titleColor}; + } + /* .cluster div { + color: ${t.titleColor}; + } */ + + div.mermaidTooltip { + position: absolute; + text-align: center; + max-width: 200px; + padding: 2px; + font-family: ${t.fontFamily}; + font-size: 12px; + background: ${t.tertiaryColor}; + border: 1px solid ${t.border2}; + border-radius: 2px; + pointer-events: none; + z-index: 100; + } + + .flowchartTitleText { + text-anchor: middle; + font-size: 18px; + fill: ${t.textColor}; + } + + rect.text { + fill: none; + stroke-width: 0; + } + + .icon-shape, .image-shape { + background-color: ${t.edgeLabelBackground}; + p { + background-color: ${t.edgeLabelBackground}; + padding: 2px; + } + .label rect { + opacity: 0.5; + background-color: ${t.edgeLabelBackground}; + fill: ${t.edgeLabelBackground}; + } + text-align: center; + } + ${qu()} +`,"getStyles"),Tye=_it});var qS={};ur(qS,{diagram:()=>Dit});var Dit,WS=P(()=>{"use strict";Ut();qle();gye();bye();kye();Dit={parser:xye,get db(){return new S5},renderer:mye,styles:Tye,init:o(t=>{t.flowchart||(t.flowchart={}),t.layout&&t2({layout:t.layout}),t.flowchart.arrowMarkerAbsolute=t.arrowMarkerAbsolute,t2({flowchart:{arrowMarkerAbsolute:t.arrowMarkerAbsolute}})},"init")}});var EF,Aye,_ye=P(()=>{"use strict";EF=(function(){var t=o(function(Ee,Ne,we,Te){for(we=we||{},Te=Ee.length;Te--;we[Ee[Te]]=Ne);return we},"o"),e=[6,8,10,22,24,26,28,33,34,35,36,37,40,43,44,48,50,51,52],r=[1,10],i=[1,11],n=[1,12],a=[1,13],s=[1,23],l=[1,24],u=[1,25],h=[1,26],f=[1,27],d=[1,19],p=[1,28],m=[1,29],g=[1,20],y=[1,18],v=[1,21],x=[1,22],b=[1,36],T=[1,37],w=[1,38],k=[1,39],C=[1,40],E=[6,8,10,13,15,17,20,21,22,24,26,28,33,34,35,36,37,40,43,44,48,50,51,52,65,66,67,68,69],S=[1,45],L=[1,46],M=[1,55],I=[40,48,50,51,52,70,71],A=[1,66],_=[1,64],D=[1,61],N=[1,65],R=[1,67],B=[6,8,10,13,17,22,24,26,28,33,34,35,36,37,40,41,42,43,44,48,49,50,51,52,65,66,67,68,69],O=[65,66,67,68,69],$=[1,84],z=[1,83],F=[1,81],V=[1,82],H=[6,10,42,47],X=[6,10,13,41,42,47,48,49],W=[1,92],Z=[1,91],Y=[1,90],ae=[19,58],J=[1,101],ee=[1,100],re=[19,58,60,62],te={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,ER_DIAGRAM:4,document:5,EOF:6,line:7,SPACE:8,statement:9,NEWLINE:10,entityName:11,relSpec:12,COLON:13,role:14,STYLE_SEPARATOR:15,idList:16,BLOCK_START:17,attributes:18,BLOCK_STOP:19,SQS:20,SQE:21,title:22,title_value:23,acc_title:24,acc_title_value:25,acc_descr:26,acc_descr_value:27,acc_descr_multiline_value:28,direction:29,classDefStatement:30,classStatement:31,styleStatement:32,direction_tb:33,direction_bt:34,direction_rl:35,direction_lr:36,CLASSDEF:37,stylesOpt:38,separator:39,UNICODE_TEXT:40,STYLE_TEXT:41,COMMA:42,CLASS:43,STYLE:44,style:45,styleComponent:46,SEMI:47,NUM:48,BRKT:49,ENTITY_NAME:50,DECIMAL_NUM:51,ENTITY_ONE:52,attribute:53,attributeType:54,attributeName:55,attributeKeyTypeList:56,attributeComment:57,ATTRIBUTE_WORD:58,attributeKeyType:59,",":60,ATTRIBUTE_KEY:61,COMMENT:62,cardinality:63,relType:64,ZERO_OR_ONE:65,ZERO_OR_MORE:66,ONE_OR_MORE:67,ONLY_ONE:68,MD_PARENT:69,NON_IDENTIFYING:70,IDENTIFYING:71,WORD:72,$accept:0,$end:1},terminals_:{2:"error",4:"ER_DIAGRAM",6:"EOF",8:"SPACE",10:"NEWLINE",13:"COLON",15:"STYLE_SEPARATOR",17:"BLOCK_START",19:"BLOCK_STOP",20:"SQS",21:"SQE",22:"title",23:"title_value",24:"acc_title",25:"acc_title_value",26:"acc_descr",27:"acc_descr_value",28:"acc_descr_multiline_value",33:"direction_tb",34:"direction_bt",35:"direction_rl",36:"direction_lr",37:"CLASSDEF",40:"UNICODE_TEXT",41:"STYLE_TEXT",42:"COMMA",43:"CLASS",44:"STYLE",47:"SEMI",48:"NUM",49:"BRKT",50:"ENTITY_NAME",51:"DECIMAL_NUM",52:"ENTITY_ONE",58:"ATTRIBUTE_WORD",60:",",61:"ATTRIBUTE_KEY",62:"COMMENT",65:"ZERO_OR_ONE",66:"ZERO_OR_MORE",67:"ONE_OR_MORE",68:"ONLY_ONE",69:"MD_PARENT",70:"NON_IDENTIFYING",71:"IDENTIFYING",72:"WORD"},productions_:[0,[3,3],[5,0],[5,2],[7,2],[7,1],[7,1],[7,1],[9,5],[9,9],[9,7],[9,7],[9,4],[9,6],[9,3],[9,5],[9,1],[9,3],[9,7],[9,9],[9,6],[9,8],[9,4],[9,6],[9,2],[9,2],[9,2],[9,1],[9,1],[9,1],[9,1],[9,1],[29,1],[29,1],[29,1],[29,1],[30,4],[16,1],[16,1],[16,3],[16,3],[31,3],[32,4],[38,1],[38,3],[45,1],[45,2],[39,1],[39,1],[39,1],[46,1],[46,1],[46,1],[46,1],[11,1],[11,1],[11,1],[11,1],[11,1],[18,1],[18,2],[53,2],[53,3],[53,3],[53,4],[54,1],[55,1],[56,1],[56,3],[59,1],[57,1],[12,3],[63,1],[63,1],[63,1],[63,1],[63,1],[64,1],[64,1],[14,1],[14,1],[14,1]],performAction:o(function(Ne,we,Te,De,$e,pe,Je){var Ce=pe.length-1;switch($e){case 1:break;case 2:this.$=[];break;case 3:pe[Ce-1].push(pe[Ce]),this.$=pe[Ce-1];break;case 4:case 5:this.$=pe[Ce];break;case 6:case 7:this.$=[];break;case 8:De.addEntity(pe[Ce-4]),De.addEntity(pe[Ce-2]),De.addRelationship(pe[Ce-4],pe[Ce],pe[Ce-2],pe[Ce-3]);break;case 9:De.addEntity(pe[Ce-8]),De.addEntity(pe[Ce-4]),De.addRelationship(pe[Ce-8],pe[Ce],pe[Ce-4],pe[Ce-5]),De.setClass([pe[Ce-8]],pe[Ce-6]),De.setClass([pe[Ce-4]],pe[Ce-2]);break;case 10:De.addEntity(pe[Ce-6]),De.addEntity(pe[Ce-2]),De.addRelationship(pe[Ce-6],pe[Ce],pe[Ce-2],pe[Ce-3]),De.setClass([pe[Ce-6]],pe[Ce-4]);break;case 11:De.addEntity(pe[Ce-6]),De.addEntity(pe[Ce-4]),De.addRelationship(pe[Ce-6],pe[Ce],pe[Ce-4],pe[Ce-5]),De.setClass([pe[Ce-4]],pe[Ce-2]);break;case 12:De.addEntity(pe[Ce-3]),De.addAttributes(pe[Ce-3],pe[Ce-1]);break;case 13:De.addEntity(pe[Ce-5]),De.addAttributes(pe[Ce-5],pe[Ce-1]),De.setClass([pe[Ce-5]],pe[Ce-3]);break;case 14:De.addEntity(pe[Ce-2]);break;case 15:De.addEntity(pe[Ce-4]),De.setClass([pe[Ce-4]],pe[Ce-2]);break;case 16:De.addEntity(pe[Ce]);break;case 17:De.addEntity(pe[Ce-2]),De.setClass([pe[Ce-2]],pe[Ce]);break;case 18:De.addEntity(pe[Ce-6],pe[Ce-4]),De.addAttributes(pe[Ce-6],pe[Ce-1]);break;case 19:De.addEntity(pe[Ce-8],pe[Ce-6]),De.addAttributes(pe[Ce-8],pe[Ce-1]),De.setClass([pe[Ce-8]],pe[Ce-3]);break;case 20:De.addEntity(pe[Ce-5],pe[Ce-3]);break;case 21:De.addEntity(pe[Ce-7],pe[Ce-5]),De.setClass([pe[Ce-7]],pe[Ce-2]);break;case 22:De.addEntity(pe[Ce-3],pe[Ce-1]);break;case 23:De.addEntity(pe[Ce-5],pe[Ce-3]),De.setClass([pe[Ce-5]],pe[Ce]);break;case 24:case 25:this.$=pe[Ce].trim(),De.setAccTitle(this.$);break;case 26:case 27:this.$=pe[Ce].trim(),De.setAccDescription(this.$);break;case 32:De.setDirection("TB");break;case 33:De.setDirection("BT");break;case 34:De.setDirection("RL");break;case 35:De.setDirection("LR");break;case 36:this.$=pe[Ce-3],De.addClass(pe[Ce-2],pe[Ce-1]);break;case 37:case 38:case 59:case 67:this.$=[pe[Ce]];break;case 39:case 40:this.$=pe[Ce-2].concat([pe[Ce]]);break;case 41:this.$=pe[Ce-2],De.setClass(pe[Ce-1],pe[Ce]);break;case 42:this.$=pe[Ce-3],De.addCssStyles(pe[Ce-2],pe[Ce-1]);break;case 43:this.$=[pe[Ce]];break;case 44:pe[Ce-2].push(pe[Ce]),this.$=pe[Ce-2];break;case 46:this.$=pe[Ce-1]+pe[Ce];break;case 54:case 79:case 80:this.$=pe[Ce].replace(/"/g,"");break;case 55:case 56:case 57:case 58:case 81:this.$=pe[Ce];break;case 60:pe[Ce].push(pe[Ce-1]),this.$=pe[Ce];break;case 61:this.$={type:pe[Ce-1],name:pe[Ce]};break;case 62:this.$={type:pe[Ce-2],name:pe[Ce-1],keys:pe[Ce]};break;case 63:this.$={type:pe[Ce-2],name:pe[Ce-1],comment:pe[Ce]};break;case 64:this.$={type:pe[Ce-3],name:pe[Ce-2],keys:pe[Ce-1],comment:pe[Ce]};break;case 65:case 66:case 69:this.$=pe[Ce];break;case 68:pe[Ce-2].push(pe[Ce]),this.$=pe[Ce-2];break;case 70:this.$=pe[Ce].replace(/"/g,"");break;case 71:this.$={cardA:pe[Ce],relType:pe[Ce-1],cardB:pe[Ce-2]};break;case 72:this.$=De.Cardinality.ZERO_OR_ONE;break;case 73:this.$=De.Cardinality.ZERO_OR_MORE;break;case 74:this.$=De.Cardinality.ONE_OR_MORE;break;case 75:this.$=De.Cardinality.ONLY_ONE;break;case 76:this.$=De.Cardinality.MD_PARENT;break;case 77:this.$=De.Identification.NON_IDENTIFYING;break;case 78:this.$=De.Identification.IDENTIFYING;break}},"anonymous"),table:[{3:1,4:[1,2]},{1:[3]},t(e,[2,2],{5:3}),{6:[1,4],7:5,8:[1,6],9:7,10:[1,8],11:9,22:r,24:i,26:n,28:a,29:14,30:15,31:16,32:17,33:s,34:l,35:u,36:h,37:f,40:d,43:p,44:m,48:g,50:y,51:v,52:x},t(e,[2,7],{1:[2,1]}),t(e,[2,3]),{9:30,11:9,22:r,24:i,26:n,28:a,29:14,30:15,31:16,32:17,33:s,34:l,35:u,36:h,37:f,40:d,43:p,44:m,48:g,50:y,51:v,52:x},t(e,[2,5]),t(e,[2,6]),t(e,[2,16],{12:31,63:35,15:[1,32],17:[1,33],20:[1,34],65:b,66:T,67:w,68:k,69:C}),{23:[1,41]},{25:[1,42]},{27:[1,43]},t(e,[2,27]),t(e,[2,28]),t(e,[2,29]),t(e,[2,30]),t(e,[2,31]),t(E,[2,54]),t(E,[2,55]),t(E,[2,56]),t(E,[2,57]),t(E,[2,58]),t(e,[2,32]),t(e,[2,33]),t(e,[2,34]),t(e,[2,35]),{16:44,40:S,41:L},{16:47,40:S,41:L},{16:48,40:S,41:L},t(e,[2,4]),{11:49,40:d,48:g,50:y,51:v,52:x},{16:50,40:S,41:L},{18:51,19:[1,52],53:53,54:54,58:M},{11:56,40:d,48:g,50:y,51:v,52:x},{64:57,70:[1,58],71:[1,59]},t(I,[2,72]),t(I,[2,73]),t(I,[2,74]),t(I,[2,75]),t(I,[2,76]),t(e,[2,24]),t(e,[2,25]),t(e,[2,26]),{13:A,38:60,41:_,42:D,45:62,46:63,48:N,49:R},t(B,[2,37]),t(B,[2,38]),{16:68,40:S,41:L,42:D},{13:A,38:69,41:_,42:D,45:62,46:63,48:N,49:R},{13:[1,70],15:[1,71]},t(e,[2,17],{63:35,12:72,17:[1,73],42:D,65:b,66:T,67:w,68:k,69:C}),{19:[1,74]},t(e,[2,14]),{18:75,19:[2,59],53:53,54:54,58:M},{55:76,58:[1,77]},{58:[2,65]},{21:[1,78]},{63:79,65:b,66:T,67:w,68:k,69:C},t(O,[2,77]),t(O,[2,78]),{6:$,10:z,39:80,42:F,47:V},{40:[1,85],41:[1,86]},t(H,[2,43],{46:87,13:A,41:_,48:N,49:R}),t(X,[2,45]),t(X,[2,50]),t(X,[2,51]),t(X,[2,52]),t(X,[2,53]),t(e,[2,41],{42:D}),{6:$,10:z,39:88,42:F,47:V},{14:89,40:W,50:Z,72:Y},{16:93,40:S,41:L},{11:94,40:d,48:g,50:y,51:v,52:x},{18:95,19:[1,96],53:53,54:54,58:M},t(e,[2,12]),{19:[2,60]},t(ae,[2,61],{56:97,57:98,59:99,61:J,62:ee}),t([19,58,61,62],[2,66]),t(e,[2,22],{15:[1,103],17:[1,102]}),t([40,48,50,51,52],[2,71]),t(e,[2,36]),{13:A,41:_,45:104,46:63,48:N,49:R},t(e,[2,47]),t(e,[2,48]),t(e,[2,49]),t(B,[2,39]),t(B,[2,40]),t(X,[2,46]),t(e,[2,42]),t(e,[2,8]),t(e,[2,79]),t(e,[2,80]),t(e,[2,81]),{13:[1,105],42:D},{13:[1,107],15:[1,106]},{19:[1,108]},t(e,[2,15]),t(ae,[2,62],{57:109,60:[1,110],62:ee}),t(ae,[2,63]),t(re,[2,67]),t(ae,[2,70]),t(re,[2,69]),{18:111,19:[1,112],53:53,54:54,58:M},{16:113,40:S,41:L},t(H,[2,44],{46:87,13:A,41:_,48:N,49:R}),{14:114,40:W,50:Z,72:Y},{16:115,40:S,41:L},{14:116,40:W,50:Z,72:Y},t(e,[2,13]),t(ae,[2,64]),{59:117,61:J},{19:[1,118]},t(e,[2,20]),t(e,[2,23],{17:[1,119],42:D}),t(e,[2,11]),{13:[1,120],42:D},t(e,[2,10]),t(re,[2,68]),t(e,[2,18]),{18:121,19:[1,122],53:53,54:54,58:M},{14:123,40:W,50:Z,72:Y},{19:[1,124]},t(e,[2,21]),t(e,[2,9]),t(e,[2,19])],defaultActions:{55:[2,65],75:[2,60]},parseError:o(function(Ne,we){if(we.recoverable)this.trace(Ne);else{var Te=new Error(Ne);throw Te.hash=we,Te}},"parseError"),parse:o(function(Ne){var we=this,Te=[0],De=[],$e=[null],pe=[],Je=this.table,Ce="",Fe=0,Ue=0,qe=0,Me=2,He=1,K=pe.slice.call(arguments,1),oe=Object.create(this.lexer),U={yy:{}};for(var ue in this.yy)Object.prototype.hasOwnProperty.call(this.yy,ue)&&(U.yy[ue]=this.yy[ue]);oe.setInput(Ne,U.yy),U.yy.lexer=oe,U.yy.parser=this,typeof oe.yylloc>"u"&&(oe.yylloc={});var G=oe.yylloc;pe.push(G);var se=oe.options&&oe.options.ranges;typeof U.yy.parseError=="function"?this.parseError=U.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function le(Nt){Te.length=Te.length-2*Nt,$e.length=$e.length-Nt,pe.length=pe.length-Nt}o(le,"popStack");function ke(){var Nt;return Nt=De.pop()||oe.lex()||He,typeof Nt!="number"&&(Nt instanceof Array&&(De=Nt,Nt=De.pop()),Nt=we.symbols_[Nt]||Nt),Nt}o(ke,"lex");for(var me,ye,Re,ve,Oe,We,Be={},Qe,ce,it,fe;;){if(Re=Te[Te.length-1],this.defaultActions[Re]?ve=this.defaultActions[Re]:((me===null||typeof me>"u")&&(me=ke()),ve=Je[Re]&&Je[Re][me]),typeof ve>"u"||!ve.length||!ve[0]){var ut="";fe=[];for(Qe in Je[Re])this.terminals_[Qe]&&Qe>Me&&fe.push("'"+this.terminals_[Qe]+"'");oe.showPosition?ut="Parse error on line "+(Fe+1)+`: +`+oe.showPosition()+` +Expecting `+fe.join(", ")+", got '"+(this.terminals_[me]||me)+"'":ut="Parse error on line "+(Fe+1)+": Unexpected "+(me==He?"end of input":"'"+(this.terminals_[me]||me)+"'"),this.parseError(ut,{text:oe.match,token:this.terminals_[me]||me,line:oe.yylineno,loc:G,expected:fe})}if(ve[0]instanceof Array&&ve.length>1)throw new Error("Parse Error: multiple actions possible at state: "+Re+", token: "+me);switch(ve[0]){case 1:Te.push(me),$e.push(oe.yytext),pe.push(oe.yylloc),Te.push(ve[1]),me=null,ye?(me=ye,ye=null):(Ue=oe.yyleng,Ce=oe.yytext,Fe=oe.yylineno,G=oe.yylloc,qe>0&&qe--);break;case 2:if(ce=this.productions_[ve[1]][1],Be.$=$e[$e.length-ce],Be._$={first_line:pe[pe.length-(ce||1)].first_line,last_line:pe[pe.length-1].last_line,first_column:pe[pe.length-(ce||1)].first_column,last_column:pe[pe.length-1].last_column},se&&(Be._$.range=[pe[pe.length-(ce||1)].range[0],pe[pe.length-1].range[1]]),We=this.performAction.apply(Be,[Ce,Ue,Fe,U.yy,ve[1],$e,pe].concat(K)),typeof We<"u")return We;ce&&(Te=Te.slice(0,-1*ce*2),$e=$e.slice(0,-1*ce),pe=pe.slice(0,-1*ce)),Te.push(this.productions_[ve[1]][0]),$e.push(Be.$),pe.push(Be._$),it=Je[Te[Te.length-2]][Te[Te.length-1]],Te.push(it);break;case 3:return!0}}return!0},"parse")},be=(function(){var Ee={EOF:1,parseError:o(function(we,Te){if(this.yy.parser)this.yy.parser.parseError(we,Te);else throw new Error(we)},"parseError"),setInput:o(function(Ne,we){return this.yy=we||this.yy||{},this._input=Ne,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var Ne=this._input[0];this.yytext+=Ne,this.yyleng++,this.offset++,this.match+=Ne,this.matched+=Ne;var we=Ne.match(/(?:\r\n?|\n).*/g);return we?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),Ne},"input"),unput:o(function(Ne){var we=Ne.length,Te=Ne.split(/(?:\r\n?|\n)/g);this._input=Ne+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-we),this.offset-=we;var De=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),Te.length-1&&(this.yylineno-=Te.length-1);var $e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:Te?(Te.length===De.length?this.yylloc.first_column:0)+De[De.length-Te.length].length-Te[0].length:this.yylloc.first_column-we},this.options.ranges&&(this.yylloc.range=[$e[0],$e[0]+this.yyleng-we]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(Ne){this.unput(this.match.slice(Ne))},"less"),pastInput:o(function(){var Ne=this.matched.substr(0,this.matched.length-this.match.length);return(Ne.length>20?"...":"")+Ne.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var Ne=this.match;return Ne.length<20&&(Ne+=this._input.substr(0,20-Ne.length)),(Ne.substr(0,20)+(Ne.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var Ne=this.pastInput(),we=new Array(Ne.length+1).join("-");return Ne+this.upcomingInput()+` +`+we+"^"},"showPosition"),test_match:o(function(Ne,we){var Te,De,$e;if(this.options.backtrack_lexer&&($e={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&($e.yylloc.range=this.yylloc.range.slice(0))),De=Ne[0].match(/(?:\r\n?|\n).*/g),De&&(this.yylineno+=De.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:De?De[De.length-1].length-De[De.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+Ne[0].length},this.yytext+=Ne[0],this.match+=Ne[0],this.matches=Ne,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(Ne[0].length),this.matched+=Ne[0],Te=this.performAction.call(this,this.yy,this,we,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),Te)return Te;if(this._backtrack){for(var pe in $e)this[pe]=$e[pe];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var Ne,we,Te,De;this._more||(this.yytext="",this.match="");for(var $e=this._currentRules(),pe=0;pe<$e.length;pe++)if(Te=this._input.match(this.rules[$e[pe]]),Te&&(!we||Te[0].length>we[0].length)){if(we=Te,De=pe,this.options.backtrack_lexer){if(Ne=this.test_match(Te,$e[pe]),Ne!==!1)return Ne;if(this._backtrack){we=!1;continue}else return!1}else if(!this.options.flex)break}return we?(Ne=this.test_match(we,$e[De]),Ne!==!1?Ne:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var we=this.next();return we||this.lex()},"lex"),begin:o(function(we){this.conditionStack.push(we)},"begin"),popState:o(function(){var we=this.conditionStack.length-1;return we>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(we){return we=this.conditionStack.length-1-Math.abs(we||0),we>=0?this.conditionStack[we]:"INITIAL"},"topState"),pushState:o(function(we){this.begin(we)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:o(function(we,Te,De,$e){var pe=$e;switch(De){case 0:return this.begin("acc_title"),24;break;case 1:return this.popState(),"acc_title_value";break;case 2:return this.begin("acc_descr"),26;break;case 3:return this.popState(),"acc_descr_value";break;case 4:this.begin("acc_descr_multiline");break;case 5:this.popState();break;case 6:return"acc_descr_multiline_value";case 7:return 33;case 8:return 34;case 9:return 35;case 10:return 36;case 11:return 10;case 12:break;case 13:return 8;case 14:return 50;case 15:return 72;case 16:return 4;case 17:return this.begin("block"),17;break;case 18:return 49;case 19:return 49;case 20:return 42;case 21:return 15;case 22:return 13;case 23:break;case 24:return 61;case 25:return 58;case 26:return 58;case 27:return 62;case 28:break;case 29:return this.popState(),19;break;case 30:return Te.yytext[0];case 31:return 20;case 32:return 21;case 33:return this.begin("style"),44;break;case 34:return this.popState(),10;break;case 35:break;case 36:return 13;case 37:return 42;case 38:return 49;case 39:return this.begin("style"),37;break;case 40:return 43;case 41:return 65;case 42:return 67;case 43:return 67;case 44:return 67;case 45:return 65;case 46:return 65;case 47:return 66;case 48:return 66;case 49:return 66;case 50:return 66;case 51:return 66;case 52:return 67;case 53:return 66;case 54:return 67;case 55:return 68;case 56:return 68;case 57:return 51;case 58:return 68;case 59:return 68;case 60:return 68;case 61:return 52;case 62:return 48;case 63:return 68;case 64:return 65;case 65:return 66;case 66:return 67;case 67:return 69;case 68:return 70;case 69:return 71;case 70:return 71;case 71:return 70;case 72:return 70;case 73:return 70;case 74:return 41;case 75:return 47;case 76:return 40;case 77:return Te.yytext[0];case 78:return 6}},"anonymous"),rules:[/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:[\s]+)/i,/^(?:"[^"%\r\n\v\b\\]+")/i,/^(?:"[^"]*")/i,/^(?:erDiagram\b)/i,/^(?:\{)/i,/^(?:#)/i,/^(?:#)/i,/^(?:,)/i,/^(?::::)/i,/^(?::)/i,/^(?:\s+)/i,/^(?:\b((?:PK)|(?:FK)|(?:UK))\b)/i,/^(?:([^\s]*)[~].*[~]([^\s]*))/i,/^(?:([\*A-Za-z_\u00C0-\uFFFF][A-Za-z0-9\-\_\[\]\(\)\u00C0-\uFFFF\*]*))/i,/^(?:"[^"]*")/i,/^(?:[\n]+)/i,/^(?:\})/i,/^(?:.)/i,/^(?:\[)/i,/^(?:\])/i,/^(?:style\b)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?::)/i,/^(?:,)/i,/^(?:#)/i,/^(?:classDef\b)/i,/^(?:class\b)/i,/^(?:one or zero\b)/i,/^(?:one or more\b)/i,/^(?:one or many\b)/i,/^(?:1\+)/i,/^(?:\|o\b)/i,/^(?:zero or one\b)/i,/^(?:zero or more\b)/i,/^(?:zero or many\b)/i,/^(?:0\+)/i,/^(?:\}o\b)/i,/^(?:many\(0\))/i,/^(?:many\(1\))/i,/^(?:many\b)/i,/^(?:\}\|)/i,/^(?:one\b)/i,/^(?:only one\b)/i,/^(?:[0-9]+\.[0-9]+)/i,/^(?:1(?=\s+[A-Za-z_"']))/i,/^(?:1(?=\s+[0-9]))/i,/^(?:1(?=(--|\.\.|\.-|-\.)))/i,/^(?:1\b)/i,/^(?:[0-9]+)/i,/^(?:\|\|)/i,/^(?:o\|)/i,/^(?:o\{)/i,/^(?:\|\{)/i,/^(?:u(?=[\.\-\|]))/i,/^(?:\.\.)/i,/^(?:--)/i,/^(?:to\b)/i,/^(?:optionally to\b)/i,/^(?:\.-)/i,/^(?:-\.)/i,/^(?:([^\x00-\x7F]|\w|-|\*)+)/i,/^(?:;)/i,/^(?:([^\x00-\x7F]|\w|-|\*|\.)+)/i,/^(?:.)/i,/^(?:$)/i],conditions:{style:{rules:[34,35,36,37,38,74,75],inclusive:!1},acc_descr_multiline:{rules:[5,6],inclusive:!1},acc_descr:{rules:[3],inclusive:!1},acc_title:{rules:[1],inclusive:!1},block:{rules:[23,24,25,26,27,28,29,30],inclusive:!1},INITIAL:{rules:[0,2,4,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,31,32,33,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,76,77,78],inclusive:!0}}};return Ee})();te.lexer=be;function de(){this.yy={}}return o(de,"Parser"),de.prototype=te,te.Parser=de,new de})();EF.parser=EF;Aye=EF});var US,Dye=P(()=>{"use strict";bt();Ut();Ki();er();US=class{constructor(){this.entities=new Map;this.relationships=[];this.classes=new Map;this.direction="TB";this.Cardinality={ZERO_OR_ONE:"ZERO_OR_ONE",ZERO_OR_MORE:"ZERO_OR_MORE",ONE_OR_MORE:"ONE_OR_MORE",ONLY_ONE:"ONLY_ONE",MD_PARENT:"MD_PARENT"};this.Identification={NON_IDENTIFYING:"NON_IDENTIFYING",IDENTIFYING:"IDENTIFYING"};this.setAccTitle=Ar;this.getAccTitle=Dr;this.setAccDescription=Lr;this.getAccDescription=Rr;this.setDiagramTitle=Mr;this.getDiagramTitle=Nr;this.getConfig=o(()=>ge().er,"getConfig");this.clear(),this.addEntity=this.addEntity.bind(this),this.addAttributes=this.addAttributes.bind(this),this.addRelationship=this.addRelationship.bind(this),this.setDirection=this.setDirection.bind(this),this.addCssStyles=this.addCssStyles.bind(this),this.addClass=this.addClass.bind(this),this.setClass=this.setClass.bind(this),this.setAccTitle=this.setAccTitle.bind(this),this.setAccDescription=this.setAccDescription.bind(this)}static{o(this,"ErDB")}addEntity(e,r=""){return this.entities.has(e)?!this.entities.get(e)?.alias&&r&&(this.entities.get(e).alias=r,Q.info(`Add alias '${r}' to entity '${e}'`)):(this.entities.set(e,{id:`entity-${e}-${this.entities.size}`,label:e,attributes:[],alias:r,shape:"erBox",look:ge().look??"default",cssClasses:"default",cssStyles:[],labelType:"markdown"}),Q.info("Added new entity :",e)),this.entities.get(e)}getEntity(e){return this.entities.get(e)}getEntities(){return this.entities}getClasses(){return this.classes}addAttributes(e,r){let i=this.addEntity(e),n;for(n=r.length-1;n>=0;n--)r[n].keys||(r[n].keys=[]),r[n].comment||(r[n].comment=""),i.attributes.push(r[n]),Q.debug("Added attribute ",r[n].name)}addRelationship(e,r,i,n){let a=this.entities.get(e),s=this.entities.get(i);if(!a||!s)return;let l={entityA:a.id,roleA:r,entityB:s.id,relSpec:n};this.relationships.push(l),Q.debug("Added new relationship :",l)}getRelationships(){return this.relationships}getDirection(){return this.direction}setDirection(e){this.direction=e}getCompiledStyles(e){let r=[];for(let i of e){let n=this.classes.get(i);n?.styles&&(r=[...r,...n.styles??[]].map(a=>a.trim())),n?.textStyles&&(r=[...r,...n.textStyles??[]].map(a=>a.trim()))}return r}addCssStyles(e,r){for(let i of e){let n=this.entities.get(i);if(!r||!n)return;for(let a of r)n.cssStyles.push(a)}}addClass(e,r){e.forEach(i=>{let n=this.classes.get(i);n===void 0&&(n={id:i,styles:[],textStyles:[]},this.classes.set(i,n)),r&&r.forEach(function(a){if(/color/.exec(a)){let s=a.replace("fill","bgFill");n.textStyles.push(s)}n.styles.push(a)})})}setClass(e,r){for(let i of e){let n=this.entities.get(i);if(n)for(let a of r)n.cssClasses+=" "+a}}clear(){this.entities=new Map,this.classes=new Map,this.relationships=[],wr()}getData(){let e=[],r=[],i=ge(),n=0;for(let s of this.entities.keys()){let l=this.entities.get(s);l&&(l.cssCompiledStyles=this.getCompiledStyles(l.cssClasses.split(" ")),l.colorIndex=n++,e.push(l))}let a=0;for(let s of this.relationships){let l={id:Cu(s.entityA,s.entityB,{prefix:"id",counter:a++}),type:"normal",curve:"basis",start:s.entityA,end:s.entityB,label:s.roleA,labelpos:"c",thickness:"normal",classes:"relationshipLine",arrowTypeStart:s.relSpec.cardB.toLowerCase(),arrowTypeEnd:s.relSpec.cardA.toLowerCase(),pattern:s.relSpec.relType=="IDENTIFYING"?"solid":"dashed",look:i.look,labelType:"markdown"};r.push(l)}return{nodes:e,edges:r,other:{},config:i,direction:"TB"}}}});var SF={};ur(SF,{draw:()=>Pit});var Pit,Lye=P(()=>{"use strict";Ut();bt();I0();Wd();Ud();er();Pr();Pit=o(async function(t,e,r,i){Q.info("REF0:"),Q.info("Drawing er diagram (unified)",e);let{securityLevel:n,er:a,layout:s}=ge(),l=i.db.getData(),u=Ol(e,n);l.type=i.type,l.layoutAlgorithm=Vu(s),l.config.flowchart.nodeSpacing=a?.nodeSpacing||140,l.config.flowchart.rankSpacing=a?.rankSpacing||80,l.direction=i.db.getDirection();let{config:h}=l,{look:f}=h;f==="neo"?l.markers=["only_one_neo","zero_or_one_neo","one_or_more_neo","zero_or_more_neo"]:l.markers=["only_one","zero_or_one","one_or_more","zero_or_more"],l.diagramId=e,await Ul(l,u),l.layoutAlgorithm==="elk"&&u.select(".edges").lower();let d=u.selectAll('[id*="-background"]');Array.from(d).length>0&&d.each(function(){let m=Ze(this),y=m.attr("id").replace("-background",""),v=u.select(`#${CSS.escape(y)}`);if(!v.empty()){let x=v.attr("transform");m.attr("transform",x)}});let p=8;Kt.insertTitle(u,"erDiagramTitleText",a?.titleTopMargin??25,i.db.getDiagramTitle()),Ro(u,p,"erDiagram",a?.useMaxWidth??!0)},"draw")});var Rye,HS,Bit,Fit,Nye,Iye=P(()=>{"use strict";Yn();Rye=o((t,e)=>{let r=zp,i=r(t,"r"),n=r(t,"g"),a=r(t,"b");return Fn(i,n,a,e)},"fade"),HS=new Set(["redux-color","redux-dark-color"]),Bit=o(t=>{let{theme:e,look:r,bkgColorArray:i,borderColorArray:n}=t;if(!HS.has(e))return"";let a=i?.length>0,s="";for(let l=0;l{let{look:e,theme:r,erEdgeLabelBackground:i,strokeWidth:n}=t;return` + ${Bit(t)} + .entityBox { + fill: ${t.mainBkg}; + stroke: ${t.nodeBorder}; + } + + .relationshipLabelBox { + fill: ${t.tertiaryColor}; + opacity: 0.7; + background-color: ${t.tertiaryColor}; + rect { + opacity: 0.5; + } + } + + .labelBkg { + background-color: ${HS.has(r)&&i?i:Rye(t.tertiaryColor,.5)}; + } + + .edgeLabel { + background-color: ${HS.has(r)&&i?i:t.edgeLabelBackground}; + } + .edgeLabel .label rect { + fill: ${HS.has(r)&&i?i:t.edgeLabelBackground}; + } + .edgeLabel .label text { + fill: ${t.textColor}; + } + + .edgeLabel .label { + fill: ${t.nodeBorder}; + font-size: 14px; + } + + .label { + font-family: ${t.fontFamily}; + color: ${t.nodeTextColor||t.textColor}; + } + + .edge-pattern-dashed { + stroke-dasharray: 8,8; + } + + .node rect, + .node circle, + .node ellipse, + .node polygon + { + fill: ${t.mainBkg}; + stroke: ${t.nodeBorder}; + stroke-width: ${e==="neo"?n:"1px"}; + } + + .relationshipLine { + stroke: ${t.lineColor}; + stroke-width: ${e==="neo"?n:"1px"}; + fill: none; + } + + .marker { + fill: none !important; + stroke: ${t.lineColor} !important; + stroke-width: 1; + } + [data-look=neo].labelBkg { + background-color: ${Rye(t.tertiaryColor,.5)}; + } +`},"getStyles"),Nye=Fit});var Mye={};ur(Mye,{diagram:()=>$it});var $it,Oye=P(()=>{"use strict";_ye();Dye();Lye();Iye();$it={parser:Aye,get db(){return new US},renderer:SF,styles:Nye}});function _n(t){return typeof t=="object"&&t!==null&&typeof t.$type=="string"}function ga(t){return typeof t=="object"&&t!==null&&typeof t.$refText=="string"&&"ref"in t}function nl(t){return typeof t=="object"&&t!==null&&typeof t.$refText=="string"&&"items"in t}function AF(t){return typeof t=="object"&&t!==null&&typeof t.name=="string"&&typeof t.type=="string"&&typeof t.path=="string"}function om(t){return typeof t=="object"&&t!==null&&typeof t.info=="object"&&typeof t.message=="string"}function Mc(t){return typeof t=="object"&&t!==null&&Array.isArray(t.content)}function Hd(t){return typeof t=="object"&&t!==null&&typeof t.tokenType=="object"}function _T(t){return Mc(t)&&typeof t.fullText=="string"}var sm,Oc=P(()=>{"use strict";o(_n,"isAstNode");o(ga,"isReference");o(nl,"isMultiReference");o(AF,"isAstNodeDescription");o(om,"isLinkingError");sm=class{static{o(this,"AbstractAstReflection")}constructor(){this.subtypes={},this.allSubtypes={}}getAllTypes(){return Object.keys(this.types)}getReferenceType(e){let r=this.types[e.container.$type];if(!r)throw new Error(`Type ${e.container.$type||"undefined"} not found.`);let i=r.properties[e.property]?.referenceType;if(!i)throw new Error(`Property ${e.property||"undefined"} of type ${e.container.$type} is not a reference.`);return i}getTypeMetaData(e){let r=this.types[e];return r||{name:e,properties:{},superTypes:[]}}isInstance(e,r){return _n(e)&&this.isSubtype(e.$type,r)}isSubtype(e,r){if(e===r)return!0;let i=this.subtypes[e];i||(i=this.subtypes[e]={});let n=i[r];if(n!==void 0)return n;{let a=this.types[e],s=a?a.superTypes.some(l=>this.isSubtype(l,r)):!1;return i[r]=s,s}}getAllSubTypes(e){let r=this.allSubtypes[e];if(r)return r;{let i=this.getAllTypes(),n=[];for(let a of i)this.isSubtype(a,e)&&n.push(a);return this.allSubtypes[e]=n,n}}};o(Mc,"isCompositeCstNode");o(Hd,"isLeafCstNode");o(_T,"isRootCstNode")});function Wit(t){return typeof t=="string"?t:typeof t>"u"?"undefined":typeof t.toString=="function"?t.toString():Object.prototype.toString.call(t)}function YS(t){return!!t&&typeof t[Symbol.iterator]=="function"}function jr(...t){if(t.length===1){let e=t[0];if(e instanceof al)return e;if(YS(e))return new al(()=>e[Symbol.iterator](),r=>r.next());if(typeof e.length=="number")return new al(()=>({index:0}),r=>r.index1?new al(()=>({collIndex:0,arrIndex:0}),e=>{do{if(e.iterator){let r=e.iterator.next();if(!r.done)return r;e.iterator=void 0}if(e.array){if(e.arrIndex{"use strict";al=class t{static{o(this,"StreamImpl")}constructor(e,r){this.startFn=e,this.nextFn=r}iterator(){let e={state:this.startFn(),next:o(()=>this.nextFn(e.state),"next"),[Symbol.iterator]:()=>e};return e}[Symbol.iterator](){return this.iterator()}isEmpty(){return!!this.iterator().next().done}count(){let e=this.iterator(),r=0,i=e.next();for(;!i.done;)r++,i=e.next();return r}toArray(){let e=[],r=this.iterator(),i;do i=r.next(),i.value!==void 0&&e.push(i.value);while(!i.done);return e}toSet(){return new Set(this)}toMap(e,r){let i=this.map(n=>[e?e(n):n,r?r(n):n]);return new Map(i)}toString(){return this.join()}concat(e){return new t(()=>({first:this.startFn(),firstDone:!1,iterator:e[Symbol.iterator]()}),r=>{let i;if(!r.firstDone){do if(i=this.nextFn(r.first),!i.done)return i;while(!i.done);r.firstDone=!0}do if(i=r.iterator.next(),!i.done)return i;while(!i.done);return xs})}join(e=","){let r=this.iterator(),i="",n,a=!1;do n=r.next(),n.done||(a&&(i+=e),i+=Wit(n.value)),a=!0;while(!n.done);return i}indexOf(e,r=0){let i=this.iterator(),n=0,a=i.next();for(;!a.done;){if(n>=r&&a.value===e)return n;a=i.next(),n++}return-1}every(e){let r=this.iterator(),i=r.next();for(;!i.done;){if(!e(i.value))return!1;i=r.next()}return!0}some(e){let r=this.iterator(),i=r.next();for(;!i.done;){if(e(i.value))return!0;i=r.next()}return!1}forEach(e){let r=this.iterator(),i=0,n=r.next();for(;!n.done;)e(n.value,i),n=r.next(),i++}map(e){return new t(this.startFn,r=>{let{done:i,value:n}=this.nextFn(r);return i?xs:{done:!1,value:e(n)}})}filter(e){return new t(this.startFn,r=>{let i;do if(i=this.nextFn(r),!i.done&&e(i.value))return i;while(!i.done);return xs})}nonNullable(){return this.filter(e=>e!=null)}reduce(e,r){let i=this.iterator(),n=r,a=i.next();for(;!a.done;)n===void 0?n=a.value:n=e(n,a.value),a=i.next();return n}reduceRight(e,r){return this.recursiveReduce(this.iterator(),e,r)}recursiveReduce(e,r,i){let n=e.next();if(n.done)return i;let a=this.recursiveReduce(e,r,i);return a===void 0?n.value:r(a,n.value)}find(e){let r=this.iterator(),i=r.next();for(;!i.done;){if(e(i.value))return i.value;i=r.next()}}findIndex(e){let r=this.iterator(),i=0,n=r.next();for(;!n.done;){if(e(n.value))return i;n=r.next(),i++}return-1}includes(e){let r=this.iterator(),i=r.next();for(;!i.done;){if(i.value===e)return!0;i=r.next()}return!1}flatMap(e){return new t(()=>({this:this.startFn()}),r=>{do{if(r.iterator){let a=r.iterator.next();if(a.done)r.iterator=void 0;else return a}let{done:i,value:n}=this.nextFn(r.this);if(!i){let a=e(n);if(YS(a))r.iterator=a[Symbol.iterator]();else return{done:!1,value:a}}}while(r.iterator);return xs})}flat(e){if(e===void 0&&(e=1),e<=0)return this;let r=e>1?this.flat(e-1):this;return new t(()=>({this:r.startFn()}),i=>{do{if(i.iterator){let s=i.iterator.next();if(s.done)i.iterator=void 0;else return s}let{done:n,value:a}=r.nextFn(i.this);if(!n)if(YS(a))i.iterator=a[Symbol.iterator]();else return{done:!1,value:a}}while(i.iterator);return xs})}head(){let r=this.iterator().next();if(!r.done)return r.value}tail(e=1){return new t(()=>{let r=this.startFn();for(let i=0;i({size:0,state:this.startFn()}),r=>(r.size++,r.size>e?xs:this.nextFn(r.state)))}distinct(e){return new t(()=>({set:new Set,internalState:this.startFn()}),r=>{let i;do if(i=this.nextFn(r.internalState),!i.done){let n=e?e(i.value):i.value;if(!r.set.has(n))return r.set.add(n),i}while(!i.done);return xs})}exclude(e,r){let i=new Set;for(let n of e){let a=r?r(n):n;i.add(a)}return this.filter(n=>{let a=r?r(n):n;return!i.has(a)})}};o(Wit,"toString");o(YS,"isIterable");Yd=new al(()=>{},()=>xs),xs=Object.freeze({done:!0,value:void 0});o(jr,"stream");Wu=class extends al{static{o(this,"TreeStreamImpl")}constructor(e,r,i){super(()=>({iterators:i?.includeRoot?[[e][Symbol.iterator]()]:[r(e)[Symbol.iterator]()],pruned:!1}),n=>{for(n.pruned&&(n.iterators.pop(),n.pruned=!1);n.iterators.length>0;){let s=n.iterators[n.iterators.length-1].next();if(s.done)n.iterators.pop();else return n.iterators.push(r(s.value)[Symbol.iterator]()),s}return xs})}iterator(){let e={state:this.startFn(),next:o(()=>this.nextFn(e.state),"next"),prune:o(()=>{e.state.pruned=!0},"prune"),[Symbol.iterator]:()=>e};return e}};(function(t){function e(a){return a.reduce((s,l)=>s+l,0)}o(e,"sum"),t.sum=e;function r(a){return a.reduce((s,l)=>s*l,0)}o(r,"product"),t.product=r;function i(a){return a.reduce((s,l)=>Math.min(s,l))}o(i,"min"),t.min=i;function n(a){return a.reduce((s,l)=>Math.max(s,l))}o(n,"max"),t.max=n})(Ey||(Ey={}))});var XS={};ur(XS,{assignMandatoryProperties:()=>LF,copyAstNode:()=>DF,findRootNode:()=>Ay,getContainerOfType:()=>ef,getDocument:()=>bs,getReferenceNodes:()=>jS,hasContainerOfType:()=>Uit,linkContentToContainer:()=>Sy,streamAllContents:()=>Pc,streamAst:()=>js,streamContents:()=>DT,streamReferences:()=>jd});function Sy(t,e={}){for(let[r,i]of Object.entries(t))r.startsWith("$")||(Array.isArray(i)?i.forEach((n,a)=>{_n(n)&&(n.$container=t,n.$containerProperty=r,n.$containerIndex=a,e.deep&&Sy(n,e))}):_n(i)&&(i.$container=t,i.$containerProperty=r,e.deep&&Sy(i,e)))}function ef(t,e){let r=t;for(;r;){if(e(r))return r;r=r.$container}}function Uit(t,e){let r=t;for(;r;){if(e(r))return!0;r=r.$container}return!1}function bs(t){let r=Ay(t).$document;if(!r)throw new Error("AST node has no document.");return r}function Ay(t){for(;t.$container;)t=t.$container;return t}function jS(t){return ga(t)?t.ref?[t.ref]:[]:nl(t)?t.items.map(e=>e.ref):[]}function DT(t,e){if(!t)throw new Error("Node must be an AstNode.");let r=e?.range;return new al(()=>({keys:Object.keys(t),keyIndex:0,arrayIndex:0}),i=>{for(;i.keyIndexDT(r,e))}function js(t,e){if(t){if(e?.range&&!_F(t,e.range))return new Wu(t,()=>[])}else throw new Error("Root node must be an AstNode.");return new Wu(t,r=>DT(r,e),{includeRoot:!0})}function _F(t,e){if(!e)return!0;let r=t.$cstNode?.range;return r?RF(r,e):!1}function jd(t){return new al(()=>({keys:Object.keys(t),keyIndex:0,arrayIndex:0}),e=>{for(;e.keyIndex{"use strict";Oc();Ys();Bc();o(Sy,"linkContentToContainer");o(ef,"getContainerOfType");o(Uit,"hasContainerOfType");o(bs,"getDocument");o(Ay,"findRootNode");o(jS,"getReferenceNodes");o(DT,"streamContents");o(Pc,"streamAllContents");o(js,"streamAst");o(_F,"isAstNodeInRange");o(jd,"streamReferences");o(LF,"assignMandatoryProperties");o(Bye,"copyDefaultValue");o(DF,"copyAstNode")});var zT={};ur(zT,{AbstractElement:()=>No,AbstractParserRule:()=>LT,AbstractRule:()=>_y,AbstractType:()=>sl,Action:()=>Xd,Alternatives:()=>RT,ArrayLiteral:()=>KS,ArrayType:()=>QS,Assignment:()=>Kd,BooleanLiteral:()=>ZS,CharacterRange:()=>Qd,Condition:()=>Zd,Conjunction:()=>NT,CrossReference:()=>Jd,Disjunction:()=>IT,EndOfFile:()=>JS,Grammar:()=>tf,GrammarImport:()=>e6,Group:()=>lm,InferredType:()=>t6,InfixRule:()=>Uu,InfixRuleOperatorList:()=>MT,InfixRuleOperators:()=>r6,Interface:()=>Dy,Keyword:()=>Ly,LangiumGrammarAstReflection:()=>Oy,LangiumGrammarTerminals:()=>Hit,NamedArgument:()=>Ry,NegatedToken:()=>cm,Negation:()=>i6,NumberLiteral:()=>n6,Parameter:()=>Ny,ParameterReference:()=>a6,ParserRule:()=>Fc,ReferenceType:()=>OT,RegexToken:()=>um,ReturnType:()=>s6,RuleCall:()=>hm,SimpleType:()=>Iy,StringLiteral:()=>o6,TerminalAlternatives:()=>fm,TerminalElement:()=>Io,TerminalGroup:()=>dm,TerminalRule:()=>rf,TerminalRuleCall:()=>pm,Type:()=>PT,TypeAttribute:()=>mm,TypeDefinition:()=>gm,UnionType:()=>l6,UnorderedGroup:()=>BT,UntilToken:()=>ym,ValueLiteral:()=>vm,Wildcard:()=>My,isAbstractElement:()=>FT,isAbstractParserRule:()=>nf,isAbstractRule:()=>Yit,isAbstractType:()=>jit,isAction:()=>af,isAlternatives:()=>c6,isArrayLiteral:()=>Xit,isArrayType:()=>NF,isAssignment:()=>$c,isBooleanLiteral:()=>IF,isCharacterRange:()=>MF,isCondition:()=>Kit,isConjunction:()=>OF,isCrossReference:()=>zc,isDisjunction:()=>PF,isEndOfFile:()=>BF,isGrammar:()=>Qit,isGrammarImport:()=>Zit,isGroup:()=>ep,isInferredType:()=>$T,isInfixRule:()=>tp,isInfixRuleOperatorList:()=>Jit,isInfixRuleOperators:()=>ent,isInterface:()=>FF,isKeyword:()=>Hl,isNamedArgument:()=>tnt,isNegatedToken:()=>$F,isNegation:()=>zF,isNumberLiteral:()=>rnt,isParameter:()=>int,isParameterReference:()=>GF,isParserRule:()=>Ba,isReferenceType:()=>VF,isRegexToken:()=>qF,isReturnType:()=>WF,isRuleCall:()=>Gc,isSimpleType:()=>u6,isStringLiteral:()=>nnt,isTerminalAlternatives:()=>UF,isTerminalElement:()=>ant,isTerminalGroup:()=>HF,isTerminalRule:()=>Xs,isTerminalRuleCall:()=>h6,isType:()=>f6,isTypeAttribute:()=>snt,isTypeDefinition:()=>ont,isUnionType:()=>YF,isUnorderedGroup:()=>d6,isUntilToken:()=>jF,isValueLiteral:()=>lnt,isWildcard:()=>XF,reflection:()=>vr});function FT(t){return vr.isInstance(t,No.$type)}function nf(t){return vr.isInstance(t,LT.$type)}function Yit(t){return vr.isInstance(t,_y.$type)}function jit(t){return vr.isInstance(t,sl.$type)}function af(t){return vr.isInstance(t,Xd.$type)}function c6(t){return vr.isInstance(t,RT.$type)}function Xit(t){return vr.isInstance(t,KS.$type)}function NF(t){return vr.isInstance(t,QS.$type)}function $c(t){return vr.isInstance(t,Kd.$type)}function IF(t){return vr.isInstance(t,ZS.$type)}function MF(t){return vr.isInstance(t,Qd.$type)}function Kit(t){return vr.isInstance(t,Zd.$type)}function OF(t){return vr.isInstance(t,NT.$type)}function zc(t){return vr.isInstance(t,Jd.$type)}function PF(t){return vr.isInstance(t,IT.$type)}function BF(t){return vr.isInstance(t,JS.$type)}function Qit(t){return vr.isInstance(t,tf.$type)}function Zit(t){return vr.isInstance(t,e6.$type)}function ep(t){return vr.isInstance(t,lm.$type)}function $T(t){return vr.isInstance(t,t6.$type)}function tp(t){return vr.isInstance(t,Uu.$type)}function Jit(t){return vr.isInstance(t,MT.$type)}function ent(t){return vr.isInstance(t,r6.$type)}function FF(t){return vr.isInstance(t,Dy.$type)}function Hl(t){return vr.isInstance(t,Ly.$type)}function tnt(t){return vr.isInstance(t,Ry.$type)}function $F(t){return vr.isInstance(t,cm.$type)}function zF(t){return vr.isInstance(t,i6.$type)}function rnt(t){return vr.isInstance(t,n6.$type)}function int(t){return vr.isInstance(t,Ny.$type)}function GF(t){return vr.isInstance(t,a6.$type)}function Ba(t){return vr.isInstance(t,Fc.$type)}function VF(t){return vr.isInstance(t,OT.$type)}function qF(t){return vr.isInstance(t,um.$type)}function WF(t){return vr.isInstance(t,s6.$type)}function Gc(t){return vr.isInstance(t,hm.$type)}function u6(t){return vr.isInstance(t,Iy.$type)}function nnt(t){return vr.isInstance(t,o6.$type)}function UF(t){return vr.isInstance(t,fm.$type)}function ant(t){return vr.isInstance(t,Io.$type)}function HF(t){return vr.isInstance(t,dm.$type)}function Xs(t){return vr.isInstance(t,rf.$type)}function h6(t){return vr.isInstance(t,pm.$type)}function f6(t){return vr.isInstance(t,PT.$type)}function snt(t){return vr.isInstance(t,mm.$type)}function ont(t){return vr.isInstance(t,gm.$type)}function YF(t){return vr.isInstance(t,l6.$type)}function d6(t){return vr.isInstance(t,BT.$type)}function jF(t){return vr.isInstance(t,ym.$type)}function lnt(t){return vr.isInstance(t,vm.$type)}function XF(t){return vr.isInstance(t,My.$type)}var Hit,No,LT,_y,sl,Xd,RT,KS,QS,Kd,ZS,Qd,Zd,NT,Jd,IT,JS,tf,e6,lm,t6,Uu,MT,r6,Dy,Ly,Ry,cm,i6,n6,Ny,a6,Fc,OT,um,s6,hm,Iy,o6,fm,Io,dm,rf,pm,PT,mm,gm,l6,BT,ym,vm,My,Oy,vr,ol=P(()=>{"use strict";Oc();Hit={ID:/\^?[_a-zA-Z][\w_]*/,STRING:/"(\\.|[^"\\])*"|'(\\.|[^'\\])*'/,NUMBER:/NaN|-?((\d*\.\d+|\d+)([Ee][+-]?\d+)?|Infinity)/,RegexLiteral:/\/(?![*+?])(?:[^\r\n\[/\\]|\\.|\[(?:[^\r\n\]\\]|\\.)*\])+\/[a-z]*/,WS:/\s+/,ML_COMMENT:/\/\*[\s\S]*?\*\//,SL_COMMENT:/\/\/[^\n\r]*/},No={$type:"AbstractElement",cardinality:"cardinality"};o(FT,"isAbstractElement");LT={$type:"AbstractParserRule"};o(nf,"isAbstractParserRule");_y={$type:"AbstractRule"};o(Yit,"isAbstractRule");sl={$type:"AbstractType"};o(jit,"isAbstractType");Xd={$type:"Action",cardinality:"cardinality",feature:"feature",inferredType:"inferredType",operator:"operator",type:"type"};o(af,"isAction");RT={$type:"Alternatives",cardinality:"cardinality",elements:"elements"};o(c6,"isAlternatives");KS={$type:"ArrayLiteral",elements:"elements"};o(Xit,"isArrayLiteral");QS={$type:"ArrayType",elementType:"elementType"};o(NF,"isArrayType");Kd={$type:"Assignment",cardinality:"cardinality",feature:"feature",operator:"operator",predicate:"predicate",terminal:"terminal"};o($c,"isAssignment");ZS={$type:"BooleanLiteral",true:"true"};o(IF,"isBooleanLiteral");Qd={$type:"CharacterRange",cardinality:"cardinality",left:"left",lookahead:"lookahead",parenthesized:"parenthesized",right:"right"};o(MF,"isCharacterRange");Zd={$type:"Condition"};o(Kit,"isCondition");NT={$type:"Conjunction",left:"left",right:"right"};o(OF,"isConjunction");Jd={$type:"CrossReference",cardinality:"cardinality",deprecatedSyntax:"deprecatedSyntax",isMulti:"isMulti",terminal:"terminal",type:"type"};o(zc,"isCrossReference");IT={$type:"Disjunction",left:"left",right:"right"};o(PF,"isDisjunction");JS={$type:"EndOfFile",cardinality:"cardinality"};o(BF,"isEndOfFile");tf={$type:"Grammar",imports:"imports",interfaces:"interfaces",isDeclared:"isDeclared",name:"name",rules:"rules",types:"types"};o(Qit,"isGrammar");e6={$type:"GrammarImport",path:"path"};o(Zit,"isGrammarImport");lm={$type:"Group",cardinality:"cardinality",elements:"elements",guardCondition:"guardCondition",predicate:"predicate"};o(ep,"isGroup");t6={$type:"InferredType",name:"name"};o($T,"isInferredType");Uu={$type:"InfixRule",call:"call",dataType:"dataType",inferredType:"inferredType",name:"name",operators:"operators",parameters:"parameters",returnType:"returnType"};o(tp,"isInfixRule");MT={$type:"InfixRuleOperatorList",associativity:"associativity",operators:"operators"};o(Jit,"isInfixRuleOperatorList");r6={$type:"InfixRuleOperators",precedences:"precedences"};o(ent,"isInfixRuleOperators");Dy={$type:"Interface",attributes:"attributes",name:"name",superTypes:"superTypes"};o(FF,"isInterface");Ly={$type:"Keyword",cardinality:"cardinality",predicate:"predicate",value:"value"};o(Hl,"isKeyword");Ry={$type:"NamedArgument",calledByName:"calledByName",parameter:"parameter",value:"value"};o(tnt,"isNamedArgument");cm={$type:"NegatedToken",cardinality:"cardinality",lookahead:"lookahead",parenthesized:"parenthesized",terminal:"terminal"};o($F,"isNegatedToken");i6={$type:"Negation",value:"value"};o(zF,"isNegation");n6={$type:"NumberLiteral",value:"value"};o(rnt,"isNumberLiteral");Ny={$type:"Parameter",name:"name"};o(int,"isParameter");a6={$type:"ParameterReference",parameter:"parameter"};o(GF,"isParameterReference");Fc={$type:"ParserRule",dataType:"dataType",definition:"definition",entry:"entry",fragment:"fragment",inferredType:"inferredType",name:"name",parameters:"parameters",returnType:"returnType"};o(Ba,"isParserRule");OT={$type:"ReferenceType",isMulti:"isMulti",referenceType:"referenceType"};o(VF,"isReferenceType");um={$type:"RegexToken",cardinality:"cardinality",lookahead:"lookahead",parenthesized:"parenthesized",regex:"regex"};o(qF,"isRegexToken");s6={$type:"ReturnType",name:"name"};o(WF,"isReturnType");hm={$type:"RuleCall",arguments:"arguments",cardinality:"cardinality",predicate:"predicate",rule:"rule"};o(Gc,"isRuleCall");Iy={$type:"SimpleType",primitiveType:"primitiveType",stringType:"stringType",typeRef:"typeRef"};o(u6,"isSimpleType");o6={$type:"StringLiteral",value:"value"};o(nnt,"isStringLiteral");fm={$type:"TerminalAlternatives",cardinality:"cardinality",elements:"elements",lookahead:"lookahead",parenthesized:"parenthesized"};o(UF,"isTerminalAlternatives");Io={$type:"TerminalElement",cardinality:"cardinality",lookahead:"lookahead",parenthesized:"parenthesized"};o(ant,"isTerminalElement");dm={$type:"TerminalGroup",cardinality:"cardinality",elements:"elements",lookahead:"lookahead",parenthesized:"parenthesized"};o(HF,"isTerminalGroup");rf={$type:"TerminalRule",definition:"definition",fragment:"fragment",hidden:"hidden",name:"name",type:"type"};o(Xs,"isTerminalRule");pm={$type:"TerminalRuleCall",cardinality:"cardinality",lookahead:"lookahead",parenthesized:"parenthesized",rule:"rule"};o(h6,"isTerminalRuleCall");PT={$type:"Type",name:"name",type:"type"};o(f6,"isType");mm={$type:"TypeAttribute",defaultValue:"defaultValue",isOptional:"isOptional",name:"name",type:"type"};o(snt,"isTypeAttribute");gm={$type:"TypeDefinition"};o(ont,"isTypeDefinition");l6={$type:"UnionType",types:"types"};o(YF,"isUnionType");BT={$type:"UnorderedGroup",cardinality:"cardinality",elements:"elements"};o(d6,"isUnorderedGroup");ym={$type:"UntilToken",cardinality:"cardinality",lookahead:"lookahead",parenthesized:"parenthesized",terminal:"terminal"};o(jF,"isUntilToken");vm={$type:"ValueLiteral"};o(lnt,"isValueLiteral");My={$type:"Wildcard",cardinality:"cardinality",lookahead:"lookahead",parenthesized:"parenthesized"};o(XF,"isWildcard");Oy=class extends sm{static{o(this,"LangiumGrammarAstReflection")}constructor(){super(...arguments),this.types={AbstractElement:{name:No.$type,properties:{cardinality:{name:No.cardinality}},superTypes:[]},AbstractParserRule:{name:LT.$type,properties:{},superTypes:[_y.$type,sl.$type]},AbstractRule:{name:_y.$type,properties:{},superTypes:[]},AbstractType:{name:sl.$type,properties:{},superTypes:[]},Action:{name:Xd.$type,properties:{cardinality:{name:Xd.cardinality},feature:{name:Xd.feature},inferredType:{name:Xd.inferredType},operator:{name:Xd.operator},type:{name:Xd.type,referenceType:sl.$type}},superTypes:[No.$type]},Alternatives:{name:RT.$type,properties:{cardinality:{name:RT.cardinality},elements:{name:RT.elements,defaultValue:[]}},superTypes:[No.$type]},ArrayLiteral:{name:KS.$type,properties:{elements:{name:KS.elements,defaultValue:[]}},superTypes:[vm.$type]},ArrayType:{name:QS.$type,properties:{elementType:{name:QS.elementType}},superTypes:[gm.$type]},Assignment:{name:Kd.$type,properties:{cardinality:{name:Kd.cardinality},feature:{name:Kd.feature},operator:{name:Kd.operator},predicate:{name:Kd.predicate},terminal:{name:Kd.terminal}},superTypes:[No.$type]},BooleanLiteral:{name:ZS.$type,properties:{true:{name:ZS.true,defaultValue:!1}},superTypes:[Zd.$type,vm.$type]},CharacterRange:{name:Qd.$type,properties:{cardinality:{name:Qd.cardinality},left:{name:Qd.left},lookahead:{name:Qd.lookahead},parenthesized:{name:Qd.parenthesized,defaultValue:!1},right:{name:Qd.right}},superTypes:[Io.$type]},Condition:{name:Zd.$type,properties:{},superTypes:[]},Conjunction:{name:NT.$type,properties:{left:{name:NT.left},right:{name:NT.right}},superTypes:[Zd.$type]},CrossReference:{name:Jd.$type,properties:{cardinality:{name:Jd.cardinality},deprecatedSyntax:{name:Jd.deprecatedSyntax,defaultValue:!1},isMulti:{name:Jd.isMulti,defaultValue:!1},terminal:{name:Jd.terminal},type:{name:Jd.type,referenceType:sl.$type}},superTypes:[No.$type]},Disjunction:{name:IT.$type,properties:{left:{name:IT.left},right:{name:IT.right}},superTypes:[Zd.$type]},EndOfFile:{name:JS.$type,properties:{cardinality:{name:JS.cardinality}},superTypes:[No.$type]},Grammar:{name:tf.$type,properties:{imports:{name:tf.imports,defaultValue:[]},interfaces:{name:tf.interfaces,defaultValue:[]},isDeclared:{name:tf.isDeclared,defaultValue:!1},name:{name:tf.name},rules:{name:tf.rules,defaultValue:[]},types:{name:tf.types,defaultValue:[]}},superTypes:[]},GrammarImport:{name:e6.$type,properties:{path:{name:e6.path}},superTypes:[]},Group:{name:lm.$type,properties:{cardinality:{name:lm.cardinality},elements:{name:lm.elements,defaultValue:[]},guardCondition:{name:lm.guardCondition},predicate:{name:lm.predicate}},superTypes:[No.$type]},InferredType:{name:t6.$type,properties:{name:{name:t6.name}},superTypes:[sl.$type]},InfixRule:{name:Uu.$type,properties:{call:{name:Uu.call},dataType:{name:Uu.dataType},inferredType:{name:Uu.inferredType},name:{name:Uu.name},operators:{name:Uu.operators},parameters:{name:Uu.parameters,defaultValue:[]},returnType:{name:Uu.returnType,referenceType:sl.$type}},superTypes:[LT.$type]},InfixRuleOperatorList:{name:MT.$type,properties:{associativity:{name:MT.associativity},operators:{name:MT.operators,defaultValue:[]}},superTypes:[]},InfixRuleOperators:{name:r6.$type,properties:{precedences:{name:r6.precedences,defaultValue:[]}},superTypes:[]},Interface:{name:Dy.$type,properties:{attributes:{name:Dy.attributes,defaultValue:[]},name:{name:Dy.name},superTypes:{name:Dy.superTypes,defaultValue:[],referenceType:sl.$type}},superTypes:[sl.$type]},Keyword:{name:Ly.$type,properties:{cardinality:{name:Ly.cardinality},predicate:{name:Ly.predicate},value:{name:Ly.value}},superTypes:[No.$type]},NamedArgument:{name:Ry.$type,properties:{calledByName:{name:Ry.calledByName,defaultValue:!1},parameter:{name:Ry.parameter,referenceType:Ny.$type},value:{name:Ry.value}},superTypes:[]},NegatedToken:{name:cm.$type,properties:{cardinality:{name:cm.cardinality},lookahead:{name:cm.lookahead},parenthesized:{name:cm.parenthesized,defaultValue:!1},terminal:{name:cm.terminal}},superTypes:[Io.$type]},Negation:{name:i6.$type,properties:{value:{name:i6.value}},superTypes:[Zd.$type]},NumberLiteral:{name:n6.$type,properties:{value:{name:n6.value}},superTypes:[vm.$type]},Parameter:{name:Ny.$type,properties:{name:{name:Ny.name}},superTypes:[]},ParameterReference:{name:a6.$type,properties:{parameter:{name:a6.parameter,referenceType:Ny.$type}},superTypes:[Zd.$type]},ParserRule:{name:Fc.$type,properties:{dataType:{name:Fc.dataType},definition:{name:Fc.definition},entry:{name:Fc.entry,defaultValue:!1},fragment:{name:Fc.fragment,defaultValue:!1},inferredType:{name:Fc.inferredType},name:{name:Fc.name},parameters:{name:Fc.parameters,defaultValue:[]},returnType:{name:Fc.returnType,referenceType:sl.$type}},superTypes:[LT.$type]},ReferenceType:{name:OT.$type,properties:{isMulti:{name:OT.isMulti,defaultValue:!1},referenceType:{name:OT.referenceType}},superTypes:[gm.$type]},RegexToken:{name:um.$type,properties:{cardinality:{name:um.cardinality},lookahead:{name:um.lookahead},parenthesized:{name:um.parenthesized,defaultValue:!1},regex:{name:um.regex}},superTypes:[Io.$type]},ReturnType:{name:s6.$type,properties:{name:{name:s6.name}},superTypes:[]},RuleCall:{name:hm.$type,properties:{arguments:{name:hm.arguments,defaultValue:[]},cardinality:{name:hm.cardinality},predicate:{name:hm.predicate},rule:{name:hm.rule,referenceType:_y.$type}},superTypes:[No.$type]},SimpleType:{name:Iy.$type,properties:{primitiveType:{name:Iy.primitiveType},stringType:{name:Iy.stringType},typeRef:{name:Iy.typeRef,referenceType:sl.$type}},superTypes:[gm.$type]},StringLiteral:{name:o6.$type,properties:{value:{name:o6.value}},superTypes:[vm.$type]},TerminalAlternatives:{name:fm.$type,properties:{cardinality:{name:fm.cardinality},elements:{name:fm.elements,defaultValue:[]},lookahead:{name:fm.lookahead},parenthesized:{name:fm.parenthesized,defaultValue:!1}},superTypes:[Io.$type]},TerminalElement:{name:Io.$type,properties:{cardinality:{name:Io.cardinality},lookahead:{name:Io.lookahead},parenthesized:{name:Io.parenthesized,defaultValue:!1}},superTypes:[No.$type]},TerminalGroup:{name:dm.$type,properties:{cardinality:{name:dm.cardinality},elements:{name:dm.elements,defaultValue:[]},lookahead:{name:dm.lookahead},parenthesized:{name:dm.parenthesized,defaultValue:!1}},superTypes:[Io.$type]},TerminalRule:{name:rf.$type,properties:{definition:{name:rf.definition},fragment:{name:rf.fragment,defaultValue:!1},hidden:{name:rf.hidden,defaultValue:!1},name:{name:rf.name},type:{name:rf.type}},superTypes:[_y.$type]},TerminalRuleCall:{name:pm.$type,properties:{cardinality:{name:pm.cardinality},lookahead:{name:pm.lookahead},parenthesized:{name:pm.parenthesized,defaultValue:!1},rule:{name:pm.rule,referenceType:rf.$type}},superTypes:[Io.$type]},Type:{name:PT.$type,properties:{name:{name:PT.name},type:{name:PT.type}},superTypes:[sl.$type]},TypeAttribute:{name:mm.$type,properties:{defaultValue:{name:mm.defaultValue},isOptional:{name:mm.isOptional,defaultValue:!1},name:{name:mm.name},type:{name:mm.type}},superTypes:[]},TypeDefinition:{name:gm.$type,properties:{},superTypes:[]},UnionType:{name:l6.$type,properties:{types:{name:l6.types,defaultValue:[]}},superTypes:[gm.$type]},UnorderedGroup:{name:BT.$type,properties:{cardinality:{name:BT.cardinality},elements:{name:BT.elements,defaultValue:[]}},superTypes:[No.$type]},UntilToken:{name:ym.$type,properties:{cardinality:{name:ym.cardinality},lookahead:{name:ym.lookahead},parenthesized:{name:ym.parenthesized,defaultValue:!1},terminal:{name:ym.terminal}},superTypes:[Io.$type]},ValueLiteral:{name:vm.$type,properties:{},superTypes:[]},Wildcard:{name:My.$type,properties:{cardinality:{name:My.cardinality},lookahead:{name:My.lookahead},parenthesized:{name:My.parenthesized,defaultValue:!1}},superTypes:[Io.$type]}}}},vr=new Oy});var m6={};ur(m6,{DefaultNameRegexp:()=>p6,RangeComparison:()=>Hu,compareRange:()=>$ye,findCommentNode:()=>ZF,findDeclarationNodeAtOffset:()=>hnt,findLeafNodeAtOffset:()=>JF,findLeafNodeBeforeOffset:()=>zye,flattenCst:()=>unt,getDatatypeNode:()=>cnt,getInteriorNodes:()=>pnt,getNextNode:()=>fnt,getPreviousNode:()=>Vye,getStartlineNode:()=>dnt,inRange:()=>RF,isChildNode:()=>QF,isCommentNode:()=>KF,streamCst:()=>xm,toDocumentSegment:()=>bm,tokenToRange:()=>Py});function cnt(t){let e=t,r=!1;for(;e;){let i=ef(e.grammarSource,Ba);if(i&&i.dataType)e=e.container,r=!0;else return r?e:void 0}}function xm(t){return new Wu(t,e=>Mc(e)?e.content:[],{includeRoot:!0})}function unt(t){return xm(t).filter(Hd)}function QF(t,e){for(;t.container;)if(t=t.container,t===e)return!0;return!1}function Py(t){return{start:{character:t.startColumn-1,line:t.startLine-1},end:{character:t.endColumn,line:t.endLine-1}}}function bm(t){if(!t)return;let{offset:e,end:r,range:i}=t;return{range:i,offset:e,end:r,length:r-e}}function $ye(t,e){if(t.end.linee.end.line||t.start.line===e.end.line&&t.start.character>=e.end.character)return Hu.After;let r=t.start.line>e.start.line||t.start.line===e.start.line&&t.start.character>=e.start.character,i=t.end.lineHu.After}function hnt(t,e,r=p6){if(t){if(e>0){let i=e-t.offset,n=t.text.charAt(i);r.test(n)||e--}return JF(t,e)}}function ZF(t,e){if(t){let r=Vye(t,!0);if(r&&KF(r,e))return r;if(_T(t)){let i=t.content.findIndex(n=>!n.hidden);for(let n=i-1;n>=0;n--){let a=t.content[n];if(KF(a,e))return a}}}}function KF(t,e){return Hd(t)&&e.includes(t.tokenType.name)}function JF(t,e){if(Hd(t))return t;if(Mc(t)){let r=Gye(t,e,!1);if(r)return JF(r,e)}}function zye(t,e){if(Hd(t))return t;if(Mc(t)){let r=Gye(t,e,!0);if(r)return zye(r,e)}}function Gye(t,e,r){let i=0,n=t.content.length-1,a;for(;i<=n;){let s=Math.floor((i+n)/2),l=t.content[s];if(l.offset<=e&&l.end>e)return l;l.end<=e?(a=r?l:void 0,i=s+1):n=s-1}return a}function Vye(t,e=!0){for(;t.container;){let r=t.container,i=r.content.indexOf(t);for(;i>0;){i--;let n=r.content[i];if(e||!n.hidden)return n}t=r}}function fnt(t,e=!0){for(;t.container;){let r=t.container,i=r.content.indexOf(t),n=r.content.length-1;for(;i{"use strict";Oc();Ys();Ts();ol();o(cnt,"getDatatypeNode");o(xm,"streamCst");o(unt,"flattenCst");o(QF,"isChildNode");o(Py,"tokenToRange");o(bm,"toDocumentSegment");(function(t){t[t.Before=0]="Before",t[t.After=1]="After",t[t.OverlapFront=2]="OverlapFront",t[t.OverlapBack=3]="OverlapBack",t[t.Inside=4]="Inside",t[t.Outside=5]="Outside"})(Hu||(Hu={}));o($ye,"compareRange");o(RF,"inRange");p6=/^[\w\p{L}]$/u;o(hnt,"findDeclarationNodeAtOffset");o(ZF,"findCommentNode");o(KF,"isCommentNode");o(JF,"findLeafNodeAtOffset");o(zye,"findLeafNodeBeforeOffset");o(Gye,"binarySearch");o(Vye,"getPreviousNode");o(fnt,"getNextNode");o(dnt,"getStartlineNode");o(pnt,"getInteriorNodes");o(mnt,"getCommonParent");o(Fye,"getParentChain")});function Yu(t,e="Error: Got unexpected value."){throw new Error(e)}function qye(t,e="Error: Condition is violated."){if(!t)throw new Error(e)}var Tm,g6=P(()=>{"use strict";Tm=class extends Error{static{o(this,"ErrorWithLocation")}constructor(e,r){super(e?`${r} at ${e.range.start.line}:${e.range.start.character}`:r)}};o(Yu,"assertUnreachable");o(qye,"assertCondition")});function br(t){return t.charCodeAt(0)}function y6(t,e){Array.isArray(t)?t.forEach(function(r){e.push(r)}):e.push(t)}function By(t,e){if(t[e]===!0)throw"duplicate flag "+e;let r=t[e];t[e]=!0}function km(t){if(t===void 0)throw Error("Internal Error - Should never get here!");return!0}function GT(){throw Error("Internal Error - Should never get here!")}function e$(t){return t.type==="Character"}var t$=P(()=>{"use strict";o(br,"cc");o(y6,"insertToSet");o(By,"addFlag");o(km,"ASSERT_EXISTS");o(GT,"ASSERT_NEVER_REACH_HERE");o(e$,"isCharacter")});var VT,qT,r$,Wye=P(()=>{"use strict";t$();VT=[];for(let t=br("0");t<=br("9");t++)VT.push(t);qT=[br("_")].concat(VT);for(let t=br("a");t<=br("z");t++)qT.push(t);for(let t=br("A");t<=br("Z");t++)qT.push(t);r$=[br(" "),br("\f"),br(` +`),br("\r"),br(" "),br("\v"),br(" "),br("\xA0"),br("\u1680"),br("\u2000"),br("\u2001"),br("\u2002"),br("\u2003"),br("\u2004"),br("\u2005"),br("\u2006"),br("\u2007"),br("\u2008"),br("\u2009"),br("\u200A"),br("\u2028"),br("\u2029"),br("\u202F"),br("\u205F"),br("\u3000"),br("\uFEFF")]});var gnt,v6,ynt,Cm,Uye=P(()=>{"use strict";t$();Wye();gnt=/[0-9a-fA-F]/,v6=/[0-9]/,ynt=/[1-9]/,Cm=class{static{o(this,"RegExpParser")}constructor(){this.idx=0,this.input="",this.groupIdx=0}saveState(){return{idx:this.idx,input:this.input,groupIdx:this.groupIdx}}restoreState(e){this.idx=e.idx,this.input=e.input,this.groupIdx=e.groupIdx}pattern(e){this.idx=0,this.input=e,this.groupIdx=0,this.consumeChar("/");let r=this.disjunction();this.consumeChar("/");let i={type:"Flags",loc:{begin:this.idx,end:e.length},global:!1,ignoreCase:!1,multiLine:!1,unicode:!1,sticky:!1};for(;this.isRegExpFlag();)switch(this.popChar()){case"g":By(i,"global");break;case"i":By(i,"ignoreCase");break;case"m":By(i,"multiLine");break;case"u":By(i,"unicode");break;case"y":By(i,"sticky");break}if(this.idx!==this.input.length)throw Error("Redundant input: "+this.input.substring(this.idx));return{type:"Pattern",flags:i,value:r,loc:this.loc(0)}}disjunction(){let e=[],r=this.idx;for(e.push(this.alternative());this.peekChar()==="|";)this.consumeChar("|"),e.push(this.alternative());return{type:"Disjunction",value:e,loc:this.loc(r)}}alternative(){let e=[],r=this.idx;for(;this.isTerm();)e.push(this.term());return{type:"Alternative",value:e,loc:this.loc(r)}}term(){return this.isAssertion()?this.assertion():this.atom()}assertion(){let e=this.idx;switch(this.popChar()){case"^":return{type:"StartAnchor",loc:this.loc(e)};case"$":return{type:"EndAnchor",loc:this.loc(e)};case"\\":switch(this.popChar()){case"b":return{type:"WordBoundary",loc:this.loc(e)};case"B":return{type:"NonWordBoundary",loc:this.loc(e)}}throw Error("Invalid Assertion Escape");case"(":this.consumeChar("?");let r;switch(this.popChar()){case"=":r="Lookahead";break;case"!":r="NegativeLookahead";break;case"<":{switch(this.popChar()){case"=":r="Lookbehind";break;case"!":r="NegativeLookbehind"}break}}km(r);let i=this.disjunction();return this.consumeChar(")"),{type:r,value:i,loc:this.loc(e)}}return GT()}quantifier(e=!1){let r,i=this.idx;switch(this.popChar()){case"*":r={atLeast:0,atMost:1/0};break;case"+":r={atLeast:1,atMost:1/0};break;case"?":r={atLeast:0,atMost:1};break;case"{":let n=this.integerIncludingZero();switch(this.popChar()){case"}":r={atLeast:n,atMost:n};break;case",":let a;this.isDigit()?(a=this.integerIncludingZero(),r={atLeast:n,atMost:a}):r={atLeast:n,atMost:1/0},this.consumeChar("}");break}if(e===!0&&r===void 0)return;km(r);break}if(!(e===!0&&r===void 0)&&km(r))return this.peekChar(0)==="?"?(this.consumeChar("?"),r.greedy=!1):r.greedy=!0,r.type="Quantifier",r.loc=this.loc(i),r}atom(){let e,r=this.idx;switch(this.peekChar()){case".":e=this.dotAll();break;case"\\":e=this.atomEscape();break;case"[":e=this.characterClass();break;case"(":e=this.group();break}return e===void 0&&this.isPatternCharacter()&&(e=this.patternCharacter()),km(e)?(e.loc=this.loc(r),this.isQuantifier()&&(e.quantifier=this.quantifier()),e):GT()}dotAll(){return this.consumeChar("."),{type:"Set",complement:!0,value:[br(` +`),br("\r"),br("\u2028"),br("\u2029")]}}atomEscape(){switch(this.consumeChar("\\"),this.peekChar()){case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":return this.decimalEscapeAtom();case"d":case"D":case"s":case"S":case"w":case"W":return this.characterClassEscape();case"f":case"n":case"r":case"t":case"v":return this.controlEscapeAtom();case"c":return this.controlLetterEscapeAtom();case"0":return this.nulCharacterAtom();case"x":return this.hexEscapeSequenceAtom();case"u":return this.regExpUnicodeEscapeSequenceAtom();default:return this.identityEscapeAtom()}}decimalEscapeAtom(){return{type:"GroupBackReference",value:this.positiveInteger()}}characterClassEscape(){let e,r=!1;switch(this.popChar()){case"d":e=VT;break;case"D":e=VT,r=!0;break;case"s":e=r$;break;case"S":e=r$,r=!0;break;case"w":e=qT;break;case"W":e=qT,r=!0;break}return km(e)?{type:"Set",value:e,complement:r}:GT()}controlEscapeAtom(){let e;switch(this.popChar()){case"f":e=br("\f");break;case"n":e=br(` +`);break;case"r":e=br("\r");break;case"t":e=br(" ");break;case"v":e=br("\v");break}return km(e)?{type:"Character",value:e}:GT()}controlLetterEscapeAtom(){this.consumeChar("c");let e=this.popChar();if(/[a-zA-Z]/.test(e)===!1)throw Error("Invalid ");return{type:"Character",value:e.toUpperCase().charCodeAt(0)-64}}nulCharacterAtom(){return this.consumeChar("0"),{type:"Character",value:br("\0")}}hexEscapeSequenceAtom(){return this.consumeChar("x"),this.parseHexDigits(2)}regExpUnicodeEscapeSequenceAtom(){return this.consumeChar("u"),this.parseHexDigits(4)}identityEscapeAtom(){let e=this.popChar();return{type:"Character",value:br(e)}}classPatternCharacterAtom(){switch(this.peekChar()){case` +`:case"\r":case"\u2028":case"\u2029":case"\\":case"]":throw Error("TBD");default:let e=this.popChar();return{type:"Character",value:br(e)}}}characterClass(){let e=[],r=!1;for(this.consumeChar("["),this.peekChar(0)==="^"&&(this.consumeChar("^"),r=!0);this.isClassAtom();){let i=this.classAtom(),n=i.type==="Character";if(e$(i)&&this.isRangeDash()){this.consumeChar("-");let a=this.classAtom(),s=a.type==="Character";if(e$(a)){if(a.value=this.input.length)throw Error("Unexpected end of input");this.idx++}loc(e){return{begin:e,end:this.idx}}}});var ju,Hye=P(()=>{"use strict";ju=class{static{o(this,"BaseRegExpVisitor")}visitChildren(e){for(let r in e){let i=e[r];e.hasOwnProperty(r)&&(i.type!==void 0?this.visit(i):Array.isArray(i)&&i.forEach(n=>{this.visit(n)},this))}}visit(e){switch(e.type){case"Pattern":this.visitPattern(e);break;case"Flags":this.visitFlags(e);break;case"Disjunction":this.visitDisjunction(e);break;case"Alternative":this.visitAlternative(e);break;case"StartAnchor":this.visitStartAnchor(e);break;case"EndAnchor":this.visitEndAnchor(e);break;case"WordBoundary":this.visitWordBoundary(e);break;case"NonWordBoundary":this.visitNonWordBoundary(e);break;case"Lookahead":this.visitLookahead(e);break;case"NegativeLookahead":this.visitNegativeLookahead(e);break;case"Lookbehind":this.visitLookbehind(e);break;case"NegativeLookbehind":this.visitNegativeLookbehind(e);break;case"Character":this.visitCharacter(e);break;case"Set":this.visitSet(e);break;case"Group":this.visitGroup(e);break;case"GroupBackReference":this.visitGroupBackReference(e);break;case"Quantifier":this.visitQuantifier(e);break}this.visitChildren(e)}visitPattern(e){}visitFlags(e){}visitDisjunction(e){}visitAlternative(e){}visitStartAnchor(e){}visitEndAnchor(e){}visitWordBoundary(e){}visitNonWordBoundary(e){}visitLookahead(e){}visitNegativeLookahead(e){}visitLookbehind(e){}visitNegativeLookbehind(e){}visitCharacter(e){}visitSet(e){}visitGroup(e){}visitGroupBackReference(e){}visitQuantifier(e){}}});var WT=P(()=>{"use strict";Uye();Hye()});var x6={};ur(x6,{NEWLINE_REGEXP:()=>n$,escapeRegExp:()=>rp,getTerminalParts:()=>vnt,isMultilineComment:()=>a$,isWhitespace:()=>UT,partialMatches:()=>s$,partialRegExp:()=>Xye,whitespaceCharacters:()=>jye});function vnt(t){try{typeof t!="string"&&(t=t.source),t=`/${t}/`;let e=Yye.pattern(t),r=[];for(let i of e.value.value)wm.reset(t),wm.visit(i),r.push({start:wm.startRegexp,end:wm.endRegex});return r}catch{return[]}}function a$(t){try{return typeof t=="string"&&(t=new RegExp(t)),t=t.toString(),wm.reset(t),wm.visit(Yye.pattern(t)),wm.multiline}catch{return!1}}function UT(t){let e=typeof t=="string"?new RegExp(t):t;return jye.some(r=>e.test(r))}function rp(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function s$(t,e){let r=Xye(t),i=e.match(r);return!!i&&i[0].length>0}function Xye(t){typeof t=="string"&&(t=new RegExp(t));let e=t,r=t.source,i=0;function n(){let a="",s;function l(h){a+=r.substr(i,h),i+=h}o(l,"appendRaw");function u(h){a+="(?:"+r.substr(i,h)+"|$)",i+=h}for(o(u,"appendOptional");i",i)-i+1);break;default:u(2);break}break;case"[":s=/\[(?:\\.|.)*?\]/g,s.lastIndex=i,s=s.exec(r)||[],u(s[0].length);break;case"|":case"^":case"$":case"*":case"+":case"?":l(1);break;case"{":s=/\{\d+,?\d*\}/g,s.lastIndex=i,s=s.exec(r),s?l(s[0].length):u(1);break;case"(":if(r[i+1]==="?")switch(r[i+2]){case":":a+="(?:",i+=3,a+=n()+"|$)";break;case"=":a+="(?=",i+=3,a+=n()+")";break;case"!":s=i,i+=3,n(),a+=r.substr(s,i-s);break;case"<":switch(r[i+3]){case"=":case"!":s=i,i+=4,n(),a+=r.substr(s,i-s);break;default:l(r.indexOf(">",i)-i+1),a+=n()+"|$)";break}break}else l(1),a+=n()+"|$)";break;case")":return++i,a;default:u(1);break}return a}return o(n,"process"),new RegExp(n(),t.flags)}var n$,Yye,i$,wm,jye,Fy=P(()=>{"use strict";WT();n$=/\r?\n/gm,Yye=new Cm,i$=class extends ju{static{o(this,"TerminalRegExpVisitor")}constructor(){super(...arguments),this.isStarting=!0,this.endRegexpStack=[],this.multiline=!1}get endRegex(){return this.endRegexpStack.join("")}reset(e){this.multiline=!1,this.regex=e,this.startRegexp="",this.isStarting=!0,this.endRegexpStack=[]}visitGroup(e){e.quantifier&&(this.isStarting=!1,this.endRegexpStack=[])}visitCharacter(e){let r=String.fromCharCode(e.value);if(!this.multiline&&r===` +`&&(this.multiline=!0),e.quantifier)this.isStarting=!1,this.endRegexpStack=[];else{let i=rp(r);this.endRegexpStack.push(i),this.isStarting&&(this.startRegexp+=i)}}visitSet(e){if(!this.multiline){let r=this.regex.substring(e.loc.begin,e.loc.end),i=new RegExp(r);this.multiline=!!` +`.match(i)}if(e.quantifier)this.isStarting=!1,this.endRegexpStack=[];else{let r=this.regex.substring(e.loc.begin,e.loc.end);this.endRegexpStack.push(r),this.isStarting&&(this.startRegexp+=r)}}visitChildren(e){e.type==="Group"&&e.quantifier||super.visitChildren(e)}},wm=new i$;o(vnt,"getTerminalParts");o(a$,"isMultilineComment");jye=`\f +\r \v \xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF`.split("");o(UT,"isWhitespace");o(rp,"escapeRegExp");o(s$,"partialMatches");o(Xye,"partialRegExp")});var k6={};ur(k6,{findAssignment:()=>m$,findNameAssignment:()=>b6,findNodeForKeyword:()=>d$,findNodeForProperty:()=>YT,findNodesForKeyword:()=>bnt,findNodesForKeywordInternal:()=>p$,findNodesForProperty:()=>h$,getActionAtElement:()=>eve,getActionType:()=>rve,getAllReachableRules:()=>HT,getAllRulesUsedForCrossReferences:()=>xnt,getCrossReferenceTerminal:()=>c$,getEntryRule:()=>Kye,getExplicitRuleType:()=>T6,getHiddenRules:()=>Qye,getRuleType:()=>g$,getRuleTypeName:()=>Ent,getTypeName:()=>ip,isArrayCardinality:()=>knt,isArrayOperator:()=>Cnt,isCommentTerminal:()=>u$,isDataType:()=>wnt,isDataTypeRule:()=>jT,isOptionalCardinality:()=>Tnt,terminalRegex:()=>$y});function Kye(t){return t.rules.find(e=>Ba(e)&&e.entry)}function Qye(t){return t.rules.filter(e=>Xs(e)&&e.hidden)}function HT(t,e){let r=new Set,i=Kye(t);if(!i)return new Set(t.rules);let n=[i].concat(Qye(t));for(let s of n)Zye(s,r,e);let a=new Set;for(let s of t.rules)(r.has(s.name)||Xs(s)&&s.hidden)&&a.add(s);return a}function Zye(t,e,r){e.add(t.name),Pc(t).forEach(i=>{if(Gc(i)||r&&h6(i)){let n=i.rule.ref;n&&!e.has(n.name)&&Zye(n,e,r)}})}function xnt(t){let e=new Set;return Pc(t).forEach(r=>{zc(r)&&(Ba(r.type.ref)&&e.add(r.type.ref),$T(r.type.ref)&&Ba(r.type.ref.$container)&&e.add(r.type.ref.$container))}),e}function c$(t){if(t.terminal)return t.terminal;if(t.type.ref)return b6(t.type.ref)?.terminal}function u$(t){return t.hidden&&!UT($y(t))}function h$(t,e){return!t||!e?[]:f$(t,e,t.astNode,!0)}function YT(t,e,r){if(!t||!e)return;let i=f$(t,e,t.astNode,!0);if(i.length!==0)return r!==void 0?r=Math.max(0,Math.min(r,i.length-1)):r=0,i[r]}function f$(t,e,r,i){if(!i){let n=ef(t.grammarSource,$c);if(n&&n.feature===e)return[t]}return Mc(t)&&t.astNode===r?t.content.flatMap(n=>f$(n,e,r,!1)):[]}function bnt(t,e){return t?p$(t,e,t?.astNode):[]}function d$(t,e,r){if(!t)return;let i=p$(t,e,t?.astNode);if(i.length!==0)return r!==void 0?r=Math.max(0,Math.min(r,i.length-1)):r=0,i[r]}function p$(t,e,r){if(t.astNode!==r)return[];if(Hl(t.grammarSource)&&t.grammarSource.value===e)return[t];let i=xm(t).iterator(),n,a=[];do if(n=i.next(),!n.done){let s=n.value;s.astNode===r?Hl(s.grammarSource)&&s.grammarSource.value===e&&a.push(s):i.prune()}while(!n.done);return a}function m$(t){let e=t.astNode;for(;e===t.container?.astNode;){let r=ef(t.grammarSource,$c);if(r)return r;t=t.container}}function b6(t){let e=t;return $T(e)&&(af(e.$container)?e=e.$container.$container:nf(e.$container)?e=e.$container:Yu(e.$container)),Jye(t,e,new Map)}function Jye(t,e,r){function i(n,a){let s;return ef(n,$c)||(s=Jye(a,a,r)),r.set(t,s),s}if(o(i,"go"),r.has(t))return r.get(t);r.set(t,void 0);for(let n of Pc(e)){if($c(n)&&n.feature.toLowerCase()==="name")return r.set(t,n),n;if(Gc(n)&&Ba(n.rule.ref))return i(n,n.rule.ref);if(u6(n)&&n.typeRef?.ref)return i(n,n.typeRef.ref)}}function eve(t){let e=t.$container;if(ep(e)){let r=e.elements,i=r.indexOf(t);for(let n=i-1;n>=0;n--){let a=r[n];if(af(a))return a;{let s=Pc(r[n]).find(af);if(s)return s}}}if(FT(e))return eve(e)}function Tnt(t,e){return t==="?"||t==="*"||ep(e)&&!!e.guardCondition}function knt(t){return t==="*"||t==="+"}function Cnt(t){return t==="+="}function jT(t){return tve(t,new Set)}function tve(t,e){if(e.has(t))return!0;e.add(t);for(let r of Pc(t))if(Gc(r)){if(!r.rule.ref||Ba(r.rule.ref)&&!tve(r.rule.ref,e)||tp(r.rule.ref))return!1}else{if($c(r))return!1;if(af(r))return!1}return!!t.definition}function wnt(t){return l$(t.type,new Set)}function l$(t,e){if(e.has(t))return!0;if(e.add(t),NF(t))return!1;if(VF(t))return!1;if(YF(t))return t.types.every(r=>l$(r,e));if(u6(t)){if(t.primitiveType!==void 0)return!0;if(t.stringType!==void 0)return!0;if(t.typeRef!==void 0){let r=t.typeRef.ref;return f6(r)?l$(r.type,e):!1}else return!1}else return!1}function T6(t){if(!Xs(t)){if(t.inferredType)return t.inferredType.name;if(t.dataType)return t.dataType;if(t.returnType){let e=t.returnType.ref;if(e)return e.name}}}function ip(t){if(nf(t))return Ba(t)&&jT(t)?t.name:T6(t)??t.name;if(FF(t)||f6(t)||WF(t))return t.name;if(af(t)){let e=rve(t);if(e)return e}else if($T(t))return t.name;throw new Error("Cannot get name of Unknown Type")}function rve(t){if(t.inferredType)return t.inferredType.name;if(t.type?.ref)return ip(t.type.ref)}function Ent(t){return Xs(t)?t.type?.name??"string":Ba(t)&&jT(t)?t.name:T6(t)??t.name}function g$(t){return Xs(t)?t.type?.name??"string":T6(t)??t.name}function $y(t){let e={s:!1,i:!1,u:!1},r=zy(t.definition,e),i=Object.entries(e).filter(([,n])=>n).map(([n])=>n).join("");return new RegExp(r,i)}function zy(t,e){if(UF(t))return Snt(t);if(HF(t))return Ant(t);if(MF(t))return Lnt(t);if(h6(t)){let r=t.rule.ref;if(!r)throw new Error("Missing rule reference.");return sf(zy(r.definition),{cardinality:t.cardinality,lookahead:t.lookahead,parenthesized:t.parenthesized})}else{if($F(t))return Dnt(t);if(jF(t))return _nt(t);if(qF(t)){let r=t.regex.lastIndexOf("/"),i=t.regex.substring(1,r),n=t.regex.substring(r+1);return e&&(e.i=n.includes("i"),e.s=n.includes("s"),e.u=n.includes("u")),sf(i,{cardinality:t.cardinality,lookahead:t.lookahead,parenthesized:t.parenthesized,wrap:!1})}else{if(XF(t))return sf(y$,{cardinality:t.cardinality,lookahead:t.lookahead,parenthesized:t.parenthesized});throw new Error(`Invalid terminal element: ${t?.$type}, ${t?.$cstNode?.text}`)}}}function Snt(t){return sf(t.elements.map(e=>zy(e)).join("|"),{cardinality:t.cardinality,lookahead:t.lookahead,parenthesized:t.parenthesized,wrap:!1})}function Ant(t){return sf(t.elements.map(e=>zy(e)).join(""),{cardinality:t.cardinality,lookahead:t.lookahead,parenthesized:t.parenthesized,wrap:!1})}function _nt(t){return sf(`${y$}*?${zy(t.terminal)}`,{cardinality:t.cardinality,lookahead:t.lookahead,parenthesized:t.parenthesized})}function Dnt(t){return sf(`(?!${zy(t.terminal)})${y$}*?`,{cardinality:t.cardinality,lookahead:t.lookahead,parenthesized:t.parenthesized})}function Lnt(t){return t.right?sf(`[${o$(t.left)}-${o$(t.right)}]`,{cardinality:t.cardinality,lookahead:t.lookahead,parenthesized:t.parenthesized,wrap:!1}):sf(o$(t.left),{cardinality:t.cardinality,lookahead:t.lookahead,parenthesized:t.parenthesized,wrap:!1})}function o$(t){return rp(t.value)}function sf(t,e){return(e.parenthesized||e.lookahead||e.wrap!==!1)&&(t=`(${e.lookahead??(e.parenthesized?"":"?:")}${t})`),e.cardinality?`${t}${e.cardinality}`:t}var y$,Vc=P(()=>{"use strict";g6();ol();Oc();Ts();Bc();Fy();o(Kye,"getEntryRule");o(Qye,"getHiddenRules");o(HT,"getAllReachableRules");o(Zye,"ruleDfs");o(xnt,"getAllRulesUsedForCrossReferences");o(c$,"getCrossReferenceTerminal");o(u$,"isCommentTerminal");o(h$,"findNodesForProperty");o(YT,"findNodeForProperty");o(f$,"findNodesForPropertyInternal");o(bnt,"findNodesForKeyword");o(d$,"findNodeForKeyword");o(p$,"findNodesForKeywordInternal");o(m$,"findAssignment");o(b6,"findNameAssignment");o(Jye,"findNameAssignmentInternal");o(eve,"getActionAtElement");o(Tnt,"isOptionalCardinality");o(knt,"isArrayCardinality");o(Cnt,"isArrayOperator");o(jT,"isDataTypeRule");o(tve,"isDataTypeRuleInternal");o(wnt,"isDataType");o(l$,"isDataTypeInternal");o(T6,"getExplicitRuleType");o(ip,"getTypeName");o(rve,"getActionType");o(Ent,"getRuleTypeName");o(g$,"getRuleType");o($y,"terminalRegex");y$=/[\s\S]/.source;o(zy,"abstractElementToRegex");o(Snt,"terminalAlternativesToRegex");o(Ant,"terminalGroupToRegex");o(_nt,"untilTokenToRegex");o(Dnt,"negateTokenToRegex");o(Lnt,"characterRangeToRegex");o(o$,"keywordToRegex");o(sf,"withCardinality")});function v$(t){let e=[],r=t.Grammar;for(let i of r.rules)Xs(i)&&u$(i)&&a$($y(i))&&e.push(i.name);return{multilineCommentRules:e,nameRegexp:p6}}var x$=P(()=>{"use strict";Bc();Vc();Fy();ol();o(v$,"createGrammarConfig")});var b$=P(()=>{"use strict"});function Gy(t){console&&console.error&&console.error(`Error: ${t}`)}function XT(t){console&&console.warn&&console.warn(`Warning: ${t}`)}var ive=P(()=>{"use strict";o(Gy,"PRINT_ERROR");o(XT,"PRINT_WARNING")});function KT(t){let e=new Date().getTime(),r=t();return{time:new Date().getTime()-e,value:r}}var nve=P(()=>{"use strict";o(KT,"timer")});function QT(t){function e(){}o(e,"FakeConstructor"),e.prototype=t;let r=new e;function i(){return typeof r.bar}return o(i,"fakeAccess"),i(),i(),t;(0,eval)(t)}var ave=P(()=>{"use strict";o(QT,"toFastProperties")});var Vy=P(()=>{"use strict";ive();nve();ave()});function Rnt(t){return Nnt(t)?t.LABEL:t.name}function Nnt(t){return Gn(t.LABEL)&&t.LABEL!==""}function C6(t){return ht(t,qy)}function qy(t){function e(r){return ht(r,qy)}if(o(e,"convertDefinition"),t instanceof Li){let r={type:"NonTerminal",name:t.nonTerminalName,idx:t.idx};return Gn(t.label)&&(r.label=t.label),r}else{if(t instanceof en)return{type:"Alternative",definition:e(t.definition)};if(t instanceof Ri)return{type:"Option",idx:t.idx,definition:e(t.definition)};if(t instanceof tn)return{type:"RepetitionMandatory",idx:t.idx,definition:e(t.definition)};if(t instanceof rn)return{type:"RepetitionMandatoryWithSeparator",idx:t.idx,separator:qy(new Xr({terminalType:t.separator})),definition:e(t.definition)};if(t instanceof Wi)return{type:"RepetitionWithSeparator",idx:t.idx,separator:qy(new Xr({terminalType:t.separator})),definition:e(t.definition)};if(t instanceof ti)return{type:"Repetition",idx:t.idx,definition:e(t.definition)};if(t instanceof Ui)return{type:"Alternation",idx:t.idx,definition:e(t.definition)};if(t instanceof Xr){let r={type:"Terminal",name:t.terminalType.name,label:Rnt(t.terminalType),idx:t.idx};Gn(t.label)&&(r.terminalLabel=t.label);let i=t.terminalType.PATTERN;return t.terminalType.PATTERN&&(r.pattern=Bl(i)?i.source:i),r}else{if(t instanceof Ks)return{type:"Rule",name:t.name,orgText:t.orgText,definition:e(t.definition)};throw Error("non exhaustive match")}}}var ll,Li,Ks,en,Ri,tn,rn,ti,Wi,Ui,Xr,w6=P(()=>{"use strict";nr();o(Rnt,"tokenLabel");o(Nnt,"hasTokenLabel");ll=class{static{o(this,"AbstractProduction")}get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){this._definition=e}accept(e){e.visit(this),Pe(this.definition,r=>{r.accept(e)})}},Li=class extends ll{static{o(this,"NonTerminal")}constructor(e){super([]),this.idx=1,Za(this,Ao(e,r=>r!==void 0))}set definition(e){}get definition(){return this.referencedRule!==void 0?this.referencedRule.definition:[]}accept(e){e.visit(this)}},Ks=class extends ll{static{o(this,"Rule")}constructor(e){super(e.definition),this.orgText="",Za(this,Ao(e,r=>r!==void 0))}},en=class extends ll{static{o(this,"Alternative")}constructor(e){super(e.definition),this.ignoreAmbiguities=!1,Za(this,Ao(e,r=>r!==void 0))}},Ri=class extends ll{static{o(this,"Option")}constructor(e){super(e.definition),this.idx=1,Za(this,Ao(e,r=>r!==void 0))}},tn=class extends ll{static{o(this,"RepetitionMandatory")}constructor(e){super(e.definition),this.idx=1,Za(this,Ao(e,r=>r!==void 0))}},rn=class extends ll{static{o(this,"RepetitionMandatoryWithSeparator")}constructor(e){super(e.definition),this.idx=1,Za(this,Ao(e,r=>r!==void 0))}},ti=class extends ll{static{o(this,"Repetition")}constructor(e){super(e.definition),this.idx=1,Za(this,Ao(e,r=>r!==void 0))}},Wi=class extends ll{static{o(this,"RepetitionWithSeparator")}constructor(e){super(e.definition),this.idx=1,Za(this,Ao(e,r=>r!==void 0))}},Ui=class extends ll{static{o(this,"Alternation")}get definition(){return this._definition}set definition(e){this._definition=e}constructor(e){super(e.definition),this.idx=1,this.ignoreAmbiguities=!1,this.hasPredicates=!1,Za(this,Ao(e,r=>r!==void 0))}},Xr=class{static{o(this,"Terminal")}constructor(e){this.idx=1,Za(this,Ao(e,r=>r!==void 0))}accept(e){e.visit(this)}};o(C6,"serializeGrammar");o(qy,"serializeProduction")});var Qs,sve=P(()=>{"use strict";w6();Qs=class{static{o(this,"GAstVisitor")}visit(e){let r=e;switch(r.constructor){case Li:return this.visitNonTerminal(r);case en:return this.visitAlternative(r);case Ri:return this.visitOption(r);case tn:return this.visitRepetitionMandatory(r);case rn:return this.visitRepetitionMandatoryWithSeparator(r);case Wi:return this.visitRepetitionWithSeparator(r);case ti:return this.visitRepetition(r);case Ui:return this.visitAlternation(r);case Xr:return this.visitTerminal(r);case Ks:return this.visitRule(r);default:throw Error("non exhaustive match")}}visitNonTerminal(e){}visitAlternative(e){}visitOption(e){}visitRepetition(e){}visitRepetitionMandatory(e){}visitRepetitionMandatoryWithSeparator(e){}visitRepetitionWithSeparator(e){}visitAlternation(e){}visitTerminal(e){}visitRule(e){}}});function T$(t){return t instanceof en||t instanceof Ri||t instanceof ti||t instanceof tn||t instanceof rn||t instanceof Wi||t instanceof Xr||t instanceof Ks}function Em(t,e=[]){return t instanceof Ri||t instanceof ti||t instanceof Wi?!0:t instanceof Ui?Fb(t.definition,i=>Em(i,e)):t instanceof Li&&pn(e,t)?!1:t instanceof ll?(t instanceof Li&&e.push(t),ms(t.definition,i=>Em(i,e))):!1}function k$(t){return t instanceof Ui}function Mo(t){if(t instanceof Li)return"SUBRULE";if(t instanceof Ri)return"OPTION";if(t instanceof Ui)return"OR";if(t instanceof tn)return"AT_LEAST_ONE";if(t instanceof rn)return"AT_LEAST_ONE_SEP";if(t instanceof Wi)return"MANY_SEP";if(t instanceof ti)return"MANY";if(t instanceof Xr)return"CONSUME";throw Error("non exhaustive match")}var ove=P(()=>{"use strict";nr();w6();o(T$,"isSequenceProd");o(Em,"isOptionalProd");o(k$,"isBranchingProd");o(Mo,"getProductionDslName")});var Zs=P(()=>{"use strict";w6();sve();ove()});function lve(t,e,r){return[new Ri({definition:[new Xr({terminalType:t.separator})].concat(t.definition)})].concat(e,r)}var of,E6=P(()=>{"use strict";nr();Zs();of=class{static{o(this,"RestWalker")}walk(e,r=[]){Pe(e.definition,(i,n)=>{let a=zn(e.definition,n+1);if(i instanceof Li)this.walkProdRef(i,a,r);else if(i instanceof Xr)this.walkTerminal(i,a,r);else if(i instanceof en)this.walkFlat(i,a,r);else if(i instanceof Ri)this.walkOption(i,a,r);else if(i instanceof tn)this.walkAtLeastOne(i,a,r);else if(i instanceof rn)this.walkAtLeastOneSep(i,a,r);else if(i instanceof Wi)this.walkManySep(i,a,r);else if(i instanceof ti)this.walkMany(i,a,r);else if(i instanceof Ui)this.walkOr(i,a,r);else throw Error("non exhaustive match")})}walkTerminal(e,r,i){}walkProdRef(e,r,i){}walkFlat(e,r,i){let n=r.concat(i);this.walk(e,n)}walkOption(e,r,i){let n=r.concat(i);this.walk(e,n)}walkAtLeastOne(e,r,i){let n=[new Ri({definition:e.definition})].concat(r,i);this.walk(e,n)}walkAtLeastOneSep(e,r,i){let n=lve(e,r,i);this.walk(e,n)}walkMany(e,r,i){let n=[new Ri({definition:e.definition})].concat(r,i);this.walk(e,n)}walkManySep(e,r,i){let n=lve(e,r,i);this.walk(e,n)}walkOr(e,r,i){let n=r.concat(i);Pe(e.definition,a=>{let s=new en({definition:[a]});this.walk(s,n)})}};o(lve,"restForRepetitionWithSeparator")});function Sm(t){if(t instanceof Li)return Sm(t.referencedRule);if(t instanceof Xr)return Ont(t);if(T$(t))return Int(t);if(k$(t))return Mnt(t);throw Error("non exhaustive match")}function Int(t){let e=[],r=t.definition,i=0,n=r.length>i,a,s=!0;for(;n&&s;)a=r[i],s=Em(a),e=e.concat(Sm(a)),i=i+1,n=r.length>i;return Z1(e)}function Mnt(t){let e=ht(t.definition,r=>Sm(r));return Z1(di(e))}function Ont(t){return[t.terminalType]}var C$=P(()=>{"use strict";nr();Zs();o(Sm,"first");o(Int,"firstForSequence");o(Mnt,"firstForBranching");o(Ont,"firstForTerminal")});var S6,w$=P(()=>{"use strict";S6="_~IN~_"});function cve(t){let e={};return Pe(t,r=>{let i=new E$(r).startWalking();Za(e,i)}),e}function Pnt(t,e){return t.name+e+S6}var E$,uve=P(()=>{"use strict";E6();C$();nr();w$();Zs();E$=class extends of{static{o(this,"ResyncFollowsWalker")}constructor(e){super(),this.topProd=e,this.follows={}}startWalking(){return this.walk(this.topProd),this.follows}walkTerminal(e,r,i){}walkProdRef(e,r,i){let n=Pnt(e.referencedRule,e.idx)+this.topProd.name,a=r.concat(i),s=new en({definition:a}),l=Sm(s);this.follows[n]=l}};o(cve,"computeAllProdsFollows");o(Pnt,"buildBetweenProdsFollowPrefix")});function Wy(t){let e=t.toString();if(A6.hasOwnProperty(e))return A6[e];{let r=Bnt.pattern(e);return A6[e]=r,r}}function hve(){A6={}}var A6,Bnt,_6=P(()=>{"use strict";WT();A6={},Bnt=new Cm;o(Wy,"getRegExpAst");o(hve,"clearRegExpParserCache")});function pve(t,e=!1){try{let r=Wy(t);return S$(r.value,{},r.flags.ignoreCase)}catch(r){if(r.message===dve)e&&XT(`${ZT} Unable to optimize: < ${t.toString()} > + Complement Sets cannot be automatically optimized. + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);else{let i="";e&&(i=` + This will disable the lexer's first char optimizations. + See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.`),Gy(`${ZT} + Failed parsing: < ${t.toString()} > + Using the @chevrotain/regexp-to-ast library + Please open an issue at: https://github.com/chevrotain/chevrotain/issues`+i)}}return[]}function S$(t,e,r){switch(t.type){case"Disjunction":for(let n=0;n{if(typeof u=="number")D6(u,e,r);else{let h=u;if(r===!0)for(let f=h.from;f<=h.to;f++)D6(f,e,r);else{for(let f=h.from;f<=h.to&&f=Uy){let f=h.from>=Uy?h.from:Uy,d=h.to,p=Xu(f),m=Xu(d);for(let g=p;g<=m;g++)e[g]=g}}}});break;case"Group":S$(s.value,e,r);break;default:throw Error("Non Exhaustive Match")}let l=s.quantifier!==void 0&&s.quantifier.atLeast===0;if(s.type==="Group"&&A$(s)===!1||s.type!=="Group"&&l===!1)break}break;default:throw Error("non exhaustive match!")}return qr(e)}function D6(t,e,r){let i=Xu(t);e[i]=i,r===!0&&Fnt(t,e)}function Fnt(t,e){let r=String.fromCharCode(t),i=r.toUpperCase();if(i!==r){let n=Xu(i.charCodeAt(0));e[n]=n}else{let n=r.toLowerCase();if(n!==r){let a=Xu(n.charCodeAt(0));e[a]=a}}}function fve(t,e){return qs(t.value,r=>{if(typeof r=="number")return pn(e,r);{let i=r;return qs(e,n=>i.from<=n&&n<=i.to)!==void 0}})}function A$(t){let e=t.quantifier;return e&&e.atLeast===0?!0:t.value?Gt(t.value)?ms(t.value,A$):A$(t.value):!1}function L6(t,e){if(e instanceof RegExp){let r=Wy(e),i=new _$(t);return i.visit(r),i.found}else return qs(e,r=>pn(t,r.charCodeAt(0)))!==void 0}var dve,ZT,_$,mve=P(()=>{"use strict";WT();nr();Vy();_6();D$();dve="Complement Sets are not supported for first char optimization",ZT=`Unable to use "first char" lexer optimizations: +`;o(pve,"getOptimizedStartCodesIndices");o(S$,"firstCharOptimizedIndices");o(D6,"addOptimizedIdxToResult");o(Fnt,"handleIgnoreCase");o(fve,"findCode");o(A$,"isWholeOptional");_$=class extends ju{static{o(this,"CharCodeFinder")}constructor(e){super(),this.targetCharCodes=e,this.found=!1}visitChildren(e){if(this.found!==!0){switch(e.type){case"Lookahead":this.visitLookahead(e);return;case"NegativeLookahead":this.visitNegativeLookahead(e);return;case"Lookbehind":this.visitLookbehind(e);return;case"NegativeLookbehind":this.visitNegativeLookbehind(e);return}super.visitChildren(e)}}visitCharacter(e){pn(this.targetCharCodes,e.value)&&(this.found=!0)}visitSet(e){e.complement?fve(e,this.targetCharCodes)===void 0&&(this.found=!0):fve(e,this.targetCharCodes)!==void 0&&(this.found=!0)}};o(L6,"canMatchCharCode")});function vve(t,e){e=xd(e,{useSticky:R$,debug:!1,safeMode:!1,positionTracking:"full",lineTerminatorCharacters:["\r",` +`],tracer:o((b,T)=>T(),"tracer")});let r=e.tracer;r("initCharCodeToOptimizedIndexMap",()=>{iat()});let i;r("Reject Lexer.NA",()=>{i=Td(t,b=>b[Am]===yn.NA)});let n=!1,a;r("Transform Patterns",()=>{n=!1,a=ht(i,b=>{let T=b[Am];if(Bl(T)){let w=T.source;return w.length===1&&w!=="^"&&w!=="$"&&w!=="."&&!T.ignoreCase?w:w.length===2&&w[0]==="\\"&&!pn(["d","D","s","S","t","r","n","t","0","c","b","B","f","v","w","W"],w[1])?w[1]:e.useSticky?yve(T):gve(T)}else{if(Qn(T))return n=!0,{exec:T};if(typeof T=="object")return n=!0,T;if(typeof T=="string"){if(T.length===1)return T;{let w=T.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"),k=new RegExp(w);return e.useSticky?yve(k):gve(k)}}else throw Error("non exhaustive match")}})});let s,l,u,h,f;r("misc mapping",()=>{s=ht(i,b=>b.tokenTypeIdx),l=ht(i,b=>{let T=b.GROUP;if(T!==yn.SKIPPED){if(Gn(T))return T;if(Br(T))return!1;throw Error("non exhaustive match")}}),u=ht(i,b=>{let T=b.LONGER_ALT;if(T)return Gt(T)?ht(T,k=>SE(i,k)):[SE(i,T)]}),h=ht(i,b=>b.PUSH_MODE),f=ht(i,b=>Vt(b,"POP_MODE"))});let d;r("Line Terminator Handling",()=>{let b=Sve(e.lineTerminatorCharacters);d=ht(i,T=>!1),e.positionTracking!=="onlyOffset"&&(d=ht(i,T=>Vt(T,"LINE_BREAKS")?!!T.LINE_BREAKS:Eve(T,b)===!1&&L6(b,T.PATTERN)))});let p,m,g,y;r("Misc Mapping #2",()=>{p=ht(i,Cve),m=ht(a,tat),g=mi(i,(b,T)=>{let w=T.GROUP;return Gn(w)&&w!==yn.SKIPPED&&(b[w]=[]),b},{}),y=ht(a,(b,T)=>({pattern:a[T],longerAlt:u[T],canLineTerminator:d[T],isCustom:p[T],short:m[T],group:l[T],push:h[T],pop:f[T],tokenTypeIdx:s[T],tokenType:i[T]}))});let v=!0,x=[];return e.safeMode||r("First Char Optimization",()=>{x=mi(i,(b,T,w)=>{if(typeof T.PATTERN=="string"){let k=T.PATTERN.charCodeAt(0),C=Xu(k);L$(b,C,y[w])}else if(Gt(T.START_CHARS_HINT)){let k;Pe(T.START_CHARS_HINT,C=>{let E=typeof C=="string"?C.charCodeAt(0):C,S=Xu(E);k!==S&&(k=S,L$(b,S,y[w]))})}else if(Bl(T.PATTERN))if(T.PATTERN.unicode)v=!1,e.ensureOptimizations&&Gy(`${ZT} Unable to analyze < ${T.PATTERN.toString()} > pattern. + The regexp unicode flag is not currently supported by the regexp-to-ast library. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);else{let k=pve(T.PATTERN,e.ensureOptimizations);_r(k)&&(v=!1),Pe(k,C=>{L$(b,C,y[w])})}else e.ensureOptimizations&&Gy(`${ZT} TokenType: <${T.name}> is using a custom token pattern without providing parameter. + This will disable the lexer's first char optimizations. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`),v=!1;return b},[])}),{emptyGroups:g,patternIdxToConfig:y,charCodeToPatternIdxToConfig:x,hasCustom:n,canBeOptimized:v}}function xve(t,e){let r=[],i=znt(t);r=r.concat(i.errors);let n=Gnt(i.valid),a=n.valid;return r=r.concat(n.errors),r=r.concat($nt(a)),r=r.concat(Xnt(a)),r=r.concat(Knt(a,e)),r=r.concat(Qnt(a)),r}function $nt(t){let e=[],r=pi(t,i=>Bl(i[Am]));return e=e.concat(qnt(r)),e=e.concat(Hnt(r)),e=e.concat(Ynt(r)),e=e.concat(jnt(r)),e=e.concat(Wnt(r)),e}function znt(t){let e=pi(t,n=>!Vt(n,Am)),r=ht(e,n=>({message:"Token Type: ->"+n.name+"<- missing static 'PATTERN' property",type:gn.MISSING_PATTERN,tokenTypes:[n]})),i=bd(t,e);return{errors:r,valid:i}}function Gnt(t){let e=pi(t,n=>{let a=n[Am];return!Bl(a)&&!Qn(a)&&!Vt(a,"exec")&&!Gn(a)}),r=ht(e,n=>({message:"Token Type: ->"+n.name+"<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",type:gn.INVALID_PATTERN,tokenTypes:[n]})),i=bd(t,e);return{errors:r,valid:i}}function qnt(t){class e extends ju{static{o(this,"EndAnchorFinder")}constructor(){super(...arguments),this.found=!1}visitEndAnchor(a){this.found=!0}}let r=pi(t,n=>{let a=n.PATTERN;try{let s=Wy(a),l=new e;return l.visit(s),l.found}catch{return Vnt.test(a.source)}});return ht(r,n=>({message:`Unexpected RegExp Anchor Error: + Token Type: ->`+n.name+`<- static 'PATTERN' cannot contain end of input anchor '$' + See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:gn.EOI_ANCHOR_FOUND,tokenTypes:[n]}))}function Wnt(t){let e=pi(t,i=>i.PATTERN.test(""));return ht(e,i=>({message:"Token Type: ->"+i.name+"<- static 'PATTERN' must not match an empty string",type:gn.EMPTY_MATCH_PATTERN,tokenTypes:[i]}))}function Hnt(t){class e extends ju{static{o(this,"StartAnchorFinder")}constructor(){super(...arguments),this.found=!1}visitStartAnchor(a){this.found=!0}}let r=pi(t,n=>{let a=n.PATTERN;try{let s=Wy(a),l=new e;return l.visit(s),l.found}catch{return Unt.test(a.source)}});return ht(r,n=>({message:`Unexpected RegExp Anchor Error: + Token Type: ->`+n.name+`<- static 'PATTERN' cannot contain start of input anchor '^' + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS for details.`,type:gn.SOI_ANCHOR_FOUND,tokenTypes:[n]}))}function Ynt(t){let e=pi(t,i=>{let n=i[Am];return n instanceof RegExp&&(n.multiline||n.global)});return ht(e,i=>({message:"Token Type: ->"+i.name+"<- static 'PATTERN' may NOT contain global('g') or multiline('m')",type:gn.UNSUPPORTED_FLAGS_FOUND,tokenTypes:[i]}))}function jnt(t){let e=[],r=ht(t,a=>mi(t,(s,l)=>(a.PATTERN.source===l.PATTERN.source&&!pn(e,l)&&l.PATTERN!==yn.NA&&(e.push(l),s.push(l)),s),[]));r=Ru(r);let i=pi(r,a=>a.length>1);return ht(i,a=>{let s=ht(a,u=>u.name);return{message:`The same RegExp pattern ->${Ia(a).PATTERN}<-has been used in all of the following Token Types: ${s.join(", ")} <-`,type:gn.DUPLICATE_PATTERNS_FOUND,tokenTypes:a}})}function Xnt(t){let e=pi(t,i=>{if(!Vt(i,"GROUP"))return!1;let n=i.GROUP;return n!==yn.SKIPPED&&n!==yn.NA&&!Gn(n)});return ht(e,i=>({message:"Token Type: ->"+i.name+"<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",type:gn.INVALID_GROUP_TYPE_FOUND,tokenTypes:[i]}))}function Knt(t,e){let r=pi(t,n=>n.PUSH_MODE!==void 0&&!pn(e,n.PUSH_MODE));return ht(r,n=>({message:`Token Type: ->${n.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${n.PUSH_MODE}<-which does not exist`,type:gn.PUSH_MODE_DOES_NOT_EXIST,tokenTypes:[n]}))}function Qnt(t){let e=[],r=mi(t,(i,n,a)=>{let s=n.PATTERN;return s===yn.NA||(Gn(s)?i.push({str:s,idx:a,tokenType:n}):Bl(s)&&Jnt(s)&&i.push({str:s.source,idx:a,tokenType:n})),i},[]);return Pe(t,(i,n)=>{Pe(r,({str:a,idx:s,tokenType:l})=>{if(n${l.name}<- can never be matched. +Because it appears AFTER the Token Type ->${i.name}<-in the lexer's definition. +See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;e.push({message:u,type:gn.UNREACHABLE_PATTERN,tokenTypes:[i,l]})}})}),e}function Znt(t,e){if(Bl(e)){if(eat(e))return!1;let r=e.exec(t);return r!==null&&r.index===0}else{if(Qn(e))return e(t,0,[],{});if(Vt(e,"exec"))return e.exec(t,0,[],{});if(typeof e=="string")return e===t;throw Error("non exhaustive match")}}function Jnt(t){return qs([".","\\","[","]","|","^","$","(",")","?","*","+","{"],r=>t.source.indexOf(r)!==-1)===void 0}function eat(t){return/(\(\?=)|(\(\?!)|(\(\?<=)|(\(\? property in its definition +`,type:gn.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE}),Vt(t,R6)||i.push({message:"A MultiMode Lexer cannot be initialized without a <"+R6+`> property in its definition +`,type:gn.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY}),Vt(t,R6)&&Vt(t,Hy)&&!Vt(t.modes,t.defaultMode)&&i.push({message:`A MultiMode Lexer cannot be initialized with a ${Hy}: <${t.defaultMode}>which does not exist +`,type:gn.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST}),Vt(t,R6)&&Pe(t.modes,(n,a)=>{Pe(n,(s,l)=>{if(Br(s))i.push({message:`A Lexer cannot be initialized using an undefined Token Type. Mode:<${a}> at index: <${l}> +`,type:gn.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED});else if(Vt(s,"LONGER_ALT")){let u=Gt(s.LONGER_ALT)?s.LONGER_ALT:[s.LONGER_ALT];Pe(u,h=>{!Br(h)&&!pn(n,h)&&i.push({message:`A MultiMode Lexer cannot be initialized with a longer_alt <${h.name}> on token <${s.name}> outside of mode <${a}> +`,type:gn.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE})})}})}),i}function Tve(t,e,r){let i=[],n=!1,a=Ru(di(qr(t.modes))),s=Td(a,u=>u[Am]===yn.NA),l=Sve(r);return e&&Pe(s,u=>{let h=Eve(u,l);if(h!==!1){let d={message:rat(u,h),type:h.issue,tokenType:u};i.push(d)}else Vt(u,"LINE_BREAKS")?u.LINE_BREAKS===!0&&(n=!0):L6(l,u.PATTERN)&&(n=!0)}),e&&!n&&i.push({message:`Warning: No LINE_BREAKS Found. + This Lexer has been defined to track line and column information, + But none of the Token Types can be identified as matching a line terminator. + See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS + for details.`,type:gn.NO_LINE_BREAKS_FLAGS}),i}function kve(t){let e={},r=ni(t);return Pe(r,i=>{let n=t[i];if(Gt(n))e[i]=[];else throw Error("non exhaustive match")}),e}function Cve(t){let e=t.PATTERN;if(Bl(e))return!1;if(Qn(e))return!0;if(Vt(e,"exec"))return!0;if(Gn(e))return!1;throw Error("non exhaustive match")}function tat(t){return Gn(t)&&t.length===1?t.charCodeAt(0):!1}function Eve(t,e){if(Vt(t,"LINE_BREAKS"))return!1;if(Bl(t.PATTERN)){try{L6(e,t.PATTERN)}catch(r){return{issue:gn.IDENTIFY_TERMINATOR,errMsg:r.message}}return!1}else{if(Gn(t.PATTERN))return!1;if(Cve(t))return{issue:gn.CUSTOM_LINE_BREAK};throw Error("non exhaustive match")}}function rat(t,e){if(e.issue===gn.IDENTIFY_TERMINATOR)return`Warning: unable to identify line terminator usage in pattern. + The problem is in the <${t.name}> Token Type + Root cause: ${e.errMsg}. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;if(e.issue===gn.CUSTOM_LINE_BREAK)return`Warning: A Custom Token Pattern should specify the option. + The problem is in the <${t.name}> Token Type + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;throw Error("non exhaustive match")}function Sve(t){return ht(t,r=>Gn(r)?r.charCodeAt(0):r)}function L$(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function Xu(t){return t255?255+~~(t/255):t}}var Am,Hy,R6,R$,Vnt,Unt,wve,Uy,N6,D$=P(()=>{"use strict";WT();JT();nr();Vy();mve();_6();Am="PATTERN",Hy="defaultMode",R6="modes",R$=typeof new RegExp("(?:)").sticky=="boolean";o(vve,"analyzeTokenTypes");o(xve,"validatePatterns");o($nt,"validateRegExpPattern");o(znt,"findMissingPatterns");o(Gnt,"findInvalidPatterns");Vnt=/[^\\][$]/;o(qnt,"findEndOfInputAnchor");o(Wnt,"findEmptyMatchRegExps");Unt=/[^\\[][\^]|^\^/;o(Hnt,"findStartOfInputAnchor");o(Ynt,"findUnsupportedFlags");o(jnt,"findDuplicatePatterns");o(Xnt,"findInvalidGroupType");o(Knt,"findModesThatDoNotExist");o(Qnt,"findUnreachablePatterns");o(Znt,"tryToMatchStrToPattern");o(Jnt,"noMetaChar");o(eat,"usesLookAheadOrBehind");o(gve,"addStartOfInput");o(yve,"addStickyFlag");o(bve,"performRuntimeChecks");o(Tve,"performWarningRuntimeChecks");o(kve,"cloneEmptyGroups");o(Cve,"isCustomPattern");o(tat,"isShortPattern");wve={test:o(function(t){let e=t.length;for(let r=this.lastIndex;r{r.isParent=r.categoryMatches.length>0})}function nat(t){let e=Si(t),r=t,i=!0;for(;i;){r=Ru(di(ht(r,a=>a.CATEGORIES)));let n=bd(r,e);e=e.concat(n),_r(n)?i=!1:r=n}return e}function aat(t){Pe(t,e=>{N$(e)||(Dve[Ave]=e,e.tokenTypeIdx=Ave++),_ve(e)&&!Gt(e.CATEGORIES)&&(e.CATEGORIES=[e.CATEGORIES]),_ve(e)||(e.CATEGORIES=[]),lat(e)||(e.categoryMatches=[]),cat(e)||(e.categoryMatchesMap={})})}function sat(t){Pe(t,e=>{e.categoryMatches=[],Pe(e.categoryMatchesMap,(r,i)=>{e.categoryMatches.push(Dve[i].tokenTypeIdx)})})}function oat(t){Pe(t,e=>{Lve([],e)})}function Lve(t,e){Pe(t,r=>{e.categoryMatchesMap[r.tokenTypeIdx]=!0}),Pe(e.CATEGORIES,r=>{let i=t.concat(e);pn(i,r)||Lve(i,r)})}function N$(t){return Vt(t,"tokenTypeIdx")}function _ve(t){return Vt(t,"CATEGORIES")}function lat(t){return Vt(t,"categoryMatches")}function cat(t){return Vt(t,"categoryMatchesMap")}function Rve(t){return Vt(t,"tokenTypeIdx")}var Ave,Dve,_m=P(()=>{"use strict";nr();o(lf,"tokenStructuredMatcher");o(Yy,"tokenStructuredMatcherNoCategories");Ave=1,Dve={};o(cf,"augmentTokenTypes");o(nat,"expandCategories");o(aat,"assignTokenDefaultProps");o(sat,"assignCategoriesTokensProp");o(oat,"assignCategoriesMapProp");o(Lve,"singleAssignCategoriesToksMap");o(N$,"hasShortKeyProperty");o(_ve,"hasCategoriesProperty");o(lat,"hasExtendingTokensTypesProperty");o(cat,"hasExtendingTokensTypesMapProperty");o(Rve,"isTokenType")});var jy,I$=P(()=>{"use strict";jy={buildUnableToPopLexerModeMessage(t){return`Unable to pop Lexer Mode after encountering Token ->${t.image}<- The Mode Stack is empty`},buildUnexpectedCharactersMessage(t,e,r,i,n,a){return`unexpected character: ->${t.charAt(e)}<- at offset: ${e}, skipped ${r} characters.`}}});var gn,ek,yn,JT=P(()=>{"use strict";D$();nr();Vy();_m();I$();_6();(function(t){t[t.MISSING_PATTERN=0]="MISSING_PATTERN",t[t.INVALID_PATTERN=1]="INVALID_PATTERN",t[t.EOI_ANCHOR_FOUND=2]="EOI_ANCHOR_FOUND",t[t.UNSUPPORTED_FLAGS_FOUND=3]="UNSUPPORTED_FLAGS_FOUND",t[t.DUPLICATE_PATTERNS_FOUND=4]="DUPLICATE_PATTERNS_FOUND",t[t.INVALID_GROUP_TYPE_FOUND=5]="INVALID_GROUP_TYPE_FOUND",t[t.PUSH_MODE_DOES_NOT_EXIST=6]="PUSH_MODE_DOES_NOT_EXIST",t[t.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE=7]="MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE",t[t.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY=8]="MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY",t[t.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST=9]="MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST",t[t.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED=10]="LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED",t[t.SOI_ANCHOR_FOUND=11]="SOI_ANCHOR_FOUND",t[t.EMPTY_MATCH_PATTERN=12]="EMPTY_MATCH_PATTERN",t[t.NO_LINE_BREAKS_FLAGS=13]="NO_LINE_BREAKS_FLAGS",t[t.UNREACHABLE_PATTERN=14]="UNREACHABLE_PATTERN",t[t.IDENTIFY_TERMINATOR=15]="IDENTIFY_TERMINATOR",t[t.CUSTOM_LINE_BREAK=16]="CUSTOM_LINE_BREAK",t[t.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE=17]="MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"})(gn||(gn={}));ek={deferDefinitionErrorsHandling:!1,positionTracking:"full",lineTerminatorsPattern:/\n|\r\n?/g,lineTerminatorCharacters:[` +`,"\r"],ensureOptimizations:!1,safeMode:!1,errorMessageProvider:jy,traceInitPerf:!1,skipValidations:!1,recoveryEnabled:!0};Object.freeze(ek);yn=class{static{o(this,"Lexer")}constructor(e,r=ek){if(this.lexerDefinition=e,this.lexerDefinitionErrors=[],this.lexerDefinitionWarning=[],this.patternIdxToConfig={},this.charCodeToPatternIdxToConfig={},this.modes=[],this.emptyGroups={},this.trackStartLines=!0,this.trackEndLines=!0,this.hasCustom=!1,this.canModeBeOptimized={},this.TRACE_INIT=(n,a)=>{if(this.traceInitPerf===!0){this.traceInitIndent++;let s=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${n}>`);let{time:l,value:u}=KT(a),h=l>10?console.warn:console.log;return this.traceInitIndent time: ${l}ms`),this.traceInitIndent--,u}else return a()},typeof r=="boolean")throw Error(`The second argument to the Lexer constructor is now an ILexerConfig Object. +a boolean 2nd argument is no longer supported`);this.config=Za({},ek,r);let i=this.config.traceInitPerf;i===!0?(this.traceInitMaxIdent=1/0,this.traceInitPerf=!0):typeof i=="number"&&(this.traceInitMaxIdent=i,this.traceInitPerf=!0),this.traceInitIndent=-1,this.TRACE_INIT("Lexer Constructor",()=>{let n,a=!0;this.TRACE_INIT("Lexer Config handling",()=>{if(this.config.lineTerminatorsPattern===ek.lineTerminatorsPattern)this.config.lineTerminatorsPattern=wve;else if(this.config.lineTerminatorCharacters===ek.lineTerminatorCharacters)throw Error(`Error: Missing property on the Lexer config. + For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS`);if(r.safeMode&&r.ensureOptimizations)throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');this.trackStartLines=/full|onlyStart/i.test(this.config.positionTracking),this.trackEndLines=/full/i.test(this.config.positionTracking),Gt(e)?n={modes:{defaultMode:Si(e)},defaultMode:Hy}:(a=!1,n=Si(e))}),this.config.skipValidations===!1&&(this.TRACE_INIT("performRuntimeChecks",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(bve(n,this.trackStartLines,this.config.lineTerminatorCharacters))}),this.TRACE_INIT("performWarningRuntimeChecks",()=>{this.lexerDefinitionWarning=this.lexerDefinitionWarning.concat(Tve(n,this.trackStartLines,this.config.lineTerminatorCharacters))})),n.modes=n.modes?n.modes:{},Pe(n.modes,(l,u)=>{n.modes[u]=Td(l,h=>Br(h))});let s=ni(n.modes);if(Pe(n.modes,(l,u)=>{this.TRACE_INIT(`Mode: <${u}> processing`,()=>{if(this.modes.push(u),this.config.skipValidations===!1&&this.TRACE_INIT("validatePatterns",()=>{this.lexerDefinitionErrors=this.lexerDefinitionErrors.concat(xve(l,s))}),_r(this.lexerDefinitionErrors)){cf(l);let h;this.TRACE_INIT("analyzeTokenTypes",()=>{h=vve(l,{lineTerminatorCharacters:this.config.lineTerminatorCharacters,positionTracking:r.positionTracking,ensureOptimizations:r.ensureOptimizations,safeMode:r.safeMode,tracer:this.TRACE_INIT})}),this.patternIdxToConfig[u]=h.patternIdxToConfig,this.charCodeToPatternIdxToConfig[u]=h.charCodeToPatternIdxToConfig,this.emptyGroups=Za({},this.emptyGroups,h.emptyGroups),this.hasCustom=h.hasCustom||this.hasCustom,this.canModeBeOptimized[u]=h.canBeOptimized}})}),this.defaultMode=n.defaultMode,!_r(this.lexerDefinitionErrors)&&!this.config.deferDefinitionErrorsHandling){let u=ht(this.lexerDefinitionErrors,h=>h.message).join(`----------------------- +`);throw new Error(`Errors detected in definition of Lexer: +`+u)}Pe(this.lexerDefinitionWarning,l=>{XT(l.message)}),this.TRACE_INIT("Choosing sub-methods implementations",()=>{if(R$?(this.chopInput=La,this.match=this.matchWithTest):(this.updateLastIndex=Sn,this.match=this.matchWithExec),a&&(this.handleModes=Sn),this.trackStartLines===!1&&(this.computeNewColumn=La),this.trackEndLines===!1&&(this.updateTokenEndLineColumnLocation=Sn),/full/i.test(this.config.positionTracking))this.createTokenInstance=this.createFullToken;else if(/onlyStart/i.test(this.config.positionTracking))this.createTokenInstance=this.createStartOnlyToken;else if(/onlyOffset/i.test(this.config.positionTracking))this.createTokenInstance=this.createOffsetOnlyToken;else throw Error(`Invalid config option: "${this.config.positionTracking}"`);this.hasCustom?(this.addToken=this.addTokenUsingPush,this.handlePayload=this.handlePayloadWithCustom):(this.addToken=this.addTokenUsingMemberAccess,this.handlePayload=this.handlePayloadNoCustom)}),this.TRACE_INIT("Failed Optimization Warnings",()=>{let l=mi(this.canModeBeOptimized,(u,h,f)=>(h===!1&&u.push(f),u),[]);if(r.ensureOptimizations&&!_r(l))throw Error(`Lexer Modes: < ${l.join(", ")} > cannot be optimized. + Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode. + Or inspect the console log for details on how to resolve these issues.`)}),this.TRACE_INIT("clearRegExpParserCache",()=>{hve()}),this.TRACE_INIT("toFastProperties",()=>{QT(this)})})}tokenize(e,r=this.defaultMode){if(!_r(this.lexerDefinitionErrors)){let n=ht(this.lexerDefinitionErrors,a=>a.message).join(`----------------------- +`);throw new Error(`Unable to Tokenize because Errors detected in definition of Lexer: +`+n)}return this.tokenizeInternal(e,r)}tokenizeInternal(e,r){let i,n,a,s,l,u,h,f,d,p,m,g,y,v,x,b,T=e,w=T.length,k=0,C=0,E=this.hasCustom?0:Math.floor(e.length/10),S=new Array(E),L=[],M=this.trackStartLines?1:void 0,I=this.trackStartLines?1:void 0,A=kve(this.emptyGroups),_=this.trackStartLines,D=this.config.lineTerminatorsPattern,N=0,R=[],B=[],O=[],$=[];Object.freeze($);let z;function F(){return R}o(F,"getPossiblePatternsSlow");function V(Y){let ae=Xu(Y),J=B[ae];return J===void 0?$:J}o(V,"getPossiblePatternsOptimized");let H=o(Y=>{if(O.length===1&&Y.tokenType.PUSH_MODE===void 0){let ae=this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(Y);L.push({offset:Y.startOffset,line:Y.startLine,column:Y.startColumn,length:Y.image.length,message:ae})}else{O.pop();let ae=Na(O);R=this.patternIdxToConfig[ae],B=this.charCodeToPatternIdxToConfig[ae],N=R.length;let J=this.canModeBeOptimized[ae]&&this.config.safeMode===!1;B&&J?z=V:z=F}},"pop_mode");function X(Y){O.push(Y),B=this.charCodeToPatternIdxToConfig[Y],R=this.patternIdxToConfig[Y],N=R.length,N=R.length;let ae=this.canModeBeOptimized[Y]&&this.config.safeMode===!1;B&&ae?z=V:z=F}o(X,"push_mode"),X.call(this,r);let W,Z=this.config.recoveryEnabled;for(;ku.length){u=s,h=f,W=be;break}}}break}}if(u!==null){if(d=u.length,p=W.group,p!==void 0&&(m=W.tokenTypeIdx,g=this.createTokenInstance(u,k,m,W.tokenType,M,I,d),this.handlePayload(g,h),p===!1?C=this.addToken(S,C,g):A[p].push(g)),e=this.chopInput(e,d),k=k+d,I=this.computeNewColumn(I,d),_===!0&&W.canLineTerminator===!0){let ee=0,re,te;D.lastIndex=0;do re=D.test(u),re===!0&&(te=D.lastIndex-1,ee++);while(re===!0);ee!==0&&(M=M+ee,I=d-te,this.updateTokenEndLineColumnLocation(g,p,te,ee,M,I,d))}this.handleModes(W,H,X,g)}else{let ee=k,re=M,te=I,be=Z===!1;for(;be===!1&&k{"use strict";nr();JT();_m();o(uf,"tokenLabel");o(M$,"hasTokenLabel");uat="parent",Nve="categories",Ive="label",Mve="group",Ove="push_mode",Pve="pop_mode",Bve="longer_alt",Fve="line_breaks",$ve="start_chars_hint";o(np,"createToken");o(hat,"createTokenInternal");cl=np({name:"EOF",pattern:yn.NA});cf([cl]);o(hf,"createTokenInstance");o(tk,"tokenMatcher")});var ff,zve,qc,Xy=P(()=>{"use strict";Dm();nr();Zs();ff={buildMismatchTokenMessage({expected:t,actual:e,previous:r,ruleName:i}){return`Expecting ${M$(t)?`--> ${uf(t)} <--`:`token of type --> ${t.name} <--`} but found --> '${e.image}' <--`},buildNotAllInputParsedMessage({firstRedundant:t,ruleName:e}){return"Redundant input, expecting EOF but found: "+t.image},buildNoViableAltMessage({expectedPathsPerAlt:t,actual:e,previous:r,customUserDescription:i,ruleName:n}){let a="Expecting: ",l=` +but found: '`+Ia(e).image+"'";if(i)return a+i+l;{let u=mi(t,(p,m)=>p.concat(m),[]),h=ht(u,p=>`[${ht(p,m=>uf(m)).join(", ")}]`),d=`one of these possible Token sequences: +${ht(h,(p,m)=>` ${m+1}. ${p}`).join(` +`)}`;return a+d+l}},buildEarlyExitMessage({expectedIterationPaths:t,actual:e,customUserDescription:r,ruleName:i}){let n="Expecting: ",s=` +but found: '`+Ia(e).image+"'";if(r)return n+r+s;{let u=`expecting at least one iteration which starts with one of these possible Token sequences:: + <${ht(t,h=>`[${ht(h,f=>uf(f)).join(",")}]`).join(" ,")}>`;return n+u+s}}};Object.freeze(ff);zve={buildRuleNotFoundError(t,e){return"Invalid grammar, reference to a rule which is not defined: ->"+e.nonTerminalName+`<- +inside top level rule: ->`+t.name+"<-"}},qc={buildDuplicateFoundError(t,e){function r(f){return f instanceof Xr?f.terminalType.name:f instanceof Li?f.nonTerminalName:""}o(r,"getExtraProductionArgument");let i=t.name,n=Ia(e),a=n.idx,s=Mo(n),l=r(n),u=a>0,h=`->${s}${u?a:""}<- ${l?`with argument: ->${l}<-`:""} + appears more than once (${e.length} times) in the top level rule: ->${i}<-. + For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES + `;return h=h.replace(/[ \t]+/g," "),h=h.replace(/\s\s+/g,` +`),h},buildNamespaceConflictError(t){return`Namespace conflict found in grammar. +The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${t.name}>. +To resolve this make sure each Terminal and Non-Terminal names are unique +This is easy to accomplish by using the convention that Terminal names start with an uppercase letter +and Non-Terminal names start with a lower case letter.`},buildAlternationPrefixAmbiguityError(t){let e=ht(t.prefixPath,n=>uf(n)).join(", "),r=t.alternation.idx===0?"":t.alternation.idx;return`Ambiguous alternatives: <${t.ambiguityIndices.join(" ,")}> due to common lookahead prefix +in inside <${t.topLevelRule.name}> Rule, +<${e}> may appears as a prefix path in all these alternatives. +See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX +For Further details.`},buildAlternationAmbiguityError(t){let e=ht(t.prefixPath,n=>uf(n)).join(", "),r=t.alternation.idx===0?"":t.alternation.idx,i=`Ambiguous Alternatives Detected: <${t.ambiguityIndices.join(" ,")}> in inside <${t.topLevelRule.name}> Rule, +<${e}> may appears as a prefix path in all these alternatives. +`;return i=i+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES +For Further details.`,i},buildEmptyRepetitionError(t){let e=Mo(t.repetition);return t.repetition.idx!==0&&(e+=t.repetition.idx),`The repetition <${e}> within Rule <${t.topLevelRule.name}> can never consume any tokens. +This could lead to an infinite loop.`},buildTokenNameError(t){return"deprecated"},buildEmptyAlternationError(t){return`Ambiguous empty alternative: <${t.emptyChoiceIdx+1}> in inside <${t.topLevelRule.name}> Rule. +Only the last alternative may be an empty alternative.`},buildTooManyAlternativesError(t){return`An Alternation cannot have more than 256 alternatives: + inside <${t.topLevelRule.name}> Rule. + has ${t.alternation.definition.length+1} alternatives.`},buildLeftRecursionError(t){let e=t.topLevelRule.name,r=ht(t.leftRecursionPath,a=>a.name),i=`${e} --> ${r.concat([e]).join(" --> ")}`;return`Left Recursion found in grammar. +rule: <${e}> can be invoked from itself (directly or indirectly) +without consuming any Tokens. The grammar path that causes this is: + ${i} + To fix this refactor your grammar to remove the left recursion. +see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`},buildInvalidRuleNameError(t){return"deprecated"},buildDuplicateRuleNameError(t){let e;return t.topLevelRule instanceof Ks?e=t.topLevelRule.name:e=t.topLevelRule,`Duplicate definition, rule: ->${e}<- is already defined in the grammar: ->${t.grammarName}<-`}}});function Gve(t,e){let r=new O$(t,e);return r.resolveRefs(),r.errors}var O$,Vve=P(()=>{"use strict";Oo();nr();Zs();o(Gve,"resolveGrammar");O$=class extends Qs{static{o(this,"GastRefResolverVisitor")}constructor(e,r){super(),this.nameToTopRule=e,this.errMsgProvider=r,this.errors=[]}resolveRefs(){Pe(qr(this.nameToTopRule),e=>{this.currTopLevel=e,e.accept(this)})}visitNonTerminal(e){let r=this.nameToTopRule[e.nonTerminalName];if(r)e.referencedRule=r;else{let i=this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel,e);this.errors.push({message:i,type:ya.UNRESOLVED_SUBRULE_REF,ruleName:this.currTopLevel.name,unresolvedRefName:e.nonTerminalName})}}}});function P6(t,e,r=[]){r=Si(r);let i=[],n=0;function a(l){return l.concat(zn(t,n+1))}o(a,"remainingPathWith");function s(l){let u=P6(a(l),e,r);return i.concat(u)}for(o(s,"getAlternativesForProd");r.length{_r(u.definition)===!1&&(i=s(u.definition))}),i;if(l instanceof Xr)r.push(l.terminalType);else throw Error("non exhaustive match")}n++}return i.push({partialPath:r,suffixDef:zn(t,n)}),i}function B6(t,e,r,i){let n="EXIT_NONE_TERMINAL",a=[n],s="EXIT_ALTERNATIVE",l=!1,u=e.length,h=u-i-1,f=[],d=[];for(d.push({idx:-1,def:t,ruleStack:[],occurrenceStack:[]});!_r(d);){let p=d.pop();if(p===s){l&&Na(d).idx<=h&&d.pop();continue}let m=p.def,g=p.idx,y=p.ruleStack,v=p.occurrenceStack;if(_r(m))continue;let x=m[0];if(x===n){let b={idx:g,def:zn(m),ruleStack:Hh(y),occurrenceStack:Hh(v)};d.push(b)}else if(x instanceof Xr)if(g=0;b--){let T=x.definition[b],w={idx:g,def:T.definition.concat(zn(m)),ruleStack:y,occurrenceStack:v};d.push(w),d.push(s)}else if(x instanceof en)d.push({idx:g,def:x.definition.concat(zn(m)),ruleStack:y,occurrenceStack:v});else if(x instanceof Ks)d.push(fat(x,g,y,v));else throw Error("non exhaustive match")}return f}function fat(t,e,r,i){let n=Si(r);n.push(t.name);let a=Si(i);return a.push(1),{idx:e,def:t.definition,ruleStack:n,occurrenceStack:a}}var P$,I6,Ky,M6,rk,O6,ik,nk=P(()=>{"use strict";nr();C$();E6();Zs();P$=class extends of{static{o(this,"AbstractNextPossibleTokensWalker")}constructor(e,r){super(),this.topProd=e,this.path=r,this.possibleTokTypes=[],this.nextProductionName="",this.nextProductionOccurrence=0,this.found=!1,this.isAtEndOfPath=!1}startWalking(){if(this.found=!1,this.path.ruleStack[0]!==this.topProd.name)throw Error("The path does not start with the walker's top Rule!");return this.ruleStack=Si(this.path.ruleStack).reverse(),this.occurrenceStack=Si(this.path.occurrenceStack).reverse(),this.ruleStack.pop(),this.occurrenceStack.pop(),this.updateExpectedNext(),this.walk(this.topProd),this.possibleTokTypes}walk(e,r=[]){this.found||super.walk(e,r)}walkProdRef(e,r,i){if(e.referencedRule.name===this.nextProductionName&&e.idx===this.nextProductionOccurrence){let n=r.concat(i);this.updateExpectedNext(),this.walk(e.referencedRule,n)}}updateExpectedNext(){_r(this.ruleStack)?(this.nextProductionName="",this.nextProductionOccurrence=0,this.isAtEndOfPath=!0):(this.nextProductionName=this.ruleStack.pop(),this.nextProductionOccurrence=this.occurrenceStack.pop())}},I6=class extends P${static{o(this,"NextAfterTokenWalker")}constructor(e,r){super(e,r),this.path=r,this.nextTerminalName="",this.nextTerminalOccurrence=0,this.nextTerminalName=this.path.lastTok.name,this.nextTerminalOccurrence=this.path.lastTokOccurrence}walkTerminal(e,r,i){if(this.isAtEndOfPath&&e.terminalType.name===this.nextTerminalName&&e.idx===this.nextTerminalOccurrence&&!this.found){let n=r.concat(i),a=new en({definition:n});this.possibleTokTypes=Sm(a),this.found=!0}}},Ky=class extends of{static{o(this,"AbstractNextTerminalAfterProductionWalker")}constructor(e,r){super(),this.topRule=e,this.occurrence=r,this.result={token:void 0,occurrence:void 0,isEndOfRule:void 0}}startWalking(){return this.walk(this.topRule),this.result}},M6=class extends Ky{static{o(this,"NextTerminalAfterManyWalker")}walkMany(e,r,i){if(e.idx===this.occurrence){let n=Ia(r.concat(i));this.result.isEndOfRule=n===void 0,n instanceof Xr&&(this.result.token=n.terminalType,this.result.occurrence=n.idx)}else super.walkMany(e,r,i)}},rk=class extends Ky{static{o(this,"NextTerminalAfterManySepWalker")}walkManySep(e,r,i){if(e.idx===this.occurrence){let n=Ia(r.concat(i));this.result.isEndOfRule=n===void 0,n instanceof Xr&&(this.result.token=n.terminalType,this.result.occurrence=n.idx)}else super.walkManySep(e,r,i)}},O6=class extends Ky{static{o(this,"NextTerminalAfterAtLeastOneWalker")}walkAtLeastOne(e,r,i){if(e.idx===this.occurrence){let n=Ia(r.concat(i));this.result.isEndOfRule=n===void 0,n instanceof Xr&&(this.result.token=n.terminalType,this.result.occurrence=n.idx)}else super.walkAtLeastOne(e,r,i)}},ik=class extends Ky{static{o(this,"NextTerminalAfterAtLeastOneSepWalker")}walkAtLeastOneSep(e,r,i){if(e.idx===this.occurrence){let n=Ia(r.concat(i));this.result.isEndOfRule=n===void 0,n instanceof Xr&&(this.result.token=n.terminalType,this.result.occurrence=n.idx)}else super.walkAtLeastOneSep(e,r,i)}};o(P6,"possiblePathsFrom");o(B6,"nextPossibleTokensAfter");o(fat,"expandTopLevelRule")});function ak(t){if(t instanceof Ri||t==="Option")return vn.OPTION;if(t instanceof ti||t==="Repetition")return vn.REPETITION;if(t instanceof tn||t==="RepetitionMandatory")return vn.REPETITION_MANDATORY;if(t instanceof rn||t==="RepetitionMandatoryWithSeparator")return vn.REPETITION_MANDATORY_WITH_SEPARATOR;if(t instanceof Wi||t==="RepetitionWithSeparator")return vn.REPETITION_WITH_SEPARATOR;if(t instanceof Ui||t==="Alternation")return vn.ALTERNATION;throw Error("non exhaustive match")}function $6(t){let{occurrence:e,rule:r,prodType:i,maxLookahead:n}=t,a=ak(i);return a===vn.ALTERNATION?Qy(e,r,n):Zy(e,r,a,n)}function Wve(t,e,r,i,n,a){let s=Qy(t,e,r),l=Kve(s)?Yy:lf;return a(s,i,l,n)}function Uve(t,e,r,i,n,a){let s=Zy(t,e,n,r),l=Kve(s)?Yy:lf;return a(s[0],l,i)}function Hve(t,e,r,i){let n=t.length,a=ms(t,s=>ms(s,l=>l.length===1));if(e)return function(s){let l=ht(s,u=>u.GATE);for(let u=0;udi(u)),l=mi(s,(u,h,f)=>(Pe(h,d=>{Vt(u,d.tokenTypeIdx)||(u[d.tokenTypeIdx]=f),Pe(d.categoryMatches,p=>{Vt(u,p)||(u[p]=f)})}),u),{});return function(){let u=this.LA(1);return l[u.tokenTypeIdx]}}else return function(){for(let s=0;sa.length===1),n=t.length;if(i&&!r){let a=di(t);if(a.length===1&&_r(a[0].categoryMatches)){let l=a[0].tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===l}}else{let s=mi(a,(l,u,h)=>(l[u.tokenTypeIdx]=!0,Pe(u.categoryMatches,f=>{l[f]=!0}),l),[]);return function(){let l=this.LA(1);return s[l.tokenTypeIdx]===!0}}}else return function(){e:for(let a=0;aP6([s],1)),i=qve(r.length),n=ht(r,s=>{let l={};return Pe(s,u=>{let h=B$(u.partialPath);Pe(h,f=>{l[f]=!0})}),l}),a=r;for(let s=1;s<=e;s++){let l=a;a=qve(l.length);for(let u=0;u{let x=B$(v.partialPath);Pe(x,b=>{n[u][b]=!0})})}}}}return i}function Qy(t,e,r,i){let n=new F6(t,vn.ALTERNATION,i);return e.accept(n),jve(n.result,r)}function Zy(t,e,r,i){let n=new F6(t,r);e.accept(n);let a=n.result,l=new F$(e,t,r).startWalking(),u=new en({definition:a}),h=new en({definition:l});return jve([u,h],i)}function z6(t,e){e:for(let r=0;r{let n=e[i];return r===n||n.categoryMatchesMap[r.tokenTypeIdx]})}function Kve(t){return ms(t,e=>ms(e,r=>ms(r,i=>_r(i.categoryMatches))))}var vn,F$,F6,Jy=P(()=>{"use strict";nr();nk();E6();_m();Zs();(function(t){t[t.OPTION=0]="OPTION",t[t.REPETITION=1]="REPETITION",t[t.REPETITION_MANDATORY=2]="REPETITION_MANDATORY",t[t.REPETITION_MANDATORY_WITH_SEPARATOR=3]="REPETITION_MANDATORY_WITH_SEPARATOR",t[t.REPETITION_WITH_SEPARATOR=4]="REPETITION_WITH_SEPARATOR",t[t.ALTERNATION=5]="ALTERNATION"})(vn||(vn={}));o(ak,"getProdType");o($6,"getLookaheadPaths");o(Wve,"buildLookaheadFuncForOr");o(Uve,"buildLookaheadFuncForOptionalProd");o(Hve,"buildAlternativesLookAheadFunc");o(Yve,"buildSingleAlternativeLookaheadFunction");F$=class extends of{static{o(this,"RestDefinitionFinderWalker")}constructor(e,r,i){super(),this.topProd=e,this.targetOccurrence=r,this.targetProdType=i}startWalking(){return this.walk(this.topProd),this.restDef}checkIsTarget(e,r,i,n){return e.idx===this.targetOccurrence&&this.targetProdType===r?(this.restDef=i.concat(n),!0):!1}walkOption(e,r,i){this.checkIsTarget(e,vn.OPTION,r,i)||super.walkOption(e,r,i)}walkAtLeastOne(e,r,i){this.checkIsTarget(e,vn.REPETITION_MANDATORY,r,i)||super.walkOption(e,r,i)}walkAtLeastOneSep(e,r,i){this.checkIsTarget(e,vn.REPETITION_MANDATORY_WITH_SEPARATOR,r,i)||super.walkOption(e,r,i)}walkMany(e,r,i){this.checkIsTarget(e,vn.REPETITION,r,i)||super.walkOption(e,r,i)}walkManySep(e,r,i){this.checkIsTarget(e,vn.REPETITION_WITH_SEPARATOR,r,i)||super.walkOption(e,r,i)}},F6=class extends Qs{static{o(this,"InsideDefinitionFinderVisitor")}constructor(e,r,i){super(),this.targetOccurrence=e,this.targetProdType=r,this.targetRef=i,this.result=[]}checkIsTarget(e,r){e.idx===this.targetOccurrence&&this.targetProdType===r&&(this.targetRef===void 0||e===this.targetRef)&&(this.result=e.definition)}visitOption(e){this.checkIsTarget(e,vn.OPTION)}visitRepetition(e){this.checkIsTarget(e,vn.REPETITION)}visitRepetitionMandatory(e){this.checkIsTarget(e,vn.REPETITION_MANDATORY)}visitRepetitionMandatoryWithSeparator(e){this.checkIsTarget(e,vn.REPETITION_MANDATORY_WITH_SEPARATOR)}visitRepetitionWithSeparator(e){this.checkIsTarget(e,vn.REPETITION_WITH_SEPARATOR)}visitAlternation(e){this.checkIsTarget(e,vn.ALTERNATION)}};o(qve,"initializeArrayOfArrays");o(B$,"pathToHashKeys");o(dat,"isUniquePrefixHash");o(jve,"lookAheadSequenceFromAlternatives");o(Qy,"getLookaheadPathsForOr");o(Zy,"getLookaheadPathsForOptionalProd");o(z6,"containsPath");o(Xve,"isStrictPrefixOfPath");o(Kve,"areTokenCategoriesNotUsed")});function Qve(t){let e=t.lookaheadStrategy.validate({rules:t.rules,tokenTypes:t.tokenTypes,grammarName:t.grammarName});return ht(e,r=>Object.assign({type:ya.CUSTOM_LOOKAHEAD_VALIDATION},r))}function Zve(t,e,r,i){let n=Ja(t,u=>pat(u,r)),a=bat(t,e,r),s=Ja(t,u=>yat(u,r)),l=Ja(t,u=>gat(u,t,i,r));return n.concat(a,s,l)}function pat(t,e){let r=new $$;t.accept(r);let i=r.allProductions,n=hO(i,mat),a=Ao(n,l=>l.length>1);return ht(qr(a),l=>{let u=Ia(l),h=e.buildDuplicateFoundError(t,l),f=Mo(u),d={message:h,type:ya.DUPLICATE_PRODUCTIONS,ruleName:t.name,dslName:f,occurrence:u.idx},p=Jve(u);return p&&(d.parameter=p),d})}function mat(t){return`${Mo(t)}_#_${t.idx}_#_${Jve(t)}`}function Jve(t){return t instanceof Xr?t.terminalType.name:t instanceof Li?t.nonTerminalName:""}function gat(t,e,r,i){let n=[];if(mi(e,(s,l)=>l.name===t.name?s+1:s,0)>1){let s=i.buildDuplicateRuleNameError({topLevelRule:t,grammarName:r});n.push({message:s,type:ya.DUPLICATE_RULE_NAME,ruleName:t.name})}return n}function exe(t,e,r){let i=[],n;return pn(e,t)||(n=`Invalid rule override, rule: ->${t}<- cannot be overridden in the grammar: ->${r}<-as it is not defined in any of the super grammars `,i.push({message:n,type:ya.INVALID_RULE_OVERRIDE,ruleName:t})),i}function G$(t,e,r,i=[]){let n=[],a=G6(e.definition);if(_r(a))return[];{let s=t.name;pn(a,t)&&n.push({message:r.buildLeftRecursionError({topLevelRule:t,leftRecursionPath:i}),type:ya.LEFT_RECURSION,ruleName:s});let u=bd(a,i.concat([t])),h=Ja(u,f=>{let d=Si(i);return d.push(f),G$(t,f,r,d)});return n.concat(h)}}function G6(t){let e=[];if(_r(t))return e;let r=Ia(t);if(r instanceof Li)e.push(r.referencedRule);else if(r instanceof en||r instanceof Ri||r instanceof tn||r instanceof rn||r instanceof Wi||r instanceof ti)e=e.concat(G6(r.definition));else if(r instanceof Ui)e=di(ht(r.definition,a=>G6(a.definition)));else if(!(r instanceof Xr))throw Error("non exhaustive match");let i=Em(r),n=t.length>1;if(i&&n){let a=zn(t);return e.concat(G6(a))}else return e}function txe(t,e){let r=new sk;t.accept(r);let i=r.alternations;return Ja(i,a=>{let s=Hh(a.definition);return Ja(s,(l,u)=>{let h=B6([l],[],lf,1);return _r(h)?[{message:e.buildEmptyAlternationError({topLevelRule:t,alternation:a,emptyChoiceIdx:u}),type:ya.NONE_LAST_EMPTY_ALT,ruleName:t.name,occurrence:a.idx,alternative:u+1}]:[]})})}function rxe(t,e,r){let i=new sk;t.accept(i);let n=i.alternations;return n=Td(n,s=>s.ignoreAmbiguities===!0),Ja(n,s=>{let l=s.idx,u=s.maxLookahead||e,h=Qy(l,t,u,s),f=vat(h,s,t,r),d=xat(h,s,t,r);return f.concat(d)})}function yat(t,e){let r=new sk;t.accept(r);let i=r.alternations;return Ja(i,a=>a.definition.length>255?[{message:e.buildTooManyAlternativesError({topLevelRule:t,alternation:a}),type:ya.TOO_MANY_ALTS,ruleName:t.name,occurrence:a.idx}]:[])}function ixe(t,e,r){let i=[];return Pe(t,n=>{let a=new z$;n.accept(a);let s=a.allProductions;Pe(s,l=>{let u=ak(l),h=l.maxLookahead||e,f=l.idx,p=Zy(f,n,u,h)[0];if(_r(di(p))){let m=r.buildEmptyRepetitionError({topLevelRule:n,repetition:l});i.push({message:m,type:ya.NO_NON_EMPTY_LOOKAHEAD,ruleName:n.name})}})}),i}function vat(t,e,r,i){let n=[],a=mi(t,(l,u,h)=>(e.definition[h].ignoreAmbiguities===!0||Pe(u,f=>{let d=[h];Pe(t,(p,m)=>{h!==m&&z6(p,f)&&e.definition[m].ignoreAmbiguities!==!0&&d.push(m)}),d.length>1&&!z6(n,f)&&(n.push(f),l.push({alts:d,path:f}))}),l),[]);return ht(a,l=>{let u=ht(l.alts,f=>f+1);return{message:i.buildAlternationAmbiguityError({topLevelRule:r,alternation:e,ambiguityIndices:u,prefixPath:l.path}),type:ya.AMBIGUOUS_ALTS,ruleName:r.name,occurrence:e.idx,alternatives:l.alts}})}function xat(t,e,r,i){let n=mi(t,(s,l,u)=>{let h=ht(l,f=>({idx:u,path:f}));return s.concat(h)},[]);return Ru(Ja(n,s=>{if(e.definition[s.idx].ignoreAmbiguities===!0)return[];let u=s.idx,h=s.path,f=pi(n,p=>e.definition[p.idx].ignoreAmbiguities!==!0&&p.idx{let m=[p.idx+1,u+1],g=e.idx===0?"":e.idx;return{message:i.buildAlternationPrefixAmbiguityError({topLevelRule:r,alternation:e,ambiguityIndices:m,prefixPath:p.path}),type:ya.AMBIGUOUS_PREFIX_ALTS,ruleName:r.name,occurrence:g,alternatives:m}})}))}function bat(t,e,r){let i=[],n=ht(e,a=>a.name);return Pe(t,a=>{let s=a.name;if(pn(n,s)){let l=r.buildNamespaceConflictError(a);i.push({message:l,type:ya.CONFLICT_TOKENS_RULES_NAMESPACE,ruleName:s})}}),i}var $$,sk,z$,ok=P(()=>{"use strict";nr();Oo();Zs();Jy();nk();_m();o(Qve,"validateLookahead");o(Zve,"validateGrammar");o(pat,"validateDuplicateProductions");o(mat,"identifyProductionForDuplicates");o(Jve,"getExtraProductionArgument");$$=class extends Qs{static{o(this,"OccurrenceValidationCollector")}constructor(){super(...arguments),this.allProductions=[]}visitNonTerminal(e){this.allProductions.push(e)}visitOption(e){this.allProductions.push(e)}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}visitAlternation(e){this.allProductions.push(e)}visitTerminal(e){this.allProductions.push(e)}};o(gat,"validateRuleDoesNotAlreadyExist");o(exe,"validateRuleIsOverridden");o(G$,"validateNoLeftRecursion");o(G6,"getFirstNoneTerminal");sk=class extends Qs{static{o(this,"OrCollector")}constructor(){super(...arguments),this.alternations=[]}visitAlternation(e){this.alternations.push(e)}};o(txe,"validateEmptyOrAlternative");o(rxe,"validateAmbiguousAlternationAlternatives");z$=class extends Qs{static{o(this,"RepetitionCollector")}constructor(){super(...arguments),this.allProductions=[]}visitRepetitionWithSeparator(e){this.allProductions.push(e)}visitRepetitionMandatory(e){this.allProductions.push(e)}visitRepetitionMandatoryWithSeparator(e){this.allProductions.push(e)}visitRepetition(e){this.allProductions.push(e)}};o(yat,"validateTooManyAlts");o(ixe,"validateSomeNonEmptyLookaheadPath");o(vat,"checkAlternativesAmbiguities");o(xat,"checkPrefixAlternativesAmbiguities");o(bat,"checkTerminalAndNoneTerminalsNameSpace")});function nxe(t){let e=xd(t,{errMsgProvider:zve}),r={};return Pe(t.rules,i=>{r[i.name]=i}),Gve(r,e.errMsgProvider)}function axe(t){return t=xd(t,{errMsgProvider:qc}),Zve(t.rules,t.tokenTypes,t.errMsgProvider,t.grammarName)}var sxe=P(()=>{"use strict";nr();Vve();ok();Xy();o(nxe,"resolveGrammar");o(axe,"validateGrammar")});function ap(t){return pn(hxe,t.name)}var oxe,lxe,cxe,uxe,hxe,ev,Lm,lk,ck,uk,tv=P(()=>{"use strict";nr();oxe="MismatchedTokenException",lxe="NoViableAltException",cxe="EarlyExitException",uxe="NotAllInputParsedException",hxe=[oxe,lxe,cxe,uxe];Object.freeze(hxe);o(ap,"isRecognitionException");ev=class extends Error{static{o(this,"RecognitionException")}constructor(e,r){super(e),this.token=r,this.resyncedTokens=[],Object.setPrototypeOf(this,new.target.prototype),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},Lm=class extends ev{static{o(this,"MismatchedTokenException")}constructor(e,r,i){super(e,r),this.previousToken=i,this.name=oxe}},lk=class extends ev{static{o(this,"NoViableAltException")}constructor(e,r,i){super(e,r),this.previousToken=i,this.name=lxe}},ck=class extends ev{static{o(this,"NotAllInputParsedException")}constructor(e,r){super(e,r),this.name=uxe}},uk=class extends ev{static{o(this,"EarlyExitException")}constructor(e,r,i){super(e,r),this.previousToken=i,this.name=cxe}}});function Tat(t,e,r,i,n,a,s){let l=this.getKeyForAutomaticLookahead(i,n),u=this.firstAfterRepMap[l];if(u===void 0){let p=this.getCurrRuleFullName(),m=this.getGAstProductions()[p];u=new a(m,n).startWalking(),this.firstAfterRepMap[l]=u}let h=u.token,f=u.occurrence,d=u.isEndOfRule;this.RULE_STACK.length===1&&d&&h===void 0&&(h=cl,f=1),!(h===void 0||f===void 0)&&this.shouldInRepetitionRecoveryBeTried(h,f,s)&&this.tryInRepetitionRecovery(t,e,r,h)}var V$,W$,q$,V6,U$=P(()=>{"use strict";Dm();nr();tv();w$();Oo();V$={},W$="InRuleRecoveryException",q$=class extends Error{static{o(this,"InRuleRecoveryException")}constructor(e){super(e),this.name=W$}},V6=class{static{o(this,"Recoverable")}initRecoverable(e){this.firstAfterRepMap={},this.resyncFollows={},this.recoveryEnabled=Vt(e,"recoveryEnabled")?e.recoveryEnabled:Js.recoveryEnabled,this.recoveryEnabled&&(this.attemptInRepetitionRecovery=Tat)}getTokenToInsert(e){let r=hf(e,"",NaN,NaN,NaN,NaN,NaN,NaN);return r.isInsertedInRecovery=!0,r}canTokenTypeBeInsertedInRecovery(e){return!0}canTokenTypeBeDeletedInRecovery(e){return!0}tryInRepetitionRecovery(e,r,i,n){let a=this.findReSyncTokenType(),s=this.exportLexerState(),l=[],u=!1,h=this.LA(1),f=this.LA(1),d=o(()=>{let p=this.LA(0),m=this.errorMessageProvider.buildMismatchTokenMessage({expected:n,actual:h,previous:p,ruleName:this.getCurrRuleFullName()}),g=new Lm(m,h,this.LA(0));g.resyncedTokens=Hh(l),this.SAVE_ERROR(g)},"generateErrorMessage");for(;!u;)if(this.tokenMatcher(f,n)){d();return}else if(i.call(this)){d(),e.apply(this,r);return}else this.tokenMatcher(f,a)?u=!0:(f=this.SKIP_TOKEN(),this.addToResyncTokens(f,l));this.importLexerState(s)}shouldInRepetitionRecoveryBeTried(e,r,i){return!(i===!1||this.tokenMatcher(this.LA(1),e)||this.isBackTracking()||this.canPerformInRuleRecovery(e,this.getFollowsForInRuleRecovery(e,r)))}getFollowsForInRuleRecovery(e,r){let i=this.getCurrentGrammarPath(e,r);return this.getNextPossibleTokenTypes(i)}tryInRuleRecovery(e,r){if(this.canRecoverWithSingleTokenInsertion(e,r))return this.getTokenToInsert(e);if(this.canRecoverWithSingleTokenDeletion(e)){let i=this.SKIP_TOKEN();return this.consumeToken(),i}throw new q$("sad sad panda")}canPerformInRuleRecovery(e,r){return this.canRecoverWithSingleTokenInsertion(e,r)||this.canRecoverWithSingleTokenDeletion(e)}canRecoverWithSingleTokenInsertion(e,r){if(!this.canTokenTypeBeInsertedInRecovery(e)||_r(r))return!1;let i=this.LA(1);return qs(r,a=>this.tokenMatcher(i,a))!==void 0}canRecoverWithSingleTokenDeletion(e){return this.canTokenTypeBeDeletedInRecovery(e)?this.tokenMatcher(this.LA(2),e):!1}isInCurrentRuleReSyncSet(e){let r=this.getCurrFollowKey(),i=this.getFollowSetFromFollowKey(r);return pn(i,e)}findReSyncTokenType(){let e=this.flattenFollowSet(),r=this.LA(1),i=2;for(;;){let n=qs(e,a=>tk(r,a));if(n!==void 0)return n;r=this.LA(i),i++}}getCurrFollowKey(){if(this.RULE_STACK.length===1)return V$;let e=this.getLastExplicitRuleShortName(),r=this.getLastExplicitRuleOccurrenceIndex(),i=this.getPreviousExplicitRuleShortName();return{ruleName:this.shortRuleNameToFullName(e),idxInCallingRule:r,inRule:this.shortRuleNameToFullName(i)}}buildFullFollowKeyStack(){let e=this.RULE_STACK,r=this.RULE_OCCURRENCE_STACK;return ht(e,(i,n)=>n===0?V$:{ruleName:this.shortRuleNameToFullName(i),idxInCallingRule:r[n],inRule:this.shortRuleNameToFullName(e[n-1])})}flattenFollowSet(){let e=ht(this.buildFullFollowKeyStack(),r=>this.getFollowSetFromFollowKey(r));return di(e)}getFollowSetFromFollowKey(e){if(e===V$)return[cl];let r=e.ruleName+e.idxInCallingRule+S6+e.inRule;return this.resyncFollows[r]}addToResyncTokens(e,r){return this.tokenMatcher(e,cl)||r.push(e),r}reSyncTo(e){let r=[],i=this.LA(1);for(;this.tokenMatcher(i,e)===!1;)i=this.SKIP_TOKEN(),this.addToResyncTokens(i,r);return Hh(r)}attemptInRepetitionRecovery(e,r,i,n,a,s,l){}getCurrentGrammarPath(e,r){let i=this.getHumanReadableRuleStack(),n=Si(this.RULE_OCCURRENCE_STACK);return{ruleStack:i,occurrenceStack:n,lastTok:e,lastTokOccurrence:r}}getHumanReadableRuleStack(){return ht(this.RULE_STACK,e=>this.shortRuleNameToFullName(e))}};o(Tat,"attemptInRepetitionRecovery")});function q6(t,e,r){return r|e|t}var W6=P(()=>{"use strict";o(q6,"getKeyForAutomaticLookahead")});var df,H$=P(()=>{"use strict";nr();Xy();Oo();ok();Jy();df=class{static{o(this,"LLkLookaheadStrategy")}constructor(e){var r;this.maxLookahead=(r=e?.maxLookahead)!==null&&r!==void 0?r:Js.maxLookahead}validate(e){let r=this.validateNoLeftRecursion(e.rules);if(_r(r)){let i=this.validateEmptyOrAlternatives(e.rules),n=this.validateAmbiguousAlternationAlternatives(e.rules,this.maxLookahead),a=this.validateSomeNonEmptyLookaheadPath(e.rules,this.maxLookahead);return[...r,...i,...n,...a]}return r}validateNoLeftRecursion(e){return Ja(e,r=>G$(r,r,qc))}validateEmptyOrAlternatives(e){return Ja(e,r=>txe(r,qc))}validateAmbiguousAlternationAlternatives(e,r){return Ja(e,i=>rxe(i,r,qc))}validateSomeNonEmptyLookaheadPath(e,r){return ixe(e,r,qc)}buildLookaheadForAlternation(e){return Wve(e.prodOccurrence,e.rule,e.maxLookahead,e.hasPredicates,e.dynamicTokensEnabled,Hve)}buildLookaheadForOptional(e){return Uve(e.prodOccurrence,e.rule,e.maxLookahead,e.dynamicTokensEnabled,ak(e.prodType),Yve)}}});function kat(t){U6.reset(),t.accept(U6);let e=U6.dslMethods;return U6.reset(),e}var H6,Y$,U6,fxe=P(()=>{"use strict";nr();Oo();W6();Zs();H$();H6=class{static{o(this,"LooksAhead")}initLooksAhead(e){this.dynamicTokensEnabled=Vt(e,"dynamicTokensEnabled")?e.dynamicTokensEnabled:Js.dynamicTokensEnabled,this.maxLookahead=Vt(e,"maxLookahead")?e.maxLookahead:Js.maxLookahead,this.lookaheadStrategy=Vt(e,"lookaheadStrategy")?e.lookaheadStrategy:new df({maxLookahead:this.maxLookahead}),this.lookAheadFuncsCache=new Map}preComputeLookaheadFunctions(e){Pe(e,r=>{this.TRACE_INIT(`${r.name} Rule Lookahead`,()=>{let{alternation:i,repetition:n,option:a,repetitionMandatory:s,repetitionMandatoryWithSeparator:l,repetitionWithSeparator:u}=kat(r);Pe(i,h=>{let f=h.idx===0?"":h.idx;this.TRACE_INIT(`${Mo(h)}${f}`,()=>{let d=this.lookaheadStrategy.buildLookaheadForAlternation({prodOccurrence:h.idx,rule:r,maxLookahead:h.maxLookahead||this.maxLookahead,hasPredicates:h.hasPredicates,dynamicTokensEnabled:this.dynamicTokensEnabled}),p=q6(this.fullRuleNameToShort[r.name],256,h.idx);this.setLaFuncCache(p,d)})}),Pe(n,h=>{this.computeLookaheadFunc(r,h.idx,768,"Repetition",h.maxLookahead,Mo(h))}),Pe(a,h=>{this.computeLookaheadFunc(r,h.idx,512,"Option",h.maxLookahead,Mo(h))}),Pe(s,h=>{this.computeLookaheadFunc(r,h.idx,1024,"RepetitionMandatory",h.maxLookahead,Mo(h))}),Pe(l,h=>{this.computeLookaheadFunc(r,h.idx,1536,"RepetitionMandatoryWithSeparator",h.maxLookahead,Mo(h))}),Pe(u,h=>{this.computeLookaheadFunc(r,h.idx,1280,"RepetitionWithSeparator",h.maxLookahead,Mo(h))})})})}computeLookaheadFunc(e,r,i,n,a,s){this.TRACE_INIT(`${s}${r===0?"":r}`,()=>{let l=this.lookaheadStrategy.buildLookaheadForOptional({prodOccurrence:r,rule:e,maxLookahead:a||this.maxLookahead,dynamicTokensEnabled:this.dynamicTokensEnabled,prodType:n}),u=q6(this.fullRuleNameToShort[e.name],i,r);this.setLaFuncCache(u,l)})}getKeyForAutomaticLookahead(e,r){let i=this.getLastExplicitRuleShortName();return q6(i,e,r)}getLaFuncFromCache(e){return this.lookAheadFuncsCache.get(e)}setLaFuncCache(e,r){this.lookAheadFuncsCache.set(e,r)}},Y$=class extends Qs{static{o(this,"DslMethodsCollectorVisitor")}constructor(){super(...arguments),this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}reset(){this.dslMethods={option:[],alternation:[],repetition:[],repetitionWithSeparator:[],repetitionMandatory:[],repetitionMandatoryWithSeparator:[]}}visitOption(e){this.dslMethods.option.push(e)}visitRepetitionWithSeparator(e){this.dslMethods.repetitionWithSeparator.push(e)}visitRepetitionMandatory(e){this.dslMethods.repetitionMandatory.push(e)}visitRepetitionMandatoryWithSeparator(e){this.dslMethods.repetitionMandatoryWithSeparator.push(e)}visitRepetition(e){this.dslMethods.repetition.push(e)}visitAlternation(e){this.dslMethods.alternation.push(e)}},U6=new Y$;o(kat,"collectMethods")});function K$(t,e){isNaN(t.startOffset)===!0?(t.startOffset=e.startOffset,t.endOffset=e.endOffset):t.endOffset{"use strict";o(K$,"setNodeLocationOnlyOffset");o(Q$,"setNodeLocationFull");o(dxe,"addTerminalToCst");o(pxe,"addNoneTerminalToCst")});function Z$(t,e){Object.defineProperty(t,Cat,{enumerable:!1,configurable:!0,writable:!1,value:e})}var Cat,gxe=P(()=>{"use strict";Cat="name";o(Z$,"defineNameProp")});function wat(t,e){let r=ni(t),i=r.length;for(let n=0;ns.msg);throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>: + ${a.join(` + +`).replace(/\n/g,` + `)}`)}},"validateVisitor")};return r.prototype=i,r.prototype.constructor=r,r._RULE_NAMES=e,r}function vxe(t,e,r){let i=o(function(){},"derivedConstructor");Z$(i,t+"BaseSemanticsWithDefaults");let n=Object.create(r.prototype);return Pe(e,a=>{n[a]=wat}),i.prototype=n,i.prototype.constructor=i,i}function Eat(t,e){return Sat(t,e)}function Sat(t,e){let r=pi(e,n=>Qn(t[n])===!1),i=ht(r,n=>({msg:`Missing visitor method: <${n}> on ${t.constructor.name} CST Visitor.`,type:J$.MISSING_METHOD,methodName:n}));return Ru(i)}var J$,xxe=P(()=>{"use strict";nr();gxe();o(wat,"defaultVisit");o(yxe,"createBaseSemanticVisitorConstructor");o(vxe,"createBaseVisitorConstructorWithDefaults");(function(t){t[t.REDUNDANT_METHOD=0]="REDUNDANT_METHOD",t[t.MISSING_METHOD=1]="MISSING_METHOD"})(J$||(J$={}));o(Eat,"validateVisitor");o(Sat,"validateMissingCstMethods")});var K6,bxe=P(()=>{"use strict";mxe();nr();xxe();Oo();K6=class{static{o(this,"TreeBuilder")}initTreeBuilder(e){if(this.CST_STACK=[],this.outputCst=e.outputCst,this.nodeLocationTracking=Vt(e,"nodeLocationTracking")?e.nodeLocationTracking:Js.nodeLocationTracking,!this.outputCst)this.cstInvocationStateUpdate=Sn,this.cstFinallyStateUpdate=Sn,this.cstPostTerminal=Sn,this.cstPostNonTerminal=Sn,this.cstPostRule=Sn;else if(/full/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=Q$,this.setNodeLocationFromNode=Q$,this.cstPostRule=Sn,this.setInitialNodeLocation=this.setInitialNodeLocationFullRecovery):(this.setNodeLocationFromToken=Sn,this.setNodeLocationFromNode=Sn,this.cstPostRule=this.cstPostRuleFull,this.setInitialNodeLocation=this.setInitialNodeLocationFullRegular);else if(/onlyOffset/i.test(this.nodeLocationTracking))this.recoveryEnabled?(this.setNodeLocationFromToken=K$,this.setNodeLocationFromNode=K$,this.cstPostRule=Sn,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRecovery):(this.setNodeLocationFromToken=Sn,this.setNodeLocationFromNode=Sn,this.cstPostRule=this.cstPostRuleOnlyOffset,this.setInitialNodeLocation=this.setInitialNodeLocationOnlyOffsetRegular);else if(/none/i.test(this.nodeLocationTracking))this.setNodeLocationFromToken=Sn,this.setNodeLocationFromNode=Sn,this.cstPostRule=Sn,this.setInitialNodeLocation=Sn;else throw Error(`Invalid config option: "${e.nodeLocationTracking}"`)}setInitialNodeLocationOnlyOffsetRecovery(e){e.location={startOffset:NaN,endOffset:NaN}}setInitialNodeLocationOnlyOffsetRegular(e){e.location={startOffset:this.LA(1).startOffset,endOffset:NaN}}setInitialNodeLocationFullRecovery(e){e.location={startOffset:NaN,startLine:NaN,startColumn:NaN,endOffset:NaN,endLine:NaN,endColumn:NaN}}setInitialNodeLocationFullRegular(e){let r=this.LA(1);e.location={startOffset:r.startOffset,startLine:r.startLine,startColumn:r.startColumn,endOffset:NaN,endLine:NaN,endColumn:NaN}}cstInvocationStateUpdate(e){let r={name:e,children:Object.create(null)};this.setInitialNodeLocation(r),this.CST_STACK.push(r)}cstFinallyStateUpdate(){this.CST_STACK.pop()}cstPostRuleFull(e){let r=this.LA(0),i=e.location;i.startOffset<=r.startOffset?(i.endOffset=r.endOffset,i.endLine=r.endLine,i.endColumn=r.endColumn):(i.startOffset=NaN,i.startLine=NaN,i.startColumn=NaN)}cstPostRuleOnlyOffset(e){let r=this.LA(0),i=e.location;i.startOffset<=r.startOffset?i.endOffset=r.endOffset:i.startOffset=NaN}cstPostTerminal(e,r){let i=this.CST_STACK[this.CST_STACK.length-1];dxe(i,r,e),this.setNodeLocationFromToken(i.location,r)}cstPostNonTerminal(e,r){let i=this.CST_STACK[this.CST_STACK.length-1];pxe(i,r,e),this.setNodeLocationFromNode(i.location,e.location)}getBaseCstVisitorConstructor(){if(Br(this.baseCstVisitorConstructor)){let e=yxe(this.className,ni(this.gastProductionsCache));return this.baseCstVisitorConstructor=e,e}return this.baseCstVisitorConstructor}getBaseCstVisitorConstructorWithDefaults(){if(Br(this.baseCstVisitorWithDefaultsConstructor)){let e=vxe(this.className,ni(this.gastProductionsCache),this.getBaseCstVisitorConstructor());return this.baseCstVisitorWithDefaultsConstructor=e,e}return this.baseCstVisitorWithDefaultsConstructor}getLastExplicitRuleShortName(){let e=this.RULE_STACK;return e[e.length-1]}getPreviousExplicitRuleShortName(){let e=this.RULE_STACK;return e[e.length-2]}getLastExplicitRuleOccurrenceIndex(){let e=this.RULE_OCCURRENCE_STACK;return e[e.length-1]}}});var Q6,Txe=P(()=>{"use strict";Oo();Q6=class{static{o(this,"LexerAdapter")}initLexerAdapter(){this.tokVector=[],this.tokVectorLength=0,this.currIdx=-1}set input(e){if(this.selfAnalysisDone!==!0)throw Error("Missing invocation at the end of the Parser's constructor.");this.reset(),this.tokVector=e,this.tokVectorLength=e.length}get input(){return this.tokVector}SKIP_TOKEN(){return this.currIdx<=this.tokVector.length-2?(this.consumeToken(),this.LA(1)):rv}LA(e){let r=this.currIdx+e;return r<0||this.tokVectorLength<=r?rv:this.tokVector[r]}consumeToken(){this.currIdx++}exportLexerState(){return this.currIdx}importLexerState(e){this.currIdx=e}resetLexerState(){this.currIdx=-1}moveToTerminatedState(){this.currIdx=this.tokVector.length-1}getLexerPosition(){return this.exportLexerState()}}});var Z6,kxe=P(()=>{"use strict";nr();tv();Oo();Xy();ok();Zs();Z6=class{static{o(this,"RecognizerApi")}ACTION(e){return e.call(this)}consume(e,r,i){return this.consumeInternal(r,e,i)}subrule(e,r,i){return this.subruleInternal(r,e,i)}option(e,r){return this.optionInternal(r,e)}or(e,r){return this.orInternal(r,e)}many(e,r){return this.manyInternal(e,r)}atLeastOne(e,r){return this.atLeastOneInternal(e,r)}CONSUME(e,r){return this.consumeInternal(e,0,r)}CONSUME1(e,r){return this.consumeInternal(e,1,r)}CONSUME2(e,r){return this.consumeInternal(e,2,r)}CONSUME3(e,r){return this.consumeInternal(e,3,r)}CONSUME4(e,r){return this.consumeInternal(e,4,r)}CONSUME5(e,r){return this.consumeInternal(e,5,r)}CONSUME6(e,r){return this.consumeInternal(e,6,r)}CONSUME7(e,r){return this.consumeInternal(e,7,r)}CONSUME8(e,r){return this.consumeInternal(e,8,r)}CONSUME9(e,r){return this.consumeInternal(e,9,r)}SUBRULE(e,r){return this.subruleInternal(e,0,r)}SUBRULE1(e,r){return this.subruleInternal(e,1,r)}SUBRULE2(e,r){return this.subruleInternal(e,2,r)}SUBRULE3(e,r){return this.subruleInternal(e,3,r)}SUBRULE4(e,r){return this.subruleInternal(e,4,r)}SUBRULE5(e,r){return this.subruleInternal(e,5,r)}SUBRULE6(e,r){return this.subruleInternal(e,6,r)}SUBRULE7(e,r){return this.subruleInternal(e,7,r)}SUBRULE8(e,r){return this.subruleInternal(e,8,r)}SUBRULE9(e,r){return this.subruleInternal(e,9,r)}OPTION(e){return this.optionInternal(e,0)}OPTION1(e){return this.optionInternal(e,1)}OPTION2(e){return this.optionInternal(e,2)}OPTION3(e){return this.optionInternal(e,3)}OPTION4(e){return this.optionInternal(e,4)}OPTION5(e){return this.optionInternal(e,5)}OPTION6(e){return this.optionInternal(e,6)}OPTION7(e){return this.optionInternal(e,7)}OPTION8(e){return this.optionInternal(e,8)}OPTION9(e){return this.optionInternal(e,9)}OR(e){return this.orInternal(e,0)}OR1(e){return this.orInternal(e,1)}OR2(e){return this.orInternal(e,2)}OR3(e){return this.orInternal(e,3)}OR4(e){return this.orInternal(e,4)}OR5(e){return this.orInternal(e,5)}OR6(e){return this.orInternal(e,6)}OR7(e){return this.orInternal(e,7)}OR8(e){return this.orInternal(e,8)}OR9(e){return this.orInternal(e,9)}MANY(e){this.manyInternal(0,e)}MANY1(e){this.manyInternal(1,e)}MANY2(e){this.manyInternal(2,e)}MANY3(e){this.manyInternal(3,e)}MANY4(e){this.manyInternal(4,e)}MANY5(e){this.manyInternal(5,e)}MANY6(e){this.manyInternal(6,e)}MANY7(e){this.manyInternal(7,e)}MANY8(e){this.manyInternal(8,e)}MANY9(e){this.manyInternal(9,e)}MANY_SEP(e){this.manySepFirstInternal(0,e)}MANY_SEP1(e){this.manySepFirstInternal(1,e)}MANY_SEP2(e){this.manySepFirstInternal(2,e)}MANY_SEP3(e){this.manySepFirstInternal(3,e)}MANY_SEP4(e){this.manySepFirstInternal(4,e)}MANY_SEP5(e){this.manySepFirstInternal(5,e)}MANY_SEP6(e){this.manySepFirstInternal(6,e)}MANY_SEP7(e){this.manySepFirstInternal(7,e)}MANY_SEP8(e){this.manySepFirstInternal(8,e)}MANY_SEP9(e){this.manySepFirstInternal(9,e)}AT_LEAST_ONE(e){this.atLeastOneInternal(0,e)}AT_LEAST_ONE1(e){return this.atLeastOneInternal(1,e)}AT_LEAST_ONE2(e){this.atLeastOneInternal(2,e)}AT_LEAST_ONE3(e){this.atLeastOneInternal(3,e)}AT_LEAST_ONE4(e){this.atLeastOneInternal(4,e)}AT_LEAST_ONE5(e){this.atLeastOneInternal(5,e)}AT_LEAST_ONE6(e){this.atLeastOneInternal(6,e)}AT_LEAST_ONE7(e){this.atLeastOneInternal(7,e)}AT_LEAST_ONE8(e){this.atLeastOneInternal(8,e)}AT_LEAST_ONE9(e){this.atLeastOneInternal(9,e)}AT_LEAST_ONE_SEP(e){this.atLeastOneSepFirstInternal(0,e)}AT_LEAST_ONE_SEP1(e){this.atLeastOneSepFirstInternal(1,e)}AT_LEAST_ONE_SEP2(e){this.atLeastOneSepFirstInternal(2,e)}AT_LEAST_ONE_SEP3(e){this.atLeastOneSepFirstInternal(3,e)}AT_LEAST_ONE_SEP4(e){this.atLeastOneSepFirstInternal(4,e)}AT_LEAST_ONE_SEP5(e){this.atLeastOneSepFirstInternal(5,e)}AT_LEAST_ONE_SEP6(e){this.atLeastOneSepFirstInternal(6,e)}AT_LEAST_ONE_SEP7(e){this.atLeastOneSepFirstInternal(7,e)}AT_LEAST_ONE_SEP8(e){this.atLeastOneSepFirstInternal(8,e)}AT_LEAST_ONE_SEP9(e){this.atLeastOneSepFirstInternal(9,e)}RULE(e,r,i=iv){if(pn(this.definedRulesNames,e)){let s={message:qc.buildDuplicateRuleNameError({topLevelRule:e,grammarName:this.className}),type:ya.DUPLICATE_RULE_NAME,ruleName:e};this.definitionErrors.push(s)}this.definedRulesNames.push(e);let n=this.defineRule(e,r,i);return this[e]=n,n}OVERRIDE_RULE(e,r,i=iv){let n=exe(e,this.definedRulesNames,this.className);this.definitionErrors=this.definitionErrors.concat(n);let a=this.defineRule(e,r,i);return this[e]=a,a}BACKTRACK(e,r){return function(){this.isBackTrackingStack.push(1);let i=this.saveRecogState();try{return e.apply(this,r),!0}catch(n){if(ap(n))return!1;throw n}finally{this.reloadRecogState(i),this.isBackTrackingStack.pop()}}}getGAstProductions(){return this.gastProductionsCache}getSerializedGastProductions(){return C6(qr(this.gastProductionsCache))}}});var J6,Cxe=P(()=>{"use strict";nr();W6();tv();Jy();nk();Oo();U$();Dm();_m();J6=class{static{o(this,"RecognizerEngine")}initRecognizerEngine(e,r){if(this.className=this.constructor.name,this.shortRuleNameToFull={},this.fullRuleNameToShort={},this.ruleShortNameIdx=256,this.tokenMatcher=Yy,this.subruleIdx=0,this.definedRulesNames=[],this.tokensMap={},this.isBackTrackingStack=[],this.RULE_STACK=[],this.RULE_OCCURRENCE_STACK=[],this.gastProductionsCache={},Vt(r,"serializedGrammar"))throw Error(`The Parser's configuration can no longer contain a property. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0 + For Further details.`);if(Gt(e)){if(_r(e))throw Error(`A Token Vocabulary cannot be empty. + Note that the first argument for the parser constructor + is no longer a Token vector (since v4.0).`);if(typeof e[0].startOffset=="number")throw Error(`The Parser constructor no longer accepts a token vector as the first argument. + See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0 + For Further details.`)}if(Gt(e))this.tokensMap=mi(e,(a,s)=>(a[s.name]=s,a),{});else if(Vt(e,"modes")&&ms(di(qr(e.modes)),Rve)){let a=di(qr(e.modes)),s=Z1(a);this.tokensMap=mi(s,(l,u)=>(l[u.name]=u,l),{})}else if(Gi(e))this.tokensMap=Si(e);else throw new Error(" argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");this.tokensMap.EOF=cl;let i=Vt(e,"modes")?di(qr(e.modes)):qr(e),n=ms(i,a=>_r(a.categoryMatches));this.tokenMatcher=n?Yy:lf,cf(qr(this.tokensMap))}defineRule(e,r,i){if(this.selfAnalysisDone)throw Error(`Grammar rule <${e}> may not be defined after the 'performSelfAnalysis' method has been called' +Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);let n=Vt(i,"resyncEnabled")?i.resyncEnabled:iv.resyncEnabled,a=Vt(i,"recoveryValueFunc")?i.recoveryValueFunc:iv.recoveryValueFunc,s=this.ruleShortNameIdx<<12;this.ruleShortNameIdx++,this.shortRuleNameToFull[s]=e,this.fullRuleNameToShort[e]=s;let l;return this.outputCst===!0?l=o(function(...f){try{this.ruleInvocationStateUpdate(s,e,this.subruleIdx),r.apply(this,f);let d=this.CST_STACK[this.CST_STACK.length-1];return this.cstPostRule(d),d}catch(d){return this.invokeRuleCatch(d,n,a)}finally{this.ruleFinallyStateUpdate()}},"invokeRuleWithTry"):l=o(function(...f){try{return this.ruleInvocationStateUpdate(s,e,this.subruleIdx),r.apply(this,f)}catch(d){return this.invokeRuleCatch(d,n,a)}finally{this.ruleFinallyStateUpdate()}},"invokeRuleWithTryCst"),Object.assign(l,{ruleName:e,originalGrammarAction:r})}invokeRuleCatch(e,r,i){let n=this.RULE_STACK.length===1,a=r&&!this.isBackTracking()&&this.recoveryEnabled;if(ap(e)){let s=e;if(a){let l=this.findReSyncTokenType();if(this.isInCurrentRuleReSyncSet(l))if(s.resyncedTokens=this.reSyncTo(l),this.outputCst){let u=this.CST_STACK[this.CST_STACK.length-1];return u.recoveredNode=!0,u}else return i(e);else{if(this.outputCst){let u=this.CST_STACK[this.CST_STACK.length-1];u.recoveredNode=!0,s.partialCstResult=u}throw s}}else{if(n)return this.moveToTerminatedState(),i(e);throw s}}else throw e}optionInternal(e,r){let i=this.getKeyForAutomaticLookahead(512,r);return this.optionInternalLogic(e,r,i)}optionInternalLogic(e,r,i){let n=this.getLaFuncFromCache(i),a;if(typeof e!="function"){a=e.DEF;let s=e.GATE;if(s!==void 0){let l=n;n=o(()=>s.call(this)&&l.call(this),"lookAheadFunc")}}else a=e;if(n.call(this)===!0)return a.call(this)}atLeastOneInternal(e,r){let i=this.getKeyForAutomaticLookahead(1024,e);return this.atLeastOneInternalLogic(e,r,i)}atLeastOneInternalLogic(e,r,i){let n=this.getLaFuncFromCache(i),a;if(typeof r!="function"){a=r.DEF;let s=r.GATE;if(s!==void 0){let l=n;n=o(()=>s.call(this)&&l.call(this),"lookAheadFunc")}}else a=r;if(n.call(this)===!0){let s=this.doSingleRepetition(a);for(;n.call(this)===!0&&s===!0;)s=this.doSingleRepetition(a)}else throw this.raiseEarlyExitException(e,vn.REPETITION_MANDATORY,r.ERR_MSG);this.attemptInRepetitionRecovery(this.atLeastOneInternal,[e,r],n,1024,e,O6)}atLeastOneSepFirstInternal(e,r){let i=this.getKeyForAutomaticLookahead(1536,e);this.atLeastOneSepFirstInternalLogic(e,r,i)}atLeastOneSepFirstInternalLogic(e,r,i){let n=r.DEF,a=r.SEP;if(this.getLaFuncFromCache(i).call(this)===!0){n.call(this);let l=o(()=>this.tokenMatcher(this.LA(1),a),"separatorLookAheadFunc");for(;this.tokenMatcher(this.LA(1),a)===!0;)this.CONSUME(a),n.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,a,l,n,ik],l,1536,e,ik)}else throw this.raiseEarlyExitException(e,vn.REPETITION_MANDATORY_WITH_SEPARATOR,r.ERR_MSG)}manyInternal(e,r){let i=this.getKeyForAutomaticLookahead(768,e);return this.manyInternalLogic(e,r,i)}manyInternalLogic(e,r,i){let n=this.getLaFuncFromCache(i),a;if(typeof r!="function"){a=r.DEF;let l=r.GATE;if(l!==void 0){let u=n;n=o(()=>l.call(this)&&u.call(this),"lookaheadFunction")}}else a=r;let s=!0;for(;n.call(this)===!0&&s===!0;)s=this.doSingleRepetition(a);this.attemptInRepetitionRecovery(this.manyInternal,[e,r],n,768,e,M6,s)}manySepFirstInternal(e,r){let i=this.getKeyForAutomaticLookahead(1280,e);this.manySepFirstInternalLogic(e,r,i)}manySepFirstInternalLogic(e,r,i){let n=r.DEF,a=r.SEP;if(this.getLaFuncFromCache(i).call(this)===!0){n.call(this);let l=o(()=>this.tokenMatcher(this.LA(1),a),"separatorLookAheadFunc");for(;this.tokenMatcher(this.LA(1),a)===!0;)this.CONSUME(a),n.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,a,l,n,rk],l,1280,e,rk)}}repetitionSepSecondInternal(e,r,i,n,a){for(;i();)this.CONSUME(r),n.call(this);this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal,[e,r,i,n,a],i,1536,e,a)}doSingleRepetition(e){let r=this.getLexerPosition();return e.call(this),this.getLexerPosition()>r}orInternal(e,r){let i=this.getKeyForAutomaticLookahead(256,r),n=Gt(e)?e:e.DEF,s=this.getLaFuncFromCache(i).call(this,n);if(s!==void 0)return n[s].ALT.call(this);this.raiseNoAltException(r,e.ERR_MSG)}ruleFinallyStateUpdate(){if(this.RULE_STACK.pop(),this.RULE_OCCURRENCE_STACK.pop(),this.cstFinallyStateUpdate(),this.RULE_STACK.length===0&&this.isAtEndOfInput()===!1){let e=this.LA(1),r=this.errorMessageProvider.buildNotAllInputParsedMessage({firstRedundant:e,ruleName:this.getCurrRuleFullName()});this.SAVE_ERROR(new ck(r,e))}}subruleInternal(e,r,i){let n;try{let a=i!==void 0?i.ARGS:void 0;return this.subruleIdx=r,n=e.apply(this,a),this.cstPostNonTerminal(n,i!==void 0&&i.LABEL!==void 0?i.LABEL:e.ruleName),n}catch(a){throw this.subruleInternalError(a,i,e.ruleName)}}subruleInternalError(e,r,i){throw ap(e)&&e.partialCstResult!==void 0&&(this.cstPostNonTerminal(e.partialCstResult,r!==void 0&&r.LABEL!==void 0?r.LABEL:i),delete e.partialCstResult),e}consumeInternal(e,r,i){let n;try{let a=this.LA(1);this.tokenMatcher(a,e)===!0?(this.consumeToken(),n=a):this.consumeInternalError(e,a,i)}catch(a){n=this.consumeInternalRecovery(e,r,a)}return this.cstPostTerminal(i!==void 0&&i.LABEL!==void 0?i.LABEL:e.name,n),n}consumeInternalError(e,r,i){let n,a=this.LA(0);throw i!==void 0&&i.ERR_MSG?n=i.ERR_MSG:n=this.errorMessageProvider.buildMismatchTokenMessage({expected:e,actual:r,previous:a,ruleName:this.getCurrRuleFullName()}),this.SAVE_ERROR(new Lm(n,r,a))}consumeInternalRecovery(e,r,i){if(this.recoveryEnabled&&i.name==="MismatchedTokenException"&&!this.isBackTracking()){let n=this.getFollowsForInRuleRecovery(e,r);try{return this.tryInRuleRecovery(e,n)}catch(a){throw a.name===W$?i:a}}else throw i}saveRecogState(){let e=this.errors,r=Si(this.RULE_STACK);return{errors:e,lexerState:this.exportLexerState(),RULE_STACK:r,CST_STACK:this.CST_STACK}}reloadRecogState(e){this.errors=e.errors,this.importLexerState(e.lexerState),this.RULE_STACK=e.RULE_STACK}ruleInvocationStateUpdate(e,r,i){this.RULE_OCCURRENCE_STACK.push(i),this.RULE_STACK.push(e),this.cstInvocationStateUpdate(r)}isBackTracking(){return this.isBackTrackingStack.length!==0}getCurrRuleFullName(){let e=this.getLastExplicitRuleShortName();return this.shortRuleNameToFull[e]}shortRuleNameToFullName(e){return this.shortRuleNameToFull[e]}isAtEndOfInput(){return this.tokenMatcher(this.LA(1),cl)}reset(){this.resetLexerState(),this.subruleIdx=0,this.isBackTrackingStack=[],this.errors=[],this.RULE_STACK=[],this.CST_STACK=[],this.RULE_OCCURRENCE_STACK=[]}}});var eA,wxe=P(()=>{"use strict";tv();nr();Jy();Oo();eA=class{static{o(this,"ErrorHandler")}initErrorHandler(e){this._errors=[],this.errorMessageProvider=Vt(e,"errorMessageProvider")?e.errorMessageProvider:Js.errorMessageProvider}SAVE_ERROR(e){if(ap(e))return e.context={ruleStack:this.getHumanReadableRuleStack(),ruleOccurrenceStack:Si(this.RULE_OCCURRENCE_STACK)},this._errors.push(e),e;throw Error("Trying to save an Error which is not a RecognitionException")}get errors(){return Si(this._errors)}set errors(e){this._errors=e}raiseEarlyExitException(e,r,i){let n=this.getCurrRuleFullName(),a=this.getGAstProductions()[n],l=Zy(e,a,r,this.maxLookahead)[0],u=[];for(let f=1;f<=this.maxLookahead;f++)u.push(this.LA(f));let h=this.errorMessageProvider.buildEarlyExitMessage({expectedIterationPaths:l,actual:u,previous:this.LA(0),customUserDescription:i,ruleName:n});throw this.SAVE_ERROR(new uk(h,this.LA(1),this.LA(0)))}raiseNoAltException(e,r){let i=this.getCurrRuleFullName(),n=this.getGAstProductions()[i],a=Qy(e,n,this.maxLookahead),s=[];for(let h=1;h<=this.maxLookahead;h++)s.push(this.LA(h));let l=this.LA(0),u=this.errorMessageProvider.buildNoViableAltMessage({expectedPathsPerAlt:a,actual:s,previous:l,customUserDescription:r,ruleName:this.getCurrRuleFullName()});throw this.SAVE_ERROR(new lk(u,this.LA(1),l))}}});var tA,Exe=P(()=>{"use strict";nk();nr();tA=class{static{o(this,"ContentAssist")}initContentAssist(){}computeContentAssist(e,r){let i=this.gastProductionsCache[e];if(Br(i))throw Error(`Rule ->${e}<- does not exist in this grammar.`);return B6([i],r,this.tokenMatcher,this.maxLookahead)}getNextPossibleTokenTypes(e){let r=Ia(e.ruleStack),n=this.getGAstProductions()[r];return new I6(n,e).startWalking()}}});function fk(t,e,r,i=!1){iA(r);let n=Na(this.recordingProdStack),a=Qn(e)?e:e.DEF,s=new t({definition:[],idx:r});return i&&(s.separator=e.SEP),Vt(e,"MAX_LOOKAHEAD")&&(s.maxLookahead=e.MAX_LOOKAHEAD),this.recordingProdStack.push(s),a.call(this),n.definition.push(s),this.recordingProdStack.pop(),nA}function Dat(t,e){iA(e);let r=Na(this.recordingProdStack),i=Gt(t)===!1,n=i===!1?t:t.DEF,a=new Ui({definition:[],idx:e,ignoreAmbiguities:i&&t.IGNORE_AMBIGUITIES===!0});Vt(t,"MAX_LOOKAHEAD")&&(a.maxLookahead=t.MAX_LOOKAHEAD);let s=Fb(n,l=>Qn(l.GATE));return a.hasPredicates=s,r.definition.push(a),Pe(n,l=>{let u=new en({definition:[]});a.definition.push(u),Vt(l,"IGNORE_AMBIGUITIES")?u.ignoreAmbiguities=l.IGNORE_AMBIGUITIES:Vt(l,"GATE")&&(u.ignoreAmbiguities=!0),this.recordingProdStack.push(u),l.ALT.call(this),this.recordingProdStack.pop()}),nA}function _xe(t){return t===0?"":`${t}`}function iA(t){if(t<0||t>Axe){let e=new Error(`Invalid DSL Method idx value: <${t}> + Idx value must be a none negative value smaller than ${Axe+1}`);throw e.KNOWN_RECORDER_ERROR=!0,e}}var nA,Sxe,Axe,Dxe,Lxe,_at,rA,Rxe=P(()=>{"use strict";nr();Zs();JT();_m();Dm();Oo();W6();nA={description:"This Object indicates the Parser is during Recording Phase"};Object.freeze(nA);Sxe=!0,Axe=Math.pow(2,8)-1,Dxe=np({name:"RECORDING_PHASE_TOKEN",pattern:yn.NA});cf([Dxe]);Lxe=hf(Dxe,`This IToken indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,-1,-1,-1,-1,-1,-1);Object.freeze(Lxe);_at={name:`This CSTNode indicates the Parser is in Recording Phase + See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details`,children:{}},rA=class{static{o(this,"GastRecorder")}initGastRecorder(e){this.recordingProdStack=[],this.RECORDING_PHASE=!1}enableRecording(){this.RECORDING_PHASE=!0,this.TRACE_INIT("Enable Recording",()=>{for(let e=0;e<10;e++){let r=e>0?e:"";this[`CONSUME${r}`]=function(i,n){return this.consumeInternalRecord(i,e,n)},this[`SUBRULE${r}`]=function(i,n){return this.subruleInternalRecord(i,e,n)},this[`OPTION${r}`]=function(i){return this.optionInternalRecord(i,e)},this[`OR${r}`]=function(i){return this.orInternalRecord(i,e)},this[`MANY${r}`]=function(i){this.manyInternalRecord(e,i)},this[`MANY_SEP${r}`]=function(i){this.manySepFirstInternalRecord(e,i)},this[`AT_LEAST_ONE${r}`]=function(i){this.atLeastOneInternalRecord(e,i)},this[`AT_LEAST_ONE_SEP${r}`]=function(i){this.atLeastOneSepFirstInternalRecord(e,i)}}this.consume=function(e,r,i){return this.consumeInternalRecord(r,e,i)},this.subrule=function(e,r,i){return this.subruleInternalRecord(r,e,i)},this.option=function(e,r){return this.optionInternalRecord(r,e)},this.or=function(e,r){return this.orInternalRecord(r,e)},this.many=function(e,r){this.manyInternalRecord(e,r)},this.atLeastOne=function(e,r){this.atLeastOneInternalRecord(e,r)},this.ACTION=this.ACTION_RECORD,this.BACKTRACK=this.BACKTRACK_RECORD,this.LA=this.LA_RECORD})}disableRecording(){this.RECORDING_PHASE=!1,this.TRACE_INIT("Deleting Recording methods",()=>{let e=this;for(let r=0;r<10;r++){let i=r>0?r:"";delete e[`CONSUME${i}`],delete e[`SUBRULE${i}`],delete e[`OPTION${i}`],delete e[`OR${i}`],delete e[`MANY${i}`],delete e[`MANY_SEP${i}`],delete e[`AT_LEAST_ONE${i}`],delete e[`AT_LEAST_ONE_SEP${i}`]}delete e.consume,delete e.subrule,delete e.option,delete e.or,delete e.many,delete e.atLeastOne,delete e.ACTION,delete e.BACKTRACK,delete e.LA})}ACTION_RECORD(e){}BACKTRACK_RECORD(e,r){return()=>!0}LA_RECORD(e){return rv}topLevelRuleRecord(e,r){try{let i=new Ks({definition:[],name:e});return i.name=e,this.recordingProdStack.push(i),r.call(this),this.recordingProdStack.pop(),i}catch(i){if(i.KNOWN_RECORDER_ERROR!==!0)try{i.message=i.message+` + This error was thrown during the "grammar recording phase" For more info see: + https://chevrotain.io/docs/guide/internals.html#grammar-recording`}catch{throw i}throw i}}optionInternalRecord(e,r){return fk.call(this,Ri,e,r)}atLeastOneInternalRecord(e,r){fk.call(this,tn,r,e)}atLeastOneSepFirstInternalRecord(e,r){fk.call(this,rn,r,e,Sxe)}manyInternalRecord(e,r){fk.call(this,ti,r,e)}manySepFirstInternalRecord(e,r){fk.call(this,Wi,r,e,Sxe)}orInternalRecord(e,r){return Dat.call(this,e,r)}subruleInternalRecord(e,r,i){if(iA(r),!e||Vt(e,"ruleName")===!1){let l=new Error(` argument is invalid expecting a Parser method reference but got: <${JSON.stringify(e)}> + inside top level rule: <${this.recordingProdStack[0].name}>`);throw l.KNOWN_RECORDER_ERROR=!0,l}let n=Na(this.recordingProdStack),a=e.ruleName,s=new Li({idx:r,nonTerminalName:a,label:i?.LABEL,referencedRule:void 0});return n.definition.push(s),this.outputCst?_at:nA}consumeInternalRecord(e,r,i){if(iA(r),!N$(e)){let s=new Error(` argument is invalid expecting a TokenType reference but got: <${JSON.stringify(e)}> + inside top level rule: <${this.recordingProdStack[0].name}>`);throw s.KNOWN_RECORDER_ERROR=!0,s}let n=Na(this.recordingProdStack),a=new Xr({idx:r,terminalType:e,label:i?.LABEL});return n.definition.push(a),Lxe}};o(fk,"recordProd");o(Dat,"recordOrProd");o(_xe,"getIdxSuffix");o(iA,"assertMethodIdxIsValid")});var aA,Nxe=P(()=>{"use strict";nr();Vy();Oo();aA=class{static{o(this,"PerformanceTracer")}initPerformanceTracer(e){if(Vt(e,"traceInitPerf")){let r=e.traceInitPerf,i=typeof r=="number";this.traceInitMaxIdent=i?r:1/0,this.traceInitPerf=i?r>0:r}else this.traceInitMaxIdent=0,this.traceInitPerf=Js.traceInitPerf;this.traceInitIndent=-1}TRACE_INIT(e,r){if(this.traceInitPerf===!0){this.traceInitIndent++;let i=new Array(this.traceInitIndent+1).join(" ");this.traceInitIndent <${e}>`);let{time:n,value:a}=KT(r),s=n>10?console.warn:console.log;return this.traceInitIndent time: ${n}ms`),this.traceInitIndent--,a}else return r()}}});function Ixe(t,e){e.forEach(r=>{let i=r.prototype;Object.getOwnPropertyNames(i).forEach(n=>{if(n==="constructor")return;let a=Object.getOwnPropertyDescriptor(i,n);a&&(a.get||a.set)?Object.defineProperty(t.prototype,n,a):t.prototype[n]=r.prototype[n]})})}var Mxe=P(()=>{"use strict";o(Ixe,"applyMixins")});function sA(t=void 0){return function(){return t}}var rv,Js,iv,ya,dk,pk,Oo=P(()=>{"use strict";nr();Vy();uve();Dm();Xy();sxe();U$();fxe();bxe();Txe();kxe();Cxe();wxe();Exe();Rxe();Nxe();Mxe();ok();rv=hf(cl,"",NaN,NaN,NaN,NaN,NaN,NaN);Object.freeze(rv);Js=Object.freeze({recoveryEnabled:!1,maxLookahead:3,dynamicTokensEnabled:!1,outputCst:!0,errorMessageProvider:ff,nodeLocationTracking:"none",traceInitPerf:!1,skipValidations:!1}),iv=Object.freeze({recoveryValueFunc:o(()=>{},"recoveryValueFunc"),resyncEnabled:!0});(function(t){t[t.INVALID_RULE_NAME=0]="INVALID_RULE_NAME",t[t.DUPLICATE_RULE_NAME=1]="DUPLICATE_RULE_NAME",t[t.INVALID_RULE_OVERRIDE=2]="INVALID_RULE_OVERRIDE",t[t.DUPLICATE_PRODUCTIONS=3]="DUPLICATE_PRODUCTIONS",t[t.UNRESOLVED_SUBRULE_REF=4]="UNRESOLVED_SUBRULE_REF",t[t.LEFT_RECURSION=5]="LEFT_RECURSION",t[t.NONE_LAST_EMPTY_ALT=6]="NONE_LAST_EMPTY_ALT",t[t.AMBIGUOUS_ALTS=7]="AMBIGUOUS_ALTS",t[t.CONFLICT_TOKENS_RULES_NAMESPACE=8]="CONFLICT_TOKENS_RULES_NAMESPACE",t[t.INVALID_TOKEN_NAME=9]="INVALID_TOKEN_NAME",t[t.NO_NON_EMPTY_LOOKAHEAD=10]="NO_NON_EMPTY_LOOKAHEAD",t[t.AMBIGUOUS_PREFIX_ALTS=11]="AMBIGUOUS_PREFIX_ALTS",t[t.TOO_MANY_ALTS=12]="TOO_MANY_ALTS",t[t.CUSTOM_LOOKAHEAD_VALIDATION=13]="CUSTOM_LOOKAHEAD_VALIDATION"})(ya||(ya={}));o(sA,"EMPTY_ALT");dk=class t{static{o(this,"Parser")}static performSelfAnalysis(e){throw Error("The **static** `performSelfAnalysis` method has been deprecated. \nUse the **instance** method with the same name instead.")}performSelfAnalysis(){this.TRACE_INIT("performSelfAnalysis",()=>{let e;this.selfAnalysisDone=!0;let r=this.className;this.TRACE_INIT("toFastProps",()=>{QT(this)}),this.TRACE_INIT("Grammar Recording",()=>{try{this.enableRecording(),Pe(this.definedRulesNames,n=>{let s=this[n].originalGrammarAction,l;this.TRACE_INIT(`${n} Rule`,()=>{l=this.topLevelRuleRecord(n,s)}),this.gastProductionsCache[n]=l})}finally{this.disableRecording()}});let i=[];if(this.TRACE_INIT("Grammar Resolving",()=>{i=nxe({rules:qr(this.gastProductionsCache)}),this.definitionErrors=this.definitionErrors.concat(i)}),this.TRACE_INIT("Grammar Validations",()=>{if(_r(i)&&this.skipValidations===!1){let n=axe({rules:qr(this.gastProductionsCache),tokenTypes:qr(this.tokensMap),errMsgProvider:qc,grammarName:r}),a=Qve({lookaheadStrategy:this.lookaheadStrategy,rules:qr(this.gastProductionsCache),tokenTypes:qr(this.tokensMap),grammarName:r});this.definitionErrors=this.definitionErrors.concat(n,a)}}),_r(this.definitionErrors)&&(this.recoveryEnabled&&this.TRACE_INIT("computeAllProdsFollows",()=>{let n=cve(qr(this.gastProductionsCache));this.resyncFollows=n}),this.TRACE_INIT("ComputeLookaheadFunctions",()=>{var n,a;(a=(n=this.lookaheadStrategy).initialize)===null||a===void 0||a.call(n,{rules:qr(this.gastProductionsCache)}),this.preComputeLookaheadFunctions(qr(this.gastProductionsCache))})),!t.DEFER_DEFINITION_ERRORS_HANDLING&&!_r(this.definitionErrors))throw e=ht(this.definitionErrors,n=>n.message),new Error(`Parser Definition Errors detected: + ${e.join(` +------------------------------- +`)}`)})}constructor(e,r){this.definitionErrors=[],this.selfAnalysisDone=!1;let i=this;if(i.initErrorHandler(r),i.initLexerAdapter(),i.initLooksAhead(r),i.initRecognizerEngine(e,r),i.initRecoverable(r),i.initTreeBuilder(r),i.initContentAssist(),i.initGastRecorder(r),i.initPerformanceTracer(r),Vt(r,"ignoredIssues"))throw new Error(`The IParserConfig property has been deprecated. + Please use the flag on the relevant DSL method instead. + See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES + For further details.`);this.skipValidations=Vt(r,"skipValidations")?r.skipValidations:Js.skipValidations}};dk.DEFER_DEFINITION_ERRORS_HANDLING=!1;Ixe(dk,[V6,H6,K6,Q6,J6,Z6,eA,tA,rA,aA]);pk=class extends dk{static{o(this,"EmbeddedActionsParser")}constructor(e,r=Js){let i=Si(r);i.outputCst=!1,super(e,i)}}});var Oxe=P(()=>{"use strict";Zs()});var Pxe=P(()=>{"use strict"});var Bxe=P(()=>{"use strict";Oxe();Pxe()});var Fxe=P(()=>{"use strict";b$()});var sp=P(()=>{"use strict";b$();Oo();JT();Dm();Jy();H$();Xy();tv();I$();Zs();Zs();Bxe();Fxe()});function Rm(t,e,r){return`${t.name}_${e}_${r}`}function Vxe(t){let e={decisionMap:{},decisionStates:[],ruleToStartState:new Map,ruleToStopState:new Map,states:[]};Pat(e,t);let r=t.length;for(let i=0;iqxe(t,e,s));return ov(t,e,i,r,...n)}function Vat(t,e,r){let i=Fa(t,e,r,{type:op});lp(t,i);let n=ov(t,e,i,r,Nm(t,e,r));return qat(t,e,r,n)}function Nm(t,e,r){let i=pi(ht(r.definition,n=>qxe(t,e,n)),n=>n!==void 0);return i.length===1?i[0]:i.length===0?void 0:Uat(t,i)}function Wxe(t,e,r,i,n){let a=i.left,s=i.right,l=Fa(t,e,r,{type:Oat});lp(t,l);let u=Fa(t,e,r,{type:Gxe});return a.loopback=l,u.loopback=l,t.decisionMap[Rm(e,n?"RepetitionMandatoryWithSeparator":"RepetitionMandatory",r.idx)]=l,ta(s,l),n===void 0?(ta(l,a),ta(l,u)):(ta(l,u),ta(l,n.left),ta(n.right,a)),{left:a,right:u}}function Uxe(t,e,r,i,n){let a=i.left,s=i.right,l=Fa(t,e,r,{type:Mat});lp(t,l);let u=Fa(t,e,r,{type:Gxe}),h=Fa(t,e,r,{type:Iat});return l.loopback=h,u.loopback=h,ta(l,a),ta(l,u),ta(s,h),n!==void 0?(ta(h,u),ta(h,n.left),ta(n.right,a)):ta(h,l),t.decisionMap[Rm(e,n?"RepetitionWithSeparator":"Repetition",r.idx)]=l,{left:l,right:u}}function qat(t,e,r,i){let n=i.left,a=i.right;return ta(n,a),t.decisionMap[Rm(e,"Option",r.idx)]=n,i}function lp(t,e){return t.decisionStates.push(e),e.decision=t.decisionStates.length-1,e.decision}function ov(t,e,r,i,...n){let a=Fa(t,e,i,{type:Nat,start:r});r.end=a;for(let l of n)l!==void 0?(ta(r,l.left),ta(l.right,a)):ta(r,a);let s={left:r,right:a};return t.decisionMap[Rm(e,Wat(i),i.idx)]=r,s}function Wat(t){if(t instanceof Ui)return"Alternation";if(t instanceof Ri)return"Option";if(t instanceof ti)return"Repetition";if(t instanceof Wi)return"RepetitionWithSeparator";if(t instanceof tn)return"RepetitionMandatory";if(t instanceof rn)return"RepetitionMandatoryWithSeparator";throw new Error("Invalid production type encountered")}function Uat(t,e){let r=e.length;for(let a=0;a{"use strict";X1();sO();sp();o(Rm,"buildATNKey");op=1,Rat=2,$xe=4,zxe=5,sv=7,Nat=8,Iat=9,Mat=10,Oat=11,Gxe=12,mk=class{static{o(this,"AbstractTransition")}constructor(e){this.target=e}isEpsilon(){return!1}},nv=class extends mk{static{o(this,"AtomTransition")}constructor(e,r){super(e),this.tokenType=r}},gk=class extends mk{static{o(this,"EpsilonTransition")}constructor(e){super(e)}isEpsilon(){return!0}},av=class extends mk{static{o(this,"RuleTransition")}constructor(e,r,i){super(e),this.rule=r,this.followState=i}isEpsilon(){return!0}};o(Vxe,"createATN");o(Pat,"createRuleStartAndStopATNStates");o(qxe,"atom");o(Bat,"repetition");o(Fat,"repetitionSep");o($at,"repetitionMandatory");o(zat,"repetitionMandatorySep");o(Gat,"alternation");o(Vat,"option");o(Nm,"block");o(Wxe,"plus");o(Uxe,"star");o(qat,"optional");o(lp,"defineDecisionState");o(ov,"makeAlts");o(Wat,"getProdType");o(Uat,"makeBlock");o(tz,"tokenRef");o(Hat,"ruleRef");o(Yat,"buildRuleHandle");o(ta,"epsilon");o(Fa,"newState");o(rz,"addTransition");o(jat,"removeState")});function iz(t,e=!0){return`${e?`a${t.alt}`:""}s${t.state.stateNumber}:${t.stack.map(r=>r.stateNumber.toString()).join("_")}`}var yk,lv,Yxe=P(()=>{"use strict";X1();yk={},lv=class{static{o(this,"ATNConfigSet")}constructor(){this.map={},this.configs=[]}get size(){return this.configs.length}finalize(){this.map={}}add(e){let r=iz(e);r in this.map||(this.map[r]=this.configs.length,this.configs.push(e))}get elements(){return this.configs}get alts(){return ht(this.configs,e=>e.alt)}get key(){let e="";for(let r in this.map)e+=r+":";return e}};o(iz,"getATNConfigKey")});function Xat(t,e){let r={};return i=>{let n=i.toString(),a=r[n];return a!==void 0||(a={atnStartState:t,decision:e,states:{}},r[n]=a),a}}function Xxe(t,e=!0){let r=new Set;for(let i of t){let n=new Set;for(let a of i){if(a===void 0){if(e)break;return!1}let s=[a.tokenTypeIdx].concat(a.categoryMatches);for(let l of s)if(r.has(l)){if(!n.has(l))return!1}else r.add(l),n.add(l)}}return!0}function Kat(t){let e=t.decisionStates.length,r=Array(e);for(let i=0;iuf(n)).join(", "),r=t.production.idx===0?"":t.production.idx,i=`Ambiguous Alternatives Detected: <${t.ambiguityIndices.join(", ")}> in <${tst(t.production)}${r}> inside <${t.topLevelRule.name}> Rule, +<${e}> may appears as a prefix path in all these alternatives. +`;return i=i+`See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES +For Further details.`,i}function tst(t){if(t instanceof Li)return"SUBRULE";if(t instanceof Ri)return"OPTION";if(t instanceof Ui)return"OR";if(t instanceof tn)return"AT_LEAST_ONE";if(t instanceof rn)return"AT_LEAST_ONE_SEP";if(t instanceof Wi)return"MANY_SEP";if(t instanceof ti)return"MANY";if(t instanceof Xr)return"CONSUME";throw Error("non exhaustive match")}function rst(t,e,r){let i=Ja(e.configs.elements,a=>a.state.transitions),n=Xfe(i.filter(a=>a instanceof nv).map(a=>a.tokenType),a=>a.tokenTypeIdx);return{actualToken:r,possibleTokenTypes:n,tokenPath:t}}function ist(t,e){return t.edges[e.tokenTypeIdx]}function nst(t,e,r){let i=new lv,n=[];for(let s of t.elements){if(r.is(s.alt)===!1)continue;if(s.state.type===sv){n.push(s);continue}let l=s.state.transitions.length;for(let u=0;u0&&!cst(a))for(let s of n)a.add(s);return a}function ast(t,e){if(t instanceof nv&&tk(e,t.tokenType))return t.target}function sst(t,e){let r;for(let i of t.elements)if(e.is(i.alt)===!0){if(r===void 0)r=i.alt;else if(r!==i.alt)return}return r}function Qxe(t){return{configs:t,edges:{},isAcceptState:!1,prediction:-1}}function Kxe(t,e,r,i){return i=Zxe(t,i),e.edges[r.tokenTypeIdx]=i,i}function Zxe(t,e){if(e===yk)return e;let r=e.configs.key,i=t.states[r];return i!==void 0?i:(e.configs.finalize(),t.states[r]=e,e)}function ost(t){let e=new lv,r=t.transitions.length;for(let i=0;i0){let n=[...t.stack],s={state:n.pop(),alt:t.alt,stack:n};lA(s,e)}else e.add(t);return}r.epsilonOnlyTransitions||e.add(t);let i=r.transitions.length;for(let n=0;n1)return!0;return!1}function pst(t){for(let e of Array.from(t.values()))if(Object.keys(e).length===1)return!0;return!1}var oA,jxe,vk,Jxe=P(()=>{"use strict";sp();Hxe();Yxe();pO();lO();Kfe();X1();Y5();kE();AE();vO();o(Xat,"createDFACache");oA=class{static{o(this,"PredicateSet")}constructor(){this.predicates=[]}is(e){return e>=this.predicates.length||this.predicates[e]}set(e,r){this.predicates[e]=r}toString(){let e="",r=this.predicates.length;for(let i=0;iconsole.log(i))}initialize(e){this.atn=Vxe(e.rules),this.dfas=Kat(this.atn)}validateAmbiguousAlternationAlternatives(){return[]}validateEmptyOrAlternatives(){return[]}buildLookaheadForAlternation(e){let{prodOccurrence:r,rule:i,hasPredicates:n,dynamicTokensEnabled:a}=e,s=this.dfas,l=this.logging,u=Rm(i,"Alternation",r),f=this.atn.decisionMap[u].decision,d=ht($6({maxLookahead:1,occurrence:r,prodType:"Alternation",rule:i}),p=>ht(p,m=>m[0]));if(Xxe(d,!1)&&!a){let p=mi(d,(m,g,y)=>(Pe(g,v=>{v&&(m[v.tokenTypeIdx]=y,Pe(v.categoryMatches,x=>{m[x]=y}))}),m),{});return n?function(m){var g;let y=this.LA(1),v=p[y.tokenTypeIdx];if(m!==void 0&&v!==void 0){let x=(g=m[v])===null||g===void 0?void 0:g.GATE;if(x!==void 0&&x.call(this)===!1)return}return v}:function(){let m=this.LA(1);return p[m.tokenTypeIdx]}}else return n?function(p){let m=new oA,g=p===void 0?0:p.length;for(let v=0;vht(p,m=>m[0]));if(Xxe(d)&&d[0][0]&&!a){let p=d[0],m=di(p);if(m.length===1&&_r(m[0].categoryMatches)){let y=m[0].tokenTypeIdx;return function(){return this.LA(1).tokenTypeIdx===y}}else{let g=mi(m,(y,v)=>(v!==void 0&&(y[v.tokenTypeIdx]=!0,Pe(v.categoryMatches,x=>{y[x]=!0})),y),{});return function(){let y=this.LA(1);return g[y.tokenTypeIdx]===!0}}}return function(){let p=nz.call(this,s,f,jxe,l);return typeof p=="object"?!1:p===0}}};o(Xxe,"isLL1Sequence");o(Kat,"initATNSimulator");o(nz,"adaptivePredict");o(Qat,"performLookahead");o(Zat,"computeLookaheadTarget");o(Jat,"reportLookaheadAmbiguity");o(est,"buildAmbiguityError");o(tst,"getProductionDslName");o(rst,"buildAdaptivePredictError");o(ist,"getExistingTargetState");o(nst,"computeReachSet");o(ast,"getReachableTarget");o(sst,"getUniqueAlt");o(Qxe,"newDFAState");o(Kxe,"addDFAEdge");o(Zxe,"addDFAState");o(ost,"computeStartState");o(lA,"closure");o(lst,"getEpsilonTarget");o(cst,"hasConfigInRuleStopState");o(ust,"allConfigsInRuleStopStates");o(hst,"hasConflictTerminatingPrediction");o(fst,"getConflictingAltSets");o(dst,"hasConflictingAltSet");o(pst,"hasStateAssociatedWithOneAlt")});var e2e=P(()=>{"use strict";Jxe()});var yA={};ur(yA,{AnnotatedTextEdit:()=>pf,ChangeAnnotation:()=>Im,ChangeAnnotationIdentifier:()=>ns,CodeAction:()=>$z,CodeActionContext:()=>Fz,CodeActionKind:()=>Bz,CodeActionTriggerKind:()=>Ek,CodeDescription:()=>pz,CodeLens:()=>zz,Color:()=>uA,ColorInformation:()=>lz,ColorPresentation:()=>cz,Command:()=>Mm,CompletionItem:()=>Ez,CompletionItemKind:()=>xz,CompletionItemLabelDetails:()=>wz,CompletionItemTag:()=>Tz,CompletionList:()=>Sz,CreateFile:()=>uv,DeleteFile:()=>fv,Diagnostic:()=>Tk,DiagnosticRelatedInformation:()=>hA,DiagnosticSeverity:()=>fz,DiagnosticTag:()=>dz,DocumentHighlight:()=>Rz,DocumentHighlightKind:()=>Lz,DocumentLink:()=>Vz,DocumentSymbol:()=>Pz,DocumentUri:()=>az,EOL:()=>mst,FoldingRange:()=>hz,FoldingRangeKind:()=>uz,FormattingOptions:()=>Gz,Hover:()=>Az,InlayHint:()=>Qz,InlayHintKind:()=>mA,InlayHintLabelPart:()=>gA,InlineCompletionContext:()=>iG,InlineCompletionItem:()=>Jz,InlineCompletionList:()=>eG,InlineCompletionTriggerKind:()=>tG,InlineValueContext:()=>Kz,InlineValueEvaluatableExpression:()=>Xz,InlineValueText:()=>Yz,InlineValueVariableLookup:()=>jz,InsertReplaceEdit:()=>kz,InsertTextFormat:()=>bz,InsertTextMode:()=>Cz,Location:()=>bk,LocationLink:()=>oz,MarkedString:()=>wk,MarkupContent:()=>dv,MarkupKind:()=>pA,OptionalVersionedTextDocumentIdentifier:()=>Ck,ParameterInformation:()=>_z,Position:()=>oi,Range:()=>Jr,RenameFile:()=>hv,SelectedCompletionInfo:()=>rG,SelectionRange:()=>qz,SemanticTokenModifiers:()=>Uz,SemanticTokenTypes:()=>Wz,SemanticTokens:()=>Hz,SignatureInformation:()=>Dz,StringValue:()=>Zz,SymbolInformation:()=>Mz,SymbolKind:()=>Nz,SymbolTag:()=>Iz,TextDocument:()=>aG,TextDocumentEdit:()=>kk,TextDocumentIdentifier:()=>gz,TextDocumentItem:()=>vz,TextEdit:()=>Ku,URI:()=>cA,VersionedTextDocumentIdentifier:()=>yz,WorkspaceChange:()=>mz,WorkspaceEdit:()=>fA,WorkspaceFolder:()=>nG,WorkspaceSymbol:()=>Oz,integer:()=>sz,uinteger:()=>xk});var az,cA,sz,xk,oi,Jr,bk,oz,uA,lz,cz,uz,hz,hA,fz,dz,pz,Tk,Mm,Ku,Im,ns,pf,kk,uv,hv,fv,fA,cv,dA,mz,gz,yz,Ck,vz,pA,dv,xz,bz,Tz,kz,Cz,wz,Ez,Sz,wk,Az,_z,Dz,Lz,Rz,Nz,Iz,Mz,Oz,Pz,Bz,Ek,Fz,$z,zz,Gz,Vz,qz,Wz,Uz,Hz,Yz,jz,Xz,Kz,mA,gA,Qz,Zz,Jz,eG,tG,rG,iG,nG,mst,aG,sG,Xe,pv=P(()=>{"use strict";(function(t){function e(r){return typeof r=="string"}o(e,"is"),t.is=e})(az||(az={}));(function(t){function e(r){return typeof r=="string"}o(e,"is"),t.is=e})(cA||(cA={}));(function(t){t.MIN_VALUE=-2147483648,t.MAX_VALUE=2147483647;function e(r){return typeof r=="number"&&t.MIN_VALUE<=r&&r<=t.MAX_VALUE}o(e,"is"),t.is=e})(sz||(sz={}));(function(t){t.MIN_VALUE=0,t.MAX_VALUE=2147483647;function e(r){return typeof r=="number"&&t.MIN_VALUE<=r&&r<=t.MAX_VALUE}o(e,"is"),t.is=e})(xk||(xk={}));(function(t){function e(i,n){return i===Number.MAX_VALUE&&(i=xk.MAX_VALUE),n===Number.MAX_VALUE&&(n=xk.MAX_VALUE),{line:i,character:n}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.objectLiteral(n)&&Xe.uinteger(n.line)&&Xe.uinteger(n.character)}o(r,"is"),t.is=r})(oi||(oi={}));(function(t){function e(i,n,a,s){if(Xe.uinteger(i)&&Xe.uinteger(n)&&Xe.uinteger(a)&&Xe.uinteger(s))return{start:oi.create(i,n),end:oi.create(a,s)};if(oi.is(i)&&oi.is(n))return{start:i,end:n};throw new Error(`Range#create called with invalid arguments[${i}, ${n}, ${a}, ${s}]`)}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.objectLiteral(n)&&oi.is(n.start)&&oi.is(n.end)}o(r,"is"),t.is=r})(Jr||(Jr={}));(function(t){function e(i,n){return{uri:i,range:n}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.objectLiteral(n)&&Jr.is(n.range)&&(Xe.string(n.uri)||Xe.undefined(n.uri))}o(r,"is"),t.is=r})(bk||(bk={}));(function(t){function e(i,n,a,s){return{targetUri:i,targetRange:n,targetSelectionRange:a,originSelectionRange:s}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.objectLiteral(n)&&Jr.is(n.targetRange)&&Xe.string(n.targetUri)&&Jr.is(n.targetSelectionRange)&&(Jr.is(n.originSelectionRange)||Xe.undefined(n.originSelectionRange))}o(r,"is"),t.is=r})(oz||(oz={}));(function(t){function e(i,n,a,s){return{red:i,green:n,blue:a,alpha:s}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.objectLiteral(n)&&Xe.numberRange(n.red,0,1)&&Xe.numberRange(n.green,0,1)&&Xe.numberRange(n.blue,0,1)&&Xe.numberRange(n.alpha,0,1)}o(r,"is"),t.is=r})(uA||(uA={}));(function(t){function e(i,n){return{range:i,color:n}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.objectLiteral(n)&&Jr.is(n.range)&&uA.is(n.color)}o(r,"is"),t.is=r})(lz||(lz={}));(function(t){function e(i,n,a){return{label:i,textEdit:n,additionalTextEdits:a}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.objectLiteral(n)&&Xe.string(n.label)&&(Xe.undefined(n.textEdit)||Ku.is(n))&&(Xe.undefined(n.additionalTextEdits)||Xe.typedArray(n.additionalTextEdits,Ku.is))}o(r,"is"),t.is=r})(cz||(cz={}));(function(t){t.Comment="comment",t.Imports="imports",t.Region="region"})(uz||(uz={}));(function(t){function e(i,n,a,s,l,u){let h={startLine:i,endLine:n};return Xe.defined(a)&&(h.startCharacter=a),Xe.defined(s)&&(h.endCharacter=s),Xe.defined(l)&&(h.kind=l),Xe.defined(u)&&(h.collapsedText=u),h}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.objectLiteral(n)&&Xe.uinteger(n.startLine)&&Xe.uinteger(n.startLine)&&(Xe.undefined(n.startCharacter)||Xe.uinteger(n.startCharacter))&&(Xe.undefined(n.endCharacter)||Xe.uinteger(n.endCharacter))&&(Xe.undefined(n.kind)||Xe.string(n.kind))}o(r,"is"),t.is=r})(hz||(hz={}));(function(t){function e(i,n){return{location:i,message:n}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.defined(n)&&bk.is(n.location)&&Xe.string(n.message)}o(r,"is"),t.is=r})(hA||(hA={}));(function(t){t.Error=1,t.Warning=2,t.Information=3,t.Hint=4})(fz||(fz={}));(function(t){t.Unnecessary=1,t.Deprecated=2})(dz||(dz={}));(function(t){function e(r){let i=r;return Xe.objectLiteral(i)&&Xe.string(i.href)}o(e,"is"),t.is=e})(pz||(pz={}));(function(t){function e(i,n,a,s,l,u){let h={range:i,message:n};return Xe.defined(a)&&(h.severity=a),Xe.defined(s)&&(h.code=s),Xe.defined(l)&&(h.source=l),Xe.defined(u)&&(h.relatedInformation=u),h}o(e,"create"),t.create=e;function r(i){var n;let a=i;return Xe.defined(a)&&Jr.is(a.range)&&Xe.string(a.message)&&(Xe.number(a.severity)||Xe.undefined(a.severity))&&(Xe.integer(a.code)||Xe.string(a.code)||Xe.undefined(a.code))&&(Xe.undefined(a.codeDescription)||Xe.string((n=a.codeDescription)===null||n===void 0?void 0:n.href))&&(Xe.string(a.source)||Xe.undefined(a.source))&&(Xe.undefined(a.relatedInformation)||Xe.typedArray(a.relatedInformation,hA.is))}o(r,"is"),t.is=r})(Tk||(Tk={}));(function(t){function e(i,n,...a){let s={title:i,command:n};return Xe.defined(a)&&a.length>0&&(s.arguments=a),s}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.defined(n)&&Xe.string(n.title)&&Xe.string(n.command)}o(r,"is"),t.is=r})(Mm||(Mm={}));(function(t){function e(a,s){return{range:a,newText:s}}o(e,"replace"),t.replace=e;function r(a,s){return{range:{start:a,end:a},newText:s}}o(r,"insert"),t.insert=r;function i(a){return{range:a,newText:""}}o(i,"del"),t.del=i;function n(a){let s=a;return Xe.objectLiteral(s)&&Xe.string(s.newText)&&Jr.is(s.range)}o(n,"is"),t.is=n})(Ku||(Ku={}));(function(t){function e(i,n,a){let s={label:i};return n!==void 0&&(s.needsConfirmation=n),a!==void 0&&(s.description=a),s}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.objectLiteral(n)&&Xe.string(n.label)&&(Xe.boolean(n.needsConfirmation)||n.needsConfirmation===void 0)&&(Xe.string(n.description)||n.description===void 0)}o(r,"is"),t.is=r})(Im||(Im={}));(function(t){function e(r){let i=r;return Xe.string(i)}o(e,"is"),t.is=e})(ns||(ns={}));(function(t){function e(a,s,l){return{range:a,newText:s,annotationId:l}}o(e,"replace"),t.replace=e;function r(a,s,l){return{range:{start:a,end:a},newText:s,annotationId:l}}o(r,"insert"),t.insert=r;function i(a,s){return{range:a,newText:"",annotationId:s}}o(i,"del"),t.del=i;function n(a){let s=a;return Ku.is(s)&&(Im.is(s.annotationId)||ns.is(s.annotationId))}o(n,"is"),t.is=n})(pf||(pf={}));(function(t){function e(i,n){return{textDocument:i,edits:n}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.defined(n)&&Ck.is(n.textDocument)&&Array.isArray(n.edits)}o(r,"is"),t.is=r})(kk||(kk={}));(function(t){function e(i,n,a){let s={kind:"create",uri:i};return n!==void 0&&(n.overwrite!==void 0||n.ignoreIfExists!==void 0)&&(s.options=n),a!==void 0&&(s.annotationId=a),s}o(e,"create"),t.create=e;function r(i){let n=i;return n&&n.kind==="create"&&Xe.string(n.uri)&&(n.options===void 0||(n.options.overwrite===void 0||Xe.boolean(n.options.overwrite))&&(n.options.ignoreIfExists===void 0||Xe.boolean(n.options.ignoreIfExists)))&&(n.annotationId===void 0||ns.is(n.annotationId))}o(r,"is"),t.is=r})(uv||(uv={}));(function(t){function e(i,n,a,s){let l={kind:"rename",oldUri:i,newUri:n};return a!==void 0&&(a.overwrite!==void 0||a.ignoreIfExists!==void 0)&&(l.options=a),s!==void 0&&(l.annotationId=s),l}o(e,"create"),t.create=e;function r(i){let n=i;return n&&n.kind==="rename"&&Xe.string(n.oldUri)&&Xe.string(n.newUri)&&(n.options===void 0||(n.options.overwrite===void 0||Xe.boolean(n.options.overwrite))&&(n.options.ignoreIfExists===void 0||Xe.boolean(n.options.ignoreIfExists)))&&(n.annotationId===void 0||ns.is(n.annotationId))}o(r,"is"),t.is=r})(hv||(hv={}));(function(t){function e(i,n,a){let s={kind:"delete",uri:i};return n!==void 0&&(n.recursive!==void 0||n.ignoreIfNotExists!==void 0)&&(s.options=n),a!==void 0&&(s.annotationId=a),s}o(e,"create"),t.create=e;function r(i){let n=i;return n&&n.kind==="delete"&&Xe.string(n.uri)&&(n.options===void 0||(n.options.recursive===void 0||Xe.boolean(n.options.recursive))&&(n.options.ignoreIfNotExists===void 0||Xe.boolean(n.options.ignoreIfNotExists)))&&(n.annotationId===void 0||ns.is(n.annotationId))}o(r,"is"),t.is=r})(fv||(fv={}));(function(t){function e(r){let i=r;return i&&(i.changes!==void 0||i.documentChanges!==void 0)&&(i.documentChanges===void 0||i.documentChanges.every(n=>Xe.string(n.kind)?uv.is(n)||hv.is(n)||fv.is(n):kk.is(n)))}o(e,"is"),t.is=e})(fA||(fA={}));cv=class{static{o(this,"TextEditChangeImpl")}constructor(e,r){this.edits=e,this.changeAnnotations=r}insert(e,r,i){let n,a;if(i===void 0?n=Ku.insert(e,r):ns.is(i)?(a=i,n=pf.insert(e,r,i)):(this.assertChangeAnnotations(this.changeAnnotations),a=this.changeAnnotations.manage(i),n=pf.insert(e,r,a)),this.edits.push(n),a!==void 0)return a}replace(e,r,i){let n,a;if(i===void 0?n=Ku.replace(e,r):ns.is(i)?(a=i,n=pf.replace(e,r,i)):(this.assertChangeAnnotations(this.changeAnnotations),a=this.changeAnnotations.manage(i),n=pf.replace(e,r,a)),this.edits.push(n),a!==void 0)return a}delete(e,r){let i,n;if(r===void 0?i=Ku.del(e):ns.is(r)?(n=r,i=pf.del(e,r)):(this.assertChangeAnnotations(this.changeAnnotations),n=this.changeAnnotations.manage(r),i=pf.del(e,n)),this.edits.push(i),n!==void 0)return n}add(e){this.edits.push(e)}all(){return this.edits}clear(){this.edits.splice(0,this.edits.length)}assertChangeAnnotations(e){if(e===void 0)throw new Error("Text edit change is not configured to manage change annotations.")}},dA=class{static{o(this,"ChangeAnnotations")}constructor(e){this._annotations=e===void 0?Object.create(null):e,this._counter=0,this._size=0}all(){return this._annotations}get size(){return this._size}manage(e,r){let i;if(ns.is(e)?i=e:(i=this.nextId(),r=e),this._annotations[i]!==void 0)throw new Error(`Id ${i} is already in use.`);if(r===void 0)throw new Error(`No annotation provided for id ${i}`);return this._annotations[i]=r,this._size++,i}nextId(){return this._counter++,this._counter.toString()}},mz=class{static{o(this,"WorkspaceChange")}constructor(e){this._textEditChanges=Object.create(null),e!==void 0?(this._workspaceEdit=e,e.documentChanges?(this._changeAnnotations=new dA(e.changeAnnotations),e.changeAnnotations=this._changeAnnotations.all(),e.documentChanges.forEach(r=>{if(kk.is(r)){let i=new cv(r.edits,this._changeAnnotations);this._textEditChanges[r.textDocument.uri]=i}})):e.changes&&Object.keys(e.changes).forEach(r=>{let i=new cv(e.changes[r]);this._textEditChanges[r]=i})):this._workspaceEdit={}}get edit(){return this.initDocumentChanges(),this._changeAnnotations!==void 0&&(this._changeAnnotations.size===0?this._workspaceEdit.changeAnnotations=void 0:this._workspaceEdit.changeAnnotations=this._changeAnnotations.all()),this._workspaceEdit}getTextEditChange(e){if(Ck.is(e)){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");let r={uri:e.uri,version:e.version},i=this._textEditChanges[r.uri];if(!i){let n=[],a={textDocument:r,edits:n};this._workspaceEdit.documentChanges.push(a),i=new cv(n,this._changeAnnotations),this._textEditChanges[r.uri]=i}return i}else{if(this.initChanges(),this._workspaceEdit.changes===void 0)throw new Error("Workspace edit is not configured for normal text edit changes.");let r=this._textEditChanges[e];if(!r){let i=[];this._workspaceEdit.changes[e]=i,r=new cv(i),this._textEditChanges[e]=r}return r}}initDocumentChanges(){this._workspaceEdit.documentChanges===void 0&&this._workspaceEdit.changes===void 0&&(this._changeAnnotations=new dA,this._workspaceEdit.documentChanges=[],this._workspaceEdit.changeAnnotations=this._changeAnnotations.all())}initChanges(){this._workspaceEdit.documentChanges===void 0&&this._workspaceEdit.changes===void 0&&(this._workspaceEdit.changes=Object.create(null))}createFile(e,r,i){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");let n;Im.is(r)||ns.is(r)?n=r:i=r;let a,s;if(n===void 0?a=uv.create(e,i):(s=ns.is(n)?n:this._changeAnnotations.manage(n),a=uv.create(e,i,s)),this._workspaceEdit.documentChanges.push(a),s!==void 0)return s}renameFile(e,r,i,n){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");let a;Im.is(i)||ns.is(i)?a=i:n=i;let s,l;if(a===void 0?s=hv.create(e,r,n):(l=ns.is(a)?a:this._changeAnnotations.manage(a),s=hv.create(e,r,n,l)),this._workspaceEdit.documentChanges.push(s),l!==void 0)return l}deleteFile(e,r,i){if(this.initDocumentChanges(),this._workspaceEdit.documentChanges===void 0)throw new Error("Workspace edit is not configured for document changes.");let n;Im.is(r)||ns.is(r)?n=r:i=r;let a,s;if(n===void 0?a=fv.create(e,i):(s=ns.is(n)?n:this._changeAnnotations.manage(n),a=fv.create(e,i,s)),this._workspaceEdit.documentChanges.push(a),s!==void 0)return s}};(function(t){function e(i){return{uri:i}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.defined(n)&&Xe.string(n.uri)}o(r,"is"),t.is=r})(gz||(gz={}));(function(t){function e(i,n){return{uri:i,version:n}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.defined(n)&&Xe.string(n.uri)&&Xe.integer(n.version)}o(r,"is"),t.is=r})(yz||(yz={}));(function(t){function e(i,n){return{uri:i,version:n}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.defined(n)&&Xe.string(n.uri)&&(n.version===null||Xe.integer(n.version))}o(r,"is"),t.is=r})(Ck||(Ck={}));(function(t){function e(i,n,a,s){return{uri:i,languageId:n,version:a,text:s}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.defined(n)&&Xe.string(n.uri)&&Xe.string(n.languageId)&&Xe.integer(n.version)&&Xe.string(n.text)}o(r,"is"),t.is=r})(vz||(vz={}));(function(t){t.PlainText="plaintext",t.Markdown="markdown";function e(r){let i=r;return i===t.PlainText||i===t.Markdown}o(e,"is"),t.is=e})(pA||(pA={}));(function(t){function e(r){let i=r;return Xe.objectLiteral(r)&&pA.is(i.kind)&&Xe.string(i.value)}o(e,"is"),t.is=e})(dv||(dv={}));(function(t){t.Text=1,t.Method=2,t.Function=3,t.Constructor=4,t.Field=5,t.Variable=6,t.Class=7,t.Interface=8,t.Module=9,t.Property=10,t.Unit=11,t.Value=12,t.Enum=13,t.Keyword=14,t.Snippet=15,t.Color=16,t.File=17,t.Reference=18,t.Folder=19,t.EnumMember=20,t.Constant=21,t.Struct=22,t.Event=23,t.Operator=24,t.TypeParameter=25})(xz||(xz={}));(function(t){t.PlainText=1,t.Snippet=2})(bz||(bz={}));(function(t){t.Deprecated=1})(Tz||(Tz={}));(function(t){function e(i,n,a){return{newText:i,insert:n,replace:a}}o(e,"create"),t.create=e;function r(i){let n=i;return n&&Xe.string(n.newText)&&Jr.is(n.insert)&&Jr.is(n.replace)}o(r,"is"),t.is=r})(kz||(kz={}));(function(t){t.asIs=1,t.adjustIndentation=2})(Cz||(Cz={}));(function(t){function e(r){let i=r;return i&&(Xe.string(i.detail)||i.detail===void 0)&&(Xe.string(i.description)||i.description===void 0)}o(e,"is"),t.is=e})(wz||(wz={}));(function(t){function e(r){return{label:r}}o(e,"create"),t.create=e})(Ez||(Ez={}));(function(t){function e(r,i){return{items:r||[],isIncomplete:!!i}}o(e,"create"),t.create=e})(Sz||(Sz={}));(function(t){function e(i){return i.replace(/[\\`*_{}[\]()#+\-.!]/g,"\\$&")}o(e,"fromPlainText"),t.fromPlainText=e;function r(i){let n=i;return Xe.string(n)||Xe.objectLiteral(n)&&Xe.string(n.language)&&Xe.string(n.value)}o(r,"is"),t.is=r})(wk||(wk={}));(function(t){function e(r){let i=r;return!!i&&Xe.objectLiteral(i)&&(dv.is(i.contents)||wk.is(i.contents)||Xe.typedArray(i.contents,wk.is))&&(r.range===void 0||Jr.is(r.range))}o(e,"is"),t.is=e})(Az||(Az={}));(function(t){function e(r,i){return i?{label:r,documentation:i}:{label:r}}o(e,"create"),t.create=e})(_z||(_z={}));(function(t){function e(r,i,...n){let a={label:r};return Xe.defined(i)&&(a.documentation=i),Xe.defined(n)?a.parameters=n:a.parameters=[],a}o(e,"create"),t.create=e})(Dz||(Dz={}));(function(t){t.Text=1,t.Read=2,t.Write=3})(Lz||(Lz={}));(function(t){function e(r,i){let n={range:r};return Xe.number(i)&&(n.kind=i),n}o(e,"create"),t.create=e})(Rz||(Rz={}));(function(t){t.File=1,t.Module=2,t.Namespace=3,t.Package=4,t.Class=5,t.Method=6,t.Property=7,t.Field=8,t.Constructor=9,t.Enum=10,t.Interface=11,t.Function=12,t.Variable=13,t.Constant=14,t.String=15,t.Number=16,t.Boolean=17,t.Array=18,t.Object=19,t.Key=20,t.Null=21,t.EnumMember=22,t.Struct=23,t.Event=24,t.Operator=25,t.TypeParameter=26})(Nz||(Nz={}));(function(t){t.Deprecated=1})(Iz||(Iz={}));(function(t){function e(r,i,n,a,s){let l={name:r,kind:i,location:{uri:a,range:n}};return s&&(l.containerName=s),l}o(e,"create"),t.create=e})(Mz||(Mz={}));(function(t){function e(r,i,n,a){return a!==void 0?{name:r,kind:i,location:{uri:n,range:a}}:{name:r,kind:i,location:{uri:n}}}o(e,"create"),t.create=e})(Oz||(Oz={}));(function(t){function e(i,n,a,s,l,u){let h={name:i,detail:n,kind:a,range:s,selectionRange:l};return u!==void 0&&(h.children=u),h}o(e,"create"),t.create=e;function r(i){let n=i;return n&&Xe.string(n.name)&&Xe.number(n.kind)&&Jr.is(n.range)&&Jr.is(n.selectionRange)&&(n.detail===void 0||Xe.string(n.detail))&&(n.deprecated===void 0||Xe.boolean(n.deprecated))&&(n.children===void 0||Array.isArray(n.children))&&(n.tags===void 0||Array.isArray(n.tags))}o(r,"is"),t.is=r})(Pz||(Pz={}));(function(t){t.Empty="",t.QuickFix="quickfix",t.Refactor="refactor",t.RefactorExtract="refactor.extract",t.RefactorInline="refactor.inline",t.RefactorRewrite="refactor.rewrite",t.Source="source",t.SourceOrganizeImports="source.organizeImports",t.SourceFixAll="source.fixAll"})(Bz||(Bz={}));(function(t){t.Invoked=1,t.Automatic=2})(Ek||(Ek={}));(function(t){function e(i,n,a){let s={diagnostics:i};return n!=null&&(s.only=n),a!=null&&(s.triggerKind=a),s}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.defined(n)&&Xe.typedArray(n.diagnostics,Tk.is)&&(n.only===void 0||Xe.typedArray(n.only,Xe.string))&&(n.triggerKind===void 0||n.triggerKind===Ek.Invoked||n.triggerKind===Ek.Automatic)}o(r,"is"),t.is=r})(Fz||(Fz={}));(function(t){function e(i,n,a){let s={title:i},l=!0;return typeof n=="string"?(l=!1,s.kind=n):Mm.is(n)?s.command=n:s.edit=n,l&&a!==void 0&&(s.kind=a),s}o(e,"create"),t.create=e;function r(i){let n=i;return n&&Xe.string(n.title)&&(n.diagnostics===void 0||Xe.typedArray(n.diagnostics,Tk.is))&&(n.kind===void 0||Xe.string(n.kind))&&(n.edit!==void 0||n.command!==void 0)&&(n.command===void 0||Mm.is(n.command))&&(n.isPreferred===void 0||Xe.boolean(n.isPreferred))&&(n.edit===void 0||fA.is(n.edit))}o(r,"is"),t.is=r})($z||($z={}));(function(t){function e(i,n){let a={range:i};return Xe.defined(n)&&(a.data=n),a}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.defined(n)&&Jr.is(n.range)&&(Xe.undefined(n.command)||Mm.is(n.command))}o(r,"is"),t.is=r})(zz||(zz={}));(function(t){function e(i,n){return{tabSize:i,insertSpaces:n}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.defined(n)&&Xe.uinteger(n.tabSize)&&Xe.boolean(n.insertSpaces)}o(r,"is"),t.is=r})(Gz||(Gz={}));(function(t){function e(i,n,a){return{range:i,target:n,data:a}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.defined(n)&&Jr.is(n.range)&&(Xe.undefined(n.target)||Xe.string(n.target))}o(r,"is"),t.is=r})(Vz||(Vz={}));(function(t){function e(i,n){return{range:i,parent:n}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.objectLiteral(n)&&Jr.is(n.range)&&(n.parent===void 0||t.is(n.parent))}o(r,"is"),t.is=r})(qz||(qz={}));(function(t){t.namespace="namespace",t.type="type",t.class="class",t.enum="enum",t.interface="interface",t.struct="struct",t.typeParameter="typeParameter",t.parameter="parameter",t.variable="variable",t.property="property",t.enumMember="enumMember",t.event="event",t.function="function",t.method="method",t.macro="macro",t.keyword="keyword",t.modifier="modifier",t.comment="comment",t.string="string",t.number="number",t.regexp="regexp",t.operator="operator",t.decorator="decorator"})(Wz||(Wz={}));(function(t){t.declaration="declaration",t.definition="definition",t.readonly="readonly",t.static="static",t.deprecated="deprecated",t.abstract="abstract",t.async="async",t.modification="modification",t.documentation="documentation",t.defaultLibrary="defaultLibrary"})(Uz||(Uz={}));(function(t){function e(r){let i=r;return Xe.objectLiteral(i)&&(i.resultId===void 0||typeof i.resultId=="string")&&Array.isArray(i.data)&&(i.data.length===0||typeof i.data[0]=="number")}o(e,"is"),t.is=e})(Hz||(Hz={}));(function(t){function e(i,n){return{range:i,text:n}}o(e,"create"),t.create=e;function r(i){let n=i;return n!=null&&Jr.is(n.range)&&Xe.string(n.text)}o(r,"is"),t.is=r})(Yz||(Yz={}));(function(t){function e(i,n,a){return{range:i,variableName:n,caseSensitiveLookup:a}}o(e,"create"),t.create=e;function r(i){let n=i;return n!=null&&Jr.is(n.range)&&Xe.boolean(n.caseSensitiveLookup)&&(Xe.string(n.variableName)||n.variableName===void 0)}o(r,"is"),t.is=r})(jz||(jz={}));(function(t){function e(i,n){return{range:i,expression:n}}o(e,"create"),t.create=e;function r(i){let n=i;return n!=null&&Jr.is(n.range)&&(Xe.string(n.expression)||n.expression===void 0)}o(r,"is"),t.is=r})(Xz||(Xz={}));(function(t){function e(i,n){return{frameId:i,stoppedLocation:n}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.defined(n)&&Jr.is(i.stoppedLocation)}o(r,"is"),t.is=r})(Kz||(Kz={}));(function(t){t.Type=1,t.Parameter=2;function e(r){return r===1||r===2}o(e,"is"),t.is=e})(mA||(mA={}));(function(t){function e(i){return{value:i}}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.objectLiteral(n)&&(n.tooltip===void 0||Xe.string(n.tooltip)||dv.is(n.tooltip))&&(n.location===void 0||bk.is(n.location))&&(n.command===void 0||Mm.is(n.command))}o(r,"is"),t.is=r})(gA||(gA={}));(function(t){function e(i,n,a){let s={position:i,label:n};return a!==void 0&&(s.kind=a),s}o(e,"create"),t.create=e;function r(i){let n=i;return Xe.objectLiteral(n)&&oi.is(n.position)&&(Xe.string(n.label)||Xe.typedArray(n.label,gA.is))&&(n.kind===void 0||mA.is(n.kind))&&n.textEdits===void 0||Xe.typedArray(n.textEdits,Ku.is)&&(n.tooltip===void 0||Xe.string(n.tooltip)||dv.is(n.tooltip))&&(n.paddingLeft===void 0||Xe.boolean(n.paddingLeft))&&(n.paddingRight===void 0||Xe.boolean(n.paddingRight))}o(r,"is"),t.is=r})(Qz||(Qz={}));(function(t){function e(r){return{kind:"snippet",value:r}}o(e,"createSnippet"),t.createSnippet=e})(Zz||(Zz={}));(function(t){function e(r,i,n,a){return{insertText:r,filterText:i,range:n,command:a}}o(e,"create"),t.create=e})(Jz||(Jz={}));(function(t){function e(r){return{items:r}}o(e,"create"),t.create=e})(eG||(eG={}));(function(t){t.Invoked=0,t.Automatic=1})(tG||(tG={}));(function(t){function e(r,i){return{range:r,text:i}}o(e,"create"),t.create=e})(rG||(rG={}));(function(t){function e(r,i){return{triggerKind:r,selectedCompletionInfo:i}}o(e,"create"),t.create=e})(iG||(iG={}));(function(t){function e(r){let i=r;return Xe.objectLiteral(i)&&cA.is(i.uri)&&Xe.string(i.name)}o(e,"is"),t.is=e})(nG||(nG={}));mst=[` +`,`\r +`,"\r"];(function(t){function e(a,s,l,u){return new sG(a,s,l,u)}o(e,"create"),t.create=e;function r(a){let s=a;return!!(Xe.defined(s)&&Xe.string(s.uri)&&(Xe.undefined(s.languageId)||Xe.string(s.languageId))&&Xe.uinteger(s.lineCount)&&Xe.func(s.getText)&&Xe.func(s.positionAt)&&Xe.func(s.offsetAt))}o(r,"is"),t.is=r;function i(a,s){let l=a.getText(),u=n(s,(f,d)=>{let p=f.range.start.line-d.range.start.line;return p===0?f.range.start.character-d.range.start.character:p}),h=l.length;for(let f=u.length-1;f>=0;f--){let d=u[f],p=a.offsetAt(d.range.start),m=a.offsetAt(d.range.end);if(m<=h)l=l.substring(0,p)+d.newText+l.substring(m,l.length);else throw new Error("Overlapping edit");h=p}return l}o(i,"applyEdits"),t.applyEdits=i;function n(a,s){if(a.length<=1)return a;let l=a.length/2|0,u=a.slice(0,l),h=a.slice(l);n(u,s),n(h,s);let f=0,d=0,p=0;for(;f0&&e.push(r.length),this._lineOffsets=e}return this._lineOffsets}positionAt(e){e=Math.max(Math.min(e,this._content.length),0);let r=this.getLineOffsets(),i=0,n=r.length;if(n===0)return oi.create(0,e);for(;ie?n=s:i=s+1}let a=i-1;return oi.create(a,e-r[a])}offsetAt(e){let r=this.getLineOffsets();if(e.line>=r.length)return this._content.length;if(e.line<0)return 0;let i=r[e.line],n=e.line+1"u"}o(i,"undefined"),t.undefined=i;function n(m){return m===!0||m===!1}o(n,"boolean"),t.boolean=n;function a(m){return e.call(m)==="[object String]"}o(a,"string"),t.string=a;function s(m){return e.call(m)==="[object Number]"}o(s,"number"),t.number=s;function l(m,g,y){return e.call(m)==="[object Number]"&&g<=m&&m<=y}o(l,"numberRange"),t.numberRange=l;function u(m){return e.call(m)==="[object Number]"&&-2147483648<=m&&m<=2147483647}o(u,"integer"),t.integer=u;function h(m){return e.call(m)==="[object Number]"&&0<=m&&m<=2147483647}o(h,"uinteger"),t.uinteger=h;function f(m){return e.call(m)==="[object Function]"}o(f,"func"),t.func=f;function d(m){return m!==null&&typeof m=="object"}o(d,"objectLiteral"),t.objectLiteral=d;function p(m,g){return Array.isArray(m)&&m.every(g)}o(p,"typedArray"),t.typedArray=p})(Xe||(Xe={}))});var Sk,Ak,Om,Pm,oG,mv,vA=P(()=>{"use strict";pv();Bc();Sk=class{static{o(this,"CstNodeBuilder")}constructor(){this.nodeStack=[]}get current(){return this.nodeStack[this.nodeStack.length-1]??this.rootNode}buildRootNode(e){return this.rootNode=new mv(e),this.rootNode.root=this.rootNode,this.nodeStack=[this.rootNode],this.rootNode}buildCompositeNode(e){let r=new Pm;return r.grammarSource=e,r.root=this.rootNode,this.current.content.push(r),this.nodeStack.push(r),r}buildLeafNode(e,r){let i=new Om(e.startOffset,e.image.length,Py(e),e.tokenType,!r);return i.grammarSource=r,i.root=this.rootNode,this.current.content.push(i),i}removeNode(e){let r=e.container;if(r){let i=r.content.indexOf(e);i>=0&&r.content.splice(i,1)}}addHiddenNodes(e){let r=[];for(let a of e){let s=new Om(a.startOffset,a.image.length,Py(a),a.tokenType,!0);s.root=this.rootNode,r.push(s)}let i=this.current,n=!1;if(i.content.length>0){i.content.push(...r);return}for(;i.container;){let a=i.container.content.indexOf(i);if(a>0){i.container.content.splice(a,0,...r),n=!0;break}i=i.container}n||this.rootNode.content.unshift(...r)}construct(e){let r=this.current;typeof e.$type=="string"&&!e.$infix&&(this.current.astNode=e),e.$cstNode=r;let i=this.nodeStack.pop();i?.content.length===0&&this.removeNode(i)}},Ak=class{static{o(this,"AbstractCstNode")}get hidden(){return!1}get astNode(){let e=typeof this._astNode?.$type=="string"?this._astNode:this.container?.astNode;if(!e)throw new Error("This node has no associated AST element");return e}set astNode(e){this._astNode=e}get text(){return this.root.fullText.substring(this.offset,this.end)}},Om=class extends Ak{static{o(this,"LeafCstNodeImpl")}get offset(){return this._offset}get length(){return this._length}get end(){return this._offset+this._length}get hidden(){return this._hidden}get tokenType(){return this._tokenType}get range(){return this._range}constructor(e,r,i,n,a=!1){super(),this._hidden=a,this._offset=e,this._tokenType=n,this._length=r,this._range=i}},Pm=class extends Ak{static{o(this,"CompositeCstNodeImpl")}constructor(){super(...arguments),this.content=new oG(this)}get offset(){return this.firstNonHiddenNode?.offset??0}get length(){return this.end-this.offset}get end(){return this.lastNonHiddenNode?.end??0}get range(){let e=this.firstNonHiddenNode,r=this.lastNonHiddenNode;if(e&&r){if(this._rangeCache===void 0){let{range:i}=e,{range:n}=r;this._rangeCache={start:i.start,end:n.end.line=0;e--){let r=this.content[e];if(!r.hidden)return r}return this.content[this.content.length-1]}},oG=class t extends Array{static{o(this,"CstNodeContainer")}constructor(e){super(),this.parent=e,Object.setPrototypeOf(this,t.prototype)}push(...e){return this.addParents(e),super.push(...e)}unshift(...e){return this.addParents(e),super.unshift(...e)}splice(e,r,...i){return this.addParents(i),super.splice(e,r,...i)}addParents(e){for(let r of e)r.container=this.parent}},mv=class extends Pm{static{o(this,"RootCstNodeImpl")}get text(){return this._text.substring(this.offset,this.end)}get fullText(){return this._text}constructor(e){super(),this._text="",this._text=e??""}}});function lG(t){return t.$type===xA}var xA,t2e,r2e,_k,Dk,bA,gv,Lk,gst,TA,cG,Rk=P(()=>{"use strict";ol();sp();e2e();ol();Vc();Ts();vA();xA=Symbol("Datatype");o(lG,"isDataTypeNode");t2e="\u200B",r2e=o(t=>t.endsWith(t2e)?t:t+t2e,"withRuleSuffix"),_k=class{static{o(this,"AbstractLangiumParser")}constructor(e){this._unorderedGroups=new Map,this.allRules=new Map,this.lexer=e.parser.Lexer;let r=this.lexer.definition,i=e.LanguageMetaData.mode==="production";e.shared.profilers.LangiumProfiler?.isActive("parsing")?this.wrapper=new cG(r,{...e.parser.ParserConfig,skipValidations:i,errorMessageProvider:e.parser.ParserErrorMessageProvider},e.shared.profilers.LangiumProfiler.createTask("parsing",e.LanguageMetaData.languageId)):this.wrapper=new TA(r,{...e.parser.ParserConfig,skipValidations:i,errorMessageProvider:e.parser.ParserErrorMessageProvider})}alternatives(e,r){this.wrapper.wrapOr(e,r)}optional(e,r){this.wrapper.wrapOption(e,r)}many(e,r){this.wrapper.wrapMany(e,r)}atLeastOne(e,r){this.wrapper.wrapAtLeastOne(e,r)}getRule(e){return this.allRules.get(e)}isRecording(){return this.wrapper.IS_RECORDING}get unorderedGroups(){return this._unorderedGroups}getRuleStack(){return this.wrapper.RULE_STACK}finalize(){this.wrapper.wrapSelfAnalysis()}},Dk=class extends _k{static{o(this,"LangiumParser")}get current(){return this.stack[this.stack.length-1]}constructor(e){super(e),this.nodeBuilder=new Sk,this.stack=[],this.assignmentMap=new Map,this.operatorPrecedence=new Map,this.linker=e.references.Linker,this.converter=e.parser.ValueConverter,this.astReflection=e.shared.AstReflection}rule(e,r){let i=this.computeRuleType(e),n;tp(e)&&(n=e.name,this.registerPrecedenceMap(e));let a=this.wrapper.DEFINE_RULE(r2e(e.name),this.startImplementation(i,n,r).bind(this));return this.allRules.set(e.name,a),Ba(e)&&e.entry&&(this.mainRule=a),a}registerPrecedenceMap(e){let r=e.name,i=new Map;for(let n=0;n0&&(r=this.construct()),r===void 0)throw new Error("No result from parser");if(this.stack.length>0)throw new Error("Parser stack is not empty after parsing");return r}startImplementation(e,r,i){return n=>{let a=!this.isRecording()&&e!==void 0;if(a){let s={$type:e};this.stack.push(s),e===xA?s.value="":r!==void 0&&(s.$infixName=r)}return i(n),a?this.construct():void 0}}extractHiddenTokens(e){let r=this.lexerResult.hidden;if(!r.length)return[];let i=e.startOffset;for(let n=0;ni)return r.splice(0,n);return r.splice(0,r.length)}consume(e,r,i){let n=this.wrapper.wrapConsume(e,r);if(!this.isRecording()&&this.isValidToken(n)){let a=this.extractHiddenTokens(n);this.nodeBuilder.addHiddenNodes(a);let s=this.nodeBuilder.buildLeafNode(n,i),{assignment:l,crossRef:u}=this.getAssignment(i),h=this.current;if(l){let f=Hl(i)?n.image:this.converter.convert(n.image,s);this.assign(l.operator,l.feature,f,s,u)}else if(lG(h)){let f=n.image;Hl(i)||(f=this.converter.convert(f,s).toString()),h.value+=f}}}isValidToken(e){return!e.isInsertedInRecovery&&!isNaN(e.startOffset)&&typeof e.endOffset=="number"&&!isNaN(e.endOffset)}subrule(e,r,i,n,a){let s;!this.isRecording()&&!i&&(s=this.nodeBuilder.buildCompositeNode(n));let l;try{l=this.wrapper.wrapSubrule(e,r,a)}finally{this.isRecording()||(l===void 0&&!i&&(l=this.construct()),l!==void 0&&s&&s.length>0&&this.performSubruleAssignment(l,n,s))}}performSubruleAssignment(e,r,i){let{assignment:n,crossRef:a}=this.getAssignment(r);if(n)this.assign(n.operator,n.feature,e,i,a);else if(!n){let s=this.current;if(lG(s))s.value+=e.toString();else if(typeof e=="object"&&e){let u=this.assignWithoutOverride(e,s);this.stack.pop(),this.stack.push(u)}}}action(e,r){if(!this.isRecording()){let i=this.current;if(r.feature&&r.operator){i=this.construct(),this.nodeBuilder.removeNode(i.$cstNode),this.nodeBuilder.buildCompositeNode(r).content.push(i.$cstNode);let a={$type:e};this.stack.push(a),this.assign(r.operator,r.feature,i,i.$cstNode)}else i.$type=e}}construct(){if(this.isRecording())return;let e=this.stack.pop();return this.nodeBuilder.construct(e),"$infixName"in e?this.constructInfix(e,this.operatorPrecedence.get(e.$infixName)):lG(e)?this.converter.convert(e.value,e.$cstNode):(LF(this.astReflection,e),e)}constructInfix(e,r){let i=e.parts;if(!Array.isArray(i)||i.length===0)return;let n=e.operators;if(!Array.isArray(n)||i.length<2)return i[0];let a=0,s=-1;for(let y=0;ys?(s=x.precedence,a=y):x.precedence===s&&(x.rightAssoc||(a=y))}let l=n.slice(0,a),u=n.slice(a+1),h=i.slice(0,a+1),f=i.slice(a+1),d={$infixName:e.$infixName,$type:e.$type,$cstNode:e.$cstNode,parts:h,operators:l},p={$infixName:e.$infixName,$type:e.$type,$cstNode:e.$cstNode,parts:f,operators:u},m=this.constructInfix(d,r),g=this.constructInfix(p,r);return{$type:e.$type,$cstNode:e.$cstNode,left:m,operator:n[a],right:g}}getAssignment(e){if(!this.assignmentMap.has(e)){let r=ef(e,$c);this.assignmentMap.set(e,{assignment:r,crossRef:r&&zc(r.terminal)?r.terminal.isMulti?"multi":"single":void 0})}return this.assignmentMap.get(e)}assign(e,r,i,n,a){let s=this.current,l;switch(a==="single"&&typeof i=="string"?l=this.linker.buildReference(s,r,n,i):a==="multi"&&typeof i=="string"?l=this.linker.buildMultiReference(s,r,n,i):l=i,e){case"=":{s[r]=l;break}case"?=":{s[r]=!0;break}case"+=":Array.isArray(s[r])||(s[r]=[]),s[r].push(l)}}assignWithoutOverride(e,r){for(let[n,a]of Object.entries(r)){let s=e[n];s===void 0?e[n]=a:Array.isArray(s)&&Array.isArray(a)&&(a.push(...s),e[n]=a)}let i=e.$cstNode;return i&&(i.astNode=void 0,e.$cstNode=void 0),e}get definitionErrors(){return this.wrapper.definitionErrors}},bA=class{static{o(this,"AbstractParserErrorMessageProvider")}buildMismatchTokenMessage(e){return ff.buildMismatchTokenMessage(e)}buildNotAllInputParsedMessage(e){return ff.buildNotAllInputParsedMessage(e)}buildNoViableAltMessage(e){return ff.buildNoViableAltMessage(e)}buildEarlyExitMessage(e){return ff.buildEarlyExitMessage(e)}},gv=class extends bA{static{o(this,"LangiumParserErrorMessageProvider")}buildMismatchTokenMessage({expected:e,actual:r}){return`Expecting ${e.LABEL?"`"+e.LABEL+"`":e.name.endsWith(":KW")?`keyword '${e.name.substring(0,e.name.length-3)}'`:`token of type '${e.name}'`} but found \`${r.image}\`.`}buildNotAllInputParsedMessage({firstRedundant:e}){return`Expecting end of file but found \`${e.image}\`.`}},Lk=class extends _k{static{o(this,"LangiumCompletionParser")}constructor(){super(...arguments),this.tokens=[],this.elementStack=[],this.lastElementStack=[],this.nextTokenIndex=0,this.stackSize=0}action(){}construct(){}parse(e){this.resetState();let r=this.lexer.tokenize(e,{mode:"partial"});return this.tokens=r.tokens,this.wrapper.input=[...this.tokens],this.mainRule.call(this.wrapper,{}),this.unorderedGroups.clear(),{tokens:this.tokens,elementStack:[...this.lastElementStack],tokenIndex:this.nextTokenIndex}}rule(e,r){let i=this.wrapper.DEFINE_RULE(r2e(e.name),this.startImplementation(r).bind(this));return this.allRules.set(e.name,i),e.entry&&(this.mainRule=i),i}resetState(){this.elementStack=[],this.lastElementStack=[],this.nextTokenIndex=0,this.stackSize=0}startImplementation(e){return r=>{let i=this.keepStackSize();try{e(r)}finally{this.resetStackSize(i)}}}removeUnexpectedElements(){this.elementStack.splice(this.stackSize)}keepStackSize(){let e=this.elementStack.length;return this.stackSize=e,e}resetStackSize(e){this.removeUnexpectedElements(),this.stackSize=e}consume(e,r,i){this.wrapper.wrapConsume(e,r),this.isRecording()||(this.lastElementStack=[...this.elementStack,i],this.nextTokenIndex=this.currIdx+1)}subrule(e,r,i,n,a){this.before(n),this.wrapper.wrapSubrule(e,r,a),this.after(n)}before(e){this.isRecording()||this.elementStack.push(e)}after(e){if(!this.isRecording()){let r=this.elementStack.lastIndexOf(e);r>=0&&this.elementStack.splice(r)}}get currIdx(){return this.wrapper.currIdx}},gst={recoveryEnabled:!0,nodeLocationTracking:"full",skipValidations:!0,errorMessageProvider:new gv},TA=class extends pk{static{o(this,"ChevrotainWrapper")}constructor(e,r){let i=r&&"maxLookahead"in r;super(e,{...gst,lookaheadStrategy:i?new df({maxLookahead:r.maxLookahead}):new vk({logging:r.skipValidations?()=>{}:void 0}),...r})}get IS_RECORDING(){return this.RECORDING_PHASE}DEFINE_RULE(e,r,i){return this.RULE(e,r,i)}wrapSelfAnalysis(){this.performSelfAnalysis()}wrapConsume(e,r){return this.consume(e,r,void 0)}wrapSubrule(e,r,i){return this.subrule(e,r,{ARGS:[i]})}wrapOr(e,r){this.or(e,r)}wrapOption(e,r){this.option(e,r)}wrapMany(e,r){this.many(e,r)}wrapAtLeastOne(e,r){this.atLeastOne(e,r)}rule(e){return e.call(this,{})}},cG=class extends TA{static{o(this,"ProfilerWrapper")}constructor(e,r,i){super(e,r),this.task=i}rule(e){this.task.start(),this.task.startSubTask(this.ruleName(e));try{return super.rule(e)}finally{this.task.stopSubTask(this.ruleName(e)),this.task.stop()}}ruleName(e){return e.ruleName}subrule(e,r,i){this.task.startSubTask(this.ruleName(r));try{return super.subrule(e,r,i)}finally{this.task.stopSubTask(this.ruleName(r))}}}});function Nk(t,e,r){return yst({parser:e,tokens:r,ruleNames:new Map},t),e}function yst(t,e){let r=HT(e,!1),i=jr(e.rules).filter(Ba).filter(a=>r.has(a));for(let a of i){let s={...t,consume:1,optional:1,subrule:1,many:1,or:1};t.parser.rule(a,Bm(s,a.definition))}let n=jr(e.rules).filter(tp).filter(a=>r.has(a));for(let a of n)t.parser.rule(a,vst(t,a))}function vst(t,e){let r=e.call.rule.ref;if(!r)throw new Error("Could not resolve reference to infix operator rule: "+e.call.rule.$refText);if(Xs(r))throw new Error("Cannot use terminal rule in infix expression");let i=e.operators.precedences.flatMap(m=>m.operators),n={$type:"Group",elements:[]},a={$container:n,$type:"Assignment",feature:"parts",operator:"+=",terminal:e.call},s={$container:n,$type:"Group",elements:[],cardinality:"*"};n.elements.push(a,s);let u={$container:s,$type:"Assignment",feature:"operators",operator:"+=",terminal:{$type:"Alternatives",elements:i}},h={...a,$container:s};s.elements.push(u,h);let d=i.map(m=>t.tokens[m.value]).map((m,g)=>({ALT:o(()=>t.parser.consume(g,m,u),"ALT")})),p;return m=>{p??(p=hG(t,r)),t.parser.subrule(0,p,!1,a,m),t.parser.many(0,{DEF:o(()=>{t.parser.alternatives(0,d),t.parser.subrule(1,p,!1,h,m)},"DEF")})}}function Bm(t,e,r=!1){let i;if(Hl(e))i=Est(t,e);else if(af(e))i=xst(t,e);else if($c(e))i=Bm(t,e.terminal);else if(zc(e))i=i2e(t,e);else if(Gc(e))i=bst(t,e);else if(c6(e))i=kst(t,e);else if(d6(e))i=Cst(t,e);else if(ep(e))i=wst(t,e);else if(BF(e)){let n=t.consume++;i=o(()=>t.parser.consume(n,cl,e),"method")}else throw new Tm(e.$cstNode,`Unexpected element type: ${e.$type}`);return n2e(t,r?void 0:kA(e),i,e.cardinality)}function xst(t,e){let r=ip(e);return()=>t.parser.action(r,e)}function bst(t,e){let r=e.rule.ref;if(nf(r)){let i=t.subrule++,n=Ba(r)&&r.fragment,a=e.arguments.length>0?Tst(r,e.arguments):()=>({}),s;return l=>{s??(s=hG(t,r)),t.parser.subrule(i,s,n,e,a(l))}}else if(Xs(r)){let i=t.consume++,n=uG(t,r.name);return()=>t.parser.consume(i,n,e)}else if(r)Yu(r);else throw new Tm(e.$cstNode,`Undefined rule: ${e.rule.$refText}`)}function Tst(t,e){if(e.some(i=>i.calledByName)){let i=e.map(n=>({parameterName:n.parameter?.ref?.name,predicate:Qu(n.value)}));return n=>{let a={};for(let{parameterName:s,predicate:l}of i)s&&(a[s]=l(n));return a}}else{let i=e.map(n=>Qu(n.value));return n=>{let a={};for(let s=0;se(i)||r(i)}else if(OF(t)){let e=Qu(t.left),r=Qu(t.right);return i=>e(i)&&r(i)}else if(zF(t)){let e=Qu(t.value);return r=>!e(r)}else if(GF(t)){let e=t.parameter.ref.name;return r=>r!==void 0&&r[e]===!0}else if(IF(t)){let e=!!t.true;return()=>e}Yu(t)}function kst(t,e){if(e.elements.length===1)return Bm(t,e.elements[0]);{let r=[];for(let n of e.elements){let a={ALT:Bm(t,n,!0)},s=kA(n);s&&(a.GATE=Qu(s)),r.push(a)}let i=t.or++;return n=>t.parser.alternatives(i,r.map(a=>{let s={ALT:o(()=>a.ALT(n),"ALT")},l=a.GATE;return l&&(s.GATE=()=>l(n)),s}))}}function Cst(t,e){if(e.elements.length===1)return Bm(t,e.elements[0]);let r=[];for(let l of e.elements){let u={ALT:Bm(t,l,!0)},h=kA(l);h&&(u.GATE=Qu(h)),r.push(u)}let i=t.or++,n=o((l,u)=>{let h=u.getRuleStack().join("-");return`uGroup_${l}_${h}`},"idFunc"),a=o(l=>t.parser.alternatives(i,r.map((u,h)=>{let f={ALT:o(()=>!0,"ALT")},d=t.parser;f.ALT=()=>{if(u.ALT(l),!d.isRecording()){let m=n(i,d);d.unorderedGroups.get(m)||d.unorderedGroups.set(m,[]);let g=d.unorderedGroups.get(m);typeof g?.[h]>"u"&&(g[h]=!0)}};let p=u.GATE;return p?f.GATE=()=>p(l):f.GATE=()=>!d.unorderedGroups.get(n(i,d))?.[h],f})),"alternatives"),s=n2e(t,kA(e),a,"*");return l=>{s(l),t.parser.isRecording()||t.parser.unorderedGroups.delete(n(i,t.parser))}}function wst(t,e){let r=e.elements.map(i=>Bm(t,i));return i=>r.forEach(n=>n(i))}function kA(t){if(ep(t))return t.guardCondition}function i2e(t,e,r=e.terminal){if(r)if(Gc(r)&&Ba(r.rule.ref)){let i=r.rule.ref,n=t.subrule++,a;return s=>{a??(a=hG(t,i)),t.parser.subrule(n,a,!1,e,s)}}else if(Gc(r)&&Xs(r.rule.ref)){let i=t.consume++,n=uG(t,r.rule.ref.name);return()=>t.parser.consume(i,n,e)}else if(Hl(r)){let i=t.consume++,n=uG(t,r.value);return()=>t.parser.consume(i,n,e)}else throw new Error("Could not build cross reference parser");else{if(!e.type.ref)throw new Error("Could not resolve reference to type: "+e.type.$refText);let n=b6(e.type.ref)?.terminal;if(!n)throw new Error("Could not find name assignment for type: "+ip(e.type.ref));return i2e(t,e,n)}}function Est(t,e){let r=t.consume++,i=t.tokens[e.value];if(!i)throw new Error("Could not find token for keyword: "+e.value);return()=>t.parser.consume(r,i,e)}function n2e(t,e,r,i){let n=e&&Qu(e);if(!i)if(n){let a=t.or++;return s=>t.parser.alternatives(a,[{ALT:o(()=>r(s),"ALT"),GATE:o(()=>n(s),"GATE")},{ALT:sA(),GATE:o(()=>!n(s),"GATE")}])}else return r;if(i==="*"){let a=t.many++;return s=>t.parser.many(a,{DEF:o(()=>r(s),"DEF"),GATE:n?()=>n(s):void 0})}else if(i==="+"){let a=t.many++;if(n){let s=t.or++;return l=>t.parser.alternatives(s,[{ALT:o(()=>t.parser.atLeastOne(a,{DEF:o(()=>r(l),"DEF")}),"ALT"),GATE:o(()=>n(l),"GATE")},{ALT:sA(),GATE:o(()=>!n(l),"GATE")}])}else return s=>t.parser.atLeastOne(a,{DEF:o(()=>r(s),"DEF")})}else if(i==="?"){let a=t.optional++;return s=>t.parser.optional(a,{DEF:o(()=>r(s),"DEF"),GATE:n?()=>n(s):void 0})}else Yu(i)}function hG(t,e){let r=Sst(t,e),i=t.parser.getRule(r);if(!i)throw new Error(`Rule "${r}" not found."`);return i}function Sst(t,e){if(nf(e))return e.name;if(t.ruleNames.has(e))return t.ruleNames.get(e);{let r=e,i=r.$container,n=e.$type;for(;!Ba(i);)(ep(i)||c6(i)||d6(i))&&(n=i.elements.indexOf(r).toString()+":"+n),r=i,i=i.$container;return n=i.name+":"+n,t.ruleNames.set(e,n),n}}function uG(t,e){let r=t.tokens[e];if(!r)throw new Error(`Token "${e}" not found."`);return r}var CA=P(()=>{"use strict";sp();ol();g6();Ys();Vc();o(Nk,"createParser");o(yst,"buildRules");o(vst,"buildInfixRule");o(Bm,"buildElement");o(xst,"buildAction");o(bst,"buildRuleCall");o(Tst,"buildRuleCallPredicate");o(Qu,"buildPredicate");o(kst,"buildAlternatives");o(Cst,"buildUnorderedGroup");o(wst,"buildGroup");o(kA,"getGuardCondition");o(i2e,"buildCrossReference");o(Est,"buildKeyword");o(n2e,"wrap");o(hG,"getRule");o(Sst,"getRuleName");o(uG,"getToken")});function fG(t){let e=t.Grammar,r=t.parser.Lexer,i=new Lk(t);return Nk(e,i,r.definition),i.finalize(),i}var dG=P(()=>{"use strict";Rk();CA();o(fG,"createCompletionParser")});function pG(t){let e=a2e(t);return e.finalize(),e}function a2e(t){let e=t.Grammar,r=t.parser.Lexer,i=new Dk(t);return Nk(e,i,r.definition)}var mG=P(()=>{"use strict";Rk();CA();o(pG,"createLangiumParser");o(a2e,"prepareLangiumParser")});var mf,wA=P(()=>{"use strict";sp();ol();Ts();Vc();Fy();Ys();mf=class{static{o(this,"DefaultTokenBuilder")}constructor(){this.diagnostics=[]}buildTokens(e,r){let i=jr(HT(e,!1)),n=this.buildTerminalTokens(i),a=this.buildKeywordTokens(i,n,r);return a.push(...n),a}flushLexingReport(e){return{diagnostics:this.popDiagnostics()}}popDiagnostics(){let e=[...this.diagnostics];return this.diagnostics=[],e}buildTerminalTokens(e){return e.filter(Xs).filter(r=>!r.fragment).map(r=>this.buildTerminalToken(r)).toArray()}buildTerminalToken(e){let r=$y(e),i=this.requiresCustomPattern(r)?this.regexPatternFunction(r):r,n={name:e.name,PATTERN:i};return typeof i=="function"&&(n.LINE_BREAKS=!0),e.hidden&&(n.GROUP=UT(r)?yn.SKIPPED:"hidden"),n}requiresCustomPattern(e){return!!(e.flags.includes("u")||e.flags.includes("s"))}regexPatternFunction(e){let r=new RegExp(e,e.flags+"y");return(i,n)=>(r.lastIndex=n,r.exec(i))}buildKeywordTokens(e,r,i){return e.filter(nf).flatMap(n=>Pc(n).filter(Hl)).distinct(n=>n.value).toArray().sort((n,a)=>a.value.length-n.value.length).map(n=>this.buildKeywordToken(n,r,!!i?.caseInsensitive))}buildKeywordToken(e,r,i){let n=this.buildKeywordPattern(e,i),a={name:e.value,PATTERN:n,LONGER_ALT:this.findLongerAlt(e,r)};return typeof n=="function"&&(a.LINE_BREAKS=!0),a}buildKeywordPattern(e,r){return r?new RegExp(rp(e.value),"i"):e.value}findLongerAlt(e,r){return r.reduce((i,n)=>{let a=n?.PATTERN;return a?.source&&s$("^"+a.source+"$",e.value)&&i.push(n),i},[])}}});var Fm,Zu,gG=P(()=>{"use strict";ol();Vc();Fm=class{static{o(this,"DefaultValueConverter")}convert(e,r){let i=r.grammarSource;if(zc(i)&&(i=c$(i)),Gc(i)){let n=i.rule.ref;if(!n)throw new Error("This cst node was not parsed by a rule.");return this.runConverter(n,e,r)}return e}runConverter(e,r,i){switch(e.name.toUpperCase()){case"INT":return Zu.convertInt(r);case"STRING":return Zu.convertString(r);case"ID":return Zu.convertID(r)}switch(g$(e)?.toLowerCase()){case"number":return Zu.convertNumber(r);case"boolean":return Zu.convertBoolean(r);case"bigint":return Zu.convertBigint(r);case"date":return Zu.convertDate(r);default:return r}}};(function(t){function e(h){let f="";for(let d=1;d{"use strict";Object.defineProperty(xG,"__esModule",{value:!0});var yG;function vG(){if(yG===void 0)throw new Error("No runtime abstraction layer installed");return yG}o(vG,"RAL");(function(t){function e(r){if(r===void 0)throw new Error("No runtime abstraction layer provided");yG=r}o(e,"install"),t.install=e})(vG||(vG={}));xG.default=vG});var yv=ar(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.stringArray=ks.array=ks.func=ks.error=ks.number=ks.string=ks.boolean=void 0;function Ast(t){return t===!0||t===!1}o(Ast,"boolean");ks.boolean=Ast;function s2e(t){return typeof t=="string"||t instanceof String}o(s2e,"string");ks.string=s2e;function _st(t){return typeof t=="number"||t instanceof Number}o(_st,"number");ks.number=_st;function Dst(t){return t instanceof Error}o(Dst,"error");ks.error=Dst;function Lst(t){return typeof t=="function"}o(Lst,"func");ks.func=Lst;function o2e(t){return Array.isArray(t)}o(o2e,"array");ks.array=o2e;function Rst(t){return o2e(t)&&t.every(e=>s2e(e))}o(Rst,"stringArray");ks.stringArray=Rst});var $m=ar(vv=>{"use strict";Object.defineProperty(vv,"__esModule",{value:!0});vv.Emitter=vv.Event=void 0;var Nst=cp(),l2e;(function(t){let e={dispose(){}};t.None=function(){return e}})(l2e||(vv.Event=l2e={}));var bG=class{static{o(this,"CallbackList")}add(e,r=null,i){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(e),this._contexts.push(r),Array.isArray(i)&&i.push({dispose:o(()=>this.remove(e,r),"dispose")})}remove(e,r=null){if(!this._callbacks)return;let i=!1;for(let n=0,a=this._callbacks.length;n{this._callbacks||(this._callbacks=new bG),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(e,r);let n={dispose:o(()=>{this._callbacks&&(this._callbacks.remove(e,r),n.dispose=t._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))},"dispose")};return Array.isArray(i)&&i.push(n),n}),this._event}fire(e){this._callbacks&&this._callbacks.invoke.call(this._callbacks,e)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}};vv.Emitter=EA;EA._noop=function(){}});var Ik=ar(xv=>{"use strict";Object.defineProperty(xv,"__esModule",{value:!0});xv.CancellationTokenSource=xv.CancellationToken=void 0;var Ist=cp(),Mst=yv(),TG=$m(),SA;(function(t){t.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:TG.Event.None}),t.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:TG.Event.None});function e(r){let i=r;return i&&(i===t.None||i===t.Cancelled||Mst.boolean(i.isCancellationRequested)&&!!i.onCancellationRequested)}o(e,"is"),t.is=e})(SA||(xv.CancellationToken=SA={}));var Ost=Object.freeze(function(t,e){let r=(0,Ist.default)().timer.setTimeout(t.bind(e),0);return{dispose(){r.dispose()}}}),AA=class{static{o(this,"MutableToken")}constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Ost:(this._emitter||(this._emitter=new TG.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}},kG=class{static{o(this,"CancellationTokenSource")}get token(){return this._token||(this._token=new AA),this._token}cancel(){this._token?this._token.cancel():this._token=SA.Cancelled}dispose(){this._token?this._token instanceof AA&&this._token.dispose():this._token=SA.None}};xv.CancellationTokenSource=kG});var $r={};var Yl=P(()=>{"use strict";Kr($r,Wa(Ik(),1))});function CG(){return new Promise(t=>{typeof setImmediate>"u"?setTimeout(t,0):setImmediate(t)})}function DA(){return _A=performance.now(),new $r.CancellationTokenSource}function u2e(t){c2e=t}function Ju(t){return t===jl}async function Dn(t){if(t===$r.CancellationToken.None)return;let e=performance.now();if(e-_A>=c2e&&(_A=e,await CG(),_A=performance.now()),t.isCancellationRequested)throw jl}var _A,c2e,jl,eo,Xl=P(()=>{"use strict";Yl();o(CG,"delayNextTick");_A=0,c2e=10;o(DA,"startCancelableOperation");o(u2e,"setInterruptionPeriod");jl=Symbol("OperationCancelled");o(Ju,"isOperationCancelled");o(Dn,"interruptAndCheck");eo=class{static{o(this,"Deferred")}constructor(){this.promise=new Promise((e,r)=>{this.resolve=i=>(e(i),this),this.reject=i=>(r(i),this)})}}});function wG(t,e){if(t.length<=1)return t;let r=t.length/2|0,i=t.slice(0,r),n=t.slice(r);wG(i,e),wG(n,e);let a=0,s=0,l=0;for(;ar.line||e.line===r.line&&e.character>r.character?{start:r,end:e}:t}function Pst(t){let e=d2e(t.range);return e!==t.range?{newText:t.newText,range:e}:t}var LA,bv,p2e=P(()=>{"use strict";LA=class t{static{o(this,"FullTextDocument")}constructor(e,r,i,n){this._uri=e,this._languageId=r,this._version=i,this._content=n,this._lineOffsets=void 0}get uri(){return this._uri}get languageId(){return this._languageId}get version(){return this._version}getText(e){if(e){let r=this.offsetAt(e.start),i=this.offsetAt(e.end);return this._content.substring(r,i)}return this._content}update(e,r){for(let i of e)if(t.isIncremental(i)){let n=d2e(i.range),a=this.offsetAt(n.start),s=this.offsetAt(n.end);this._content=this._content.substring(0,a)+i.text+this._content.substring(s,this._content.length);let l=Math.max(n.start.line,0),u=Math.max(n.end.line,0),h=this._lineOffsets,f=h2e(i.text,!1,a);if(u-l===f.length)for(let p=0,m=f.length;pe?n=s:i=s+1}let a=i-1;return e=this.ensureBeforeEOL(e,r[a]),{line:a,character:e-r[a]}}offsetAt(e){let r=this.getLineOffsets();if(e.line>=r.length)return this._content.length;if(e.line<0)return 0;let i=r[e.line];if(e.character<=0)return i;let n=e.line+1r&&f2e(this._content.charCodeAt(e-1));)e--;return e}get lineCount(){return this.getLineOffsets().length}static isIncremental(e){let r=e;return r!=null&&typeof r.text=="string"&&r.range!==void 0&&(r.rangeLength===void 0||typeof r.rangeLength=="number")}static isFull(e){let r=e;return r!=null&&typeof r.text=="string"&&r.range===void 0&&r.rangeLength===void 0}};(function(t){function e(n,a,s,l){return new LA(n,a,s,l)}o(e,"create"),t.create=e;function r(n,a,s){if(n instanceof LA)return n.update(a,s),n;throw new Error("TextDocument.update: document must be created by TextDocument.create")}o(r,"update"),t.update=r;function i(n,a){let s=n.getText(),l=wG(a.map(Pst),(f,d)=>{let p=f.range.start.line-d.range.start.line;return p===0?f.range.start.character-d.range.start.character:p}),u=0,h=[];for(let f of l){let d=n.offsetAt(f.range.start);if(du&&h.push(s.substring(u,d)),f.newText.length&&h.push(f.newText),u=n.offsetAt(f.range.end)}return h.push(s.substr(u)),h.join("")}o(i,"applyEdits"),t.applyEdits=i})(bv||(bv={}));o(wG,"mergeSort");o(h2e,"computeLineOffsets");o(f2e,"isEOL");o(d2e,"getWellformedRange");o(Pst,"getWellformedEdit")});var m2e,va,Tv,EG=P(()=>{"use strict";(()=>{"use strict";var t={975:I=>{function A(N){if(typeof N!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(N))}o(A,"e");function _(N,R){for(var B,O="",$=0,z=-1,F=0,V=0;V<=N.length;++V){if(V2){var H=O.lastIndexOf("/");if(H!==O.length-1){H===-1?(O="",$=0):$=(O=O.slice(0,H)).length-1-O.lastIndexOf("/"),z=V,F=0;continue}}else if(O.length===2||O.length===1){O="",$=0,z=V,F=0;continue}}R&&(O.length>0?O+="/..":O="..",$=2)}else O.length>0?O+="/"+N.slice(z+1,V):O=N.slice(z+1,V),$=V-z-1;z=V,F=0}else B===46&&F!==-1?++F:F=-1}return O}o(_,"r");var D={resolve:o(function(){for(var N,R="",B=!1,O=arguments.length-1;O>=-1&&!B;O--){var $;O>=0?$=arguments[O]:(N===void 0&&(N=process.cwd()),$=N),A($),$.length!==0&&(R=$+"/"+R,B=$.charCodeAt(0)===47)}return R=_(R,!B),B?R.length>0?"/"+R:"/":R.length>0?R:"."},"resolve"),normalize:o(function(N){if(A(N),N.length===0)return".";var R=N.charCodeAt(0)===47,B=N.charCodeAt(N.length-1)===47;return(N=_(N,!R)).length!==0||R||(N="."),N.length>0&&B&&(N+="/"),R?"/"+N:N},"normalize"),isAbsolute:o(function(N){return A(N),N.length>0&&N.charCodeAt(0)===47},"isAbsolute"),join:o(function(){if(arguments.length===0)return".";for(var N,R=0;R0&&(N===void 0?N=B:N+="/"+B)}return N===void 0?".":D.normalize(N)},"join"),relative:o(function(N,R){if(A(N),A(R),N===R||(N=D.resolve(N))===(R=D.resolve(R)))return"";for(var B=1;BV){if(R.charCodeAt(z+X)===47)return R.slice(z+X+1);if(X===0)return R.slice(z+X)}else $>V&&(N.charCodeAt(B+X)===47?H=X:X===0&&(H=0));break}var W=N.charCodeAt(B+X);if(W!==R.charCodeAt(z+X))break;W===47&&(H=X)}var Z="";for(X=B+H+1;X<=O;++X)X!==O&&N.charCodeAt(X)!==47||(Z.length===0?Z+="..":Z+="/..");return Z.length>0?Z+R.slice(z+H):(z+=H,R.charCodeAt(z)===47&&++z,R.slice(z))},"relative"),_makeLong:o(function(N){return N},"_makeLong"),dirname:o(function(N){if(A(N),N.length===0)return".";for(var R=N.charCodeAt(0),B=R===47,O=-1,$=!0,z=N.length-1;z>=1;--z)if((R=N.charCodeAt(z))===47){if(!$){O=z;break}}else $=!1;return O===-1?B?"/":".":B&&O===1?"//":N.slice(0,O)},"dirname"),basename:o(function(N,R){if(R!==void 0&&typeof R!="string")throw new TypeError('"ext" argument must be a string');A(N);var B,O=0,$=-1,z=!0;if(R!==void 0&&R.length>0&&R.length<=N.length){if(R.length===N.length&&R===N)return"";var F=R.length-1,V=-1;for(B=N.length-1;B>=0;--B){var H=N.charCodeAt(B);if(H===47){if(!z){O=B+1;break}}else V===-1&&(z=!1,V=B+1),F>=0&&(H===R.charCodeAt(F)?--F==-1&&($=B):(F=-1,$=V))}return O===$?$=V:$===-1&&($=N.length),N.slice(O,$)}for(B=N.length-1;B>=0;--B)if(N.charCodeAt(B)===47){if(!z){O=B+1;break}}else $===-1&&(z=!1,$=B+1);return $===-1?"":N.slice(O,$)},"basename"),extname:o(function(N){A(N);for(var R=-1,B=0,O=-1,$=!0,z=0,F=N.length-1;F>=0;--F){var V=N.charCodeAt(F);if(V!==47)O===-1&&($=!1,O=F+1),V===46?R===-1?R=F:z!==1&&(z=1):R!==-1&&(z=-1);else if(!$){B=F+1;break}}return R===-1||O===-1||z===0||z===1&&R===O-1&&R===B+1?"":N.slice(R,O)},"extname"),format:o(function(N){if(N===null||typeof N!="object")throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof N);return(function(R,B){var O=B.dir||B.root,$=B.base||(B.name||"")+(B.ext||"");return O?O===B.root?O+$:O+"/"+$:$})(0,N)},"format"),parse:o(function(N){A(N);var R={root:"",dir:"",base:"",ext:"",name:""};if(N.length===0)return R;var B,O=N.charCodeAt(0),$=O===47;$?(R.root="/",B=1):B=0;for(var z=-1,F=0,V=-1,H=!0,X=N.length-1,W=0;X>=B;--X)if((O=N.charCodeAt(X))!==47)V===-1&&(H=!1,V=X+1),O===46?z===-1?z=X:W!==1&&(W=1):z!==-1&&(W=-1);else if(!H){F=X+1;break}return z===-1||V===-1||W===0||W===1&&z===V-1&&z===F+1?V!==-1&&(R.base=R.name=F===0&&$?N.slice(1,V):N.slice(F,V)):(F===0&&$?(R.name=N.slice(1,z),R.base=N.slice(1,V)):(R.name=N.slice(F,z),R.base=N.slice(F,V)),R.ext=N.slice(z,V)),F>0?R.dir=N.slice(0,F-1):$&&(R.dir="/"),R},"parse"),sep:"/",delimiter:":",win32:null,posix:null};D.posix=D,I.exports=D}},e={};function r(I){var A=e[I];if(A!==void 0)return A.exports;var _=e[I]={exports:{}};return t[I](_,_.exports,r),_.exports}o(r,"r"),r.d=(I,A)=>{for(var _ in A)r.o(A,_)&&!r.o(I,_)&&Object.defineProperty(I,_,{enumerable:!0,get:A[_]})},r.o=(I,A)=>Object.prototype.hasOwnProperty.call(I,A),r.r=I=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(I,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(I,"__esModule",{value:!0})};var i={};let n;r.r(i),r.d(i,{URI:o(()=>p,"URI"),Utils:o(()=>M,"Utils")}),typeof process=="object"?n=process.platform==="win32":typeof navigator=="object"&&(n=navigator.userAgent.indexOf("Windows")>=0);let a=/^\w[\w\d+.-]*$/,s=/^\//,l=/^\/\//;function u(I,A){if(!I.scheme&&A)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${I.authority}", path: "${I.path}", query: "${I.query}", fragment: "${I.fragment}"}`);if(I.scheme&&!a.test(I.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(I.path){if(I.authority){if(!s.test(I.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(l.test(I.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}}o(u,"a");let h="",f="/",d=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class p{static{o(this,"l")}static isUri(A){return A instanceof p||!!A&&typeof A.authority=="string"&&typeof A.fragment=="string"&&typeof A.path=="string"&&typeof A.query=="string"&&typeof A.scheme=="string"&&typeof A.fsPath=="string"&&typeof A.with=="function"&&typeof A.toString=="function"}scheme;authority;path;query;fragment;constructor(A,_,D,N,R,B=!1){typeof A=="object"?(this.scheme=A.scheme||h,this.authority=A.authority||h,this.path=A.path||h,this.query=A.query||h,this.fragment=A.fragment||h):(this.scheme=(function(O,$){return O||$?O:"file"})(A,B),this.authority=_||h,this.path=(function(O,$){switch(O){case"https":case"http":case"file":$?$[0]!==f&&($=f+$):$=f}return $})(this.scheme,D||h),this.query=N||h,this.fragment=R||h,u(this,B))}get fsPath(){return b(this,!1)}with(A){if(!A)return this;let{scheme:_,authority:D,path:N,query:R,fragment:B}=A;return _===void 0?_=this.scheme:_===null&&(_=h),D===void 0?D=this.authority:D===null&&(D=h),N===void 0?N=this.path:N===null&&(N=h),R===void 0?R=this.query:R===null&&(R=h),B===void 0?B=this.fragment:B===null&&(B=h),_===this.scheme&&D===this.authority&&N===this.path&&R===this.query&&B===this.fragment?this:new g(_,D,N,R,B)}static parse(A,_=!1){let D=d.exec(A);return D?new g(D[2]||h,C(D[4]||h),C(D[5]||h),C(D[7]||h),C(D[9]||h),_):new g(h,h,h,h,h)}static file(A){let _=h;if(n&&(A=A.replace(/\\/g,f)),A[0]===f&&A[1]===f){let D=A.indexOf(f,2);D===-1?(_=A.substring(2),A=f):(_=A.substring(2,D),A=A.substring(D)||f)}return new g("file",_,A,h,h)}static from(A){let _=new g(A.scheme,A.authority,A.path,A.query,A.fragment);return u(_,!0),_}toString(A=!1){return T(this,A)}toJSON(){return this}static revive(A){if(A){if(A instanceof p)return A;{let _=new g(A);return _._formatted=A.external,_._fsPath=A._sep===m?A.fsPath:null,_}}return A}}let m=n?1:void 0;class g extends p{static{o(this,"d")}_formatted=null;_fsPath=null;get fsPath(){return this._fsPath||(this._fsPath=b(this,!1)),this._fsPath}toString(A=!1){return A?T(this,!0):(this._formatted||(this._formatted=T(this,!1)),this._formatted)}toJSON(){let A={$mid:1};return this._fsPath&&(A.fsPath=this._fsPath,A._sep=m),this._formatted&&(A.external=this._formatted),this.path&&(A.path=this.path),this.scheme&&(A.scheme=this.scheme),this.authority&&(A.authority=this.authority),this.query&&(A.query=this.query),this.fragment&&(A.fragment=this.fragment),A}}let y={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function v(I,A,_){let D,N=-1;for(let R=0;R=97&&B<=122||B>=65&&B<=90||B>=48&&B<=57||B===45||B===46||B===95||B===126||A&&B===47||_&&B===91||_&&B===93||_&&B===58)N!==-1&&(D+=encodeURIComponent(I.substring(N,R)),N=-1),D!==void 0&&(D+=I.charAt(R));else{D===void 0&&(D=I.substr(0,R));let O=y[B];O!==void 0?(N!==-1&&(D+=encodeURIComponent(I.substring(N,R)),N=-1),D+=O):N===-1&&(N=R)}}return N!==-1&&(D+=encodeURIComponent(I.substring(N))),D!==void 0?D:I}o(v,"m");function x(I){let A;for(let _=0;_1&&I.scheme==="file"?`//${I.authority}${I.path}`:I.path.charCodeAt(0)===47&&(I.path.charCodeAt(1)>=65&&I.path.charCodeAt(1)<=90||I.path.charCodeAt(1)>=97&&I.path.charCodeAt(1)<=122)&&I.path.charCodeAt(2)===58?A?I.path.substr(1):I.path[1].toLowerCase()+I.path.substr(2):I.path,n&&(_=_.replace(/\//g,"\\")),_}o(b,"v");function T(I,A){let _=A?x:v,D="",{scheme:N,authority:R,path:B,query:O,fragment:$}=I;if(N&&(D+=N,D+=":"),(R||N==="file")&&(D+=f,D+=f),R){let z=R.indexOf("@");if(z!==-1){let F=R.substr(0,z);R=R.substr(z+1),z=F.lastIndexOf(":"),z===-1?D+=_(F,!1,!1):(D+=_(F.substr(0,z),!1,!1),D+=":",D+=_(F.substr(z+1),!1,!0)),D+="@"}R=R.toLowerCase(),z=R.lastIndexOf(":"),z===-1?D+=_(R,!1,!0):(D+=_(R.substr(0,z),!1,!0),D+=R.substr(z))}if(B){if(B.length>=3&&B.charCodeAt(0)===47&&B.charCodeAt(2)===58){let z=B.charCodeAt(1);z>=65&&z<=90&&(B=`/${String.fromCharCode(z+32)}:${B.substr(3)}`)}else if(B.length>=2&&B.charCodeAt(1)===58){let z=B.charCodeAt(0);z>=65&&z<=90&&(B=`${String.fromCharCode(z+32)}:${B.substr(2)}`)}D+=_(B,!0,!1)}return O&&(D+="?",D+=_(O,!1,!1)),$&&(D+="#",D+=A?$:v($,!1,!1)),D}o(T,"b");function w(I){try{return decodeURIComponent(I)}catch{return I.length>3?I.substr(0,3)+w(I.substr(3)):I}}o(w,"C");let k=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function C(I){return I.match(k)?I.replace(k,(A=>w(A))):I}o(C,"w");var E=r(975);let S=E.posix||E,L="/";var M;(function(I){I.joinPath=function(A,..._){return A.with({path:S.join(A.path,..._)})},I.resolvePath=function(A,..._){let D=A.path,N=!1;D[0]!==L&&(D=L+D,N=!0);let R=S.resolve(D,..._);return N&&R[0]===L&&!A.authority&&(R=R.substring(1)),A.with({path:R})},I.dirname=function(A){if(A.path.length===0||A.path===L)return A;let _=S.dirname(A.path);return _.length===1&&_.charCodeAt(0)===46&&(_=""),A.with({path:_})},I.basename=function(A){return S.basename(A.path)},I.extname=function(A){return S.extname(A.path)}})(M||(M={})),m2e=i})();({URI:va,Utils:Tv}=m2e)});var Vn,kv,Wc=P(()=>{"use strict";EG();(function(t){t.basename=Tv.basename,t.dirname=Tv.dirname,t.extname=Tv.extname,t.joinPath=Tv.joinPath,t.resolvePath=Tv.resolvePath;let e=typeof process=="object"&&process?.platform==="win32";function r(s,l){return s?.toString()===l?.toString()}o(r,"equals"),t.equals=r;function i(s,l){let u=typeof s=="string"?va.parse(s).path:s.path,h=typeof l=="string"?va.parse(l).path:l.path,f=u.split("/").filter(y=>y.length>0),d=h.split("/").filter(y=>y.length>0);if(e){let y=/^[A-Z]:$/;if(f[0]&&y.test(f[0])&&(f[0]=f[0].toLowerCase()),d[0]&&y.test(d[0])&&(d[0]=d[0].toLowerCase()),f[0]!==d[0])return h.substring(1)}let p=0;for(;p({name:n.name,uri:Vn.joinPath(va.parse(r),n.name).toString(),element:n.element})):[]}all(){return this.collectValues(this.root)}findAll(e){let r=this.getNode(Vn.normalize(e),!1);return r?this.collectValues(r):[]}getNode(e,r){let i=e.split("/");e.charAt(e.length-1)==="/"&&i.pop();let n=this.root;for(let a of i){let s=n.children.get(a);if(!s)if(r)s={name:a,children:new Map,parent:n},n.children.set(a,s);else return;n=s}return n}collectValues(e){let r=[];e.element&&r.push(e.element);for(let i of e.children.values())r.push(...this.collectValues(i));return r}}});var Ur,Mk,Ok,Cv=P(()=>{"use strict";p2e();Cv();Yl();Ys();Wc();(function(t){t[t.Changed=0]="Changed",t[t.Parsed=1]="Parsed",t[t.IndexedContent=2]="IndexedContent",t[t.ComputedScopes=3]="ComputedScopes",t[t.Linked=4]="Linked",t[t.IndexedReferences=5]="IndexedReferences",t[t.Validated=6]="Validated"})(Ur||(Ur={}));Mk=class{static{o(this,"DefaultLangiumDocumentFactory")}constructor(e){this.serviceRegistry=e.ServiceRegistry,this.textDocuments=e.workspace.TextDocuments,this.fileSystemProvider=e.workspace.FileSystemProvider}async fromUri(e,r=$r.CancellationToken.None){let i=await this.fileSystemProvider.readFile(e);return this.createAsync(e,i,r)}fromTextDocument(e,r,i){return r=r??va.parse(e.uri),$r.CancellationToken.is(i)?this.createAsync(r,e,i):this.create(r,e,i)}fromString(e,r,i){return $r.CancellationToken.is(i)?this.createAsync(r,e,i):this.create(r,e,i)}fromModel(e,r){return this.create(r,{$model:e})}create(e,r,i){if(typeof r=="string"){let n=this.parse(e,r,i);return this.createLangiumDocument(n,e,void 0,r)}else if("$model"in r){let n={value:r.$model,parserErrors:[],lexerErrors:[]};return this.createLangiumDocument(n,e)}else{let n=this.parse(e,r.getText(),i);return this.createLangiumDocument(n,e,r)}}async createAsync(e,r,i){if(typeof r=="string"){let n=await this.parseAsync(e,r,i);return this.createLangiumDocument(n,e,void 0,r)}else{let n=await this.parseAsync(e,r.getText(),i);return this.createLangiumDocument(n,e,r)}}createLangiumDocument(e,r,i,n){let a;if(i)a={parseResult:e,uri:r,state:Ur.Parsed,references:[],textDocument:i};else{let s=this.createTextDocumentGetter(r,n);a={parseResult:e,uri:r,state:Ur.Parsed,references:[],get textDocument(){return s()}}}return e.value.$document=a,a}async update(e,r){let i=e.parseResult.value.$cstNode?.root.fullText,n=this.textDocuments?.get(e.uri.toString()),a=n?n.getText():await this.fileSystemProvider.readFile(e.uri);if(n)Object.defineProperty(e,"textDocument",{value:n});else{let s=this.createTextDocumentGetter(e.uri,a);Object.defineProperty(e,"textDocument",{get:s})}return i!==a&&(e.parseResult=await this.parseAsync(e.uri,a,r),e.parseResult.value.$document=e),e.state=Ur.Parsed,e}parse(e,r,i){return this.serviceRegistry.getServices(e).parser.LangiumParser.parse(r,i)}parseAsync(e,r,i){return this.serviceRegistry.getServices(e).parser.AsyncParser.parse(r,i)}createTextDocumentGetter(e,r){let i=this.serviceRegistry,n;return()=>n??(n=bv.create(e.toString(),i.getServices(e).LanguageMetaData.languageId,0,r??""))}},Ok=class{static{o(this,"DefaultLangiumDocuments")}constructor(e){this.documentTrie=new kv,this.services=e,this.langiumDocumentFactory=e.workspace.LangiumDocumentFactory,this.documentBuilder=()=>e.workspace.DocumentBuilder}get all(){return jr(this.documentTrie.all())}addDocument(e){let r=e.uri.toString();if(this.documentTrie.has(r))throw new Error(`A document with the URI '${r}' is already present.`);this.documentTrie.insert(r,e)}getDocument(e){let r=e.toString();return this.documentTrie.find(r)}getDocuments(e){let r=e.toString();return this.documentTrie.findAll(r)}async getOrCreateDocument(e,r){let i=this.getDocument(e);return i||(i=await this.langiumDocumentFactory.fromUri(e,r),this.addDocument(i),i)}createDocument(e,r,i){if(i)return this.langiumDocumentFactory.fromString(r,e,i).then(n=>(this.addDocument(n),n));{let n=this.langiumDocumentFactory.fromString(r,e);return this.addDocument(n),n}}hasDocument(e){return this.documentTrie.has(e.toString())}invalidateDocument(e){let r=e.toString(),i=this.documentTrie.find(r);return i&&this.documentBuilder().resetToState(i,Ur.Changed),i}deleteDocument(e){let r=e.toString(),i=this.documentTrie.find(r);return i&&(i.state=Ur.Changed,this.documentTrie.delete(r)),i}deleteDocuments(e){let r=e.toString(),i=this.documentTrie.findAll(r);for(let n of i)n.state=Ur.Changed;return this.documentTrie.delete(r),i}}});var zm,Pk,SG=P(()=>{"use strict";Yl();Oc();Ts();Xl();Cv();zm=Symbol("RefResolving"),Pk=class{static{o(this,"DefaultLinker")}constructor(e){this.reflection=e.shared.AstReflection,this.langiumDocuments=()=>e.shared.workspace.LangiumDocuments,this.scopeProvider=e.references.ScopeProvider,this.astNodeLocator=e.workspace.AstNodeLocator,this.profiler=e.shared.profilers.LangiumProfiler,this.languageId=e.LanguageMetaData.languageId}async link(e,r=$r.CancellationToken.None){if(this.profiler?.isActive("linking")){let i=this.profiler.createTask("linking",this.languageId);i.start();try{for(let n of js(e.parseResult.value))await Dn(r),jd(n).forEach(a=>{let s=`${n.$type}:${a.property}`;i.startSubTask(s);try{this.doLink(a,e)}finally{i.stopSubTask(s)}})}finally{i.stop()}}else for(let i of js(e.parseResult.value))await Dn(r),jd(i).forEach(n=>this.doLink(n,e))}doLink(e,r){let i=e.reference;if("_ref"in i&&i._ref===void 0){i._ref=zm;try{let n=this.getCandidate(e);if(om(n))i._ref=n;else{i._nodeDescription=n;let a=this.loadAstNode(n);i._ref=a??this.createLinkingError(e,n)}}catch(n){console.error(`An error occurred while resolving reference to '${i.$refText}':`,n);let a=n.message??String(n);i._ref={info:e,message:`An error occurred while resolving reference to '${i.$refText}': ${a}`}}r.references.push(i)}else if("_items"in i&&i._items===void 0){i._items=zm;try{let n=this.getCandidates(e),a=[];if(om(n))i._linkingError=n;else for(let s of n){let l=this.loadAstNode(s);l&&a.push({ref:l,$nodeDescription:s})}i._items=a}catch(n){i._linkingError={info:e,message:`An error occurred while resolving reference to '${i.$refText}': ${n}`},i._items=[]}r.references.push(i)}}unlink(e){for(let r of e.references)"_ref"in r?(r._ref=void 0,delete r._nodeDescription):"_items"in r&&(r._items=void 0,delete r._linkingError);e.references=[]}getCandidate(e){return this.scopeProvider.getScope(e).getElement(e.reference.$refText)??this.createLinkingError(e)}getCandidates(e){let i=this.scopeProvider.getScope(e).getElements(e.reference.$refText).distinct(n=>`${n.documentUri}#${n.path}`).toArray();return i.length>0?i:this.createLinkingError(e)}buildReference(e,r,i,n){let a=this,s={$refNode:i,$refText:n,_ref:void 0,get ref(){if(_n(this._ref))return this._ref;if(AF(this._nodeDescription)){let l=a.loadAstNode(this._nodeDescription);this._ref=l??a.createLinkingError({reference:s,container:e,property:r},this._nodeDescription)}else if(this._ref===void 0){this._ref=zm;let l=Ay(e).$document,u=a.getLinkedNode({reference:s,container:e,property:r});if(u.error&&l&&l.state0))return this._linkingError=a.createLinkingError({reference:s,container:e,property:r})}};return s}throwCyclicReferenceError(e,r,i){throw new Error(`Cyclic reference resolution detected: ${this.astNodeLocator.getAstNodePath(e)}/${r} (symbol '${i}')`)}getLinkedNode(e){try{let r=this.getCandidate(e);if(om(r))return{error:r};let i=this.loadAstNode(r);return i?{node:i,descr:r}:{descr:r,error:this.createLinkingError(e,r)}}catch(r){console.error(`An error occurred while resolving reference to '${e.reference.$refText}':`,r);let i=r.message??String(r);return{error:{info:e,message:`An error occurred while resolving reference to '${e.reference.$refText}': ${i}`}}}}loadAstNode(e){if(e.node)return e.node;let r=this.langiumDocuments().getDocument(e.documentUri);if(r)return this.astNodeLocator.getAstNode(r.parseResult.value,e.path)}createLinkingError(e,r){let i=Ay(e.container).$document;i&&i.state{"use strict";Vc();o(g2e,"isNamed");Bk=class{static{o(this,"DefaultNameProvider")}getName(e){if(g2e(e))return e.name}getNameNode(e){return YT(e.$cstNode,"name")}}});var Fk,_G=P(()=>{"use strict";Vc();Oc();Ts();Bc();Ys();Wc();ol();Fk=class{static{o(this,"DefaultReferences")}constructor(e){this.nameProvider=e.references.NameProvider,this.index=e.shared.workspace.IndexManager,this.nodeLocator=e.workspace.AstNodeLocator,this.documents=e.shared.workspace.LangiumDocuments,this.hasMultiReference=js(e.Grammar).some(r=>zc(r)&&r.isMulti)}findDeclarations(e){if(e){let r=m$(e),i=e.astNode;if(r&&i){let n=i[r.feature];if(ga(n)||nl(n))return jS(n);if(Array.isArray(n)){for(let a of n)if((ga(a)||nl(a))&&a.$refNode&&a.$refNode.offset<=e.offset&&a.$refNode.end>=e.end)return jS(a)}}if(i){let n=this.nameProvider.getNameNode(i);if(n&&(n===e||QF(e,n)))return this.getSelfNodes(i)}}return[]}getSelfNodes(e){if(this.hasMultiReference){let r=this.index.findAllReferences(e,this.nodeLocator.getAstNodePath(e)),i=this.getNodeFromReferenceDescription(r.head());if(i){for(let n of jd(i))if(nl(n.reference)&&n.reference.items.some(a=>a.ref===e))return n.reference.items.map(a=>a.ref)}return[e]}else return[e]}getNodeFromReferenceDescription(e){if(!e)return;let r=this.documents.getDocument(e.sourceUri);if(r)return this.nodeLocator.getAstNode(r.parseResult.value,e.sourcePath)}findDeclarationNodes(e){let r=this.findDeclarations(e),i=[];for(let n of r){let a=this.nameProvider.getNameNode(n)??n.$cstNode;a&&i.push(a)}return i}findReferences(e,r){let i=[];r.includeDeclaration&&i.push(...this.getSelfReferences(e));let n=this.index.findAllReferences(e,this.nodeLocator.getAstNodePath(e));return r.documentUri&&(n=n.filter(a=>Vn.equals(a.sourceUri,r.documentUri))),i.push(...n),jr(i)}getSelfReferences(e){let r=this.getSelfNodes(e),i=[];for(let n of r){let a=this.nameProvider.getNameNode(n);if(a){let s=bs(n),l=this.nodeLocator.getAstNodePath(n);i.push({sourceUri:s.uri,sourcePath:l,targetUri:s.uri,targetPath:l,segment:bm(a),local:!0})}}return i}}});var Cs,Gm,up=P(()=>{"use strict";Ys();Cs=class{static{o(this,"MultiMap")}constructor(e){if(this.map=new Map,e)for(let[r,i]of e)this.add(r,i)}get size(){return Ey.sum(jr(this.map.values()).map(e=>e.length))}clear(){this.map.clear()}delete(e,r){if(r===void 0)return this.map.delete(e);{let i=this.map.get(e);if(i){let n=i.indexOf(r);if(n>=0)return i.length===1?this.map.delete(e):i.splice(n,1),!0}return!1}}get(e){return this.map.get(e)??[]}getStream(e){let r=this.map.get(e);return r?jr(r):Yd}has(e,r){if(r===void 0)return this.map.has(e);{let i=this.map.get(e);return i?i.indexOf(r)>=0:!1}}add(e,r){return this.map.has(e)?this.map.get(e).push(r):this.map.set(e,[r]),this}addAll(e,r){return this.map.has(e)?this.map.get(e).push(...r):this.map.set(e,Array.from(r)),this}forEach(e){this.map.forEach((r,i)=>r.forEach(n=>e(n,i,this)))}[Symbol.iterator](){return this.entries().iterator()}entries(){return jr(this.map.entries()).flatMap(([e,r])=>r.map(i=>[e,i]))}keys(){return jr(this.map.keys())}values(){return jr(this.map.values()).flat()}entriesGroupedByKey(){return jr(this.map.entries())}},Gm=class{static{o(this,"BiMap")}get size(){return this.map.size}constructor(e){if(this.map=new Map,this.inverse=new Map,e)for(let[r,i]of e)this.set(r,i)}clear(){this.map.clear(),this.inverse.clear()}set(e,r){return this.map.set(e,r),this.inverse.set(r,e),this}get(e){return this.map.get(e)}getKey(e){return this.inverse.get(e)}delete(e){let r=this.map.get(e);return r!==void 0?(this.map.delete(e),this.inverse.delete(r),!0):!1}}});var $k,DG=P(()=>{"use strict";Ts();Yl();up();Xl();$k=class{static{o(this,"DefaultScopeComputation")}constructor(e){this.nameProvider=e.references.NameProvider,this.descriptions=e.workspace.AstNodeDescriptionProvider}async collectExportedSymbols(e,r=$r.CancellationToken.None){return this.collectExportedSymbolsForNode(e.parseResult.value,e,void 0,r)}async collectExportedSymbolsForNode(e,r,i=DT,n=$r.CancellationToken.None){let a=[];this.addExportedSymbol(e,a,r);for(let s of i(e))await Dn(n),this.addExportedSymbol(s,a,r);return a}addExportedSymbol(e,r,i){let n=this.nameProvider.getName(e);n&&r.push(this.descriptions.createDescription(e,n,i))}async collectLocalSymbols(e,r=$r.CancellationToken.None){let i=e.parseResult.value,n=new Cs;for(let a of Pc(i))await Dn(r),this.addLocalSymbol(a,e,n);return n}addLocalSymbol(e,r,i){let n=e.$container;if(n){let a=this.nameProvider.getName(e);a&&i.add(n,this.descriptions.createDescription(e,a,r))}}}});var wv,LG,zk,Bst,RG=P(()=>{"use strict";up();Ys();wv=class{static{o(this,"StreamScope")}constructor(e,r,i){this.elements=e,this.outerScope=r,this.caseInsensitive=i?.caseInsensitive??!1,this.concatOuterScope=i?.concatOuterScope??!0}getAllElements(){return this.outerScope?this.elements.concat(this.outerScope.getAllElements()):this.elements}getElement(e){let r=this.caseInsensitive?e.toLowerCase():e,i=this.caseInsensitive?this.elements.find(n=>n.name.toLowerCase()===r):this.elements.find(n=>n.name===e);if(i)return i;if(this.outerScope)return this.outerScope.getElement(e)}getElements(e){let r=this.caseInsensitive?e.toLowerCase():e,i=this.caseInsensitive?this.elements.filter(n=>n.name.toLowerCase()===r):this.elements.filter(n=>n.name===e);return(this.concatOuterScope||i.isEmpty())&&this.outerScope?i.concat(this.outerScope.getElements(e)):i}},LG=class{static{o(this,"MapScope")}constructor(e,r,i){this.elements=new Map,this.caseInsensitive=i?.caseInsensitive??!1,this.concatOuterScope=i?.concatOuterScope??!0;for(let n of e){let a=this.caseInsensitive?n.name.toLowerCase():n.name;this.elements.set(a,n)}this.outerScope=r}getElement(e){let r=this.caseInsensitive?e.toLowerCase():e,i=this.elements.get(r);if(i)return i;if(this.outerScope)return this.outerScope.getElement(e)}getElements(e){let r=this.caseInsensitive?e.toLowerCase():e,i=this.elements.get(r),n=i?[i]:[];return(this.concatOuterScope||n.length>0)&&this.outerScope?jr(n).concat(this.outerScope.getElements(e)):jr(n)}getAllElements(){let e=jr(this.elements.values());return this.outerScope&&(e=e.concat(this.outerScope.getAllElements())),e}},zk=class{static{o(this,"MultiMapScope")}constructor(e,r,i){this.elements=new Cs,this.caseInsensitive=i?.caseInsensitive??!1,this.concatOuterScope=i?.concatOuterScope??!0;for(let n of e){let a=this.caseInsensitive?n.name.toLowerCase():n.name;this.elements.add(a,n)}this.outerScope=r}getElement(e){let r=this.caseInsensitive?e.toLowerCase():e,i=this.elements.get(r)[0];if(i)return i;if(this.outerScope)return this.outerScope.getElement(e)}getElements(e){let r=this.caseInsensitive?e.toLowerCase():e,i=this.elements.get(r);return(this.concatOuterScope||i.length===0)&&this.outerScope?jr(i).concat(this.outerScope.getElements(e)):jr(i)}getAllElements(){let e=jr(this.elements.values());return this.outerScope&&(e=e.concat(this.outerScope.getAllElements())),e}},Bst={getElement(){},getElements(){return Yd},getAllElements(){return Yd}}});var Ev,Gk,Vm,RA,Sv,NA=P(()=>{"use strict";Ev=class{static{o(this,"DisposableCache")}constructor(){this.toDispose=[],this.isDisposed=!1}onDispose(e){this.toDispose.push(e)}dispose(){this.throwIfDisposed(),this.clear(),this.isDisposed=!0,this.toDispose.forEach(e=>e.dispose())}throwIfDisposed(){if(this.isDisposed)throw new Error("This cache has already been disposed")}},Gk=class extends Ev{static{o(this,"SimpleCache")}constructor(){super(...arguments),this.cache=new Map}has(e){return this.throwIfDisposed(),this.cache.has(e)}set(e,r){this.throwIfDisposed(),this.cache.set(e,r)}get(e,r){if(this.throwIfDisposed(),this.cache.has(e))return this.cache.get(e);if(r){let i=r();return this.cache.set(e,i),i}else return}delete(e){return this.throwIfDisposed(),this.cache.delete(e)}clear(){this.throwIfDisposed(),this.cache.clear()}},Vm=class extends Ev{static{o(this,"ContextCache")}constructor(e){super(),this.cache=new Map,this.converter=e??(r=>r)}has(e,r){return this.throwIfDisposed(),this.cacheForContext(e).has(r)}set(e,r,i){this.throwIfDisposed(),this.cacheForContext(e).set(r,i)}get(e,r,i){this.throwIfDisposed();let n=this.cacheForContext(e);if(n.has(r))return n.get(r);if(i){let a=i();return n.set(r,a),a}else return}delete(e,r){return this.throwIfDisposed(),this.cacheForContext(e).delete(r)}clear(e){if(this.throwIfDisposed(),e){let r=this.converter(e);this.cache.delete(r)}else this.cache.clear()}cacheForContext(e){let r=this.converter(e),i=this.cache.get(r);return i||(i=new Map,this.cache.set(r,i)),i}},RA=class extends Vm{static{o(this,"DocumentCache")}constructor(e,r){super(i=>i.toString()),r?(this.toDispose.push(e.workspace.DocumentBuilder.onDocumentPhase(r,i=>{this.clear(i.uri.toString())})),this.toDispose.push(e.workspace.DocumentBuilder.onUpdate((i,n)=>{for(let a of n)this.clear(a)}))):this.toDispose.push(e.workspace.DocumentBuilder.onUpdate((i,n)=>{let a=i.concat(n);for(let s of a)this.clear(s)}))}},Sv=class extends Gk{static{o(this,"WorkspaceCache")}constructor(e,r){super(),r?(this.toDispose.push(e.workspace.DocumentBuilder.onBuildPhase(r,()=>{this.clear()})),this.toDispose.push(e.workspace.DocumentBuilder.onUpdate((i,n)=>{n.length>0&&this.clear()}))):this.toDispose.push(e.workspace.DocumentBuilder.onUpdate(()=>{this.clear()}))}}});var Vk,NG=P(()=>{"use strict";RG();Ts();Ys();NA();Vk=class{static{o(this,"DefaultScopeProvider")}constructor(e){this.reflection=e.shared.AstReflection,this.nameProvider=e.references.NameProvider,this.descriptions=e.workspace.AstNodeDescriptionProvider,this.indexManager=e.shared.workspace.IndexManager,this.globalScopeCache=new Sv(e.shared)}getScope(e){let r=[],i=this.reflection.getReferenceType(e),n=bs(e.container).localSymbols;if(n){let s=e.container;do n.has(s)&&r.push(n.getStream(s).filter(l=>this.reflection.isSubtype(l.type,i))),s=s.$container;while(s)}let a=this.getGlobalScope(i,e);for(let s=r.length-1;s>=0;s--)a=this.createScope(r[s],a);return a}createScope(e,r,i){return new wv(jr(e),r,i)}createScopeForNodes(e,r,i){let n=jr(e).map(a=>{let s=this.nameProvider.getName(a);if(s)return this.descriptions.createDescription(a,s)}).nonNullable();return new wv(n,r,i)}getGlobalScope(e,r){return this.globalScopeCache.get(e,()=>new zk(this.indexManager.allElements(e)))}}});function IG(t){return typeof t.$comment=="string"}function y2e(t){return typeof t=="object"&&!!t&&("$ref"in t||"$error"in t)}var qk,IA=P(()=>{"use strict";EG();Oc();Ts();Vc();o(IG,"isAstNodeWithComment");o(y2e,"isIntermediateReference");qk=class{static{o(this,"DefaultJsonSerializer")}constructor(e){this.ignoreProperties=new Set(["$container","$containerProperty","$containerIndex","$document","$cstNode"]),this.langiumDocuments=e.shared.workspace.LangiumDocuments,this.astNodeLocator=e.workspace.AstNodeLocator,this.nameProvider=e.references.NameProvider,this.commentProvider=e.documentation.CommentProvider}serialize(e,r){let i=r??{},n=r?.replacer,a=o((l,u)=>this.replacer(l,u,i),"defaultReplacer"),s=n?(l,u)=>n(l,u,a):a;try{return this.currentDocument=bs(e),JSON.stringify(e,s,r?.space)}finally{this.currentDocument=void 0}}deserialize(e,r){let i=r??{},n=JSON.parse(e);return this.linkNode(n,n,i),n}replacer(e,r,{refText:i,sourceText:n,textRegions:a,comments:s,uriConverter:l}){if(!this.ignoreProperties.has(e))if(ga(r)){let u=r.ref,h=i?r.$refText:void 0;if(u){let f=bs(u),d="";this.currentDocument&&this.currentDocument!==f&&(l?d=l(f.uri,u):d=f.uri.toString());let p=this.astNodeLocator.getAstNodePath(u);return{$ref:`${d}#${p}`,$refText:h}}else return{$error:r.error?.message??"Could not resolve reference",$refText:h}}else if(nl(r)){let u=i?r.$refText:void 0,h=[];for(let f of r.items){let d=f.ref,p=bs(f.ref),m="";this.currentDocument&&this.currentDocument!==p&&(l?m=l(p.uri,d):m=p.uri.toString());let g=this.astNodeLocator.getAstNodePath(d);h.push(`${m}#${g}`)}return{$refs:h,$refText:u}}else if(_n(r)){let u;if(a&&(u=this.addAstNodeRegionWithAssignmentsTo({...r}),(!e||r.$document)&&u?.$textRegion&&(u.$textRegion.documentURI=this.currentDocument?.uri.toString())),n&&!e&&(u??(u={...r}),u.$sourceText=r.$cstNode?.text),s){u??(u={...r});let h=this.commentProvider.getComment(r);h&&(u.$comment=h.replace(/\r/g,""))}return u??r}else return r}addAstNodeRegionWithAssignmentsTo(e){let r=o(i=>({offset:i.offset,end:i.end,length:i.length,range:i.range}),"createDocumentSegment");if(e.$cstNode){let i=e.$textRegion=r(e.$cstNode),n=i.assignments={};return Object.keys(e).filter(a=>!a.startsWith("$")).forEach(a=>{let s=h$(e.$cstNode,a).map(r);s.length!==0&&(n[a]=s)}),e}}linkNode(e,r,i,n,a,s){for(let[u,h]of Object.entries(e))if(Array.isArray(h))for(let f=0;f{"use strict";Wc();Wk=class{static{o(this,"DefaultServiceRegistry")}get map(){return this.fileExtensionMap}constructor(e){this.languageIdMap=new Map,this.fileExtensionMap=new Map,this.fileNameMap=new Map,this.textDocuments=e?.workspace.TextDocuments}register(e){let r=e.LanguageMetaData;for(let i of r.fileExtensions)this.fileExtensionMap.has(i)&&console.warn(`The file extension ${i} is used by multiple languages. It is now assigned to '${r.languageId}'.`),this.fileExtensionMap.set(i,e);if(r.fileNames)for(let i of r.fileNames)this.fileNameMap.has(i)&&console.warn(`The file name ${i} is used by multiple languages. It is now assigned to '${r.languageId}'.`),this.fileNameMap.set(i,e);this.languageIdMap.set(r.languageId,e)}getServices(e){if(this.languageIdMap.size===0)throw new Error("The service registry is empty. Use `register` to register the services of a language.");let r=this.textDocuments?.get(e)?.languageId;if(r!==void 0){let s=this.languageIdMap.get(r);if(s)return s}let i=Vn.extname(e),n=Vn.basename(e),a=this.fileNameMap.get(n)??this.fileExtensionMap.get(i);if(!a)throw r?new Error(`The service registry contains no services for the extension '${i}' for language '${r}'.`):new Error(`The service registry contains no services for the extension '${i}'.`);return a}hasServices(e){try{return this.getServices(e),!0}catch{return!1}}get all(){return Array.from(this.languageIdMap.values())}}});function qm(t){return{code:t}}var MA,Uk,OA=P(()=>{"use strict";to();up();Xl();Ys();o(qm,"diagnosticData");(function(t){t.defaults=["fast","slow","built-in"],t.all=t.defaults})(MA||(MA={}));Uk=class{static{o(this,"ValidationRegistry")}constructor(e){this.entries=new Cs,this.knownCategories=new Set(MA.defaults),this.entriesBefore=[],this.entriesAfter=[],this.reflection=e.shared.AstReflection}register(e,r=this,i="fast"){if(i==="built-in")throw new Error("The 'built-in' category is reserved for lexer, parser, and linker errors.");this.knownCategories.add(i);for(let[n,a]of Object.entries(e)){let s=a;if(Array.isArray(s))for(let l of s){let u={check:this.wrapValidationException(l,r),category:i};this.addEntry(n,u)}else if(typeof s=="function"){let l={check:this.wrapValidationException(s,r),category:i};this.addEntry(n,l)}else Yu(s)}}wrapValidationException(e,r){return async(i,n,a)=>{await this.handleException(()=>e.call(r,i,n,a),"An error occurred during validation",n,i)}}async handleException(e,r,i,n){try{await e()}catch(a){if(Ju(a))throw a;console.error(`${r}:`,a),a instanceof Error&&a.stack&&console.error(a.stack);let s=a instanceof Error?a.message:String(a);i("error",`${r}: ${s}`,{node:n})}}addEntry(e,r){if(e==="AstNode"){this.entries.add("AstNode",r);return}for(let i of this.reflection.getAllSubTypes(e))this.entries.add(i,r)}getChecks(e,r){let i=jr(this.entries.get(e)).concat(this.entries.get("AstNode"));return r&&(i=i.filter(n=>r.includes(n.category))),i.map(n=>n.check)}registerBeforeDocument(e,r=this){this.entriesBefore.push(this.wrapPreparationException(e,"An error occurred during set-up of the validation",r))}registerAfterDocument(e,r=this){this.entriesAfter.push(this.wrapPreparationException(e,"An error occurred during tear-down of the validation",r))}wrapPreparationException(e,r,i){return async(n,a,s,l)=>{await this.handleException(()=>e.call(i,n,a,s,l),r,a,n)}}get checksBefore(){return this.entriesBefore}get checksAfter(){return this.entriesAfter}getAllValidationCategories(e){return this.knownCategories}}});function x2e(t){if(t.range)return t.range;let e;return typeof t.property=="string"?e=YT(t.node.$cstNode,t.property,t.index):typeof t.keyword=="string"&&(e=d$(t.node.$cstNode,t.keyword,t.index)),e??(e=t.node.$cstNode),e?e.range:{start:{line:0,character:0},end:{line:0,character:0}}}function PA(t){switch(t){case"error":return 1;case"warning":return 2;case"info":return 3;case"hint":return 4;default:throw new Error("Invalid diagnostic severity: "+t)}}function b2e(t){switch(t){case"error":return qm(Kl.LexingError);case"warning":return qm(Kl.LexingWarning);case"info":return qm(Kl.LexingInfo);case"hint":return qm(Kl.LexingHint);default:throw new Error("Invalid diagnostic severity: "+t)}}var v2e,Hk,Kl,OG=P(()=>{"use strict";Yl();Vc();Ts();Bc();Xl();OA();v2e=Object.freeze({validateNode:!0,validateChildren:!0}),Hk=class{static{o(this,"DefaultDocumentValidator")}constructor(e){this.validationRegistry=e.validation.ValidationRegistry,this.metadata=e.LanguageMetaData,this.profiler=e.shared.profilers.LangiumProfiler,this.languageId=e.LanguageMetaData.languageId}async validateDocument(e,r={},i=$r.CancellationToken.None){let n=e.parseResult,a=[];if(await Dn(i),(!r.categories||r.categories.includes("built-in"))&&(this.processLexingErrors(n,a,r),r.stopAfterLexingErrors&&a.some(s=>s.data?.code===Kl.LexingError)||(this.processParsingErrors(n,a,r),r.stopAfterParsingErrors&&a.some(s=>s.data?.code===Kl.ParsingError))||(this.processLinkingErrors(e,a,r),r.stopAfterLinkingErrors&&a.some(s=>s.data?.code===Kl.LinkingError))))return a;try{a.push(...await this.validateAst(n.value,r,i))}catch(s){if(Ju(s))throw s;console.error("An error occurred during validation:",s)}return await Dn(i),a}processLexingErrors(e,r,i){let n=[...e.lexerErrors,...e.lexerReport?.diagnostics??[]];for(let a of n){let s=a.severity??"error",l={severity:PA(s),range:{start:{line:a.line-1,character:a.column-1},end:{line:a.line-1,character:a.column+a.length-1}},message:a.message,data:b2e(s),source:this.getSource()};r.push(l)}}processParsingErrors(e,r,i){for(let n of e.parserErrors){let a;if(isNaN(n.token.startOffset)){if("previousToken"in n){let s=n.previousToken;if(isNaN(s.startOffset)){let l={line:0,character:0};a={start:l,end:l}}else{let l={line:s.endLine-1,character:s.endColumn};a={start:l,end:l}}}}else a=Py(n.token);if(a){let s={severity:PA("error"),range:a,message:n.message,data:qm(Kl.ParsingError),source:this.getSource()};r.push(s)}}}processLinkingErrors(e,r,i){for(let n of e.references){let a=n.error;if(a){let s={node:a.info.container,range:n.$refNode?.range,property:a.info.property,index:a.info.index,data:{code:Kl.LinkingError,containerType:a.info.container.$type,property:a.info.property,refText:a.info.reference.$refText}};r.push(this.toDiagnostic("error",a.message,s))}}}async validateAst(e,r,i=$r.CancellationToken.None){let n=[],a=o((s,l,u)=>{n.push(this.toDiagnostic(s,l,u))},"acceptor");return await this.validateAstBefore(e,r,a,i),await this.validateAstNodes(e,r,a,i),await this.validateAstAfter(e,r,a,i),n}async validateAstBefore(e,r,i,n=$r.CancellationToken.None){let a=this.validationRegistry.checksBefore;for(let s of a)await Dn(n),await s(e,i,r.categories??[],n)}async validateAstNodes(e,r,i,n=$r.CancellationToken.None){if(this.profiler?.isActive("validating")){let a=this.profiler.createTask("validating",this.languageId);a.start();try{let s=js(e).iterator();for(let l of s){a.startSubTask(l.$type);let u=this.validateSingleNodeOptions(l,r);if(u.validateNode)try{let h=this.validationRegistry.getChecks(l.$type,r.categories);for(let f of h)await f(l,i,n)}finally{a.stopSubTask(l.$type)}u.validateChildren||s.prune()}}finally{a.stop()}}else{let a=js(e).iterator();for(let s of a){await Dn(n);let l=this.validateSingleNodeOptions(s,r);if(l.validateNode){let u=this.validationRegistry.getChecks(s.$type,r.categories);for(let h of u)await h(s,i,n)}l.validateChildren||a.prune()}}}validateSingleNodeOptions(e,r){return v2e}async validateAstAfter(e,r,i,n=$r.CancellationToken.None){let a=this.validationRegistry.checksAfter;for(let s of a)await Dn(n),await s(e,i,r.categories??[],n)}toDiagnostic(e,r,i){return{message:r,range:x2e(i),severity:PA(e),code:i.code,codeDescription:i.codeDescription,tags:i.tags,relatedInformation:i.relatedInformation,data:i.data,source:this.getSource()}}getSource(){return this.metadata.languageId}};o(x2e,"getDiagnosticRange");o(PA,"toDiagnosticSeverity");o(b2e,"toDiagnosticData");(function(t){t.LexingError="lexing-error",t.LexingWarning="lexing-warning",t.LexingInfo="lexing-info",t.LexingHint="lexing-hint",t.ParsingError="parsing-error",t.LinkingError="linking-error"})(Kl||(Kl={}))});var Yk,jk,PG=P(()=>{"use strict";Yl();Oc();Ts();Bc();Xl();Wc();Yk=class{static{o(this,"DefaultAstNodeDescriptionProvider")}constructor(e){this.astNodeLocator=e.workspace.AstNodeLocator,this.nameProvider=e.references.NameProvider}createDescription(e,r,i){let n=i??bs(e);r??(r=this.nameProvider.getName(e));let a=this.astNodeLocator.getAstNodePath(e);if(!r)throw new Error(`Node at path ${a} has no name.`);let s,l=o(()=>s??(s=bm(this.nameProvider.getNameNode(e)??e.$cstNode)),"nameSegmentGetter");return{node:e,name:r,get nameSegment(){return l()},selectionSegment:bm(e.$cstNode),type:e.$type,documentUri:n.uri,path:a}}},jk=class{static{o(this,"DefaultReferenceDescriptionProvider")}constructor(e){this.nodeLocator=e.workspace.AstNodeLocator}async createDescriptions(e,r=$r.CancellationToken.None){let i=[],n=e.parseResult.value;for(let a of js(n))await Dn(r),jd(a).forEach(s=>{s.reference.error||i.push(...this.createInfoDescriptions(s))});return i}createInfoDescriptions(e){let r=e.reference;if(r.error||!r.$refNode)return[];let i=[];ga(r)&&r.$nodeDescription?i=[r.$nodeDescription]:nl(r)&&(i=r.items.map(u=>u.$nodeDescription).filter(u=>u!==void 0));let n=bs(e.container).uri,a=this.nodeLocator.getAstNodePath(e.container),s=[],l=bm(r.$refNode);for(let u of i)s.push({sourceUri:n,sourcePath:a,targetUri:u.documentUri,targetPath:u.path,segment:l,local:Vn.equals(u.documentUri,n)});return s}}});var Xk,BG=P(()=>{"use strict";Xk=class{static{o(this,"DefaultAstNodeLocator")}constructor(){this.segmentSeparator="/",this.indexSeparator="@"}getAstNodePath(e){if(e.$container){let r=this.getAstNodePath(e.$container),i=this.getPathSegment(e);return r+this.segmentSeparator+i}return""}getPathSegment({$containerProperty:e,$containerIndex:r}){if(!e)throw new Error("Missing '$containerProperty' in AST node.");return r!==void 0?e+this.indexSeparator+r:e}getAstNode(e,r){return r.split(this.segmentSeparator).reduce((n,a)=>{if(!n||a.length===0)return n;let s=a.indexOf(this.indexSeparator);if(s>0){let l=a.substring(0,s),u=parseInt(a.substring(s+1));return n[l]?.[u]}return n[a]},e)}}});var xn={};var BA=P(()=>{"use strict";Kr(xn,Wa($m(),1))});var Kk,FG=P(()=>{"use strict";BA();Xl();Kk=class{static{o(this,"DefaultConfigurationProvider")}constructor(e){this._ready=new eo,this.onConfigurationSectionUpdateEmitter=new xn.Emitter,this.settings={},this.workspaceConfig=!1,this.serviceRegistry=e.ServiceRegistry}get ready(){return this._ready.promise}initialize(e){this.workspaceConfig=e.capabilities.workspace?.configuration??!1}async initialized(e){if(this.workspaceConfig){if(e.register){let r=this.serviceRegistry.all;e.register({section:r.map(i=>this.toSectionName(i.LanguageMetaData.languageId))})}if(e.fetchConfiguration){let r=this.serviceRegistry.all.map(n=>({section:this.toSectionName(n.LanguageMetaData.languageId)})),i=await e.fetchConfiguration(r);r.forEach((n,a)=>{this.updateSectionConfiguration(n.section,i[a])})}}this._ready.resolve()}updateConfiguration(e){typeof e.settings!="object"||e.settings===null||Object.entries(e.settings).forEach(([r,i])=>{this.updateSectionConfiguration(r,i),this.onConfigurationSectionUpdateEmitter.fire({section:r,configuration:i})})}updateSectionConfiguration(e,r){this.settings[e]=r}async getConfiguration(e,r){await this.ready;let i=this.toSectionName(e);if(this.settings[i])return this.settings[i][r]}toSectionName(e){return`${e}`}get onConfigurationSectionUpdate(){return this.onConfigurationSectionUpdateEmitter.event}}});var cV=ar(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.Message=cr.NotificationType9=cr.NotificationType8=cr.NotificationType7=cr.NotificationType6=cr.NotificationType5=cr.NotificationType4=cr.NotificationType3=cr.NotificationType2=cr.NotificationType1=cr.NotificationType0=cr.NotificationType=cr.RequestType9=cr.RequestType8=cr.RequestType7=cr.RequestType6=cr.RequestType5=cr.RequestType4=cr.RequestType3=cr.RequestType2=cr.RequestType1=cr.RequestType=cr.RequestType0=cr.AbstractMessageSignature=cr.ParameterStructures=cr.ResponseError=cr.ErrorCodes=void 0;var Wm=yv(),$G;(function(t){t.ParseError=-32700,t.InvalidRequest=-32600,t.MethodNotFound=-32601,t.InvalidParams=-32602,t.InternalError=-32603,t.jsonrpcReservedErrorRangeStart=-32099,t.serverErrorStart=-32099,t.MessageWriteError=-32099,t.MessageReadError=-32098,t.PendingResponseRejected=-32097,t.ConnectionInactive=-32096,t.ServerNotInitialized=-32002,t.UnknownErrorCode=-32001,t.jsonrpcReservedErrorRangeEnd=-32e3,t.serverErrorEnd=-32e3})($G||(cr.ErrorCodes=$G={}));var zG=class t extends Error{static{o(this,"ResponseError")}constructor(e,r,i){super(r),this.code=Wm.number(e)?e:$G.UnknownErrorCode,this.data=i,Object.setPrototypeOf(this,t.prototype)}toJson(){let e={code:this.code,message:this.message};return this.data!==void 0&&(e.data=this.data),e}};cr.ResponseError=zG;var Po=class t{static{o(this,"ParameterStructures")}constructor(e){this.kind=e}static is(e){return e===t.auto||e===t.byName||e===t.byPosition}toString(){return this.kind}};cr.ParameterStructures=Po;Po.auto=new Po("auto");Po.byPosition=new Po("byPosition");Po.byName=new Po("byName");var un=class{static{o(this,"AbstractMessageSignature")}constructor(e,r){this.method=e,this.numberOfParams=r}get parameterStructures(){return Po.auto}};cr.AbstractMessageSignature=un;var GG=class extends un{static{o(this,"RequestType0")}constructor(e){super(e,0)}};cr.RequestType0=GG;var VG=class extends un{static{o(this,"RequestType")}constructor(e,r=Po.auto){super(e,1),this._parameterStructures=r}get parameterStructures(){return this._parameterStructures}};cr.RequestType=VG;var qG=class extends un{static{o(this,"RequestType1")}constructor(e,r=Po.auto){super(e,1),this._parameterStructures=r}get parameterStructures(){return this._parameterStructures}};cr.RequestType1=qG;var WG=class extends un{static{o(this,"RequestType2")}constructor(e){super(e,2)}};cr.RequestType2=WG;var UG=class extends un{static{o(this,"RequestType3")}constructor(e){super(e,3)}};cr.RequestType3=UG;var HG=class extends un{static{o(this,"RequestType4")}constructor(e){super(e,4)}};cr.RequestType4=HG;var YG=class extends un{static{o(this,"RequestType5")}constructor(e){super(e,5)}};cr.RequestType5=YG;var jG=class extends un{static{o(this,"RequestType6")}constructor(e){super(e,6)}};cr.RequestType6=jG;var XG=class extends un{static{o(this,"RequestType7")}constructor(e){super(e,7)}};cr.RequestType7=XG;var KG=class extends un{static{o(this,"RequestType8")}constructor(e){super(e,8)}};cr.RequestType8=KG;var QG=class extends un{static{o(this,"RequestType9")}constructor(e){super(e,9)}};cr.RequestType9=QG;var ZG=class extends un{static{o(this,"NotificationType")}constructor(e,r=Po.auto){super(e,1),this._parameterStructures=r}get parameterStructures(){return this._parameterStructures}};cr.NotificationType=ZG;var JG=class extends un{static{o(this,"NotificationType0")}constructor(e){super(e,0)}};cr.NotificationType0=JG;var eV=class extends un{static{o(this,"NotificationType1")}constructor(e,r=Po.auto){super(e,1),this._parameterStructures=r}get parameterStructures(){return this._parameterStructures}};cr.NotificationType1=eV;var tV=class extends un{static{o(this,"NotificationType2")}constructor(e){super(e,2)}};cr.NotificationType2=tV;var rV=class extends un{static{o(this,"NotificationType3")}constructor(e){super(e,3)}};cr.NotificationType3=rV;var iV=class extends un{static{o(this,"NotificationType4")}constructor(e){super(e,4)}};cr.NotificationType4=iV;var nV=class extends un{static{o(this,"NotificationType5")}constructor(e){super(e,5)}};cr.NotificationType5=nV;var aV=class extends un{static{o(this,"NotificationType6")}constructor(e){super(e,6)}};cr.NotificationType6=aV;var sV=class extends un{static{o(this,"NotificationType7")}constructor(e){super(e,7)}};cr.NotificationType7=sV;var oV=class extends un{static{o(this,"NotificationType8")}constructor(e){super(e,8)}};cr.NotificationType8=oV;var lV=class extends un{static{o(this,"NotificationType9")}constructor(e){super(e,9)}};cr.NotificationType9=lV;var T2e;(function(t){function e(n){let a=n;return a&&Wm.string(a.method)&&(Wm.string(a.id)||Wm.number(a.id))}o(e,"isRequest"),t.isRequest=e;function r(n){let a=n;return a&&Wm.string(a.method)&&n.id===void 0}o(r,"isNotification"),t.isNotification=r;function i(n){let a=n;return a&&(a.result!==void 0||!!a.error)&&(Wm.string(a.id)||Wm.number(a.id)||a.id===null)}o(i,"isResponse"),t.isResponse=i})(T2e||(cr.Message=T2e={}))});var hV=ar(hp=>{"use strict";var k2e;Object.defineProperty(hp,"__esModule",{value:!0});hp.LRUCache=hp.LinkedMap=hp.Touch=void 0;var ws;(function(t){t.None=0,t.First=1,t.AsOld=t.First,t.Last=2,t.AsNew=t.Last})(ws||(hp.Touch=ws={}));var FA=class{static{o(this,"LinkedMap")}constructor(){this[k2e]="LinkedMap",this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has(e){return this._map.has(e)}get(e,r=ws.None){let i=this._map.get(e);if(i)return r!==ws.None&&this.touch(i,r),i.value}set(e,r,i=ws.None){let n=this._map.get(e);if(n)n.value=r,i!==ws.None&&this.touch(n,i);else{switch(n={key:e,value:r,next:void 0,previous:void 0},i){case ws.None:this.addItemLast(n);break;case ws.First:this.addItemFirst(n);break;case ws.Last:this.addItemLast(n);break;default:this.addItemLast(n);break}this._map.set(e,n),this._size++}return this}delete(e){return!!this.remove(e)}remove(e){let r=this._map.get(e);if(r)return this._map.delete(e),this.removeItem(r),this._size--,r.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw new Error("Invalid list");let e=this._head;return this._map.delete(e.key),this.removeItem(e),this._size--,e.value}forEach(e,r){let i=this._state,n=this._head;for(;n;){if(r?e.bind(r)(n.value,n.key,this):e(n.value,n.key,this),this._state!==i)throw new Error("LinkedMap got modified during iteration.");n=n.next}}keys(){let e=this._state,r=this._head,i={[Symbol.iterator]:()=>i,next:o(()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(r){let n={value:r.key,done:!1};return r=r.next,n}else return{value:void 0,done:!0}},"next")};return i}values(){let e=this._state,r=this._head,i={[Symbol.iterator]:()=>i,next:o(()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(r){let n={value:r.value,done:!1};return r=r.next,n}else return{value:void 0,done:!0}},"next")};return i}entries(){let e=this._state,r=this._head,i={[Symbol.iterator]:()=>i,next:o(()=>{if(this._state!==e)throw new Error("LinkedMap got modified during iteration.");if(r){let n={value:[r.key,r.value],done:!1};return r=r.next,n}else return{value:void 0,done:!0}},"next")};return i}[(k2e=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(e){if(e>=this.size)return;if(e===0){this.clear();return}let r=this._head,i=this.size;for(;r&&i>e;)this._map.delete(r.key),r=r.next,i--;this._head=r,this._size=i,r&&(r.previous=void 0),this._state++}addItemFirst(e){if(!this._head&&!this._tail)this._tail=e;else if(this._head)e.next=this._head,this._head.previous=e;else throw new Error("Invalid list");this._head=e,this._state++}addItemLast(e){if(!this._head&&!this._tail)this._head=e;else if(this._tail)e.previous=this._tail,this._tail.next=e;else throw new Error("Invalid list");this._tail=e,this._state++}removeItem(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head){if(!e.next)throw new Error("Invalid list");e.next.previous=void 0,this._head=e.next}else if(e===this._tail){if(!e.previous)throw new Error("Invalid list");e.previous.next=void 0,this._tail=e.previous}else{let r=e.next,i=e.previous;if(!r||!i)throw new Error("Invalid list");r.previous=i,i.next=r}e.next=void 0,e.previous=void 0,this._state++}touch(e,r){if(!this._head||!this._tail)throw new Error("Invalid list");if(!(r!==ws.First&&r!==ws.Last)){if(r===ws.First){if(e===this._head)return;let i=e.next,n=e.previous;e===this._tail?(n.next=void 0,this._tail=n):(i.previous=n,n.next=i),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e,this._state++}else if(r===ws.Last){if(e===this._tail)return;let i=e.next,n=e.previous;e===this._head?(i.previous=void 0,this._head=i):(i.previous=n,n.next=i),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e,this._state++}}}toJSON(){let e=[];return this.forEach((r,i)=>{e.push([i,r])}),e}fromJSON(e){this.clear();for(let[r,i]of e)this.set(r,i)}};hp.LinkedMap=FA;var uV=class extends FA{static{o(this,"LRUCache")}constructor(e,r=1){super(),this._limit=e,this._ratio=Math.min(Math.max(0,r),1)}get limit(){return this._limit}set limit(e){this._limit=e,this.checkTrim()}get ratio(){return this._ratio}set ratio(e){this._ratio=Math.min(Math.max(0,e),1),this.checkTrim()}get(e,r=ws.AsNew){return super.get(e,r)}peek(e){return super.get(e,ws.None)}set(e,r){return super.set(e,r,ws.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}};hp.LRUCache=uV});var w2e=ar($A=>{"use strict";Object.defineProperty($A,"__esModule",{value:!0});$A.Disposable=void 0;var C2e;(function(t){function e(r){return{dispose:r}}o(e,"create"),t.create=e})(C2e||($A.Disposable=C2e={}))});var E2e=ar(Av=>{"use strict";Object.defineProperty(Av,"__esModule",{value:!0});Av.SharedArrayReceiverStrategy=Av.SharedArraySenderStrategy=void 0;var Fst=Ik(),Qk;(function(t){t.Continue=0,t.Cancelled=1})(Qk||(Qk={}));var fV=class{static{o(this,"SharedArraySenderStrategy")}constructor(){this.buffers=new Map}enableCancellation(e){if(e.id===null)return;let r=new SharedArrayBuffer(4),i=new Int32Array(r,0,1);i[0]=Qk.Continue,this.buffers.set(e.id,r),e.$cancellationData=r}async sendCancellation(e,r){let i=this.buffers.get(r);if(i===void 0)return;let n=new Int32Array(i,0,1);Atomics.store(n,0,Qk.Cancelled)}cleanup(e){this.buffers.delete(e)}dispose(){this.buffers.clear()}};Av.SharedArraySenderStrategy=fV;var dV=class{static{o(this,"SharedArrayBufferCancellationToken")}constructor(e){this.data=new Int32Array(e,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===Qk.Cancelled}get onCancellationRequested(){throw new Error("Cancellation over SharedArrayBuffer doesn't support cancellation events")}},pV=class{static{o(this,"SharedArrayBufferCancellationTokenSource")}constructor(e){this.token=new dV(e)}cancel(){}dispose(){}},mV=class{static{o(this,"SharedArrayReceiverStrategy")}constructor(){this.kind="request"}createCancellationTokenSource(e){let r=e.$cancellationData;return r===void 0?new Fst.CancellationTokenSource:new pV(r)}};Av.SharedArrayReceiverStrategy=mV});var yV=ar(zA=>{"use strict";Object.defineProperty(zA,"__esModule",{value:!0});zA.Semaphore=void 0;var $st=cp(),gV=class{static{o(this,"Semaphore")}constructor(e=1){if(e<=0)throw new Error("Capacity must be greater than 0");this._capacity=e,this._active=0,this._waiting=[]}lock(e){return new Promise((r,i)=>{this._waiting.push({thunk:e,resolve:r,reject:i}),this.runNext()})}get active(){return this._active}runNext(){this._waiting.length===0||this._active===this._capacity||(0,$st.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;let e=this._waiting.shift();if(this._active++,this._active>this._capacity)throw new Error("To many thunks active");try{let r=e.thunk();r instanceof Promise?r.then(i=>{this._active--,e.resolve(i),this.runNext()},i=>{this._active--,e.reject(i),this.runNext()}):(this._active--,e.resolve(r),this.runNext())}catch(r){this._active--,e.reject(r),this.runNext()}}};zA.Semaphore=gV});var A2e=ar(fp=>{"use strict";Object.defineProperty(fp,"__esModule",{value:!0});fp.ReadableStreamMessageReader=fp.AbstractMessageReader=fp.MessageReader=void 0;var xV=cp(),_v=yv(),vV=$m(),zst=yV(),S2e;(function(t){function e(r){let i=r;return i&&_v.func(i.listen)&&_v.func(i.dispose)&&_v.func(i.onError)&&_v.func(i.onClose)&&_v.func(i.onPartialMessage)}o(e,"is"),t.is=e})(S2e||(fp.MessageReader=S2e={}));var GA=class{static{o(this,"AbstractMessageReader")}constructor(){this.errorEmitter=new vV.Emitter,this.closeEmitter=new vV.Emitter,this.partialMessageEmitter=new vV.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e){this.errorEmitter.fire(this.asError(e))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(e){this.partialMessageEmitter.fire(e)}asError(e){return e instanceof Error?e:new Error(`Reader received error. Reason: ${_v.string(e.message)?e.message:"unknown"}`)}};fp.AbstractMessageReader=GA;var bV;(function(t){function e(r){let i,n,a,s=new Map,l,u=new Map;if(r===void 0||typeof r=="string")i=r??"utf-8";else{if(i=r.charset??"utf-8",r.contentDecoder!==void 0&&(a=r.contentDecoder,s.set(a.name,a)),r.contentDecoders!==void 0)for(let h of r.contentDecoders)s.set(h.name,h);if(r.contentTypeDecoder!==void 0&&(l=r.contentTypeDecoder,u.set(l.name,l)),r.contentTypeDecoders!==void 0)for(let h of r.contentTypeDecoders)u.set(h.name,h)}return l===void 0&&(l=(0,xV.default)().applicationJson.decoder,u.set(l.name,l)),{charset:i,contentDecoder:a,contentDecoders:s,contentTypeDecoder:l,contentTypeDecoders:u}}o(e,"fromOptions"),t.fromOptions=e})(bV||(bV={}));var TV=class extends GA{static{o(this,"ReadableStreamMessageReader")}constructor(e,r){super(),this.readable=e,this.options=bV.fromOptions(r),this.buffer=(0,xV.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new zst.Semaphore(1)}set partialMessageTimeout(e){this._partialMessageTimeout=e}get partialMessageTimeout(){return this._partialMessageTimeout}listen(e){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=e;let r=this.readable.onData(i=>{this.onData(i)});return this.readable.onError(i=>this.fireError(i)),this.readable.onClose(()=>this.fireClose()),r}onData(e){try{for(this.buffer.append(e);;){if(this.nextMessageLength===-1){let i=this.buffer.tryReadHeaders(!0);if(!i)return;let n=i.get("content-length");if(!n){this.fireError(new Error(`Header must provide a Content-Length property. +${JSON.stringify(Object.fromEntries(i))}`));return}let a=parseInt(n);if(isNaN(a)){this.fireError(new Error(`Content-Length value must be a number. Got ${n}`));return}this.nextMessageLength=a}let r=this.buffer.tryReadBody(this.nextMessageLength);if(r===void 0){this.setPartialMessageTimer();return}this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.readSemaphore.lock(async()=>{let i=this.options.contentDecoder!==void 0?await this.options.contentDecoder.decode(r):r,n=await this.options.contentTypeDecoder.decode(i,this.options);this.callback(n)}).catch(i=>{this.fireError(i)})}}catch(r){this.fireError(r)}}clearPartialMessageTimer(){this.partialMessageTimer&&(this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),!(this._partialMessageTimeout<=0)&&(this.partialMessageTimer=(0,xV.default)().timer.setTimeout((e,r)=>{this.partialMessageTimer=void 0,e===this.messageToken&&(this.firePartialMessage({messageToken:e,waitingTime:r}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}};fp.ReadableStreamMessageReader=TV});var N2e=ar(dp=>{"use strict";Object.defineProperty(dp,"__esModule",{value:!0});dp.WriteableStreamMessageWriter=dp.AbstractMessageWriter=dp.MessageWriter=void 0;var _2e=cp(),Zk=yv(),Gst=yV(),D2e=$m(),Vst="Content-Length: ",L2e=`\r +`,R2e;(function(t){function e(r){let i=r;return i&&Zk.func(i.dispose)&&Zk.func(i.onClose)&&Zk.func(i.onError)&&Zk.func(i.write)}o(e,"is"),t.is=e})(R2e||(dp.MessageWriter=R2e={}));var VA=class{static{o(this,"AbstractMessageWriter")}constructor(){this.errorEmitter=new D2e.Emitter,this.closeEmitter=new D2e.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(e,r,i){this.errorEmitter.fire([this.asError(e),r,i])}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}asError(e){return e instanceof Error?e:new Error(`Writer received error. Reason: ${Zk.string(e.message)?e.message:"unknown"}`)}};dp.AbstractMessageWriter=VA;var kV;(function(t){function e(r){return r===void 0||typeof r=="string"?{charset:r??"utf-8",contentTypeEncoder:(0,_2e.default)().applicationJson.encoder}:{charset:r.charset??"utf-8",contentEncoder:r.contentEncoder,contentTypeEncoder:r.contentTypeEncoder??(0,_2e.default)().applicationJson.encoder}}o(e,"fromOptions"),t.fromOptions=e})(kV||(kV={}));var CV=class extends VA{static{o(this,"WriteableStreamMessageWriter")}constructor(e,r){super(),this.writable=e,this.options=kV.fromOptions(r),this.errorCount=0,this.writeSemaphore=new Gst.Semaphore(1),this.writable.onError(i=>this.fireError(i)),this.writable.onClose(()=>this.fireClose())}async write(e){return this.writeSemaphore.lock(async()=>this.options.contentTypeEncoder.encode(e,this.options).then(i=>this.options.contentEncoder!==void 0?this.options.contentEncoder.encode(i):i).then(i=>{let n=[];return n.push(Vst,i.byteLength.toString(),L2e),n.push(L2e),this.doWrite(e,n,i)},i=>{throw this.fireError(i),i}))}async doWrite(e,r,i){try{return await this.writable.write(r.join(""),"ascii"),this.writable.write(i)}catch(n){return this.handleError(n,e),Promise.reject(n)}}handleError(e,r){this.errorCount++,this.fireError(e,r,this.errorCount)}end(){this.writable.end()}};dp.WriteableStreamMessageWriter=CV});var I2e=ar(qA=>{"use strict";Object.defineProperty(qA,"__esModule",{value:!0});qA.AbstractMessageBuffer=void 0;var qst=13,Wst=10,Ust=`\r +`,wV=class{static{o(this,"AbstractMessageBuffer")}constructor(e="utf-8"){this._encoding=e,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append(e){let r=typeof e=="string"?this.fromString(e,this._encoding):e;this._chunks.push(r),this._totalLength+=r.byteLength}tryReadHeaders(e=!1){if(this._chunks.length===0)return;let r=0,i=0,n=0,a=0;e:for(;ithis._totalLength)throw new Error("Cannot read so many bytes!");if(this._chunks[0].byteLength===e){let a=this._chunks[0];return this._chunks.shift(),this._totalLength-=e,this.asNative(a)}if(this._chunks[0].byteLength>e){let a=this._chunks[0],s=this.asNative(a,e);return this._chunks[0]=a.slice(e),this._totalLength-=e,s}let r=this.allocNative(e),i=0,n=0;for(;e>0;){let a=this._chunks[n];if(a.byteLength>e){let s=a.slice(0,e);r.set(s,i),i+=e,this._chunks[n]=a.slice(e),this._totalLength-=e,e-=e}else r.set(a,i),i+=a.byteLength,this._chunks.shift(),this._totalLength-=a.byteLength,e-=a.byteLength}return r}};qA.AbstractMessageBuffer=wV});var F2e=ar(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.createMessageConnection=Fr.ConnectionOptions=Fr.MessageStrategy=Fr.CancellationStrategy=Fr.CancellationSenderStrategy=Fr.CancellationReceiverStrategy=Fr.RequestCancellationReceiverStrategy=Fr.IdCancellationReceiverStrategy=Fr.ConnectionStrategy=Fr.ConnectionError=Fr.ConnectionErrors=Fr.LogTraceNotification=Fr.SetTraceNotification=Fr.TraceFormat=Fr.TraceValues=Fr.Trace=Fr.NullLogger=Fr.ProgressType=Fr.ProgressToken=void 0;var M2e=cp(),Ln=yv(),kr=cV(),O2e=hV(),Jk=$m(),EV=Ik(),rC;(function(t){t.type=new kr.NotificationType("$/cancelRequest")})(rC||(rC={}));var SV;(function(t){function e(r){return typeof r=="string"||typeof r=="number"}o(e,"is"),t.is=e})(SV||(Fr.ProgressToken=SV={}));var eC;(function(t){t.type=new kr.NotificationType("$/progress")})(eC||(eC={}));var AV=class{static{o(this,"ProgressType")}constructor(){}};Fr.ProgressType=AV;var _V;(function(t){function e(r){return Ln.func(r)}o(e,"is"),t.is=e})(_V||(_V={}));Fr.NullLogger=Object.freeze({error:o(()=>{},"error"),warn:o(()=>{},"warn"),info:o(()=>{},"info"),log:o(()=>{},"log")});var Ti;(function(t){t[t.Off=0]="Off",t[t.Messages=1]="Messages",t[t.Compact=2]="Compact",t[t.Verbose=3]="Verbose"})(Ti||(Fr.Trace=Ti={}));var P2e;(function(t){t.Off="off",t.Messages="messages",t.Compact="compact",t.Verbose="verbose"})(P2e||(Fr.TraceValues=P2e={}));(function(t){function e(i){if(!Ln.string(i))return t.Off;switch(i=i.toLowerCase(),i){case"off":return t.Off;case"messages":return t.Messages;case"compact":return t.Compact;case"verbose":return t.Verbose;default:return t.Off}}o(e,"fromString"),t.fromString=e;function r(i){switch(i){case t.Off:return"off";case t.Messages:return"messages";case t.Compact:return"compact";case t.Verbose:return"verbose";default:return"off"}}o(r,"toString"),t.toString=r})(Ti||(Fr.Trace=Ti={}));var ul;(function(t){t.Text="text",t.JSON="json"})(ul||(Fr.TraceFormat=ul={}));(function(t){function e(r){return Ln.string(r)?(r=r.toLowerCase(),r==="json"?t.JSON:t.Text):t.Text}o(e,"fromString"),t.fromString=e})(ul||(Fr.TraceFormat=ul={}));var DV;(function(t){t.type=new kr.NotificationType("$/setTrace")})(DV||(Fr.SetTraceNotification=DV={}));var WA;(function(t){t.type=new kr.NotificationType("$/logTrace")})(WA||(Fr.LogTraceNotification=WA={}));var tC;(function(t){t[t.Closed=1]="Closed",t[t.Disposed=2]="Disposed",t[t.AlreadyListening=3]="AlreadyListening"})(tC||(Fr.ConnectionErrors=tC={}));var Dv=class t extends Error{static{o(this,"ConnectionError")}constructor(e,r){super(r),this.code=e,Object.setPrototypeOf(this,t.prototype)}};Fr.ConnectionError=Dv;var LV;(function(t){function e(r){let i=r;return i&&Ln.func(i.cancelUndispatched)}o(e,"is"),t.is=e})(LV||(Fr.ConnectionStrategy=LV={}));var UA;(function(t){function e(r){let i=r;return i&&(i.kind===void 0||i.kind==="id")&&Ln.func(i.createCancellationTokenSource)&&(i.dispose===void 0||Ln.func(i.dispose))}o(e,"is"),t.is=e})(UA||(Fr.IdCancellationReceiverStrategy=UA={}));var RV;(function(t){function e(r){let i=r;return i&&i.kind==="request"&&Ln.func(i.createCancellationTokenSource)&&(i.dispose===void 0||Ln.func(i.dispose))}o(e,"is"),t.is=e})(RV||(Fr.RequestCancellationReceiverStrategy=RV={}));var HA;(function(t){t.Message=Object.freeze({createCancellationTokenSource(r){return new EV.CancellationTokenSource}});function e(r){return UA.is(r)||RV.is(r)}o(e,"is"),t.is=e})(HA||(Fr.CancellationReceiverStrategy=HA={}));var YA;(function(t){t.Message=Object.freeze({sendCancellation(r,i){return r.sendNotification(rC.type,{id:i})},cleanup(r){}});function e(r){let i=r;return i&&Ln.func(i.sendCancellation)&&Ln.func(i.cleanup)}o(e,"is"),t.is=e})(YA||(Fr.CancellationSenderStrategy=YA={}));var jA;(function(t){t.Message=Object.freeze({receiver:HA.Message,sender:YA.Message});function e(r){let i=r;return i&&HA.is(i.receiver)&&YA.is(i.sender)}o(e,"is"),t.is=e})(jA||(Fr.CancellationStrategy=jA={}));var XA;(function(t){function e(r){let i=r;return i&&Ln.func(i.handleMessage)}o(e,"is"),t.is=e})(XA||(Fr.MessageStrategy=XA={}));var B2e;(function(t){function e(r){let i=r;return i&&(jA.is(i.cancellationStrategy)||LV.is(i.connectionStrategy)||XA.is(i.messageStrategy))}o(e,"is"),t.is=e})(B2e||(Fr.ConnectionOptions=B2e={}));var Uc;(function(t){t[t.New=1]="New",t[t.Listening=2]="Listening",t[t.Closed=3]="Closed",t[t.Disposed=4]="Disposed"})(Uc||(Uc={}));function Hst(t,e,r,i){let n=r!==void 0?r:Fr.NullLogger,a=0,s=0,l=0,u="2.0",h,f=new Map,d,p=new Map,m=new Map,g,y=new O2e.LinkedMap,v=new Map,x=new Set,b=new Map,T=Ti.Off,w=ul.Text,k,C=Uc.New,E=new Jk.Emitter,S=new Jk.Emitter,L=new Jk.Emitter,M=new Jk.Emitter,I=new Jk.Emitter,A=i&&i.cancellationStrategy?i.cancellationStrategy:jA.Message;function _(K){if(K===null)throw new Error("Can't send requests with id null since the response can't be correlated.");return"req-"+K.toString()}o(_,"createRequestQueueKey");function D(K){return K===null?"res-unknown-"+(++l).toString():"res-"+K.toString()}o(D,"createResponseQueueKey");function N(){return"not-"+(++s).toString()}o(N,"createNotificationQueueKey");function R(K,oe){kr.Message.isRequest(oe)?K.set(_(oe.id),oe):kr.Message.isResponse(oe)?K.set(D(oe.id),oe):K.set(N(),oe)}o(R,"addMessageToQueue");function B(K){}o(B,"cancelUndispatched");function O(){return C===Uc.Listening}o(O,"isListening");function $(){return C===Uc.Closed}o($,"isClosed");function z(){return C===Uc.Disposed}o(z,"isDisposed");function F(){(C===Uc.New||C===Uc.Listening)&&(C=Uc.Closed,S.fire(void 0))}o(F,"closeHandler");function V(K){E.fire([K,void 0,void 0])}o(V,"readErrorHandler");function H(K){E.fire(K)}o(H,"writeErrorHandler"),t.onClose(F),t.onError(V),e.onClose(F),e.onError(H);function X(){g||y.size===0||(g=(0,M2e.default)().timer.setImmediate(()=>{g=void 0,Z()}))}o(X,"triggerMessageQueue");function W(K){kr.Message.isRequest(K)?ae(K):kr.Message.isNotification(K)?ee(K):kr.Message.isResponse(K)?J(K):re(K)}o(W,"handleMessage");function Z(){if(y.size===0)return;let K=y.shift();try{let oe=i?.messageStrategy;XA.is(oe)?oe.handleMessage(K,W):W(K)}finally{X()}}o(Z,"processMessageQueue");let Y=o(K=>{try{if(kr.Message.isNotification(K)&&K.method===rC.type.method){let oe=K.params.id,U=_(oe),ue=y.get(U);if(kr.Message.isRequest(ue)){let se=i?.connectionStrategy,le=se&&se.cancelUndispatched?se.cancelUndispatched(ue,B):void 0;if(le&&(le.error!==void 0||le.result!==void 0)){y.delete(U),b.delete(oe),le.id=ue.id,Ee(le,K.method,Date.now()),e.write(le).catch(()=>n.error("Sending response for canceled message failed."));return}}let G=b.get(oe);if(G!==void 0){G.cancel(),we(K);return}else x.add(oe)}R(y,K)}finally{X()}},"callback");function ae(K){if(z())return;function oe(me,ye,Re){let ve={jsonrpc:u,id:K.id};me instanceof kr.ResponseError?ve.error=me.toJson():ve.result=me===void 0?null:me,Ee(ve,ye,Re),e.write(ve).catch(()=>n.error("Sending response failed."))}o(oe,"reply");function U(me,ye,Re){let ve={jsonrpc:u,id:K.id,error:me.toJson()};Ee(ve,ye,Re),e.write(ve).catch(()=>n.error("Sending response failed."))}o(U,"replyError");function ue(me,ye,Re){me===void 0&&(me=null);let ve={jsonrpc:u,id:K.id,result:me};Ee(ve,ye,Re),e.write(ve).catch(()=>n.error("Sending response failed."))}o(ue,"replySuccess"),Ne(K);let G=f.get(K.method),se,le;G&&(se=G.type,le=G.handler);let ke=Date.now();if(le||h){let me=K.id??String(Date.now()),ye=UA.is(A.receiver)?A.receiver.createCancellationTokenSource(me):A.receiver.createCancellationTokenSource(K);K.id!==null&&x.has(K.id)&&ye.cancel(),K.id!==null&&b.set(me,ye);try{let Re;if(le)if(K.params===void 0){if(se!==void 0&&se.numberOfParams!==0){U(new kr.ResponseError(kr.ErrorCodes.InvalidParams,`Request ${K.method} defines ${se.numberOfParams} params but received none.`),K.method,ke);return}Re=le(ye.token)}else if(Array.isArray(K.params)){if(se!==void 0&&se.parameterStructures===kr.ParameterStructures.byName){U(new kr.ResponseError(kr.ErrorCodes.InvalidParams,`Request ${K.method} defines parameters by name but received parameters by position`),K.method,ke);return}Re=le(...K.params,ye.token)}else{if(se!==void 0&&se.parameterStructures===kr.ParameterStructures.byPosition){U(new kr.ResponseError(kr.ErrorCodes.InvalidParams,`Request ${K.method} defines parameters by position but received parameters by name`),K.method,ke);return}Re=le(K.params,ye.token)}else h&&(Re=h(K.method,K.params,ye.token));let ve=Re;Re?ve.then?ve.then(Oe=>{b.delete(me),oe(Oe,K.method,ke)},Oe=>{b.delete(me),Oe instanceof kr.ResponseError?U(Oe,K.method,ke):Oe&&Ln.string(Oe.message)?U(new kr.ResponseError(kr.ErrorCodes.InternalError,`Request ${K.method} failed with message: ${Oe.message}`),K.method,ke):U(new kr.ResponseError(kr.ErrorCodes.InternalError,`Request ${K.method} failed unexpectedly without providing any details.`),K.method,ke)}):(b.delete(me),oe(Re,K.method,ke)):(b.delete(me),ue(Re,K.method,ke))}catch(Re){b.delete(me),Re instanceof kr.ResponseError?oe(Re,K.method,ke):Re&&Ln.string(Re.message)?U(new kr.ResponseError(kr.ErrorCodes.InternalError,`Request ${K.method} failed with message: ${Re.message}`),K.method,ke):U(new kr.ResponseError(kr.ErrorCodes.InternalError,`Request ${K.method} failed unexpectedly without providing any details.`),K.method,ke)}}else U(new kr.ResponseError(kr.ErrorCodes.MethodNotFound,`Unhandled method ${K.method}`),K.method,ke)}o(ae,"handleRequest");function J(K){if(!z())if(K.id===null)K.error?n.error(`Received response message without id: Error is: +${JSON.stringify(K.error,void 0,4)}`):n.error("Received response message without id. No further error information provided.");else{let oe=K.id,U=v.get(oe);if(Te(K,U),U!==void 0){v.delete(oe);try{if(K.error){let ue=K.error;U.reject(new kr.ResponseError(ue.code,ue.message,ue.data))}else if(K.result!==void 0)U.resolve(K.result);else throw new Error("Should never happen.")}catch(ue){ue.message?n.error(`Response handler '${U.method}' failed with message: ${ue.message}`):n.error(`Response handler '${U.method}' failed unexpectedly.`)}}}}o(J,"handleResponse");function ee(K){if(z())return;let oe,U;if(K.method===rC.type.method){let ue=K.params.id;x.delete(ue),we(K);return}else{let ue=p.get(K.method);ue&&(U=ue.handler,oe=ue.type)}if(U||d)try{if(we(K),U)if(K.params===void 0)oe!==void 0&&oe.numberOfParams!==0&&oe.parameterStructures!==kr.ParameterStructures.byName&&n.error(`Notification ${K.method} defines ${oe.numberOfParams} params but received none.`),U();else if(Array.isArray(K.params)){let ue=K.params;K.method===eC.type.method&&ue.length===2&&SV.is(ue[0])?U({token:ue[0],value:ue[1]}):(oe!==void 0&&(oe.parameterStructures===kr.ParameterStructures.byName&&n.error(`Notification ${K.method} defines parameters by name but received parameters by position`),oe.numberOfParams!==K.params.length&&n.error(`Notification ${K.method} defines ${oe.numberOfParams} params but received ${ue.length} arguments`)),U(...ue))}else oe!==void 0&&oe.parameterStructures===kr.ParameterStructures.byPosition&&n.error(`Notification ${K.method} defines parameters by position but received parameters by name`),U(K.params);else d&&d(K.method,K.params)}catch(ue){ue.message?n.error(`Notification handler '${K.method}' failed with message: ${ue.message}`):n.error(`Notification handler '${K.method}' failed unexpectedly.`)}else L.fire(K)}o(ee,"handleNotification");function re(K){if(!K){n.error("Received empty message.");return}n.error(`Received message which is neither a response nor a notification message: +${JSON.stringify(K,null,4)}`);let oe=K;if(Ln.string(oe.id)||Ln.number(oe.id)){let U=oe.id,ue=v.get(U);ue&&ue.reject(new Error("The received response has neither a result nor an error property."))}}o(re,"handleInvalidMessage");function te(K){if(K!=null)switch(T){case Ti.Verbose:return JSON.stringify(K,null,4);case Ti.Compact:return JSON.stringify(K);default:return}}o(te,"stringifyTrace");function be(K){if(!(T===Ti.Off||!k))if(w===ul.Text){let oe;(T===Ti.Verbose||T===Ti.Compact)&&K.params&&(oe=`Params: ${te(K.params)} + +`),k.log(`Sending request '${K.method} - (${K.id})'.`,oe)}else De("send-request",K)}o(be,"traceSendingRequest");function de(K){if(!(T===Ti.Off||!k))if(w===ul.Text){let oe;(T===Ti.Verbose||T===Ti.Compact)&&(K.params?oe=`Params: ${te(K.params)} + +`:oe=`No parameters provided. + +`),k.log(`Sending notification '${K.method}'.`,oe)}else De("send-notification",K)}o(de,"traceSendingNotification");function Ee(K,oe,U){if(!(T===Ti.Off||!k))if(w===ul.Text){let ue;(T===Ti.Verbose||T===Ti.Compact)&&(K.error&&K.error.data?ue=`Error data: ${te(K.error.data)} + +`:K.result?ue=`Result: ${te(K.result)} + +`:K.error===void 0&&(ue=`No result returned. + +`)),k.log(`Sending response '${oe} - (${K.id})'. Processing request took ${Date.now()-U}ms`,ue)}else De("send-response",K)}o(Ee,"traceSendingResponse");function Ne(K){if(!(T===Ti.Off||!k))if(w===ul.Text){let oe;(T===Ti.Verbose||T===Ti.Compact)&&K.params&&(oe=`Params: ${te(K.params)} + +`),k.log(`Received request '${K.method} - (${K.id})'.`,oe)}else De("receive-request",K)}o(Ne,"traceReceivedRequest");function we(K){if(!(T===Ti.Off||!k||K.method===WA.type.method))if(w===ul.Text){let oe;(T===Ti.Verbose||T===Ti.Compact)&&(K.params?oe=`Params: ${te(K.params)} + +`:oe=`No parameters provided. + +`),k.log(`Received notification '${K.method}'.`,oe)}else De("receive-notification",K)}o(we,"traceReceivedNotification");function Te(K,oe){if(!(T===Ti.Off||!k))if(w===ul.Text){let U;if((T===Ti.Verbose||T===Ti.Compact)&&(K.error&&K.error.data?U=`Error data: ${te(K.error.data)} + +`:K.result?U=`Result: ${te(K.result)} + +`:K.error===void 0&&(U=`No result returned. + +`)),oe){let ue=K.error?` Request failed: ${K.error.message} (${K.error.code}).`:"";k.log(`Received response '${oe.method} - (${K.id})' in ${Date.now()-oe.timerStart}ms.${ue}`,U)}else k.log(`Received response ${K.id} without active response promise.`,U)}else De("receive-response",K)}o(Te,"traceReceivedResponse");function De(K,oe){if(!k||T===Ti.Off)return;let U={isLSPMessage:!0,type:K,message:oe,timestamp:Date.now()};k.log(U)}o(De,"logLSPMessage");function $e(){if($())throw new Dv(tC.Closed,"Connection is closed.");if(z())throw new Dv(tC.Disposed,"Connection is disposed.")}o($e,"throwIfClosedOrDisposed");function pe(){if(O())throw new Dv(tC.AlreadyListening,"Connection is already listening")}o(pe,"throwIfListening");function Je(){if(!O())throw new Error("Call listen() first.")}o(Je,"throwIfNotListening");function Ce(K){return K===void 0?null:K}o(Ce,"undefinedToNull");function Fe(K){if(K!==null)return K}o(Fe,"nullToUndefined");function Ue(K){return K!=null&&!Array.isArray(K)&&typeof K=="object"}o(Ue,"isNamedParam");function qe(K,oe){switch(K){case kr.ParameterStructures.auto:return Ue(oe)?Fe(oe):[Ce(oe)];case kr.ParameterStructures.byName:if(!Ue(oe))throw new Error("Received parameters by name but param is not an object literal.");return Fe(oe);case kr.ParameterStructures.byPosition:return[Ce(oe)];default:throw new Error(`Unknown parameter structure ${K.toString()}`)}}o(qe,"computeSingleParam");function Me(K,oe){let U,ue=K.numberOfParams;switch(ue){case 0:U=void 0;break;case 1:U=qe(K.parameterStructures,oe[0]);break;default:U=[];for(let G=0;G{$e();let U,ue;if(Ln.string(K)){U=K;let se=oe[0],le=0,ke=kr.ParameterStructures.auto;kr.ParameterStructures.is(se)&&(le=1,ke=se);let me=oe.length,ye=me-le;switch(ye){case 0:ue=void 0;break;case 1:ue=qe(ke,oe[le]);break;default:if(ke===kr.ParameterStructures.byName)throw new Error(`Received ${ye} parameters for 'by Name' notification parameter structure.`);ue=oe.slice(le,me).map(Re=>Ce(Re));break}}else{let se=oe;U=K.method,ue=Me(K,se)}let G={jsonrpc:u,method:U,params:ue};return de(G),e.write(G).catch(se=>{throw n.error("Sending notification failed."),se})},"sendNotification"),onNotification:o((K,oe)=>{$e();let U;return Ln.func(K)?d=K:oe&&(Ln.string(K)?(U=K,p.set(K,{type:void 0,handler:oe})):(U=K.method,p.set(K.method,{type:K,handler:oe}))),{dispose:o(()=>{U!==void 0?p.delete(U):d=void 0},"dispose")}},"onNotification"),onProgress:o((K,oe,U)=>{if(m.has(oe))throw new Error(`Progress handler for token ${oe} already registered`);return m.set(oe,U),{dispose:o(()=>{m.delete(oe)},"dispose")}},"onProgress"),sendProgress:o((K,oe,U)=>He.sendNotification(eC.type,{token:oe,value:U}),"sendProgress"),onUnhandledProgress:M.event,sendRequest:o((K,...oe)=>{$e(),Je();let U,ue,G;if(Ln.string(K)){U=K;let me=oe[0],ye=oe[oe.length-1],Re=0,ve=kr.ParameterStructures.auto;kr.ParameterStructures.is(me)&&(Re=1,ve=me);let Oe=oe.length;EV.CancellationToken.is(ye)&&(Oe=Oe-1,G=ye);let We=Oe-Re;switch(We){case 0:ue=void 0;break;case 1:ue=qe(ve,oe[Re]);break;default:if(ve===kr.ParameterStructures.byName)throw new Error(`Received ${We} parameters for 'by Name' request parameter structure.`);ue=oe.slice(Re,Oe).map(Be=>Ce(Be));break}}else{let me=oe;U=K.method,ue=Me(K,me);let ye=K.numberOfParams;G=EV.CancellationToken.is(me[ye])?me[ye]:void 0}let se=a++,le;G&&(le=G.onCancellationRequested(()=>{let me=A.sender.sendCancellation(He,se);return me===void 0?(n.log(`Received no promise from cancellation strategy when cancelling id ${se}`),Promise.resolve()):me.catch(()=>{n.log(`Sending cancellation messages for id ${se} failed`)})}));let ke={jsonrpc:u,id:se,method:U,params:ue};return be(ke),typeof A.sender.enableCancellation=="function"&&A.sender.enableCancellation(ke),new Promise(async(me,ye)=>{let Re=o(We=>{me(We),A.sender.cleanup(se),le?.dispose()},"resolveWithCleanup"),ve=o(We=>{ye(We),A.sender.cleanup(se),le?.dispose()},"rejectWithCleanup"),Oe={method:U,timerStart:Date.now(),resolve:Re,reject:ve};try{await e.write(ke),v.set(se,Oe)}catch(We){throw n.error("Sending request failed."),Oe.reject(new kr.ResponseError(kr.ErrorCodes.MessageWriteError,We.message?We.message:"Unknown reason")),We}})},"sendRequest"),onRequest:o((K,oe)=>{$e();let U=null;return _V.is(K)?(U=void 0,h=K):Ln.string(K)?(U=null,oe!==void 0&&(U=K,f.set(K,{handler:oe,type:void 0}))):oe!==void 0&&(U=K.method,f.set(K.method,{type:K,handler:oe})),{dispose:o(()=>{U!==null&&(U!==void 0?f.delete(U):h=void 0)},"dispose")}},"onRequest"),hasPendingResponse:o(()=>v.size>0,"hasPendingResponse"),trace:o(async(K,oe,U)=>{let ue=!1,G=ul.Text;U!==void 0&&(Ln.boolean(U)?ue=U:(ue=U.sendNotification||!1,G=U.traceFormat||ul.Text)),T=K,w=G,T===Ti.Off?k=void 0:k=oe,ue&&!$()&&!z()&&await He.sendNotification(DV.type,{value:Ti.toString(K)})},"trace"),onError:E.event,onClose:S.event,onUnhandledNotification:L.event,onDispose:I.event,end:o(()=>{e.end()},"end"),dispose:o(()=>{if(z())return;C=Uc.Disposed,I.fire(void 0);let K=new kr.ResponseError(kr.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(let oe of v.values())oe.reject(K);v=new Map,b=new Map,x=new Set,y=new O2e.LinkedMap,Ln.func(e.dispose)&&e.dispose(),Ln.func(t.dispose)&&t.dispose()},"dispose"),listen:o(()=>{$e(),pe(),C=Uc.Listening,t.listen(Y)},"listen"),inspect:o(()=>{(0,M2e.default)().console.log("inspect")},"inspect")};return He.onNotification(WA.type,K=>{if(T===Ti.Off||!k)return;let oe=T===Ti.Verbose||T===Ti.Compact;k.log(K.message,oe?K.verbose:void 0)}),He.onNotification(eC.type,K=>{let oe=m.get(K.token);oe?oe(K.value):M.fire(K)}),He}o(Hst,"createMessageConnection");Fr.createMessageConnection=Hst});var KA=ar(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.ProgressType=nt.ProgressToken=nt.createMessageConnection=nt.NullLogger=nt.ConnectionOptions=nt.ConnectionStrategy=nt.AbstractMessageBuffer=nt.WriteableStreamMessageWriter=nt.AbstractMessageWriter=nt.MessageWriter=nt.ReadableStreamMessageReader=nt.AbstractMessageReader=nt.MessageReader=nt.SharedArrayReceiverStrategy=nt.SharedArraySenderStrategy=nt.CancellationToken=nt.CancellationTokenSource=nt.Emitter=nt.Event=nt.Disposable=nt.LRUCache=nt.Touch=nt.LinkedMap=nt.ParameterStructures=nt.NotificationType9=nt.NotificationType8=nt.NotificationType7=nt.NotificationType6=nt.NotificationType5=nt.NotificationType4=nt.NotificationType3=nt.NotificationType2=nt.NotificationType1=nt.NotificationType0=nt.NotificationType=nt.ErrorCodes=nt.ResponseError=nt.RequestType9=nt.RequestType8=nt.RequestType7=nt.RequestType6=nt.RequestType5=nt.RequestType4=nt.RequestType3=nt.RequestType2=nt.RequestType1=nt.RequestType0=nt.RequestType=nt.Message=nt.RAL=void 0;nt.MessageStrategy=nt.CancellationStrategy=nt.CancellationSenderStrategy=nt.CancellationReceiverStrategy=nt.ConnectionError=nt.ConnectionErrors=nt.LogTraceNotification=nt.SetTraceNotification=nt.TraceFormat=nt.TraceValues=nt.Trace=void 0;var nn=cV();Object.defineProperty(nt,"Message",{enumerable:!0,get:o(function(){return nn.Message},"get")});Object.defineProperty(nt,"RequestType",{enumerable:!0,get:o(function(){return nn.RequestType},"get")});Object.defineProperty(nt,"RequestType0",{enumerable:!0,get:o(function(){return nn.RequestType0},"get")});Object.defineProperty(nt,"RequestType1",{enumerable:!0,get:o(function(){return nn.RequestType1},"get")});Object.defineProperty(nt,"RequestType2",{enumerable:!0,get:o(function(){return nn.RequestType2},"get")});Object.defineProperty(nt,"RequestType3",{enumerable:!0,get:o(function(){return nn.RequestType3},"get")});Object.defineProperty(nt,"RequestType4",{enumerable:!0,get:o(function(){return nn.RequestType4},"get")});Object.defineProperty(nt,"RequestType5",{enumerable:!0,get:o(function(){return nn.RequestType5},"get")});Object.defineProperty(nt,"RequestType6",{enumerable:!0,get:o(function(){return nn.RequestType6},"get")});Object.defineProperty(nt,"RequestType7",{enumerable:!0,get:o(function(){return nn.RequestType7},"get")});Object.defineProperty(nt,"RequestType8",{enumerable:!0,get:o(function(){return nn.RequestType8},"get")});Object.defineProperty(nt,"RequestType9",{enumerable:!0,get:o(function(){return nn.RequestType9},"get")});Object.defineProperty(nt,"ResponseError",{enumerable:!0,get:o(function(){return nn.ResponseError},"get")});Object.defineProperty(nt,"ErrorCodes",{enumerable:!0,get:o(function(){return nn.ErrorCodes},"get")});Object.defineProperty(nt,"NotificationType",{enumerable:!0,get:o(function(){return nn.NotificationType},"get")});Object.defineProperty(nt,"NotificationType0",{enumerable:!0,get:o(function(){return nn.NotificationType0},"get")});Object.defineProperty(nt,"NotificationType1",{enumerable:!0,get:o(function(){return nn.NotificationType1},"get")});Object.defineProperty(nt,"NotificationType2",{enumerable:!0,get:o(function(){return nn.NotificationType2},"get")});Object.defineProperty(nt,"NotificationType3",{enumerable:!0,get:o(function(){return nn.NotificationType3},"get")});Object.defineProperty(nt,"NotificationType4",{enumerable:!0,get:o(function(){return nn.NotificationType4},"get")});Object.defineProperty(nt,"NotificationType5",{enumerable:!0,get:o(function(){return nn.NotificationType5},"get")});Object.defineProperty(nt,"NotificationType6",{enumerable:!0,get:o(function(){return nn.NotificationType6},"get")});Object.defineProperty(nt,"NotificationType7",{enumerable:!0,get:o(function(){return nn.NotificationType7},"get")});Object.defineProperty(nt,"NotificationType8",{enumerable:!0,get:o(function(){return nn.NotificationType8},"get")});Object.defineProperty(nt,"NotificationType9",{enumerable:!0,get:o(function(){return nn.NotificationType9},"get")});Object.defineProperty(nt,"ParameterStructures",{enumerable:!0,get:o(function(){return nn.ParameterStructures},"get")});var NV=hV();Object.defineProperty(nt,"LinkedMap",{enumerable:!0,get:o(function(){return NV.LinkedMap},"get")});Object.defineProperty(nt,"LRUCache",{enumerable:!0,get:o(function(){return NV.LRUCache},"get")});Object.defineProperty(nt,"Touch",{enumerable:!0,get:o(function(){return NV.Touch},"get")});var Yst=w2e();Object.defineProperty(nt,"Disposable",{enumerable:!0,get:o(function(){return Yst.Disposable},"get")});var $2e=$m();Object.defineProperty(nt,"Event",{enumerable:!0,get:o(function(){return $2e.Event},"get")});Object.defineProperty(nt,"Emitter",{enumerable:!0,get:o(function(){return $2e.Emitter},"get")});var z2e=Ik();Object.defineProperty(nt,"CancellationTokenSource",{enumerable:!0,get:o(function(){return z2e.CancellationTokenSource},"get")});Object.defineProperty(nt,"CancellationToken",{enumerable:!0,get:o(function(){return z2e.CancellationToken},"get")});var G2e=E2e();Object.defineProperty(nt,"SharedArraySenderStrategy",{enumerable:!0,get:o(function(){return G2e.SharedArraySenderStrategy},"get")});Object.defineProperty(nt,"SharedArrayReceiverStrategy",{enumerable:!0,get:o(function(){return G2e.SharedArrayReceiverStrategy},"get")});var IV=A2e();Object.defineProperty(nt,"MessageReader",{enumerable:!0,get:o(function(){return IV.MessageReader},"get")});Object.defineProperty(nt,"AbstractMessageReader",{enumerable:!0,get:o(function(){return IV.AbstractMessageReader},"get")});Object.defineProperty(nt,"ReadableStreamMessageReader",{enumerable:!0,get:o(function(){return IV.ReadableStreamMessageReader},"get")});var MV=N2e();Object.defineProperty(nt,"MessageWriter",{enumerable:!0,get:o(function(){return MV.MessageWriter},"get")});Object.defineProperty(nt,"AbstractMessageWriter",{enumerable:!0,get:o(function(){return MV.AbstractMessageWriter},"get")});Object.defineProperty(nt,"WriteableStreamMessageWriter",{enumerable:!0,get:o(function(){return MV.WriteableStreamMessageWriter},"get")});var jst=I2e();Object.defineProperty(nt,"AbstractMessageBuffer",{enumerable:!0,get:o(function(){return jst.AbstractMessageBuffer},"get")});var as=F2e();Object.defineProperty(nt,"ConnectionStrategy",{enumerable:!0,get:o(function(){return as.ConnectionStrategy},"get")});Object.defineProperty(nt,"ConnectionOptions",{enumerable:!0,get:o(function(){return as.ConnectionOptions},"get")});Object.defineProperty(nt,"NullLogger",{enumerable:!0,get:o(function(){return as.NullLogger},"get")});Object.defineProperty(nt,"createMessageConnection",{enumerable:!0,get:o(function(){return as.createMessageConnection},"get")});Object.defineProperty(nt,"ProgressToken",{enumerable:!0,get:o(function(){return as.ProgressToken},"get")});Object.defineProperty(nt,"ProgressType",{enumerable:!0,get:o(function(){return as.ProgressType},"get")});Object.defineProperty(nt,"Trace",{enumerable:!0,get:o(function(){return as.Trace},"get")});Object.defineProperty(nt,"TraceValues",{enumerable:!0,get:o(function(){return as.TraceValues},"get")});Object.defineProperty(nt,"TraceFormat",{enumerable:!0,get:o(function(){return as.TraceFormat},"get")});Object.defineProperty(nt,"SetTraceNotification",{enumerable:!0,get:o(function(){return as.SetTraceNotification},"get")});Object.defineProperty(nt,"LogTraceNotification",{enumerable:!0,get:o(function(){return as.LogTraceNotification},"get")});Object.defineProperty(nt,"ConnectionErrors",{enumerable:!0,get:o(function(){return as.ConnectionErrors},"get")});Object.defineProperty(nt,"ConnectionError",{enumerable:!0,get:o(function(){return as.ConnectionError},"get")});Object.defineProperty(nt,"CancellationReceiverStrategy",{enumerable:!0,get:o(function(){return as.CancellationReceiverStrategy},"get")});Object.defineProperty(nt,"CancellationSenderStrategy",{enumerable:!0,get:o(function(){return as.CancellationSenderStrategy},"get")});Object.defineProperty(nt,"CancellationStrategy",{enumerable:!0,get:o(function(){return as.CancellationStrategy},"get")});Object.defineProperty(nt,"MessageStrategy",{enumerable:!0,get:o(function(){return as.MessageStrategy},"get")});var Xst=cp();nt.RAL=Xst.default});var q2e=ar(FV=>{"use strict";Object.defineProperty(FV,"__esModule",{value:!0});var eh=KA(),QA=class t extends eh.AbstractMessageBuffer{static{o(this,"MessageBuffer")}constructor(e="utf-8"){super(e),this.asciiDecoder=new TextDecoder("ascii")}emptyBuffer(){return t.emptyBuffer}fromString(e,r){return new TextEncoder().encode(e)}toString(e,r){return r==="ascii"?this.asciiDecoder.decode(e):new TextDecoder(r).decode(e)}asNative(e,r){return r===void 0?e:e.slice(0,r)}allocNative(e){return new Uint8Array(e)}};QA.emptyBuffer=new Uint8Array(0);var OV=class{static{o(this,"ReadableStreamWrapper")}constructor(e){this.socket=e,this._onData=new eh.Emitter,this._messageListener=r=>{r.data.arrayBuffer().then(n=>{this._onData.fire(new Uint8Array(n))},()=>{(0,eh.RAL)().console.error("Converting blob to array buffer failed.")})},this.socket.addEventListener("message",this._messageListener)}onClose(e){return this.socket.addEventListener("close",e),eh.Disposable.create(()=>this.socket.removeEventListener("close",e))}onError(e){return this.socket.addEventListener("error",e),eh.Disposable.create(()=>this.socket.removeEventListener("error",e))}onEnd(e){return this.socket.addEventListener("end",e),eh.Disposable.create(()=>this.socket.removeEventListener("end",e))}onData(e){return this._onData.event(e)}},PV=class{static{o(this,"WritableStreamWrapper")}constructor(e){this.socket=e}onClose(e){return this.socket.addEventListener("close",e),eh.Disposable.create(()=>this.socket.removeEventListener("close",e))}onError(e){return this.socket.addEventListener("error",e),eh.Disposable.create(()=>this.socket.removeEventListener("error",e))}onEnd(e){return this.socket.addEventListener("end",e),eh.Disposable.create(()=>this.socket.removeEventListener("end",e))}write(e,r){if(typeof e=="string"){if(r!==void 0&&r!=="utf-8")throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${r}`);this.socket.send(e)}else this.socket.send(e);return Promise.resolve()}end(){this.socket.close()}},Kst=new TextEncoder,V2e=Object.freeze({messageBuffer:Object.freeze({create:o(t=>new QA(t),"create")}),applicationJson:Object.freeze({encoder:Object.freeze({name:"application/json",encode:o((t,e)=>{if(e.charset!=="utf-8")throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${e.charset}`);return Promise.resolve(Kst.encode(JSON.stringify(t,void 0,0)))},"encode")}),decoder:Object.freeze({name:"application/json",decode:o((t,e)=>{if(!(t instanceof Uint8Array))throw new Error("In a Browser environments only Uint8Arrays are supported.");return Promise.resolve(JSON.parse(new TextDecoder(e.charset).decode(t)))},"decode")})}),stream:Object.freeze({asReadableStream:o(t=>new OV(t),"asReadableStream"),asWritableStream:o(t=>new PV(t),"asWritableStream")}),console,timer:Object.freeze({setTimeout(t,e,...r){let i=setTimeout(t,e,...r);return{dispose:o(()=>clearTimeout(i),"dispose")}},setImmediate(t,...e){let r=setTimeout(t,0,...e);return{dispose:o(()=>clearTimeout(r),"dispose")}},setInterval(t,e,...r){let i=setInterval(t,e,...r);return{dispose:o(()=>clearInterval(i),"dispose")}}})});function BV(){return V2e}o(BV,"RIL");(function(t){function e(){eh.RAL.install(V2e)}o(e,"install"),t.install=e})(BV||(BV={}));FV.default=BV});var Um=ar(hl=>{"use strict";var Qst=hl&&hl.__createBinding||(Object.create?(function(t,e,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(e,r);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:o(function(){return e[r]},"get")}),Object.defineProperty(t,i,n)}):(function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]})),Zst=hl&&hl.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Qst(e,t,r)};Object.defineProperty(hl,"__esModule",{value:!0});hl.createMessageConnection=hl.BrowserMessageWriter=hl.BrowserMessageReader=void 0;var Jst=q2e();Jst.default.install();var Lv=KA();Zst(KA(),hl);var $V=class extends Lv.AbstractMessageReader{static{o(this,"BrowserMessageReader")}constructor(e){super(),this._onData=new Lv.Emitter,this._messageListener=r=>{this._onData.fire(r.data)},e.addEventListener("error",r=>this.fireError(r)),e.onmessage=this._messageListener}listen(e){return this._onData.event(e)}};hl.BrowserMessageReader=$V;var zV=class extends Lv.AbstractMessageWriter{static{o(this,"BrowserMessageWriter")}constructor(e){super(),this.port=e,this.errorCount=0,e.addEventListener("error",r=>this.fireError(r))}write(e){try{return this.port.postMessage(e),Promise.resolve()}catch(r){return this.handleError(r,e),Promise.reject(r)}}handleError(e,r){this.errorCount++,this.fireError(e,r,this.errorCount)}end(){}};hl.BrowserMessageWriter=zV;function eot(t,e,r,i){return r===void 0&&(r=Lv.NullLogger),Lv.ConnectionStrategy.is(i)&&(i={connectionStrategy:i}),(0,Lv.createMessageConnection)(t,e,r,i)}o(eot,"createMessageConnection");hl.createMessageConnection=eot});var GV=ar((Rbr,W2e)=>{"use strict";W2e.exports=Um()});var bn=ar(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.ProtocolNotificationType=Bo.ProtocolNotificationType0=Bo.ProtocolRequestType=Bo.ProtocolRequestType0=Bo.RegistrationType=Bo.MessageDirection=void 0;var Rv=Um(),U2e;(function(t){t.clientToServer="clientToServer",t.serverToClient="serverToClient",t.both="both"})(U2e||(Bo.MessageDirection=U2e={}));var VV=class{static{o(this,"RegistrationType")}constructor(e){this.method=e}};Bo.RegistrationType=VV;var qV=class extends Rv.RequestType0{static{o(this,"ProtocolRequestType0")}constructor(e){super(e)}};Bo.ProtocolRequestType0=qV;var WV=class extends Rv.RequestType{static{o(this,"ProtocolRequestType")}constructor(e){super(e,Rv.ParameterStructures.byName)}};Bo.ProtocolRequestType=WV;var UV=class extends Rv.NotificationType0{static{o(this,"ProtocolNotificationType0")}constructor(e){super(e)}};Bo.ProtocolNotificationType0=UV;var HV=class extends Rv.NotificationType{static{o(this,"ProtocolNotificationType")}constructor(e){super(e,Rv.ParameterStructures.byName)}};Bo.ProtocolNotificationType=HV});var ZA=ar(ra=>{"use strict";Object.defineProperty(ra,"__esModule",{value:!0});ra.objectLiteral=ra.typedArray=ra.stringArray=ra.array=ra.func=ra.error=ra.number=ra.string=ra.boolean=void 0;function tot(t){return t===!0||t===!1}o(tot,"boolean");ra.boolean=tot;function H2e(t){return typeof t=="string"||t instanceof String}o(H2e,"string");ra.string=H2e;function rot(t){return typeof t=="number"||t instanceof Number}o(rot,"number");ra.number=rot;function iot(t){return t instanceof Error}o(iot,"error");ra.error=iot;function not(t){return typeof t=="function"}o(not,"func");ra.func=not;function Y2e(t){return Array.isArray(t)}o(Y2e,"array");ra.array=Y2e;function aot(t){return Y2e(t)&&t.every(e=>H2e(e))}o(aot,"stringArray");ra.stringArray=aot;function sot(t,e){return Array.isArray(t)&&t.every(e)}o(sot,"typedArray");ra.typedArray=sot;function oot(t){return t!==null&&typeof t=="object"}o(oot,"objectLiteral");ra.objectLiteral=oot});var K2e=ar(JA=>{"use strict";Object.defineProperty(JA,"__esModule",{value:!0});JA.ImplementationRequest=void 0;var j2e=bn(),X2e;(function(t){t.method="textDocument/implementation",t.messageDirection=j2e.MessageDirection.clientToServer,t.type=new j2e.ProtocolRequestType(t.method)})(X2e||(JA.ImplementationRequest=X2e={}))});var J2e=ar(e7=>{"use strict";Object.defineProperty(e7,"__esModule",{value:!0});e7.TypeDefinitionRequest=void 0;var Q2e=bn(),Z2e;(function(t){t.method="textDocument/typeDefinition",t.messageDirection=Q2e.MessageDirection.clientToServer,t.type=new Q2e.ProtocolRequestType(t.method)})(Z2e||(e7.TypeDefinitionRequest=Z2e={}))});var rbe=ar(Nv=>{"use strict";Object.defineProperty(Nv,"__esModule",{value:!0});Nv.DidChangeWorkspaceFoldersNotification=Nv.WorkspaceFoldersRequest=void 0;var t7=bn(),ebe;(function(t){t.method="workspace/workspaceFolders",t.messageDirection=t7.MessageDirection.serverToClient,t.type=new t7.ProtocolRequestType0(t.method)})(ebe||(Nv.WorkspaceFoldersRequest=ebe={}));var tbe;(function(t){t.method="workspace/didChangeWorkspaceFolders",t.messageDirection=t7.MessageDirection.clientToServer,t.type=new t7.ProtocolNotificationType(t.method)})(tbe||(Nv.DidChangeWorkspaceFoldersNotification=tbe={}))});var abe=ar(r7=>{"use strict";Object.defineProperty(r7,"__esModule",{value:!0});r7.ConfigurationRequest=void 0;var ibe=bn(),nbe;(function(t){t.method="workspace/configuration",t.messageDirection=ibe.MessageDirection.serverToClient,t.type=new ibe.ProtocolRequestType(t.method)})(nbe||(r7.ConfigurationRequest=nbe={}))});var lbe=ar(Iv=>{"use strict";Object.defineProperty(Iv,"__esModule",{value:!0});Iv.ColorPresentationRequest=Iv.DocumentColorRequest=void 0;var i7=bn(),sbe;(function(t){t.method="textDocument/documentColor",t.messageDirection=i7.MessageDirection.clientToServer,t.type=new i7.ProtocolRequestType(t.method)})(sbe||(Iv.DocumentColorRequest=sbe={}));var obe;(function(t){t.method="textDocument/colorPresentation",t.messageDirection=i7.MessageDirection.clientToServer,t.type=new i7.ProtocolRequestType(t.method)})(obe||(Iv.ColorPresentationRequest=obe={}))});var hbe=ar(Mv=>{"use strict";Object.defineProperty(Mv,"__esModule",{value:!0});Mv.FoldingRangeRefreshRequest=Mv.FoldingRangeRequest=void 0;var n7=bn(),cbe;(function(t){t.method="textDocument/foldingRange",t.messageDirection=n7.MessageDirection.clientToServer,t.type=new n7.ProtocolRequestType(t.method)})(cbe||(Mv.FoldingRangeRequest=cbe={}));var ube;(function(t){t.method="workspace/foldingRange/refresh",t.messageDirection=n7.MessageDirection.serverToClient,t.type=new n7.ProtocolRequestType0(t.method)})(ube||(Mv.FoldingRangeRefreshRequest=ube={}))});var pbe=ar(a7=>{"use strict";Object.defineProperty(a7,"__esModule",{value:!0});a7.DeclarationRequest=void 0;var fbe=bn(),dbe;(function(t){t.method="textDocument/declaration",t.messageDirection=fbe.MessageDirection.clientToServer,t.type=new fbe.ProtocolRequestType(t.method)})(dbe||(a7.DeclarationRequest=dbe={}))});var ybe=ar(s7=>{"use strict";Object.defineProperty(s7,"__esModule",{value:!0});s7.SelectionRangeRequest=void 0;var mbe=bn(),gbe;(function(t){t.method="textDocument/selectionRange",t.messageDirection=mbe.MessageDirection.clientToServer,t.type=new mbe.ProtocolRequestType(t.method)})(gbe||(s7.SelectionRangeRequest=gbe={}))});var Tbe=ar(pp=>{"use strict";Object.defineProperty(pp,"__esModule",{value:!0});pp.WorkDoneProgressCancelNotification=pp.WorkDoneProgressCreateRequest=pp.WorkDoneProgress=void 0;var lot=Um(),o7=bn(),vbe;(function(t){t.type=new lot.ProgressType;function e(r){return r===t.type}o(e,"is"),t.is=e})(vbe||(pp.WorkDoneProgress=vbe={}));var xbe;(function(t){t.method="window/workDoneProgress/create",t.messageDirection=o7.MessageDirection.serverToClient,t.type=new o7.ProtocolRequestType(t.method)})(xbe||(pp.WorkDoneProgressCreateRequest=xbe={}));var bbe;(function(t){t.method="window/workDoneProgress/cancel",t.messageDirection=o7.MessageDirection.clientToServer,t.type=new o7.ProtocolNotificationType(t.method)})(bbe||(pp.WorkDoneProgressCancelNotification=bbe={}))});var Ebe=ar(mp=>{"use strict";Object.defineProperty(mp,"__esModule",{value:!0});mp.CallHierarchyOutgoingCallsRequest=mp.CallHierarchyIncomingCallsRequest=mp.CallHierarchyPrepareRequest=void 0;var Ov=bn(),kbe;(function(t){t.method="textDocument/prepareCallHierarchy",t.messageDirection=Ov.MessageDirection.clientToServer,t.type=new Ov.ProtocolRequestType(t.method)})(kbe||(mp.CallHierarchyPrepareRequest=kbe={}));var Cbe;(function(t){t.method="callHierarchy/incomingCalls",t.messageDirection=Ov.MessageDirection.clientToServer,t.type=new Ov.ProtocolRequestType(t.method)})(Cbe||(mp.CallHierarchyIncomingCallsRequest=Cbe={}));var wbe;(function(t){t.method="callHierarchy/outgoingCalls",t.messageDirection=Ov.MessageDirection.clientToServer,t.type=new Ov.ProtocolRequestType(t.method)})(wbe||(mp.CallHierarchyOutgoingCallsRequest=wbe={}))});var Rbe=ar(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});Fo.SemanticTokensRefreshRequest=Fo.SemanticTokensRangeRequest=Fo.SemanticTokensDeltaRequest=Fo.SemanticTokensRequest=Fo.SemanticTokensRegistrationType=Fo.TokenFormat=void 0;var gf=bn(),Sbe;(function(t){t.Relative="relative"})(Sbe||(Fo.TokenFormat=Sbe={}));var iC;(function(t){t.method="textDocument/semanticTokens",t.type=new gf.RegistrationType(t.method)})(iC||(Fo.SemanticTokensRegistrationType=iC={}));var Abe;(function(t){t.method="textDocument/semanticTokens/full",t.messageDirection=gf.MessageDirection.clientToServer,t.type=new gf.ProtocolRequestType(t.method),t.registrationMethod=iC.method})(Abe||(Fo.SemanticTokensRequest=Abe={}));var _be;(function(t){t.method="textDocument/semanticTokens/full/delta",t.messageDirection=gf.MessageDirection.clientToServer,t.type=new gf.ProtocolRequestType(t.method),t.registrationMethod=iC.method})(_be||(Fo.SemanticTokensDeltaRequest=_be={}));var Dbe;(function(t){t.method="textDocument/semanticTokens/range",t.messageDirection=gf.MessageDirection.clientToServer,t.type=new gf.ProtocolRequestType(t.method),t.registrationMethod=iC.method})(Dbe||(Fo.SemanticTokensRangeRequest=Dbe={}));var Lbe;(function(t){t.method="workspace/semanticTokens/refresh",t.messageDirection=gf.MessageDirection.serverToClient,t.type=new gf.ProtocolRequestType0(t.method)})(Lbe||(Fo.SemanticTokensRefreshRequest=Lbe={}))});var Mbe=ar(l7=>{"use strict";Object.defineProperty(l7,"__esModule",{value:!0});l7.ShowDocumentRequest=void 0;var Nbe=bn(),Ibe;(function(t){t.method="window/showDocument",t.messageDirection=Nbe.MessageDirection.serverToClient,t.type=new Nbe.ProtocolRequestType(t.method)})(Ibe||(l7.ShowDocumentRequest=Ibe={}))});var Bbe=ar(c7=>{"use strict";Object.defineProperty(c7,"__esModule",{value:!0});c7.LinkedEditingRangeRequest=void 0;var Obe=bn(),Pbe;(function(t){t.method="textDocument/linkedEditingRange",t.messageDirection=Obe.MessageDirection.clientToServer,t.type=new Obe.ProtocolRequestType(t.method)})(Pbe||(c7.LinkedEditingRangeRequest=Pbe={}))});var Ube=ar(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});Es.WillDeleteFilesRequest=Es.DidDeleteFilesNotification=Es.DidRenameFilesNotification=Es.WillRenameFilesRequest=Es.DidCreateFilesNotification=Es.WillCreateFilesRequest=Es.FileOperationPatternKind=void 0;var Ql=bn(),Fbe;(function(t){t.file="file",t.folder="folder"})(Fbe||(Es.FileOperationPatternKind=Fbe={}));var $be;(function(t){t.method="workspace/willCreateFiles",t.messageDirection=Ql.MessageDirection.clientToServer,t.type=new Ql.ProtocolRequestType(t.method)})($be||(Es.WillCreateFilesRequest=$be={}));var zbe;(function(t){t.method="workspace/didCreateFiles",t.messageDirection=Ql.MessageDirection.clientToServer,t.type=new Ql.ProtocolNotificationType(t.method)})(zbe||(Es.DidCreateFilesNotification=zbe={}));var Gbe;(function(t){t.method="workspace/willRenameFiles",t.messageDirection=Ql.MessageDirection.clientToServer,t.type=new Ql.ProtocolRequestType(t.method)})(Gbe||(Es.WillRenameFilesRequest=Gbe={}));var Vbe;(function(t){t.method="workspace/didRenameFiles",t.messageDirection=Ql.MessageDirection.clientToServer,t.type=new Ql.ProtocolNotificationType(t.method)})(Vbe||(Es.DidRenameFilesNotification=Vbe={}));var qbe;(function(t){t.method="workspace/didDeleteFiles",t.messageDirection=Ql.MessageDirection.clientToServer,t.type=new Ql.ProtocolNotificationType(t.method)})(qbe||(Es.DidDeleteFilesNotification=qbe={}));var Wbe;(function(t){t.method="workspace/willDeleteFiles",t.messageDirection=Ql.MessageDirection.clientToServer,t.type=new Ql.ProtocolRequestType(t.method)})(Wbe||(Es.WillDeleteFilesRequest=Wbe={}))});var Kbe=ar(gp=>{"use strict";Object.defineProperty(gp,"__esModule",{value:!0});gp.MonikerRequest=gp.MonikerKind=gp.UniquenessLevel=void 0;var Hbe=bn(),Ybe;(function(t){t.document="document",t.project="project",t.group="group",t.scheme="scheme",t.global="global"})(Ybe||(gp.UniquenessLevel=Ybe={}));var jbe;(function(t){t.$import="import",t.$export="export",t.local="local"})(jbe||(gp.MonikerKind=jbe={}));var Xbe;(function(t){t.method="textDocument/moniker",t.messageDirection=Hbe.MessageDirection.clientToServer,t.type=new Hbe.ProtocolRequestType(t.method)})(Xbe||(gp.MonikerRequest=Xbe={}))});var eTe=ar(yp=>{"use strict";Object.defineProperty(yp,"__esModule",{value:!0});yp.TypeHierarchySubtypesRequest=yp.TypeHierarchySupertypesRequest=yp.TypeHierarchyPrepareRequest=void 0;var Pv=bn(),Qbe;(function(t){t.method="textDocument/prepareTypeHierarchy",t.messageDirection=Pv.MessageDirection.clientToServer,t.type=new Pv.ProtocolRequestType(t.method)})(Qbe||(yp.TypeHierarchyPrepareRequest=Qbe={}));var Zbe;(function(t){t.method="typeHierarchy/supertypes",t.messageDirection=Pv.MessageDirection.clientToServer,t.type=new Pv.ProtocolRequestType(t.method)})(Zbe||(yp.TypeHierarchySupertypesRequest=Zbe={}));var Jbe;(function(t){t.method="typeHierarchy/subtypes",t.messageDirection=Pv.MessageDirection.clientToServer,t.type=new Pv.ProtocolRequestType(t.method)})(Jbe||(yp.TypeHierarchySubtypesRequest=Jbe={}))});var iTe=ar(Bv=>{"use strict";Object.defineProperty(Bv,"__esModule",{value:!0});Bv.InlineValueRefreshRequest=Bv.InlineValueRequest=void 0;var u7=bn(),tTe;(function(t){t.method="textDocument/inlineValue",t.messageDirection=u7.MessageDirection.clientToServer,t.type=new u7.ProtocolRequestType(t.method)})(tTe||(Bv.InlineValueRequest=tTe={}));var rTe;(function(t){t.method="workspace/inlineValue/refresh",t.messageDirection=u7.MessageDirection.serverToClient,t.type=new u7.ProtocolRequestType0(t.method)})(rTe||(Bv.InlineValueRefreshRequest=rTe={}))});var oTe=ar(vp=>{"use strict";Object.defineProperty(vp,"__esModule",{value:!0});vp.InlayHintRefreshRequest=vp.InlayHintResolveRequest=vp.InlayHintRequest=void 0;var Fv=bn(),nTe;(function(t){t.method="textDocument/inlayHint",t.messageDirection=Fv.MessageDirection.clientToServer,t.type=new Fv.ProtocolRequestType(t.method)})(nTe||(vp.InlayHintRequest=nTe={}));var aTe;(function(t){t.method="inlayHint/resolve",t.messageDirection=Fv.MessageDirection.clientToServer,t.type=new Fv.ProtocolRequestType(t.method)})(aTe||(vp.InlayHintResolveRequest=aTe={}));var sTe;(function(t){t.method="workspace/inlayHint/refresh",t.messageDirection=Fv.MessageDirection.serverToClient,t.type=new Fv.ProtocolRequestType0(t.method)})(sTe||(vp.InlayHintRefreshRequest=sTe={}))});var pTe=ar(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});Zl.DiagnosticRefreshRequest=Zl.WorkspaceDiagnosticRequest=Zl.DocumentDiagnosticRequest=Zl.DocumentDiagnosticReportKind=Zl.DiagnosticServerCancellationData=void 0;var dTe=Um(),cot=ZA(),$v=bn(),lTe;(function(t){function e(r){let i=r;return i&&cot.boolean(i.retriggerRequest)}o(e,"is"),t.is=e})(lTe||(Zl.DiagnosticServerCancellationData=lTe={}));var cTe;(function(t){t.Full="full",t.Unchanged="unchanged"})(cTe||(Zl.DocumentDiagnosticReportKind=cTe={}));var uTe;(function(t){t.method="textDocument/diagnostic",t.messageDirection=$v.MessageDirection.clientToServer,t.type=new $v.ProtocolRequestType(t.method),t.partialResult=new dTe.ProgressType})(uTe||(Zl.DocumentDiagnosticRequest=uTe={}));var hTe;(function(t){t.method="workspace/diagnostic",t.messageDirection=$v.MessageDirection.clientToServer,t.type=new $v.ProtocolRequestType(t.method),t.partialResult=new dTe.ProgressType})(hTe||(Zl.WorkspaceDiagnosticRequest=hTe={}));var fTe;(function(t){t.method="workspace/diagnostic/refresh",t.messageDirection=$v.MessageDirection.serverToClient,t.type=new $v.ProtocolRequestType0(t.method)})(fTe||(Zl.DiagnosticRefreshRequest=fTe={}))});var TTe=ar(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.DidCloseNotebookDocumentNotification=Bn.DidSaveNotebookDocumentNotification=Bn.DidChangeNotebookDocumentNotification=Bn.NotebookCellArrayChange=Bn.DidOpenNotebookDocumentNotification=Bn.NotebookDocumentSyncRegistrationType=Bn.NotebookDocument=Bn.NotebookCell=Bn.ExecutionSummary=Bn.NotebookCellKind=void 0;var nC=(pv(),s4(yA)),Hc=ZA(),th=bn(),YV;(function(t){t.Markup=1,t.Code=2;function e(r){return r===1||r===2}o(e,"is"),t.is=e})(YV||(Bn.NotebookCellKind=YV={}));var jV;(function(t){function e(n,a){let s={executionOrder:n};return(a===!0||a===!1)&&(s.success=a),s}o(e,"create"),t.create=e;function r(n){let a=n;return Hc.objectLiteral(a)&&nC.uinteger.is(a.executionOrder)&&(a.success===void 0||Hc.boolean(a.success))}o(r,"is"),t.is=r;function i(n,a){return n===a?!0:n==null||a===null||a===void 0?!1:n.executionOrder===a.executionOrder&&n.success===a.success}o(i,"equals"),t.equals=i})(jV||(Bn.ExecutionSummary=jV={}));var h7;(function(t){function e(a,s){return{kind:a,document:s}}o(e,"create"),t.create=e;function r(a){let s=a;return Hc.objectLiteral(s)&&YV.is(s.kind)&&nC.DocumentUri.is(s.document)&&(s.metadata===void 0||Hc.objectLiteral(s.metadata))}o(r,"is"),t.is=r;function i(a,s){let l=new Set;return a.document!==s.document&&l.add("document"),a.kind!==s.kind&&l.add("kind"),a.executionSummary!==s.executionSummary&&l.add("executionSummary"),(a.metadata!==void 0||s.metadata!==void 0)&&!n(a.metadata,s.metadata)&&l.add("metadata"),(a.executionSummary!==void 0||s.executionSummary!==void 0)&&!jV.equals(a.executionSummary,s.executionSummary)&&l.add("executionSummary"),l}o(i,"diff"),t.diff=i;function n(a,s){if(a===s)return!0;if(a==null||s===null||s===void 0||typeof a!=typeof s||typeof a!="object")return!1;let l=Array.isArray(a),u=Array.isArray(s);if(l!==u)return!1;if(l&&u){if(a.length!==s.length)return!1;for(let h=0;h{"use strict";Object.defineProperty(f7,"__esModule",{value:!0});f7.InlineCompletionRequest=void 0;var kTe=bn(),CTe;(function(t){t.method="textDocument/inlineCompletion",t.messageDirection=kTe.MessageDirection.clientToServer,t.type=new kTe.ProtocolRequestType(t.method)})(CTe||(f7.InlineCompletionRequest=CTe={}))});var Bke=ar(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.WorkspaceSymbolRequest=Ae.CodeActionResolveRequest=Ae.CodeActionRequest=Ae.DocumentSymbolRequest=Ae.DocumentHighlightRequest=Ae.ReferencesRequest=Ae.DefinitionRequest=Ae.SignatureHelpRequest=Ae.SignatureHelpTriggerKind=Ae.HoverRequest=Ae.CompletionResolveRequest=Ae.CompletionRequest=Ae.CompletionTriggerKind=Ae.PublishDiagnosticsNotification=Ae.WatchKind=Ae.RelativePattern=Ae.FileChangeType=Ae.DidChangeWatchedFilesNotification=Ae.WillSaveTextDocumentWaitUntilRequest=Ae.WillSaveTextDocumentNotification=Ae.TextDocumentSaveReason=Ae.DidSaveTextDocumentNotification=Ae.DidCloseTextDocumentNotification=Ae.DidChangeTextDocumentNotification=Ae.TextDocumentContentChangeEvent=Ae.DidOpenTextDocumentNotification=Ae.TextDocumentSyncKind=Ae.TelemetryEventNotification=Ae.LogMessageNotification=Ae.ShowMessageRequest=Ae.ShowMessageNotification=Ae.MessageType=Ae.DidChangeConfigurationNotification=Ae.ExitNotification=Ae.ShutdownRequest=Ae.InitializedNotification=Ae.InitializeErrorCodes=Ae.InitializeRequest=Ae.WorkDoneProgressOptions=Ae.TextDocumentRegistrationOptions=Ae.StaticRegistrationOptions=Ae.PositionEncodingKind=Ae.FailureHandlingKind=Ae.ResourceOperationKind=Ae.UnregistrationRequest=Ae.RegistrationRequest=Ae.DocumentSelector=Ae.NotebookCellTextDocumentFilter=Ae.NotebookDocumentFilter=Ae.TextDocumentFilter=void 0;Ae.MonikerRequest=Ae.MonikerKind=Ae.UniquenessLevel=Ae.WillDeleteFilesRequest=Ae.DidDeleteFilesNotification=Ae.WillRenameFilesRequest=Ae.DidRenameFilesNotification=Ae.WillCreateFilesRequest=Ae.DidCreateFilesNotification=Ae.FileOperationPatternKind=Ae.LinkedEditingRangeRequest=Ae.ShowDocumentRequest=Ae.SemanticTokensRegistrationType=Ae.SemanticTokensRefreshRequest=Ae.SemanticTokensRangeRequest=Ae.SemanticTokensDeltaRequest=Ae.SemanticTokensRequest=Ae.TokenFormat=Ae.CallHierarchyPrepareRequest=Ae.CallHierarchyOutgoingCallsRequest=Ae.CallHierarchyIncomingCallsRequest=Ae.WorkDoneProgressCancelNotification=Ae.WorkDoneProgressCreateRequest=Ae.WorkDoneProgress=Ae.SelectionRangeRequest=Ae.DeclarationRequest=Ae.FoldingRangeRefreshRequest=Ae.FoldingRangeRequest=Ae.ColorPresentationRequest=Ae.DocumentColorRequest=Ae.ConfigurationRequest=Ae.DidChangeWorkspaceFoldersNotification=Ae.WorkspaceFoldersRequest=Ae.TypeDefinitionRequest=Ae.ImplementationRequest=Ae.ApplyWorkspaceEditRequest=Ae.ExecuteCommandRequest=Ae.PrepareRenameRequest=Ae.RenameRequest=Ae.PrepareSupportDefaultBehavior=Ae.DocumentOnTypeFormattingRequest=Ae.DocumentRangesFormattingRequest=Ae.DocumentRangeFormattingRequest=Ae.DocumentFormattingRequest=Ae.DocumentLinkResolveRequest=Ae.DocumentLinkRequest=Ae.CodeLensRefreshRequest=Ae.CodeLensResolveRequest=Ae.CodeLensRequest=Ae.WorkspaceSymbolResolveRequest=void 0;Ae.InlineCompletionRequest=Ae.DidCloseNotebookDocumentNotification=Ae.DidSaveNotebookDocumentNotification=Ae.DidChangeNotebookDocumentNotification=Ae.NotebookCellArrayChange=Ae.DidOpenNotebookDocumentNotification=Ae.NotebookDocumentSyncRegistrationType=Ae.NotebookDocument=Ae.NotebookCell=Ae.ExecutionSummary=Ae.NotebookCellKind=Ae.DiagnosticRefreshRequest=Ae.WorkspaceDiagnosticRequest=Ae.DocumentDiagnosticRequest=Ae.DocumentDiagnosticReportKind=Ae.DiagnosticServerCancellationData=Ae.InlayHintRefreshRequest=Ae.InlayHintResolveRequest=Ae.InlayHintRequest=Ae.InlineValueRefreshRequest=Ae.InlineValueRequest=Ae.TypeHierarchySupertypesRequest=Ae.TypeHierarchySubtypesRequest=Ae.TypeHierarchyPrepareRequest=void 0;var At=bn(),ETe=(pv(),s4(yA)),$a=ZA(),uot=K2e();Object.defineProperty(Ae,"ImplementationRequest",{enumerable:!0,get:o(function(){return uot.ImplementationRequest},"get")});var hot=J2e();Object.defineProperty(Ae,"TypeDefinitionRequest",{enumerable:!0,get:o(function(){return hot.TypeDefinitionRequest},"get")});var Ike=rbe();Object.defineProperty(Ae,"WorkspaceFoldersRequest",{enumerable:!0,get:o(function(){return Ike.WorkspaceFoldersRequest},"get")});Object.defineProperty(Ae,"DidChangeWorkspaceFoldersNotification",{enumerable:!0,get:o(function(){return Ike.DidChangeWorkspaceFoldersNotification},"get")});var fot=abe();Object.defineProperty(Ae,"ConfigurationRequest",{enumerable:!0,get:o(function(){return fot.ConfigurationRequest},"get")});var Mke=lbe();Object.defineProperty(Ae,"DocumentColorRequest",{enumerable:!0,get:o(function(){return Mke.DocumentColorRequest},"get")});Object.defineProperty(Ae,"ColorPresentationRequest",{enumerable:!0,get:o(function(){return Mke.ColorPresentationRequest},"get")});var Oke=hbe();Object.defineProperty(Ae,"FoldingRangeRequest",{enumerable:!0,get:o(function(){return Oke.FoldingRangeRequest},"get")});Object.defineProperty(Ae,"FoldingRangeRefreshRequest",{enumerable:!0,get:o(function(){return Oke.FoldingRangeRefreshRequest},"get")});var dot=pbe();Object.defineProperty(Ae,"DeclarationRequest",{enumerable:!0,get:o(function(){return dot.DeclarationRequest},"get")});var pot=ybe();Object.defineProperty(Ae,"SelectionRangeRequest",{enumerable:!0,get:o(function(){return pot.SelectionRangeRequest},"get")});var JV=Tbe();Object.defineProperty(Ae,"WorkDoneProgress",{enumerable:!0,get:o(function(){return JV.WorkDoneProgress},"get")});Object.defineProperty(Ae,"WorkDoneProgressCreateRequest",{enumerable:!0,get:o(function(){return JV.WorkDoneProgressCreateRequest},"get")});Object.defineProperty(Ae,"WorkDoneProgressCancelNotification",{enumerable:!0,get:o(function(){return JV.WorkDoneProgressCancelNotification},"get")});var eq=Ebe();Object.defineProperty(Ae,"CallHierarchyIncomingCallsRequest",{enumerable:!0,get:o(function(){return eq.CallHierarchyIncomingCallsRequest},"get")});Object.defineProperty(Ae,"CallHierarchyOutgoingCallsRequest",{enumerable:!0,get:o(function(){return eq.CallHierarchyOutgoingCallsRequest},"get")});Object.defineProperty(Ae,"CallHierarchyPrepareRequest",{enumerable:!0,get:o(function(){return eq.CallHierarchyPrepareRequest},"get")});var Gv=Rbe();Object.defineProperty(Ae,"TokenFormat",{enumerable:!0,get:o(function(){return Gv.TokenFormat},"get")});Object.defineProperty(Ae,"SemanticTokensRequest",{enumerable:!0,get:o(function(){return Gv.SemanticTokensRequest},"get")});Object.defineProperty(Ae,"SemanticTokensDeltaRequest",{enumerable:!0,get:o(function(){return Gv.SemanticTokensDeltaRequest},"get")});Object.defineProperty(Ae,"SemanticTokensRangeRequest",{enumerable:!0,get:o(function(){return Gv.SemanticTokensRangeRequest},"get")});Object.defineProperty(Ae,"SemanticTokensRefreshRequest",{enumerable:!0,get:o(function(){return Gv.SemanticTokensRefreshRequest},"get")});Object.defineProperty(Ae,"SemanticTokensRegistrationType",{enumerable:!0,get:o(function(){return Gv.SemanticTokensRegistrationType},"get")});var mot=Mbe();Object.defineProperty(Ae,"ShowDocumentRequest",{enumerable:!0,get:o(function(){return mot.ShowDocumentRequest},"get")});var got=Bbe();Object.defineProperty(Ae,"LinkedEditingRangeRequest",{enumerable:!0,get:o(function(){return got.LinkedEditingRangeRequest},"get")});var Hm=Ube();Object.defineProperty(Ae,"FileOperationPatternKind",{enumerable:!0,get:o(function(){return Hm.FileOperationPatternKind},"get")});Object.defineProperty(Ae,"DidCreateFilesNotification",{enumerable:!0,get:o(function(){return Hm.DidCreateFilesNotification},"get")});Object.defineProperty(Ae,"WillCreateFilesRequest",{enumerable:!0,get:o(function(){return Hm.WillCreateFilesRequest},"get")});Object.defineProperty(Ae,"DidRenameFilesNotification",{enumerable:!0,get:o(function(){return Hm.DidRenameFilesNotification},"get")});Object.defineProperty(Ae,"WillRenameFilesRequest",{enumerable:!0,get:o(function(){return Hm.WillRenameFilesRequest},"get")});Object.defineProperty(Ae,"DidDeleteFilesNotification",{enumerable:!0,get:o(function(){return Hm.DidDeleteFilesNotification},"get")});Object.defineProperty(Ae,"WillDeleteFilesRequest",{enumerable:!0,get:o(function(){return Hm.WillDeleteFilesRequest},"get")});var tq=Kbe();Object.defineProperty(Ae,"UniquenessLevel",{enumerable:!0,get:o(function(){return tq.UniquenessLevel},"get")});Object.defineProperty(Ae,"MonikerKind",{enumerable:!0,get:o(function(){return tq.MonikerKind},"get")});Object.defineProperty(Ae,"MonikerRequest",{enumerable:!0,get:o(function(){return tq.MonikerRequest},"get")});var rq=eTe();Object.defineProperty(Ae,"TypeHierarchyPrepareRequest",{enumerable:!0,get:o(function(){return rq.TypeHierarchyPrepareRequest},"get")});Object.defineProperty(Ae,"TypeHierarchySubtypesRequest",{enumerable:!0,get:o(function(){return rq.TypeHierarchySubtypesRequest},"get")});Object.defineProperty(Ae,"TypeHierarchySupertypesRequest",{enumerable:!0,get:o(function(){return rq.TypeHierarchySupertypesRequest},"get")});var Pke=iTe();Object.defineProperty(Ae,"InlineValueRequest",{enumerable:!0,get:o(function(){return Pke.InlineValueRequest},"get")});Object.defineProperty(Ae,"InlineValueRefreshRequest",{enumerable:!0,get:o(function(){return Pke.InlineValueRefreshRequest},"get")});var iq=oTe();Object.defineProperty(Ae,"InlayHintRequest",{enumerable:!0,get:o(function(){return iq.InlayHintRequest},"get")});Object.defineProperty(Ae,"InlayHintResolveRequest",{enumerable:!0,get:o(function(){return iq.InlayHintResolveRequest},"get")});Object.defineProperty(Ae,"InlayHintRefreshRequest",{enumerable:!0,get:o(function(){return iq.InlayHintRefreshRequest},"get")});var aC=pTe();Object.defineProperty(Ae,"DiagnosticServerCancellationData",{enumerable:!0,get:o(function(){return aC.DiagnosticServerCancellationData},"get")});Object.defineProperty(Ae,"DocumentDiagnosticReportKind",{enumerable:!0,get:o(function(){return aC.DocumentDiagnosticReportKind},"get")});Object.defineProperty(Ae,"DocumentDiagnosticRequest",{enumerable:!0,get:o(function(){return aC.DocumentDiagnosticRequest},"get")});Object.defineProperty(Ae,"WorkspaceDiagnosticRequest",{enumerable:!0,get:o(function(){return aC.WorkspaceDiagnosticRequest},"get")});Object.defineProperty(Ae,"DiagnosticRefreshRequest",{enumerable:!0,get:o(function(){return aC.DiagnosticRefreshRequest},"get")});var rh=TTe();Object.defineProperty(Ae,"NotebookCellKind",{enumerable:!0,get:o(function(){return rh.NotebookCellKind},"get")});Object.defineProperty(Ae,"ExecutionSummary",{enumerable:!0,get:o(function(){return rh.ExecutionSummary},"get")});Object.defineProperty(Ae,"NotebookCell",{enumerable:!0,get:o(function(){return rh.NotebookCell},"get")});Object.defineProperty(Ae,"NotebookDocument",{enumerable:!0,get:o(function(){return rh.NotebookDocument},"get")});Object.defineProperty(Ae,"NotebookDocumentSyncRegistrationType",{enumerable:!0,get:o(function(){return rh.NotebookDocumentSyncRegistrationType},"get")});Object.defineProperty(Ae,"DidOpenNotebookDocumentNotification",{enumerable:!0,get:o(function(){return rh.DidOpenNotebookDocumentNotification},"get")});Object.defineProperty(Ae,"NotebookCellArrayChange",{enumerable:!0,get:o(function(){return rh.NotebookCellArrayChange},"get")});Object.defineProperty(Ae,"DidChangeNotebookDocumentNotification",{enumerable:!0,get:o(function(){return rh.DidChangeNotebookDocumentNotification},"get")});Object.defineProperty(Ae,"DidSaveNotebookDocumentNotification",{enumerable:!0,get:o(function(){return rh.DidSaveNotebookDocumentNotification},"get")});Object.defineProperty(Ae,"DidCloseNotebookDocumentNotification",{enumerable:!0,get:o(function(){return rh.DidCloseNotebookDocumentNotification},"get")});var yot=wTe();Object.defineProperty(Ae,"InlineCompletionRequest",{enumerable:!0,get:o(function(){return yot.InlineCompletionRequest},"get")});var XV;(function(t){function e(r){let i=r;return $a.string(i)||$a.string(i.language)||$a.string(i.scheme)||$a.string(i.pattern)}o(e,"is"),t.is=e})(XV||(Ae.TextDocumentFilter=XV={}));var KV;(function(t){function e(r){let i=r;return $a.objectLiteral(i)&&($a.string(i.notebookType)||$a.string(i.scheme)||$a.string(i.pattern))}o(e,"is"),t.is=e})(KV||(Ae.NotebookDocumentFilter=KV={}));var QV;(function(t){function e(r){let i=r;return $a.objectLiteral(i)&&($a.string(i.notebook)||KV.is(i.notebook))&&(i.language===void 0||$a.string(i.language))}o(e,"is"),t.is=e})(QV||(Ae.NotebookCellTextDocumentFilter=QV={}));var ZV;(function(t){function e(r){if(!Array.isArray(r))return!1;for(let i of r)if(!$a.string(i)&&!XV.is(i)&&!QV.is(i))return!1;return!0}o(e,"is"),t.is=e})(ZV||(Ae.DocumentSelector=ZV={}));var STe;(function(t){t.method="client/registerCapability",t.messageDirection=At.MessageDirection.serverToClient,t.type=new At.ProtocolRequestType(t.method)})(STe||(Ae.RegistrationRequest=STe={}));var ATe;(function(t){t.method="client/unregisterCapability",t.messageDirection=At.MessageDirection.serverToClient,t.type=new At.ProtocolRequestType(t.method)})(ATe||(Ae.UnregistrationRequest=ATe={}));var _Te;(function(t){t.Create="create",t.Rename="rename",t.Delete="delete"})(_Te||(Ae.ResourceOperationKind=_Te={}));var DTe;(function(t){t.Abort="abort",t.Transactional="transactional",t.TextOnlyTransactional="textOnlyTransactional",t.Undo="undo"})(DTe||(Ae.FailureHandlingKind=DTe={}));var LTe;(function(t){t.UTF8="utf-8",t.UTF16="utf-16",t.UTF32="utf-32"})(LTe||(Ae.PositionEncodingKind=LTe={}));var RTe;(function(t){function e(r){let i=r;return i&&$a.string(i.id)&&i.id.length>0}o(e,"hasId"),t.hasId=e})(RTe||(Ae.StaticRegistrationOptions=RTe={}));var NTe;(function(t){function e(r){let i=r;return i&&(i.documentSelector===null||ZV.is(i.documentSelector))}o(e,"is"),t.is=e})(NTe||(Ae.TextDocumentRegistrationOptions=NTe={}));var ITe;(function(t){function e(i){let n=i;return $a.objectLiteral(n)&&(n.workDoneProgress===void 0||$a.boolean(n.workDoneProgress))}o(e,"is"),t.is=e;function r(i){let n=i;return n&&$a.boolean(n.workDoneProgress)}o(r,"hasWorkDoneProgress"),t.hasWorkDoneProgress=r})(ITe||(Ae.WorkDoneProgressOptions=ITe={}));var MTe;(function(t){t.method="initialize",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(MTe||(Ae.InitializeRequest=MTe={}));var OTe;(function(t){t.unknownProtocolVersion=1})(OTe||(Ae.InitializeErrorCodes=OTe={}));var PTe;(function(t){t.method="initialized",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolNotificationType(t.method)})(PTe||(Ae.InitializedNotification=PTe={}));var BTe;(function(t){t.method="shutdown",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType0(t.method)})(BTe||(Ae.ShutdownRequest=BTe={}));var FTe;(function(t){t.method="exit",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolNotificationType0(t.method)})(FTe||(Ae.ExitNotification=FTe={}));var $Te;(function(t){t.method="workspace/didChangeConfiguration",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolNotificationType(t.method)})($Te||(Ae.DidChangeConfigurationNotification=$Te={}));var zTe;(function(t){t.Error=1,t.Warning=2,t.Info=3,t.Log=4,t.Debug=5})(zTe||(Ae.MessageType=zTe={}));var GTe;(function(t){t.method="window/showMessage",t.messageDirection=At.MessageDirection.serverToClient,t.type=new At.ProtocolNotificationType(t.method)})(GTe||(Ae.ShowMessageNotification=GTe={}));var VTe;(function(t){t.method="window/showMessageRequest",t.messageDirection=At.MessageDirection.serverToClient,t.type=new At.ProtocolRequestType(t.method)})(VTe||(Ae.ShowMessageRequest=VTe={}));var qTe;(function(t){t.method="window/logMessage",t.messageDirection=At.MessageDirection.serverToClient,t.type=new At.ProtocolNotificationType(t.method)})(qTe||(Ae.LogMessageNotification=qTe={}));var WTe;(function(t){t.method="telemetry/event",t.messageDirection=At.MessageDirection.serverToClient,t.type=new At.ProtocolNotificationType(t.method)})(WTe||(Ae.TelemetryEventNotification=WTe={}));var UTe;(function(t){t.None=0,t.Full=1,t.Incremental=2})(UTe||(Ae.TextDocumentSyncKind=UTe={}));var HTe;(function(t){t.method="textDocument/didOpen",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolNotificationType(t.method)})(HTe||(Ae.DidOpenTextDocumentNotification=HTe={}));var YTe;(function(t){function e(i){let n=i;return n!=null&&typeof n.text=="string"&&n.range!==void 0&&(n.rangeLength===void 0||typeof n.rangeLength=="number")}o(e,"isIncremental"),t.isIncremental=e;function r(i){let n=i;return n!=null&&typeof n.text=="string"&&n.range===void 0&&n.rangeLength===void 0}o(r,"isFull"),t.isFull=r})(YTe||(Ae.TextDocumentContentChangeEvent=YTe={}));var jTe;(function(t){t.method="textDocument/didChange",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolNotificationType(t.method)})(jTe||(Ae.DidChangeTextDocumentNotification=jTe={}));var XTe;(function(t){t.method="textDocument/didClose",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolNotificationType(t.method)})(XTe||(Ae.DidCloseTextDocumentNotification=XTe={}));var KTe;(function(t){t.method="textDocument/didSave",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolNotificationType(t.method)})(KTe||(Ae.DidSaveTextDocumentNotification=KTe={}));var QTe;(function(t){t.Manual=1,t.AfterDelay=2,t.FocusOut=3})(QTe||(Ae.TextDocumentSaveReason=QTe={}));var ZTe;(function(t){t.method="textDocument/willSave",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolNotificationType(t.method)})(ZTe||(Ae.WillSaveTextDocumentNotification=ZTe={}));var JTe;(function(t){t.method="textDocument/willSaveWaitUntil",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(JTe||(Ae.WillSaveTextDocumentWaitUntilRequest=JTe={}));var eke;(function(t){t.method="workspace/didChangeWatchedFiles",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolNotificationType(t.method)})(eke||(Ae.DidChangeWatchedFilesNotification=eke={}));var tke;(function(t){t.Created=1,t.Changed=2,t.Deleted=3})(tke||(Ae.FileChangeType=tke={}));var rke;(function(t){function e(r){let i=r;return $a.objectLiteral(i)&&(ETe.URI.is(i.baseUri)||ETe.WorkspaceFolder.is(i.baseUri))&&$a.string(i.pattern)}o(e,"is"),t.is=e})(rke||(Ae.RelativePattern=rke={}));var ike;(function(t){t.Create=1,t.Change=2,t.Delete=4})(ike||(Ae.WatchKind=ike={}));var nke;(function(t){t.method="textDocument/publishDiagnostics",t.messageDirection=At.MessageDirection.serverToClient,t.type=new At.ProtocolNotificationType(t.method)})(nke||(Ae.PublishDiagnosticsNotification=nke={}));var ake;(function(t){t.Invoked=1,t.TriggerCharacter=2,t.TriggerForIncompleteCompletions=3})(ake||(Ae.CompletionTriggerKind=ake={}));var ske;(function(t){t.method="textDocument/completion",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(ske||(Ae.CompletionRequest=ske={}));var oke;(function(t){t.method="completionItem/resolve",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(oke||(Ae.CompletionResolveRequest=oke={}));var lke;(function(t){t.method="textDocument/hover",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(lke||(Ae.HoverRequest=lke={}));var cke;(function(t){t.Invoked=1,t.TriggerCharacter=2,t.ContentChange=3})(cke||(Ae.SignatureHelpTriggerKind=cke={}));var uke;(function(t){t.method="textDocument/signatureHelp",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(uke||(Ae.SignatureHelpRequest=uke={}));var hke;(function(t){t.method="textDocument/definition",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(hke||(Ae.DefinitionRequest=hke={}));var fke;(function(t){t.method="textDocument/references",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(fke||(Ae.ReferencesRequest=fke={}));var dke;(function(t){t.method="textDocument/documentHighlight",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(dke||(Ae.DocumentHighlightRequest=dke={}));var pke;(function(t){t.method="textDocument/documentSymbol",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(pke||(Ae.DocumentSymbolRequest=pke={}));var mke;(function(t){t.method="textDocument/codeAction",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(mke||(Ae.CodeActionRequest=mke={}));var gke;(function(t){t.method="codeAction/resolve",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(gke||(Ae.CodeActionResolveRequest=gke={}));var yke;(function(t){t.method="workspace/symbol",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(yke||(Ae.WorkspaceSymbolRequest=yke={}));var vke;(function(t){t.method="workspaceSymbol/resolve",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(vke||(Ae.WorkspaceSymbolResolveRequest=vke={}));var xke;(function(t){t.method="textDocument/codeLens",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(xke||(Ae.CodeLensRequest=xke={}));var bke;(function(t){t.method="codeLens/resolve",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(bke||(Ae.CodeLensResolveRequest=bke={}));var Tke;(function(t){t.method="workspace/codeLens/refresh",t.messageDirection=At.MessageDirection.serverToClient,t.type=new At.ProtocolRequestType0(t.method)})(Tke||(Ae.CodeLensRefreshRequest=Tke={}));var kke;(function(t){t.method="textDocument/documentLink",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(kke||(Ae.DocumentLinkRequest=kke={}));var Cke;(function(t){t.method="documentLink/resolve",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(Cke||(Ae.DocumentLinkResolveRequest=Cke={}));var wke;(function(t){t.method="textDocument/formatting",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(wke||(Ae.DocumentFormattingRequest=wke={}));var Eke;(function(t){t.method="textDocument/rangeFormatting",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(Eke||(Ae.DocumentRangeFormattingRequest=Eke={}));var Ske;(function(t){t.method="textDocument/rangesFormatting",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(Ske||(Ae.DocumentRangesFormattingRequest=Ske={}));var Ake;(function(t){t.method="textDocument/onTypeFormatting",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(Ake||(Ae.DocumentOnTypeFormattingRequest=Ake={}));var _ke;(function(t){t.Identifier=1})(_ke||(Ae.PrepareSupportDefaultBehavior=_ke={}));var Dke;(function(t){t.method="textDocument/rename",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(Dke||(Ae.RenameRequest=Dke={}));var Lke;(function(t){t.method="textDocument/prepareRename",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(Lke||(Ae.PrepareRenameRequest=Lke={}));var Rke;(function(t){t.method="workspace/executeCommand",t.messageDirection=At.MessageDirection.clientToServer,t.type=new At.ProtocolRequestType(t.method)})(Rke||(Ae.ExecuteCommandRequest=Rke={}));var Nke;(function(t){t.method="workspace/applyEdit",t.messageDirection=At.MessageDirection.serverToClient,t.type=new At.ProtocolRequestType("workspace/applyEdit")})(Nke||(Ae.ApplyWorkspaceEditRequest=Nke={}))});var $ke=ar(d7=>{"use strict";Object.defineProperty(d7,"__esModule",{value:!0});d7.createProtocolConnection=void 0;var Fke=Um();function vot(t,e,r,i){return Fke.ConnectionStrategy.is(i)&&(i={connectionStrategy:i}),(0,Fke.createMessageConnection)(t,e,r,i)}o(vot,"createProtocolConnection");d7.createProtocolConnection=vot});var Gke=ar($o=>{"use strict";var xot=$o&&$o.__createBinding||(Object.create?(function(t,e,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(e,r);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:o(function(){return e[r]},"get")}),Object.defineProperty(t,i,n)}):(function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]})),p7=$o&&$o.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&xot(e,t,r)};Object.defineProperty($o,"__esModule",{value:!0});$o.LSPErrorCodes=$o.createProtocolConnection=void 0;p7(Um(),$o);p7((pv(),s4(yA)),$o);p7(bn(),$o);p7(Bke(),$o);var bot=$ke();Object.defineProperty($o,"createProtocolConnection",{enumerable:!0,get:o(function(){return bot.createProtocolConnection},"get")});var zke;(function(t){t.lspReservedErrorRangeStart=-32899,t.RequestFailed=-32803,t.ServerCancelled=-32802,t.ContentModified=-32801,t.RequestCancelled=-32800,t.lspReservedErrorRangeEnd=-32800})(zke||($o.LSPErrorCodes=zke={}))});var qke=ar(ih=>{"use strict";var Tot=ih&&ih.__createBinding||(Object.create?(function(t,e,r,i){i===void 0&&(i=r);var n=Object.getOwnPropertyDescriptor(e,r);(!n||("get"in n?!e.__esModule:n.writable||n.configurable))&&(n={enumerable:!0,get:o(function(){return e[r]},"get")}),Object.defineProperty(t,i,n)}):(function(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]})),Vke=ih&&ih.__exportStar||function(t,e){for(var r in t)r!=="default"&&!Object.prototype.hasOwnProperty.call(e,r)&&Tot(e,t,r)};Object.defineProperty(ih,"__esModule",{value:!0});ih.createProtocolConnection=void 0;var kot=GV();Vke(GV(),ih);Vke(Gke(),ih);function Cot(t,e,r,i){return(0,kot.createMessageConnection)(t,e,r,i)}o(Cot,"createProtocolConnection");ih.createProtocolConnection=Cot});var xp,nq=P(()=>{"use strict";(function(t){function e(r){return{dispose:o(async()=>await r(),"dispose")}}o(e,"create"),t.create=e})(xp||(xp={}))});var Vv,sC,aq=P(()=>{"use strict";Vv=Wa(qke(),1);Yl();nq();up();Xl();Ys();Wc();Cv();sC=class{static{o(this,"DefaultDocumentBuilder")}constructor(e){this.updateBuildOptions={validation:{categories:["built-in","fast"]}},this.updateListeners=[],this.buildPhaseListeners=new Cs,this.documentPhaseListeners=new Cs,this.buildState=new Map,this.documentBuildWaiters=new Map,this.currentState=Ur.Changed,this.langiumDocuments=e.workspace.LangiumDocuments,this.langiumDocumentFactory=e.workspace.LangiumDocumentFactory,this.textDocuments=e.workspace.TextDocuments,this.indexManager=e.workspace.IndexManager,this.fileSystemProvider=e.workspace.FileSystemProvider,this.workspaceManager=()=>e.workspace.WorkspaceManager,this.serviceRegistry=e.ServiceRegistry}async build(e,r={},i=$r.CancellationToken.None){for(let n of e){let a=n.uri.toString();if(n.state===Ur.Validated){if(typeof r.validation=="boolean"&&r.validation)this.resetToState(n,Ur.IndexedReferences);else if(typeof r.validation=="object"){let s=this.findMissingValidationCategories(n,r);s.length>0&&(this.buildState.set(a,{completed:!1,options:{validation:{categories:s}},result:this.buildState.get(a)?.result}),n.state=Ur.IndexedReferences)}}else this.buildState.delete(a)}this.currentState=Ur.Changed,await this.emitUpdate(e.map(n=>n.uri),[]),await this.buildDocuments(e,r,i)}async update(e,r,i=$r.CancellationToken.None){this.currentState=Ur.Changed;let n=[];for(let u of r){let h=this.langiumDocuments.deleteDocuments(u);for(let f of h)n.push(f.uri),this.cleanUpDeleted(f)}let a=(await Promise.all(e.map(u=>this.findChangedUris(u)))).flat();for(let u of a){let h=this.langiumDocuments.getDocument(u);h===void 0&&(h=this.langiumDocumentFactory.fromModel({$type:"INVALID"},u),h.state=Ur.Changed,this.langiumDocuments.addDocument(h)),this.resetToState(h,Ur.Changed)}let s=jr(a).concat(n).map(u=>u.toString()).toSet();this.langiumDocuments.all.filter(u=>!s.has(u.uri.toString())&&this.shouldRelink(u,s)).forEach(u=>this.resetToState(u,Ur.ComputedScopes)),await this.emitUpdate(a,n),await Dn(i);let l=this.sortDocuments(this.langiumDocuments.all.filter(u=>u.state=1}findMissingValidationCategories(e,r){let i=this.buildState.get(e.uri.toString()),n=this.serviceRegistry.getServices(e.uri).validation.ValidationRegistry.getAllValidationCategories(e),a=i?.result?.validationChecks?new Set(i?.result?.validationChecks):i?.completed?n:new Set,s=r===void 0||r.validation===!0?n:typeof r.validation=="object"?r.validation.categories??n:[];return jr(s).filter(l=>!a.has(l)).toArray()}async findChangedUris(e){if(this.langiumDocuments.getDocument(e)??this.textDocuments?.get(e))return[e];try{let i=await this.fileSystemProvider.stat(e);if(i.isDirectory)return await this.workspaceManager().searchFolder(e);if(this.workspaceManager().shouldIncludeEntry(i))return[e]}catch{}return[]}async emitUpdate(e,r){await Promise.all(this.updateListeners.map(i=>i(e,r)))}sortDocuments(e){let r=0,i=e.length-1;for(;r=0&&!this.hasTextDocument(e[i]);)i--;ri.error!==void 0)?!0:this.indexManager.isAffected(e,r)}onUpdate(e){return this.updateListeners.push(e),xp.create(()=>{let r=this.updateListeners.indexOf(e);r>=0&&this.updateListeners.splice(r,1)})}resetToState(e,r){switch(r){case Ur.Changed:case Ur.Parsed:this.indexManager.removeContent(e.uri);case Ur.IndexedContent:e.localSymbols=void 0;case Ur.ComputedScopes:this.serviceRegistry.getServices(e.uri).references.Linker.unlink(e);case Ur.Linked:this.indexManager.removeReferences(e.uri);case Ur.IndexedReferences:e.diagnostics=void 0,this.buildState.delete(e.uri.toString());case Ur.Validated:}e.state>r&&(e.state=r)}cleanUpDeleted(e){this.buildState.delete(e.uri.toString()),this.indexManager.remove(e.uri),e.state=Ur.Changed}async buildDocuments(e,r,i){this.prepareBuild(e,r),await this.runCancelable(e,Ur.Parsed,i,s=>this.langiumDocumentFactory.update(s,i)),await this.runCancelable(e,Ur.IndexedContent,i,s=>this.indexManager.updateContent(s,i)),await this.runCancelable(e,Ur.ComputedScopes,i,async s=>{let l=this.serviceRegistry.getServices(s.uri).references.ScopeComputation;s.localSymbols=await l.collectLocalSymbols(s,i)});let n=e.filter(s=>this.shouldLink(s));await this.runCancelable(n,Ur.Linked,i,s=>this.serviceRegistry.getServices(s.uri).references.Linker.link(s,i)),await this.runCancelable(n,Ur.IndexedReferences,i,s=>this.indexManager.updateReferences(s,i));let a=e.filter(s=>this.shouldValidate(s)?!0:(this.markAsCompleted(s),!1));await this.runCancelable(a,Ur.Validated,i,async s=>{await this.validate(s,i),this.markAsCompleted(s)})}markAsCompleted(e){let r=this.buildState.get(e.uri.toString());r&&(r.completed=!0)}prepareBuild(e,r){for(let i of e){let n=i.uri.toString(),a=this.buildState.get(n);(!a||a.completed)&&this.buildState.set(n,{completed:!1,options:r,result:a?.result})}}async runCancelable(e,r,i,n){for(let s of e)s.states.state===r);await this.notifyBuildPhase(a,r,i),this.currentState=r}onBuildPhase(e,r){return this.buildPhaseListeners.add(e,r),xp.create(()=>{this.buildPhaseListeners.delete(e,r)})}onDocumentPhase(e,r){return this.documentPhaseListeners.add(e,r),xp.create(()=>{this.documentPhaseListeners.delete(e,r)})}waitUntil(e,r,i){let n;return r&&"path"in r?n=r:i=r,i??(i=$r.CancellationToken.None),n?this.awaitDocumentState(e,n,i):this.awaitBuilderState(e,i)}awaitDocumentState(e,r,i){let n=this.langiumDocuments.getDocument(r);if(n){if(n.state>=e)return Promise.resolve(r);if(i.isCancellationRequested)return Promise.reject(jl);if(this.currentState>=e&&e>n.state)return Promise.reject(new Vv.ResponseError(Vv.LSPErrorCodes.RequestFailed,`Document state of ${r.toString()} is ${Ur[n.state]}, requiring ${Ur[e]}, but workspace state is already ${Ur[this.currentState]}. Returning undefined.`))}else return Promise.reject(new Vv.ResponseError(Vv.LSPErrorCodes.ServerCancelled,`No document found for URI: ${r.toString()}`));return new Promise((a,s)=>{let l=this.onDocumentPhase(e,h=>{Vn.equals(h.uri,r)&&(l.dispose(),u.dispose(),a(h.uri))}),u=i.onCancellationRequested(()=>{l.dispose(),u.dispose(),s(jl)})})}awaitBuilderState(e,r){return this.currentState>=e?Promise.resolve():r.isCancellationRequested?Promise.reject(jl):new Promise((i,n)=>{let a=this.onBuildPhase(e,()=>{a.dispose(),s.dispose(),i()}),s=r.onCancellationRequested(()=>{a.dispose(),s.dispose(),n(jl)})})}async notifyDocumentPhase(e,r,i){let a=this.documentPhaseListeners.get(r).slice();for(let s of a)try{await Dn(i),await s(e,i)}catch(l){if(!Ju(l))throw l}}async notifyBuildPhase(e,r,i){if(e.length===0)return;let a=this.buildPhaseListeners.get(r).slice();for(let s of a)await Dn(i),await s(e,i)}shouldLink(e){return this.getBuildOptions(e).eagerLinking??!0}shouldValidate(e){return!!this.getBuildOptions(e).validation}async validate(e,r){let i=this.serviceRegistry.getServices(e.uri).validation.DocumentValidator,n=this.getBuildOptions(e),a=typeof n.validation=="object"?{...n.validation}:{};a.categories=this.findMissingValidationCategories(e,n);let s=await i.validateDocument(e,a,r);e.diagnostics?e.diagnostics.push(...s):e.diagnostics=s;let l=this.buildState.get(e.uri.toString());l&&(l.result??(l.result={}),l.result.validationChecks?l.result.validationChecks=jr(l.result.validationChecks).concat(a.categories).distinct().toArray():l.result.validationChecks=[...a.categories])}getBuildOptions(e){return this.buildState.get(e.uri.toString())?.options??{}}}});var oC,sq=P(()=>{"use strict";Ts();NA();Yl();Ys();Wc();oC=class{static{o(this,"DefaultIndexManager")}constructor(e){this.symbolIndex=new Map,this.symbolByTypeIndex=new Vm,this.referenceIndex=new Map,this.documents=e.workspace.LangiumDocuments,this.serviceRegistry=e.ServiceRegistry,this.astReflection=e.AstReflection}findAllReferences(e,r){let i=bs(e).uri,n=[];return this.referenceIndex.forEach(a=>{a.forEach(s=>{Vn.equals(s.targetUri,i)&&s.targetPath===r&&n.push(s)})}),jr(n)}allElements(e,r){let i=jr(this.symbolIndex.keys());return r&&(i=i.filter(n=>!r||r.has(n))),i.map(n=>this.getFileDescriptions(n,e)).flat()}getFileDescriptions(e,r){return r?this.symbolByTypeIndex.get(e,r,()=>(this.symbolIndex.get(e)??[]).filter(a=>this.astReflection.isSubtype(a.type,r))):this.symbolIndex.get(e)??[]}remove(e){this.removeContent(e),this.removeReferences(e)}removeContent(e){let r=e.toString();this.symbolIndex.delete(r),this.symbolByTypeIndex.clear(r)}removeReferences(e){let r=e.toString();this.referenceIndex.delete(r)}async updateContent(e,r=$r.CancellationToken.None){let n=await this.serviceRegistry.getServices(e.uri).references.ScopeComputation.collectExportedSymbols(e,r),a=e.uri.toString();this.symbolIndex.set(a,n),this.symbolByTypeIndex.clear(a)}async updateReferences(e,r=$r.CancellationToken.None){let n=await this.serviceRegistry.getServices(e.uri).workspace.ReferenceDescriptionProvider.createDescriptions(e,r);this.referenceIndex.set(e.uri.toString(),n)}isAffected(e,r){let i=this.referenceIndex.get(e.uri.toString());return i?i.some(n=>!n.local&&r.has(n.targetUri.toString())):!1}}});var lC,oq=P(()=>{"use strict";Yl();Xl();Wc();Ys();lC=class{static{o(this,"DefaultWorkspaceManager")}constructor(e){this.initialBuildOptions={},this._ready=new eo,this.serviceRegistry=e.ServiceRegistry,this.langiumDocuments=e.workspace.LangiumDocuments,this.documentBuilder=e.workspace.DocumentBuilder,this.fileSystemProvider=e.workspace.FileSystemProvider,this.mutex=e.workspace.WorkspaceLock}get ready(){return this._ready.promise}get workspaceFolders(){return this.folders}initialize(e){this.folders=e.workspaceFolders??void 0}initialized(e){return this.mutex.write(r=>this.initializeWorkspace(this.folders??[],r))}async initializeWorkspace(e,r=$r.CancellationToken.None){let i=await this.performStartup(e);await Dn(r),await this.documentBuilder.build(i,this.initialBuildOptions,r)}async performStartup(e){let r=[],i=o(s=>{r.push(s),this.langiumDocuments.hasDocument(s.uri)||this.langiumDocuments.addDocument(s)},"collector");await this.loadAdditionalDocuments(e,i);let n=[];await Promise.all(e.map(s=>this.getRootFolder(s)).map(async s=>this.traverseFolder(s,n)));let a=jr(n).distinct(s=>s.toString()).filter(s=>!this.langiumDocuments.hasDocument(s));return await this.loadWorkspaceDocuments(a,i),this._ready.resolve(),r}async loadWorkspaceDocuments(e,r){await Promise.all(e.map(async i=>{let n=await this.langiumDocuments.getOrCreateDocument(i);r(n)}))}loadAdditionalDocuments(e,r){return Promise.resolve()}getRootFolder(e){return va.parse(e.uri)}async traverseFolder(e,r){try{let i=await this.fileSystemProvider.readDirectory(e);await Promise.all(i.map(async n=>{this.shouldIncludeEntry(n)&&(n.isDirectory?await this.traverseFolder(n.uri,r):n.isFile&&r.push(n.uri))}))}catch(i){console.error("Failure to read directory content of "+e.toString(!0),i)}}async searchFolder(e){let r=[];return await this.traverseFolder(e,r),r}shouldIncludeEntry(e){let r=Vn.basename(e.uri);return r.startsWith(".")?!1:e.isDirectory?r!=="node_modules"&&r!=="out":e.isFile?this.serviceRegistry.hasServices(e.uri):!1}}});function g7(t){return Array.isArray(t)&&(t.length===0||"name"in t[0])}function cq(t){return t&&"modes"in t&&"defaultMode"in t}function lq(t){return!g7(t)&&!cq(t)}var cC,m7,Ym,y7=P(()=>{"use strict";sp();cC=class{static{o(this,"DefaultLexerErrorMessageProvider")}buildUnexpectedCharactersMessage(e,r,i,n,a){return jy.buildUnexpectedCharactersMessage(e,r,i,n,a)}buildUnableToPopLexerModeMessage(e){return jy.buildUnableToPopLexerModeMessage(e)}},m7={mode:"full"},Ym=class{static{o(this,"DefaultLexer")}constructor(e){this.errorMessageProvider=e.parser.LexerErrorMessageProvider,this.tokenBuilder=e.parser.TokenBuilder;let r=this.tokenBuilder.buildTokens(e.Grammar,{caseInsensitive:e.LanguageMetaData.caseInsensitive});this.tokenTypes=this.toTokenTypeDictionary(r);let i=lq(r)?Object.values(r):r,n=e.LanguageMetaData.mode==="production";this.chevrotainLexer=new yn(i,{positionTracking:"full",skipValidations:n,errorMessageProvider:this.errorMessageProvider})}get definition(){return this.tokenTypes}tokenize(e,r=m7){let i=this.chevrotainLexer.tokenize(e);return{tokens:i.tokens,errors:i.errors,hidden:i.groups.hidden??[],report:this.tokenBuilder.flushLexingReport?.(e)}}toTokenTypeDictionary(e){if(lq(e))return e;let r=cq(e)?Object.values(e.modes).flat():e,i={};return r.forEach(n=>i[n.name]=n),i}};o(g7,"isTokenTypeArray");o(cq,"isIMultiModeLexerDefinition");o(lq,"isTokenTypeDictionary")});function fq(t,e,r){let i,n;typeof t=="string"?(n=e,i=r):(n=t.range.start,i=e),n||(n=oi.create(0,0));let a=Hke(t),s=pq(i),l=Eot({lines:a,position:n,options:s});return Lot({index:0,tokens:l,position:n})}function dq(t,e){let r=pq(e),i=Hke(t);if(i.length===0)return!1;let n=i[0],a=i[i.length-1],s=r.start,l=r.end;return!!s?.exec(n)&&!!l?.exec(a)}function Hke(t){let e="";return typeof t=="string"?e=t:e=t.text,e.split(n$)}function Eot(t){let e=[],r=t.position.line,i=t.position.character;for(let n=0;n=l.length){if(e.length>0){let f=oi.create(r,i);e.push({type:"break",content:"",range:Jr.create(f,f)})}}else{Wke.lastIndex=u;let f=Wke.exec(l);if(f){let d=f[0],p=f[1],m=oi.create(r,i+u),g=oi.create(r,i+u+d.length);e.push({type:"tag",content:p,range:Jr.create(m,g)}),u+=d.length,u=hq(l,u)}if(u0&&e[e.length-1].type==="break"?e.slice(0,-1):e}function Sot(t,e,r,i){let n=[];if(t.length===0){let a=oi.create(r,i),s=oi.create(r,i+e.length);n.push({type:"text",content:e,range:Jr.create(a,s)})}else{let a=0;for(let l of t){let u=l.index,h=e.substring(a,u);h.length>0&&n.push({type:"text",content:e.substring(a,u),range:Jr.create(oi.create(r,a+i),oi.create(r,u+i))});let f=h.length+1,d=l[1];if(n.push({type:"inline-tag",content:d,range:Jr.create(oi.create(r,a+f+i),oi.create(r,a+f+d.length+i))}),f+=d.length,l.length===4){f+=l[2].length;let p=l[3];n.push({type:"text",content:p,range:Jr.create(oi.create(r,a+f+i),oi.create(r,a+f+p.length+i))})}else n.push({type:"text",content:"",range:Jr.create(oi.create(r,a+f+i),oi.create(r,a+f+i))});a=u+l[0].length}let s=e.substring(a);s.length>0&&n.push({type:"text",content:s,range:Jr.create(oi.create(r,a+i),oi.create(r,a+i+s.length))})}return n}function hq(t,e){let r=t.substring(e).match(Aot);return r?e+r.index:t.length}function Dot(t){let e=t.match(_ot);if(e&&typeof e.index=="number")return e.index}function Lot(t){let e=oi.create(t.position.line,t.position.character);if(t.tokens.length===0)return new v7([],Jr.create(e,e));let r=[];for(;t.index0){let s=hq(e,i);n=e.substring(s),e=e.substring(0,i)}return(t==="linkcode"||t==="link"&&r.link==="code")&&(n=`\`${n}\``),r.renderLink?.(e,n)??Oot(e,n)}}function Oot(t,e){try{return va.parse(t,!0),`[${e}](${t})`}catch{return t}}function Uke(t){return t.endsWith(` +`)?` +`:` + +`}var Wke,wot,Aot,_ot,v7,uC,hC,x7,mq=P(()=>{"use strict";pv();Fy();Wc();o(fq,"parseJSDoc");o(dq,"isJSDoc");o(Hke,"getLines");Wke=/\s*(@([\p{L}][\p{L}\p{N}]*)?)/uy,wot=/\{(@[\p{L}][\p{L}\p{N}]*)(\s*)([^\r\n}]+)?\}/gu;o(Eot,"tokenize");o(Sot,"buildInlineTokens");Aot=/\S/,_ot=/\s*$/;o(hq,"skipWhitespace");o(Dot,"lastCharacter");o(Lot,"parseJSDocComment");o(Rot,"parseJSDocElement");o(Not,"appendEmptyLine");o(Yke,"parseJSDocText");o(Iot,"parseJSDocInline");o(jke,"parseJSDocTag");o(Xke,"parseJSDocLine");o(pq,"normalizeOptions");o(uq,"normalizeOption");v7=class{static{o(this,"JSDocCommentImpl")}constructor(e,r){this.elements=e,this.range=r}getTag(e){return this.getAllTags().find(r=>r.name===e)}getTags(e){return this.getAllTags().filter(r=>r.name===e)}getAllTags(){return this.elements.filter(e=>"name"in e)}toString(){let e="";for(let r of this.elements)if(e.length===0)e=r.toString();else{let i=r.toString();e+=Uke(e)+i}return e.trim()}toMarkdown(e){let r="";for(let i of this.elements)if(r.length===0)r=i.toMarkdown(e);else{let n=i.toMarkdown(e);r+=Uke(r)+n}return r.trim()}},uC=class{static{o(this,"JSDocTagImpl")}constructor(e,r,i,n){this.name=e,this.content=r,this.inline=i,this.range=n}toString(){let e=`@${this.name}`,r=this.content.toString();return this.content.inlines.length===1?e=`${e} ${r}`:this.content.inlines.length>1&&(e=`${e} +${r}`),this.inline?`{${e}}`:e}toMarkdown(e){return e?.renderTag?.(this)??this.toMarkdownDefault(e)}toMarkdownDefault(e){let r=this.content.toMarkdown(e);if(this.inline){let a=Mot(this.name,r,e??{});if(typeof a=="string")return a}let i="";e?.tag==="italic"||e?.tag===void 0?i="*":e?.tag==="bold"?i="**":e?.tag==="bold-italic"&&(i="***");let n=`${i}@${this.name}${i}`;return this.content.inlines.length===1?n=`${n} \u2014 ${r}`:this.content.inlines.length>1&&(n=`${n} +${r}`),this.inline?`{${n}}`:n}};o(Mot,"renderInlineTag");o(Oot,"renderLinkDefault");hC=class{static{o(this,"JSDocTextImpl")}constructor(e,r){this.inlines=e,this.range=r}toString(){let e="";for(let r=0;ri.range.start.line&&(e+=` +`)}return e}toMarkdown(e){let r="";for(let i=0;in.range.start.line&&(r+=` +`)}return r}},x7=class{static{o(this,"JSDocLineImpl")}constructor(e,r){this.text=e,this.range=r}toString(){return this.text}toMarkdown(){return this.text}};o(Uke,"fillNewlines")});var fC,gq=P(()=>{"use strict";Ts();mq();fC=class{static{o(this,"JSDocDocumentationProvider")}constructor(e){this.indexManager=e.shared.workspace.IndexManager,this.commentProvider=e.documentation.CommentProvider}getDocumentation(e){let r=this.commentProvider.getComment(e);if(r&&dq(r))return fq(r).toMarkdown({renderLink:o((n,a)=>this.documentationLinkRenderer(e,n,a),"renderLink"),renderTag:o(n=>this.documentationTagRenderer(e,n),"renderTag")})}documentationLinkRenderer(e,r,i){let n=this.findNameInLocalSymbols(e,r)??this.findNameInGlobalScope(e,r);if(n&&n.nameSegment){let a=n.nameSegment.range.start.line+1,s=n.nameSegment.range.start.character+1,l=n.documentUri.with({fragment:`L${a},${s}`});return`[${i}](${l.toString()})`}else return}documentationTagRenderer(e,r){}findNameInLocalSymbols(e,r){let n=bs(e).localSymbols;if(!n)return;let a=e;do{let l=n.getStream(a).find(u=>u.name===r);if(l)return l;a=a.$container}while(a)}findNameInGlobalScope(e,r){return this.indexManager.allElements().find(n=>n.name===r)}}});var dC,yq=P(()=>{"use strict";IA();Bc();dC=class{static{o(this,"DefaultCommentProvider")}constructor(e){this.grammarConfig=()=>e.parser.GrammarConfig}getComment(e){return IG(e)?e.$comment:ZF(e.$cstNode,this.grammarConfig().multilineCommentRules)?.text}}});var pC,vq,xq,bq=P(()=>{"use strict";Xl();BA();pC=class{static{o(this,"DefaultAsyncParser")}constructor(e){this.syncParser=e.parser.LangiumParser}parse(e,r){return Promise.resolve(this.syncParser.parse(e))}},vq=class{static{o(this,"AbstractThreadedAsyncParser")}constructor(e){this.threadCount=8,this.terminationDelay=200,this.workerPool=[],this.queue=[],this.hydrator=e.serializer.Hydrator}initializeWorkers(){for(;this.workerPool.length{if(this.queue.length>0){let r=this.queue.shift();r&&(e.lock(),r.resolve(e))}}),this.workerPool.push(e)}}async parse(e,r){let i=await this.acquireParserWorker(r),n=new eo,a,s=r.onCancellationRequested(()=>{a=setTimeout(()=>{this.terminateWorker(i)},this.terminationDelay)});return i.parse(e).then(l=>{let u=this.hydrator.hydrate(l);n.resolve(u)}).catch(l=>{n.reject(l)}).finally(()=>{s.dispose(),clearTimeout(a)}),n.promise}terminateWorker(e){e.terminate();let r=this.workerPool.indexOf(e);r>=0&&this.workerPool.splice(r,1)}async acquireParserWorker(e){this.initializeWorkers();for(let i of this.workerPool)if(i.ready)return i.lock(),i;let r=new eo;return e.onCancellationRequested(()=>{let i=this.queue.indexOf(r);i>=0&&this.queue.splice(i,1),r.reject(jl)}),this.queue.push(r),r.promise}},xq=class{static{o(this,"ParserWorker")}get ready(){return this._ready}get onReady(){return this.onReadyEmitter.event}constructor(e,r,i,n){this.onReadyEmitter=new xn.Emitter,this.deferred=new eo,this._ready=!0,this._parsing=!1,this.sendMessage=e,this._terminate=n,r(a=>{let s=a;this.deferred.resolve(s),this.unlock()}),i(a=>{this.deferred.reject(a),this.unlock()})}terminate(){this.deferred.reject(jl),this._terminate()}lock(){this._ready=!1}unlock(){this._parsing=!1,this._ready=!0,this.onReadyEmitter.fire()}parse(e){if(this._parsing)throw new Error("Parser worker is busy");return this._parsing=!0,this.deferred=new eo,this.sendMessage(e),this.deferred.promise}}});var mC,Tq=P(()=>{"use strict";Yl();Xl();mC=class{static{o(this,"DefaultWorkspaceLock")}constructor(){this.previousTokenSource=new $r.CancellationTokenSource,this.writeQueue=[],this.readQueue=[],this.done=!0}write(e){this.cancelWrite();let r=DA();return this.previousTokenSource=r,this.enqueue(this.writeQueue,e,r.token)}read(e){return this.enqueue(this.readQueue,e)}enqueue(e,r,i=$r.CancellationToken.None){let n=new eo,a={action:r,deferred:n,cancellationToken:i};return e.push(a),this.performNextOperation(),n.promise}async performNextOperation(){if(!this.done)return;let e=[];if(this.writeQueue.length>0)e.push(this.writeQueue.shift());else if(this.readQueue.length>0)e.push(...this.readQueue.splice(0,this.readQueue.length));else return;this.done=!1,await Promise.all(e.map(async({action:r,deferred:i,cancellationToken:n})=>{try{let a=await Promise.resolve().then(()=>r(n));i.resolve(a)}catch(a){Ju(a)?i.resolve(void 0):i.reject(a)}})),this.done=!0,this.performNextOperation()}cancelWrite(){this.previousTokenSource.cancel()}}});var gC,kq=P(()=>{"use strict";vA();ol();Oc();Ts();up();Bc();gC=class{static{o(this,"DefaultHydrator")}constructor(e){this.grammarElementIdMap=new Gm,this.tokenTypeIdMap=new Gm,this.grammar=e.Grammar,this.lexer=e.parser.Lexer,this.linker=e.references.Linker}dehydrate(e){return{lexerErrors:e.lexerErrors,lexerReport:e.lexerReport?this.dehydrateLexerReport(e.lexerReport):void 0,parserErrors:e.parserErrors.map(r=>({...r,message:r.message})),value:this.dehydrateAstNode(e.value,this.createDehyrationContext(e.value))}}dehydrateLexerReport(e){return e}createDehyrationContext(e){let r=new Map,i=new Map;for(let n of js(e))r.set(n,{});if(e.$cstNode)for(let n of xm(e.$cstNode))i.set(n,{});return{astNodes:r,cstNodes:i}}dehydrateAstNode(e,r){let i=r.astNodes.get(e);i.$type=e.$type,i.$containerIndex=e.$containerIndex,i.$containerProperty=e.$containerProperty,e.$cstNode!==void 0&&(i.$cstNode=this.dehydrateCstNode(e.$cstNode,r));for(let[n,a]of Object.entries(e))if(!n.startsWith("$"))if(Array.isArray(a)){let s=[];i[n]=s;for(let l of a)_n(l)?s.push(this.dehydrateAstNode(l,r)):ga(l)?s.push(this.dehydrateReference(l,r)):s.push(l)}else _n(a)?i[n]=this.dehydrateAstNode(a,r):ga(a)?i[n]=this.dehydrateReference(a,r):a!==void 0&&(i[n]=a);return i}dehydrateReference(e,r){let i={};return i.$refText=e.$refText,e.$refNode&&(i.$refNode=r.cstNodes.get(e.$refNode)),i}dehydrateCstNode(e,r){let i=r.cstNodes.get(e);return _T(e)?i.fullText=e.fullText:i.grammarSource=this.getGrammarElementId(e.grammarSource),i.hidden=e.hidden,i.astNode=r.astNodes.get(e.astNode),Mc(e)?i.content=e.content.map(n=>this.dehydrateCstNode(n,r)):Hd(e)&&(i.tokenType=e.tokenType.name,i.offset=e.offset,i.length=e.length,i.startLine=e.range.start.line,i.startColumn=e.range.start.character,i.endLine=e.range.end.line,i.endColumn=e.range.end.character),i}hydrate(e){let r=e.value,i=this.createHydrationContext(r);return"$cstNode"in r&&this.hydrateCstNode(r.$cstNode,i),{lexerErrors:e.lexerErrors,lexerReport:e.lexerReport,parserErrors:e.parserErrors,value:this.hydrateAstNode(r,i)}}createHydrationContext(e){let r=new Map,i=new Map;for(let a of js(e))r.set(a,{});let n;if(e.$cstNode)for(let a of xm(e.$cstNode)){let s;"fullText"in a?(s=new mv(a.fullText),n=s):"content"in a?s=new Pm:"tokenType"in a&&(s=this.hydrateCstLeafNode(a)),s&&(i.set(a,s),s.root=n)}return{astNodes:r,cstNodes:i}}hydrateAstNode(e,r){let i=r.astNodes.get(e);i.$type=e.$type,i.$containerIndex=e.$containerIndex,i.$containerProperty=e.$containerProperty,e.$cstNode&&(i.$cstNode=r.cstNodes.get(e.$cstNode));for(let[n,a]of Object.entries(e))if(!n.startsWith("$"))if(Array.isArray(a)){let s=[];i[n]=s;for(let l of a)_n(l)?s.push(this.setParent(this.hydrateAstNode(l,r),i)):ga(l)?s.push(this.hydrateReference(l,i,n,r)):s.push(l)}else _n(a)?i[n]=this.setParent(this.hydrateAstNode(a,r),i):ga(a)?i[n]=this.hydrateReference(a,i,n,r):a!==void 0&&(i[n]=a);return i}setParent(e,r){return e.$container=r,e}hydrateReference(e,r,i,n){return this.linker.buildReference(r,i,n.cstNodes.get(e.$refNode),e.$refText)}hydrateCstNode(e,r,i=0){let n=r.cstNodes.get(e);if(typeof e.grammarSource=="number"&&(n.grammarSource=this.getGrammarElement(e.grammarSource)),n.astNode=r.astNodes.get(e.astNode),Mc(n))for(let a of e.content){let s=this.hydrateCstNode(a,r,i++);n.content.push(s)}return n}hydrateCstLeafNode(e){let r=this.getTokenType(e.tokenType),i=e.offset,n=e.length,a=e.startLine,s=e.startColumn,l=e.endLine,u=e.endColumn,h=e.hidden;return new Om(i,n,{start:{line:a,character:s},end:{line:l,character:u}},r,h)}getTokenType(e){return this.lexer.definition[e]}getGrammarElementId(e){if(e)return this.grammarElementIdMap.size===0&&this.createGrammarElementIdMap(),this.grammarElementIdMap.get(e)}getGrammarElement(e){return this.grammarElementIdMap.size===0&&this.createGrammarElementIdMap(),this.grammarElementIdMap.getKey(e)}createGrammarElementIdMap(){let e=0;for(let r of js(this.grammar))FT(r)&&this.grammarElementIdMap.set(r,e++)}}});function qn(t){return{documentation:{CommentProvider:o(e=>new dC(e),"CommentProvider"),DocumentationProvider:o(e=>new fC(e),"DocumentationProvider")},parser:{AsyncParser:o(e=>new pC(e),"AsyncParser"),GrammarConfig:o(e=>v$(e),"GrammarConfig"),LangiumParser:o(e=>pG(e),"LangiumParser"),CompletionParser:o(e=>fG(e),"CompletionParser"),ValueConverter:o(()=>new Fm,"ValueConverter"),TokenBuilder:o(()=>new mf,"TokenBuilder"),Lexer:o(e=>new Ym(e),"Lexer"),ParserErrorMessageProvider:o(()=>new gv,"ParserErrorMessageProvider"),LexerErrorMessageProvider:o(()=>new cC,"LexerErrorMessageProvider")},workspace:{AstNodeLocator:o(()=>new Xk,"AstNodeLocator"),AstNodeDescriptionProvider:o(e=>new Yk(e),"AstNodeDescriptionProvider"),ReferenceDescriptionProvider:o(e=>new jk(e),"ReferenceDescriptionProvider")},references:{Linker:o(e=>new Pk(e),"Linker"),NameProvider:o(()=>new Bk,"NameProvider"),ScopeProvider:o(e=>new Vk(e),"ScopeProvider"),ScopeComputation:o(e=>new $k(e),"ScopeComputation"),References:o(e=>new Fk(e),"References")},serializer:{Hydrator:o(e=>new gC(e),"Hydrator"),JsonSerializer:o(e=>new qk(e),"JsonSerializer")},validation:{DocumentValidator:o(e=>new Hk(e),"DocumentValidator"),ValidationRegistry:o(e=>new Uk(e),"ValidationRegistry")},shared:o(()=>t.shared,"shared")}}function Wn(t){return{ServiceRegistry:o(e=>new Wk(e),"ServiceRegistry"),workspace:{LangiumDocuments:o(e=>new Ok(e),"LangiumDocuments"),LangiumDocumentFactory:o(e=>new Mk(e),"LangiumDocumentFactory"),DocumentBuilder:o(e=>new sC(e),"DocumentBuilder"),IndexManager:o(e=>new oC(e),"IndexManager"),WorkspaceManager:o(e=>new lC(e),"WorkspaceManager"),FileSystemProvider:o(e=>t.fileSystemProvider(e),"FileSystemProvider"),WorkspaceLock:o(()=>new mC,"WorkspaceLock"),ConfigurationProvider:o(e=>new Kk(e),"ConfigurationProvider")},profilers:{}}}var Cq=P(()=>{"use strict";x$();dG();mG();wA();gG();SG();AG();_G();DG();NG();IA();MG();OG();OA();PG();BG();FG();aq();Cv();sq();oq();y7();gq();yq();Rk();bq();Tq();kq();o(qn,"createDefaultCoreModule");o(Wn,"createDefaultSharedCoreModule")});function ki(t,e,r,i,n,a,s,l,u){let h=[t,e,r,i,n,a,s,l,u].reduce(yC,{});return eCe(h)}function Jke(t){if(t&&t[Zke])for(let e of Object.values(t))Jke(e);return t}function eCe(t,e){let r=new Proxy({},{deleteProperty:o(()=>!1,"deleteProperty"),set:o(()=>{throw new Error("Cannot set property on injected service container")},"set"),get:o((i,n)=>n===Zke?!0:Qke(i,n,t,e||r),"get"),getOwnPropertyDescriptor:o((i,n)=>(Qke(i,n,t,e||r),Object.getOwnPropertyDescriptor(i,n)),"getOwnPropertyDescriptor"),has:o((i,n)=>n in t,"has"),ownKeys:o(()=>[...Object.getOwnPropertyNames(t)],"ownKeys")});return r}function Qke(t,e,r,i){if(e in t){if(t[e]instanceof Error)throw new Error("Construction failure. Please make sure that your dependencies are constructable. Cause: "+t[e]);if(t[e]===Kke)throw new Error('Cycle detected. Please make "'+String(e)+'" lazy. Visit https://langium.org/docs/reference/configuration-services/#resolving-cyclic-dependencies');return t[e]}else if(e in r){let n=r[e];t[e]=Kke;try{t[e]=typeof n=="function"?n(i):eCe(n,i)}catch(a){throw t[e]=a instanceof Error?a:void 0,a}return t[e]}else return}function yC(t,e){if(e){for(let[r,i]of Object.entries(e))if(i!=null)if(typeof i=="object"){let n=t[r];typeof n=="object"&&n!==null?t[r]=yC(n,i):t[r]=yC({},i)}else t[r]=i}return t}var wq,Zke,Kke,Eq=P(()=>{"use strict";(function(t){t.merge=(e,r)=>yC(yC({},e),r)})(wq||(wq={}));o(ki,"inject");Zke=Symbol("isProxy");o(Jke,"eagerLoad");o(eCe,"_inject");Kke=Symbol();o(Qke,"_resolve");o(yC,"_merge")});var tCe=P(()=>{"use strict"});var rCe=P(()=>{"use strict";yq();gq();mq()});var iCe=P(()=>{"use strict"});var nCe=P(()=>{"use strict";x$();iCe()});var Sq,jm,b7,Aq,aCe=P(()=>{"use strict";sp();wA();y7();Sq={indentTokenName:"INDENT",dedentTokenName:"DEDENT",whitespaceTokenName:"WS",ignoreIndentationDelimiters:[]};(function(t){t.REGULAR="indentation-sensitive",t.IGNORE_INDENTATION="ignore-indentation"})(jm||(jm={}));b7=class extends mf{static{o(this,"IndentationAwareTokenBuilder")}constructor(e=Sq){super(),this.indentationStack=[0],this.whitespaceRegExp=/[ \t]+/y,this.options={...Sq,...e},this.indentTokenType=np({name:this.options.indentTokenName,pattern:this.indentMatcher.bind(this),line_breaks:!1}),this.dedentTokenType=np({name:this.options.dedentTokenName,pattern:this.dedentMatcher.bind(this),line_breaks:!1})}buildTokens(e,r){let i=super.buildTokens(e,r);if(!g7(i))throw new Error("Invalid tokens built by default builder");let{indentTokenName:n,dedentTokenName:a,whitespaceTokenName:s,ignoreIndentationDelimiters:l}=this.options,u,h,f,d=[];for(let p of i){for(let[m,g]of l)p.name===m?p.PUSH_MODE=jm.IGNORE_INDENTATION:p.name===g&&(p.POP_MODE=!0);p.name===a?u=p:p.name===n?h=p:p.name===s?f=p:d.push(p)}if(!u||!h||!f)throw new Error("Some indentation/whitespace tokens not found!");return l.length>0?{modes:{[jm.REGULAR]:[u,h,...d,f],[jm.IGNORE_INDENTATION]:[...d,f]},defaultMode:jm.REGULAR}:[u,h,f,...d]}flushLexingReport(e){return{...super.flushLexingReport(e),remainingDedents:this.flushRemainingDedents(e)}}isStartOfLine(e,r){return r===0||`\r +`.includes(e[r-1])}matchWhitespace(e,r,i,n){this.whitespaceRegExp.lastIndex=r;let a=this.whitespaceRegExp.exec(e);return{currIndentLevel:a?.[0].length??0,prevIndentLevel:this.indentationStack.at(-1),match:a}}createIndentationTokenInstance(e,r,i,n){let a=this.getLineNumber(r,n);return hf(e,i,n,n+i.length,a,a,1,i.length)}getLineNumber(e,r){return e.substring(0,r).split(/\r\n|\r|\n/).length}indentMatcher(e,r,i,n){if(!this.isStartOfLine(e,r))return null;let{currIndentLevel:a,prevIndentLevel:s,match:l}=this.matchWhitespace(e,r,i,n);return a<=s?null:(this.indentationStack.push(a),l)}dedentMatcher(e,r,i,n){if(!this.isStartOfLine(e,r))return null;let{currIndentLevel:a,prevIndentLevel:s,match:l}=this.matchWhitespace(e,r,i,n);if(a>=s)return null;let u=this.indentationStack.lastIndexOf(a);if(u===-1)return this.diagnostics.push({severity:"error",message:`Invalid dedent level ${a} at offset: ${r}. Current indentation stack: ${this.indentationStack}`,offset:r,length:l?.[0]?.length??0,line:this.getLineNumber(e,r),column:1}),null;let h=this.indentationStack.length-u-1,f=e.substring(0,r).match(/[\r\n]+$/)?.[0].length??1;for(let d=0;d1;)r.push(this.createIndentationTokenInstance(this.dedentTokenType,e,"",e.length)),this.indentationStack.pop();return this.indentationStack=[0],r}},Aq=class extends Ym{static{o(this,"IndentationAwareLexer")}constructor(e){if(super(e),e.parser.TokenBuilder instanceof b7)this.indentationTokenBuilder=e.parser.TokenBuilder;else throw new Error("IndentationAwareLexer requires an accompanying IndentationAwareTokenBuilder")}tokenize(e,r=m7){let i=super.tokenize(e),n=i.report;r?.mode==="full"&&i.tokens.push(...n.remainingDedents),n.remainingDedents=[];let{indentTokenType:a,dedentTokenType:s}=this.indentationTokenBuilder,l=a.tokenTypeIdx,u=s.tokenTypeIdx,h=[],f=i.tokens.length-1;for(let d=0;d=0&&h.push(i.tokens[f]),i.tokens=h,i}}});var sCe=P(()=>{"use strict"});var oCe=P(()=>{"use strict";bq();dG();vA();aCe();mG();Rk();y7();CA();sCe();wA();gG()});var lCe=P(()=>{"use strict";SG();AG();_G();RG();DG();NG()});var cCe=P(()=>{"use strict";kq();IA()});var T7,Un,_q=P(()=>{"use strict";T7=class{static{o(this,"EmptyFileSystemProvider")}stat(e){throw new Error("No file system is available.")}statSync(e){throw new Error("No file system is available.")}async exists(){return!1}existsSync(){return!1}readBinary(){throw new Error("No file system is available.")}readBinarySync(){throw new Error("No file system is available.")}readFile(){throw new Error("No file system is available.")}readFileSync(){throw new Error("No file system is available.")}async readDirectory(){return[]}readDirectorySync(){return[]}},Un={fileSystemProvider:o(()=>new T7,"fileSystemProvider")}});function Fot(){let t=ki(Wn(Un),Bot),e=ki(qn({shared:t}),Pot);return t.ServiceRegistry.register(e),e}function Jl(t){let e=Fot(),r=e.serializer.JsonSerializer.deserialize(t);return e.shared.workspace.LangiumDocumentFactory.fromModel(r,va.parse(`memory:/${r.name??"grammar"}.langium`)),r}var Pot,Bot,uCe=P(()=>{"use strict";Cq();Eq();ol();_q();Wc();Pot={Grammar:o(()=>{},"Grammar"),LanguageMetaData:o(()=>({caseInsensitive:!1,fileExtensions:[".langium"],languageId:"langium"}),"LanguageMetaData")},Bot={AstReflection:o(()=>new Oy,"AstReflection")};o(Fot,"createMinimalGrammarServices");o(Jl,"loadGrammarFromJson")});var li={};ur(li,{AstUtils:()=>XS,BiMap:()=>Gm,Cancellation:()=>$r,ContextCache:()=>Vm,CstUtils:()=>m6,DONE_RESULT:()=>xs,Deferred:()=>eo,Disposable:()=>xp,DisposableCache:()=>Ev,DocumentCache:()=>RA,EMPTY_STREAM:()=>Yd,ErrorWithLocation:()=>Tm,GrammarUtils:()=>k6,MultiMap:()=>Cs,OperationCancelled:()=>jl,Reduction:()=>Ey,RegExpUtils:()=>x6,SimpleCache:()=>Gk,StreamImpl:()=>al,TreeStreamImpl:()=>Wu,URI:()=>va,UriTrie:()=>kv,UriUtils:()=>Vn,WorkspaceCache:()=>Sv,assertCondition:()=>qye,assertUnreachable:()=>Yu,delayNextTick:()=>CG,interruptAndCheck:()=>Dn,isOperationCancelled:()=>Ju,loadGrammarFromJson:()=>Jl,setInterruptionPeriod:()=>u2e,startCancelableOperation:()=>DA,stream:()=>jr});var hCe=P(()=>{"use strict";NA();BA();Kr(li,xn);up();nq();g6();uCe();Xl();Ys();Wc();Ts();Yl();Bc();Vc();Fy()});var fCe=P(()=>{"use strict";OG();OA()});var Dq,k7,dCe=P(()=>{"use strict";up();Dq=class{static{o(this,"DefaultLangiumProfiler")}constructor(e){this.activeCategories=new Set,this.allCategories=new Set(["validating","parsing","linking"]),this.activeCategories=e??new Set(this.allCategories),this.records=new Cs}isActive(e){return this.activeCategories.has(e)}start(...e){e?e.forEach(r=>this.activeCategories.add(r)):this.activeCategories=new Set(this.allCategories)}stop(...e){e?e.forEach(r=>this.activeCategories.delete(r)):this.activeCategories.clear()}createTask(e,r){if(!this.isActive(e))throw new Error(`Category "${e}" is not active.`);return console.log(`Creating profiling task for '${e}.${r}'.`),new k7(i=>this.records.add(e,this.dumpRecord(e,i)),r)}dumpRecord(e,r){console.info(`Task ${e}.${r.identifier} executed in ${r.duration.toFixed(2)}ms and ended at ${r.date.toISOString()}`);let i=[];for(let s of r.entries.keys()){let l=r.entries.get(s),u=l.reduce((h,f)=>h+f);i.push({name:`${r.identifier}.${s}`,count:l.length,duration:u})}let n=r.duration-i.map(s=>s.duration).reduce((s,l)=>s+l,0);i.push({name:r.identifier,count:1,duration:n}),i.sort((s,l)=>l.duration-s.duration);function a(s){return Math.round(100*s)/100}return o(a,"Round"),console.table(i.map(s=>({Element:s.name,Count:s.count,"Self %":a(100*s.duration/r.duration),"Time (ms)":a(s.duration)}))),r}getRecords(...e){return e.length===0?this.records.values():this.records.entries().filter(r=>e.some(i=>i===r[0])).flatMap(r=>r[1])}},k7=class{static{o(this,"ProfilingTask")}constructor(e,r){this.stack=[],this.entries=new Cs,this.addRecord=e,this.identifier=r}start(){if(this.startTime!==void 0)throw new Error(`Task "${this.identifier}" is already started.`);this.startTime=performance.now()}stop(){if(this.startTime===void 0)throw new Error(`Task "${this.identifier}" was not started.`);if(this.stack.length!==0)throw new Error(`Task "${this.identifier}" cannot be stopped before sub-task(s): ${this.stack.map(r=>r.id).join(", ")}.`);let e={identifier:this.identifier,date:new Date,duration:performance.now()-this.startTime,entries:this.entries};this.addRecord(e),this.startTime=void 0,this.entries.clear()}startSubTask(e){this.stack.push({id:e,start:performance.now(),content:0})}stopSubTask(e){let r=this.stack.pop();if(!r)throw new Error(`Task "${this.identifier}.${e}" was not started.`);if(r.id!==e)throw new Error(`Sub-Task "${r.id}" is not already stopped.`);let i=performance.now()-r.start;this.stack.at(-1)!==void 0&&(this.stack[this.stack.length-1].content+=i);let n=i-r.content;this.entries.add(e,n)}}});var pCe=P(()=>{"use strict";PG();BG();FG();aq();Cv();_q();sq();Tq();oq();dCe()});var za={};ur(za,{AbstractAstReflection:()=>sm,AbstractCstNode:()=>Ak,AbstractLangiumParser:()=>_k,AbstractParserErrorMessageProvider:()=>bA,AbstractThreadedAsyncParser:()=>vq,AstUtils:()=>XS,BiMap:()=>Gm,Cancellation:()=>$r,CompositeCstNodeImpl:()=>Pm,ContextCache:()=>Vm,CstNodeBuilder:()=>Sk,CstUtils:()=>m6,DEFAULT_TOKENIZE_OPTIONS:()=>m7,DONE_RESULT:()=>xs,DatatypeSymbol:()=>xA,DefaultAstNodeDescriptionProvider:()=>Yk,DefaultAstNodeLocator:()=>Xk,DefaultAsyncParser:()=>pC,DefaultCommentProvider:()=>dC,DefaultConfigurationProvider:()=>Kk,DefaultDocumentBuilder:()=>sC,DefaultDocumentValidator:()=>Hk,DefaultHydrator:()=>gC,DefaultIndexManager:()=>oC,DefaultJsonSerializer:()=>qk,DefaultLangiumDocumentFactory:()=>Mk,DefaultLangiumDocuments:()=>Ok,DefaultLangiumProfiler:()=>Dq,DefaultLexer:()=>Ym,DefaultLexerErrorMessageProvider:()=>cC,DefaultLinker:()=>Pk,DefaultNameProvider:()=>Bk,DefaultReferenceDescriptionProvider:()=>jk,DefaultReferences:()=>Fk,DefaultScopeComputation:()=>$k,DefaultScopeProvider:()=>Vk,DefaultServiceRegistry:()=>Wk,DefaultTokenBuilder:()=>mf,DefaultValueConverter:()=>Fm,DefaultWorkspaceLock:()=>mC,DefaultWorkspaceManager:()=>lC,Deferred:()=>eo,Disposable:()=>xp,DisposableCache:()=>Ev,DocumentCache:()=>RA,DocumentState:()=>Ur,DocumentValidator:()=>Kl,EMPTY_SCOPE:()=>Bst,EMPTY_STREAM:()=>Yd,EmptyFileSystem:()=>Un,EmptyFileSystemProvider:()=>T7,ErrorWithLocation:()=>Tm,GrammarAST:()=>zT,GrammarUtils:()=>k6,IndentationAwareLexer:()=>Aq,IndentationAwareTokenBuilder:()=>b7,JSDocDocumentationProvider:()=>fC,LangiumCompletionParser:()=>Lk,LangiumParser:()=>Dk,LangiumParserErrorMessageProvider:()=>gv,LeafCstNodeImpl:()=>Om,LexingMode:()=>jm,MapScope:()=>LG,Module:()=>wq,MultiMap:()=>Cs,MultiMapScope:()=>zk,OperationCancelled:()=>jl,ParserWorker:()=>xq,ProfilingTask:()=>k7,Reduction:()=>Ey,RefResolving:()=>zm,RegExpUtils:()=>x6,RootCstNodeImpl:()=>mv,SimpleCache:()=>Gk,StreamImpl:()=>al,StreamScope:()=>wv,TextDocument:()=>bv,TreeStreamImpl:()=>Wu,URI:()=>va,UriTrie:()=>kv,UriUtils:()=>Vn,VALIDATE_EACH_NODE:()=>v2e,ValidationCategory:()=>MA,ValidationRegistry:()=>Uk,ValueConverter:()=>Zu,WorkspaceCache:()=>Sv,assertCondition:()=>qye,assertUnreachable:()=>Yu,createCompletionParser:()=>fG,createDefaultCoreModule:()=>qn,createDefaultSharedCoreModule:()=>Wn,createGrammarConfig:()=>v$,createLangiumParser:()=>pG,createParser:()=>Nk,delayNextTick:()=>CG,diagnosticData:()=>qm,eagerLoad:()=>Jke,getDiagnosticRange:()=>x2e,indentationBuilderDefaultOptions:()=>Sq,inject:()=>ki,interruptAndCheck:()=>Dn,isAstNode:()=>_n,isAstNodeDescription:()=>AF,isAstNodeWithComment:()=>IG,isCompositeCstNode:()=>Mc,isIMultiModeLexerDefinition:()=>cq,isJSDoc:()=>dq,isLeafCstNode:()=>Hd,isLinkingError:()=>om,isMultiReference:()=>nl,isNamed:()=>g2e,isOperationCancelled:()=>Ju,isReference:()=>ga,isRootCstNode:()=>_T,isTokenTypeArray:()=>g7,isTokenTypeDictionary:()=>lq,loadGrammarFromJson:()=>Jl,parseJSDoc:()=>fq,prepareLangiumParser:()=>a2e,setInterruptionPeriod:()=>u2e,startCancelableOperation:()=>DA,stream:()=>jr,toDiagnosticData:()=>b2e,toDiagnosticSeverity:()=>PA});var to=P(()=>{"use strict";Cq();Eq();MG();tCe();Oc();rCe();nCe();oCe();lCe();cCe();hCe();Kr(za,li);fCe();pCe();ol()});function ACe(t){return ec.isInstance(t,ah.$type)}function _Ce(t){return ec.isInstance(t,kC.$type)}function DCe(t){return ec.isInstance(t,Zm.$type)}function LCe(t){return ec.isInstance(t,Tp.$type)}function RCe(t){return ec.isInstance(t,Hv.$type)}function NCe(t){return ec.isInstance(t,Jm.$type)}function ICe(t){return ec.isInstance(t,eg.$type)}function MCe(t){return ec.isInstance(t,tg.$type)}function OCe(t){return ec.isInstance(t,kp.$type)}function PCe(t){return ec.isInstance(t,CC.$type)}function BCe(t){return ec.isInstance(t,rg.$type)}function FCe(t){return ec.isInstance(t,Ga.$type)}var $ot,dt,zq,Gq,Vq,qq,Wq,Uq,Hq,Yq,jq,T4r,C7,w7,vC,Lq,ah,E7,kC,mCe,S7,Rq,Zm,Xm,A7,_7,gCe,qv,nh,Nq,yCe,D7,Iq,Tp,xC,Hv,bC,Mq,TC,L7,Km,Jm,R7,Oq,eg,tg,kp,CC,Pq,N7,bp,Bq,Wv,Fq,Qm,rg,$q,I7,Uv,Ga,$Ce,ec,vCe,zot,xCe,Got,bCe,Vot,TCe,qot,kCe,Wot,CCe,Uot,wCe,Hot,ECe,Yot,SCe,jot,Xot,Kot,Qot,Zot,Jot,elt,tlt,rlt,ilt,xa,Xq,Kq,Qq,Zq,Jq,eW,tW,rW,iW,nlt,alt,slt,olt,tc,yf,Va,llt,ia=P(()=>{"use strict";to();to();to();to();$ot=Object.defineProperty,dt=o((t,e)=>$ot(t,"name",{value:e,configurable:!0}),"__name");(t=>{t.Terminals={ARROW_DIRECTION:/L|R|T|B/,ARROW_GROUP:/\{group\}/,ARROW_INTO:/<|>/,ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,ID:/[\w]([-\w]*\w)?/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/,ARCH_ICON:/\([\w-:]+\)/,ARCH_TITLE:/\[(?:"([^"\\]|\\.)*"|'([^'\\]|\\.)*'|[\w ]+)\]/}})(zq||(zq={}));(t=>{t.Terminals={ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,INT:/0|[1-9][0-9]*(?!\.)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/,REFERENCE:/\w([-\./\w]*[-\w])?/}})(Gq||(Gq={}));(t=>{t.Terminals={ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(Vq||(Vq={}));(t=>{t.Terminals={ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,INT:/0|[1-9][0-9]*(?!\.)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(qq||(qq={}));(t=>{t.Terminals={NUMBER_PIE:/(?:-?[0-9]+\.[0-9]+(?!\.))|(?:-?(0|[1-9][0-9]*)(?!\.))/,ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(Wq||(Wq={}));(t=>{t.Terminals={GRATICULE:/circle|polygon/,BOOLEAN:/true|false/,ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,NUMBER:/(?:[0-9]+\.[0-9]+(?!\.))|(?:0|[1-9][0-9]*(?!\.))/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,ID:/[\w]([-\w]*\w)?/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(Uq||(Uq={}));(t=>{t.Terminals={ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,TREEMAP_KEYWORD:/treemap-beta|treemap/,CLASS_DEF:/classDef\s+([a-zA-Z_][a-zA-Z0-9_]+)(?:\s+([^;\r\n]*))?(?:;)?/,STYLE_SEPARATOR:/:::/,SEPARATOR:/:/,COMMA:/,/,INDENTATION:/[ \t]{1,}/,WS:/[ \t]+/,ML_COMMENT:/\%\%[^\n]*/,NL:/\r?\n/,ID2:/[a-zA-Z_][a-zA-Z0-9_]*/,NUMBER2:/[0-9_\.\,]+/,STRING2:/"[^"]*"|'[^']*'/}})(Hq||(Hq={}));(t=>{t.Terminals={ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,INDENTATION:/[ \t]{1,}/,WS:/[ \t]+/,ML_COMMENT:/\%\%[^\n]*/,NL:/\r?\n/,STRING2:/"[^"]*"|'[^']*'/}})(Yq||(Yq={}));(t=>{t.Terminals={WARDLEY_NUMBER:/[0-9]+\.[0-9]+/,ARROW:/->/,LINK_PORT:/\+<>|\+>|\+|-\.->|>|\+'[^']*'<>|\+'[^']*'<|\+'[^']*'>/,LINK_LABEL:/;[^\n\r]+/,STRATEGY:/build|buy|outsource|market/,KW_WARDLEY:/wardley-beta/,KW_SIZE:/size/,KW_EVOLUTION:/evolution/,KW_ANCHOR:/anchor/,KW_COMPONENT:/component/,KW_LABEL:/label/,KW_INERTIA:/inertia/,KW_EVOLVE:/evolve/,KW_PIPELINE:/pipeline/,KW_NOTE:/note/,KW_ANNOTATIONS:/annotations/,KW_ANNOTATION:/annotation/,KW_ACCELERATOR:/accelerator/,KW_DEACCELERATOR:/deaccelerator/,NAME_WITH_SPACES:/(?!title\s|accTitle|accDescr)[A-Za-z][A-Za-z0-9_()&]*(?:[ \t]+[A-Za-z(][A-Za-z0-9_()&]*)*/,WS:/[ \t]+/,ACC_DESCR:/[\t ]*accDescr(?:[\t ]*:([^\n\r]*?(?=%%)|[^\n\r]*)|\s*{([^}]*)})/,ACC_TITLE:/[\t ]*accTitle[\t ]*:(?:[^\n\r]*?(?=%%)|[^\n\r]*)/,TITLE:/[\t ]*title(?:[\t ][^\n\r]*?(?=%%)|[\t ][^\n\r]*|)/,INT:/0|[1-9][0-9]*(?!\.)/,STRING:/"([^"\\]|\\.)*"|'([^'\\]|\\.)*'/,ID:/[\w]([-\w]*\w)?/,NEWLINE:/\r?\n/,WHITESPACE:/[\t ]+/,YAML:/---[\t ]*\r?\n(?:[\S\s]*?\r?\n)?---(?:\r?\n|(?!\S))/,DIRECTIVE:/[\t ]*%%{[\S\s]*?}%%(?:\r?\n|(?!\S))/,SINGLE_LINE_COMMENT:/[\t ]*%%[^\n\r]*/}})(jq||(jq={}));T4r={...zq.Terminals,...Gq.Terminals,...Vq.Terminals,...qq.Terminals,...Wq.Terminals,...Uq.Terminals,...Yq.Terminals,...Hq.Terminals,...jq.Terminals},C7={$type:"Accelerator",name:"name",x:"x",y:"y"},w7={$type:"Anchor",evolution:"evolution",name:"name",visibility:"visibility"},vC={$type:"Annotation",number:"number",text:"text",x:"x",y:"y"},Lq={$type:"Annotations",x:"x",y:"y"},ah={$type:"Architecture",accDescr:"accDescr",accTitle:"accTitle",edges:"edges",groups:"groups",junctions:"junctions",services:"services",title:"title"};o(ACe,"isArchitecture");dt(ACe,"isArchitecture");E7={$type:"Axis",label:"label",name:"name"},kC={$type:"Branch",name:"name",order:"order"};o(_Ce,"isBranch");dt(_Ce,"isBranch");mCe={$type:"Checkout",branch:"branch"},S7={$type:"CherryPicking",id:"id",parent:"parent",tags:"tags"},Rq={$type:"ClassDefStatement",className:"className",styleText:"styleText"},Zm={$type:"Commit",id:"id",message:"message",tags:"tags",type:"type"};o(DCe,"isCommit");dt(DCe,"isCommit");Xm={$type:"Component",decorator:"decorator",evolution:"evolution",inertia:"inertia",label:"label",name:"name",visibility:"visibility"},A7={$type:"Curve",entries:"entries",label:"label",name:"name"},_7={$type:"Deaccelerator",name:"name",x:"x",y:"y"},gCe={$type:"Decorator",strategy:"strategy"},qv={$type:"Direction",accDescr:"accDescr",accTitle:"accTitle",dir:"dir",statements:"statements",title:"title"},nh={$type:"Edge",lhsDir:"lhsDir",lhsGroup:"lhsGroup",lhsId:"lhsId",lhsInto:"lhsInto",rhsDir:"rhsDir",rhsGroup:"rhsGroup",rhsId:"rhsId",rhsInto:"rhsInto",title:"title"},Nq={$type:"Entry",axis:"axis",value:"value"},yCe={$type:"Evolution",stages:"stages"},D7={$type:"EvolutionStage",boundary:"boundary",name:"name",secondName:"secondName"},Iq={$type:"Evolve",component:"component",target:"target"},Tp={$type:"GitGraph",accDescr:"accDescr",accTitle:"accTitle",statements:"statements",title:"title"};o(LCe,"isGitGraph");dt(LCe,"isGitGraph");xC={$type:"Group",icon:"icon",id:"id",in:"in",title:"title"},Hv={$type:"Info",accDescr:"accDescr",accTitle:"accTitle",title:"title"};o(RCe,"isInfo");dt(RCe,"isInfo");bC={$type:"Item",classSelector:"classSelector",name:"name"},Mq={$type:"Junction",id:"id",in:"in"},TC={$type:"Label",negX:"negX",negY:"negY",offsetX:"offsetX",offsetY:"offsetY"},L7={$type:"Leaf",classSelector:"classSelector",name:"name",value:"value"},Km={$type:"Link",arrow:"arrow",from:"from",fromPort:"fromPort",linkLabel:"linkLabel",to:"to",toPort:"toPort"},Jm={$type:"Merge",branch:"branch",id:"id",tags:"tags",type:"type"};o(NCe,"isMerge");dt(NCe,"isMerge");R7={$type:"Note",evolution:"evolution",text:"text",visibility:"visibility"},Oq={$type:"Option",name:"name",value:"value"},eg={$type:"Packet",accDescr:"accDescr",accTitle:"accTitle",blocks:"blocks",title:"title"};o(ICe,"isPacket");dt(ICe,"isPacket");tg={$type:"PacketBlock",bits:"bits",end:"end",label:"label",start:"start"};o(MCe,"isPacketBlock");dt(MCe,"isPacketBlock");kp={$type:"Pie",accDescr:"accDescr",accTitle:"accTitle",sections:"sections",showData:"showData",title:"title"};o(OCe,"isPie");dt(OCe,"isPie");CC={$type:"PieSection",label:"label",value:"value"};o(PCe,"isPieSection");dt(PCe,"isPieSection");Pq={$type:"Pipeline",components:"components",parent:"parent"},N7={$type:"PipelineComponent",evolution:"evolution",label:"label",name:"name"},bp={$type:"Radar",accDescr:"accDescr",accTitle:"accTitle",axes:"axes",curves:"curves",options:"options",title:"title"},Bq={$type:"Section",classSelector:"classSelector",name:"name"},Wv={$type:"Service",icon:"icon",iconText:"iconText",id:"id",in:"in",title:"title"},Fq={$type:"Size",height:"height",width:"width"},Qm={$type:"Statement"},rg={$type:"Treemap",accDescr:"accDescr",accTitle:"accTitle",title:"title",TreemapRows:"TreemapRows"};o(BCe,"isTreemap");dt(BCe,"isTreemap");$q={$type:"TreemapRow",indent:"indent",item:"item"},I7={$type:"TreeNode",indent:"indent",name:"name"},Uv={$type:"TreeView",accDescr:"accDescr",accTitle:"accTitle",nodes:"nodes",title:"title"},Ga={$type:"Wardley",accDescr:"accDescr",accelerators:"accelerators",accTitle:"accTitle",anchors:"anchors",annotation:"annotation",annotations:"annotations",components:"components",deaccelerators:"deaccelerators",evolution:"evolution",evolves:"evolves",links:"links",notes:"notes",pipelines:"pipelines",size:"size",title:"title"};o(FCe,"isWardley");dt(FCe,"isWardley");$Ce=class extends sm{static{o(this,"MermaidAstReflection")}constructor(){super(...arguments),this.types={Accelerator:{name:C7.$type,properties:{name:{name:C7.name},x:{name:C7.x},y:{name:C7.y}},superTypes:[]},Anchor:{name:w7.$type,properties:{evolution:{name:w7.evolution},name:{name:w7.name},visibility:{name:w7.visibility}},superTypes:[]},Annotation:{name:vC.$type,properties:{number:{name:vC.number},text:{name:vC.text},x:{name:vC.x},y:{name:vC.y}},superTypes:[]},Annotations:{name:Lq.$type,properties:{x:{name:Lq.x},y:{name:Lq.y}},superTypes:[]},Architecture:{name:ah.$type,properties:{accDescr:{name:ah.accDescr},accTitle:{name:ah.accTitle},edges:{name:ah.edges,defaultValue:[]},groups:{name:ah.groups,defaultValue:[]},junctions:{name:ah.junctions,defaultValue:[]},services:{name:ah.services,defaultValue:[]},title:{name:ah.title}},superTypes:[]},Axis:{name:E7.$type,properties:{label:{name:E7.label},name:{name:E7.name}},superTypes:[]},Branch:{name:kC.$type,properties:{name:{name:kC.name},order:{name:kC.order}},superTypes:[Qm.$type]},Checkout:{name:mCe.$type,properties:{branch:{name:mCe.branch}},superTypes:[Qm.$type]},CherryPicking:{name:S7.$type,properties:{id:{name:S7.id},parent:{name:S7.parent},tags:{name:S7.tags,defaultValue:[]}},superTypes:[Qm.$type]},ClassDefStatement:{name:Rq.$type,properties:{className:{name:Rq.className},styleText:{name:Rq.styleText}},superTypes:[]},Commit:{name:Zm.$type,properties:{id:{name:Zm.id},message:{name:Zm.message},tags:{name:Zm.tags,defaultValue:[]},type:{name:Zm.type}},superTypes:[Qm.$type]},Component:{name:Xm.$type,properties:{decorator:{name:Xm.decorator},evolution:{name:Xm.evolution},inertia:{name:Xm.inertia,defaultValue:!1},label:{name:Xm.label},name:{name:Xm.name},visibility:{name:Xm.visibility}},superTypes:[]},Curve:{name:A7.$type,properties:{entries:{name:A7.entries,defaultValue:[]},label:{name:A7.label},name:{name:A7.name}},superTypes:[]},Deaccelerator:{name:_7.$type,properties:{name:{name:_7.name},x:{name:_7.x},y:{name:_7.y}},superTypes:[]},Decorator:{name:gCe.$type,properties:{strategy:{name:gCe.strategy}},superTypes:[]},Direction:{name:qv.$type,properties:{accDescr:{name:qv.accDescr},accTitle:{name:qv.accTitle},dir:{name:qv.dir},statements:{name:qv.statements,defaultValue:[]},title:{name:qv.title}},superTypes:[Tp.$type]},Edge:{name:nh.$type,properties:{lhsDir:{name:nh.lhsDir},lhsGroup:{name:nh.lhsGroup,defaultValue:!1},lhsId:{name:nh.lhsId},lhsInto:{name:nh.lhsInto,defaultValue:!1},rhsDir:{name:nh.rhsDir},rhsGroup:{name:nh.rhsGroup,defaultValue:!1},rhsId:{name:nh.rhsId},rhsInto:{name:nh.rhsInto,defaultValue:!1},title:{name:nh.title}},superTypes:[]},Entry:{name:Nq.$type,properties:{axis:{name:Nq.axis,referenceType:E7.$type},value:{name:Nq.value}},superTypes:[]},Evolution:{name:yCe.$type,properties:{stages:{name:yCe.stages,defaultValue:[]}},superTypes:[]},EvolutionStage:{name:D7.$type,properties:{boundary:{name:D7.boundary},name:{name:D7.name},secondName:{name:D7.secondName}},superTypes:[]},Evolve:{name:Iq.$type,properties:{component:{name:Iq.component},target:{name:Iq.target}},superTypes:[]},GitGraph:{name:Tp.$type,properties:{accDescr:{name:Tp.accDescr},accTitle:{name:Tp.accTitle},statements:{name:Tp.statements,defaultValue:[]},title:{name:Tp.title}},superTypes:[]},Group:{name:xC.$type,properties:{icon:{name:xC.icon},id:{name:xC.id},in:{name:xC.in},title:{name:xC.title}},superTypes:[]},Info:{name:Hv.$type,properties:{accDescr:{name:Hv.accDescr},accTitle:{name:Hv.accTitle},title:{name:Hv.title}},superTypes:[]},Item:{name:bC.$type,properties:{classSelector:{name:bC.classSelector},name:{name:bC.name}},superTypes:[]},Junction:{name:Mq.$type,properties:{id:{name:Mq.id},in:{name:Mq.in}},superTypes:[]},Label:{name:TC.$type,properties:{negX:{name:TC.negX,defaultValue:!1},negY:{name:TC.negY,defaultValue:!1},offsetX:{name:TC.offsetX},offsetY:{name:TC.offsetY}},superTypes:[]},Leaf:{name:L7.$type,properties:{classSelector:{name:L7.classSelector},name:{name:L7.name},value:{name:L7.value}},superTypes:[bC.$type]},Link:{name:Km.$type,properties:{arrow:{name:Km.arrow},from:{name:Km.from},fromPort:{name:Km.fromPort},linkLabel:{name:Km.linkLabel},to:{name:Km.to},toPort:{name:Km.toPort}},superTypes:[]},Merge:{name:Jm.$type,properties:{branch:{name:Jm.branch},id:{name:Jm.id},tags:{name:Jm.tags,defaultValue:[]},type:{name:Jm.type}},superTypes:[Qm.$type]},Note:{name:R7.$type,properties:{evolution:{name:R7.evolution},text:{name:R7.text},visibility:{name:R7.visibility}},superTypes:[]},Option:{name:Oq.$type,properties:{name:{name:Oq.name},value:{name:Oq.value,defaultValue:!1}},superTypes:[]},Packet:{name:eg.$type,properties:{accDescr:{name:eg.accDescr},accTitle:{name:eg.accTitle},blocks:{name:eg.blocks,defaultValue:[]},title:{name:eg.title}},superTypes:[]},PacketBlock:{name:tg.$type,properties:{bits:{name:tg.bits},end:{name:tg.end},label:{name:tg.label},start:{name:tg.start}},superTypes:[]},Pie:{name:kp.$type,properties:{accDescr:{name:kp.accDescr},accTitle:{name:kp.accTitle},sections:{name:kp.sections,defaultValue:[]},showData:{name:kp.showData,defaultValue:!1},title:{name:kp.title}},superTypes:[]},PieSection:{name:CC.$type,properties:{label:{name:CC.label},value:{name:CC.value}},superTypes:[]},Pipeline:{name:Pq.$type,properties:{components:{name:Pq.components,defaultValue:[]},parent:{name:Pq.parent}},superTypes:[]},PipelineComponent:{name:N7.$type,properties:{evolution:{name:N7.evolution},label:{name:N7.label},name:{name:N7.name}},superTypes:[]},Radar:{name:bp.$type,properties:{accDescr:{name:bp.accDescr},accTitle:{name:bp.accTitle},axes:{name:bp.axes,defaultValue:[]},curves:{name:bp.curves,defaultValue:[]},options:{name:bp.options,defaultValue:[]},title:{name:bp.title}},superTypes:[]},Section:{name:Bq.$type,properties:{classSelector:{name:Bq.classSelector},name:{name:Bq.name}},superTypes:[bC.$type]},Service:{name:Wv.$type,properties:{icon:{name:Wv.icon},iconText:{name:Wv.iconText},id:{name:Wv.id},in:{name:Wv.in},title:{name:Wv.title}},superTypes:[]},Size:{name:Fq.$type,properties:{height:{name:Fq.height},width:{name:Fq.width}},superTypes:[]},Statement:{name:Qm.$type,properties:{},superTypes:[]},TreeNode:{name:I7.$type,properties:{indent:{name:I7.indent},name:{name:I7.name}},superTypes:[]},TreeView:{name:Uv.$type,properties:{accDescr:{name:Uv.accDescr},accTitle:{name:Uv.accTitle},nodes:{name:Uv.nodes,defaultValue:[]},title:{name:Uv.title}},superTypes:[]},Treemap:{name:rg.$type,properties:{accDescr:{name:rg.accDescr},accTitle:{name:rg.accTitle},title:{name:rg.title},TreemapRows:{name:rg.TreemapRows,defaultValue:[]}},superTypes:[]},TreemapRow:{name:$q.$type,properties:{indent:{name:$q.indent},item:{name:$q.item}},superTypes:[]},Wardley:{name:Ga.$type,properties:{accDescr:{name:Ga.accDescr},accelerators:{name:Ga.accelerators,defaultValue:[]},accTitle:{name:Ga.accTitle},anchors:{name:Ga.anchors,defaultValue:[]},annotation:{name:Ga.annotation,defaultValue:[]},annotations:{name:Ga.annotations,defaultValue:[]},components:{name:Ga.components,defaultValue:[]},deaccelerators:{name:Ga.deaccelerators,defaultValue:[]},evolution:{name:Ga.evolution},evolves:{name:Ga.evolves,defaultValue:[]},links:{name:Ga.links,defaultValue:[]},notes:{name:Ga.notes,defaultValue:[]},pipelines:{name:Ga.pipelines,defaultValue:[]},size:{name:Ga.size},title:{name:Ga.title}},superTypes:[]}}}static{dt(this,"MermaidAstReflection")}},ec=new $Ce,zot=dt(()=>vCe??(vCe=Jl(`{"$type":"Grammar","isDeclared":true,"name":"ArchitectureGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Architecture","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[],"cardinality":"*"},{"$type":"Keyword","value":"architecture-beta"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Statement","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"groups","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"services","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"junctions","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}},{"$type":"Assignment","feature":"edges","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"LeftPort","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"lhsDir","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"RightPort","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"rhsDir","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Keyword","value":":"}]},"entry":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Arrow","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]},{"$type":"Assignment","feature":"lhsInto","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"--"},{"$type":"Group","elements":[{"$type":"Keyword","value":"-"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]}},{"$type":"Keyword","value":"-"}]}]},{"$type":"Assignment","feature":"rhsInto","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"Group","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"group"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Assignment","feature":"icon","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@28"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},"cardinality":"?"},{"$type":"Group","elements":[{"$type":"Keyword","value":"in"},{"$type":"Assignment","feature":"in","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Service","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"service"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"iconText","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]}},{"$type":"Assignment","feature":"icon","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@28"},"arguments":[]}}],"cardinality":"?"},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},"cardinality":"?"},{"$type":"Group","elements":[{"$type":"Keyword","value":"in"},{"$type":"Assignment","feature":"in","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Junction","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"junction"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"in"},{"$type":"Assignment","feature":"in","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Edge","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"lhsId","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Assignment","feature":"lhsGroup","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},{"$type":"Assignment","feature":"rhsId","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Assignment","feature":"rhsGroup","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"ARROW_DIRECTION","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"L"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"R"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"T"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"B"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARROW_GROUP","definition":{"$type":"RegexToken","regex":"/\\\\{group\\\\}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARROW_INTO","definition":{"$type":"RegexToken","regex":"/<|>/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@18"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@19"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","name":"ARCH_ICON","definition":{"$type":"RegexToken","regex":"/\\\\([\\\\w-:]+\\\\)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARCH_TITLE","definition":{"$type":"RegexToken","regex":"/\\\\[(?:\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'|[\\\\w ]+)\\\\]/","parenthesized":false},"fragment":false,"hidden":false}],"interfaces":[],"types":[]}`)),"ArchitectureGrammarGrammar"),Got=dt(()=>xCe??(xCe=Jl(`{"$type":"Grammar","isDeclared":true,"name":"GitGraphGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"GitGraph","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"gitGraph"},{"$type":"Group","elements":[{"$type":"Keyword","value":"gitGraph"},{"$type":"Keyword","value":":"}]},{"$type":"Keyword","value":"gitGraph:"},{"$type":"Group","elements":[{"$type":"Keyword","value":"gitGraph"},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]},{"$type":"Keyword","value":":"}]}]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]},{"$type":"Assignment","feature":"statements","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Statement","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Direction","definition":{"$type":"Assignment","feature":"dir","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"LR"},{"$type":"Keyword","value":"TB"},{"$type":"Keyword","value":"BT"}]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Commit","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"commit"},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"id:"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"msg:","cardinality":"?"},{"$type":"Assignment","feature":"message","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"tag:"},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"type:"},{"$type":"Assignment","feature":"type","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"NORMAL"},{"$type":"Keyword","value":"REVERSE"},{"$type":"Keyword","value":"HIGHLIGHT"}]}}]}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Branch","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"branch"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"order:"},{"$type":"Assignment","feature":"order","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Merge","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"merge"},{"$type":"Assignment","feature":"branch","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]}},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"id:"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"tag:"},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"type:"},{"$type":"Assignment","feature":"type","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"NORMAL"},{"$type":"Keyword","value":"REVERSE"},{"$type":"Keyword","value":"HIGHLIGHT"}]}}]}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Checkout","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"checkout"},{"$type":"Keyword","value":"switch"}]},{"$type":"Assignment","feature":"branch","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"CherryPicking","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"cherry-pick"},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Keyword","value":"id:"},{"$type":"Assignment","feature":"id","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"tag:"},{"$type":"Assignment","feature":"tags","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"parent:"},{"$type":"Assignment","feature":"parent","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@14"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@15"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","name":"REFERENCE","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\\\w([-\\\\./\\\\w]*[-\\\\w])?/","parenthesized":false},"fragment":false,"hidden":false}],"interfaces":[],"types":[]}`)),"GitGraphGrammarGrammar"),Vot=dt(()=>bCe??(bCe=Jl(`{"$type":"Grammar","isDeclared":true,"name":"InfoGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Info","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"*"},{"$type":"Keyword","value":"info"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"*"},{"$type":"Group","elements":[{"$type":"Keyword","value":"showInfo"},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"*"}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[],"cardinality":"?"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@7"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@8"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`)),"InfoGrammarGrammar"),qot=dt(()=>TCe??(TCe=Jl(`{"$type":"Grammar","isDeclared":true,"name":"PacketGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Packet","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"packet"},{"$type":"Keyword","value":"packet-beta"}]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]},{"$type":"Assignment","feature":"blocks","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PacketBlock","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Assignment","feature":"start","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"-"},{"$type":"Assignment","feature":"end","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}}],"cardinality":"?"}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"+"},{"$type":"Assignment","feature":"bits","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}}]}]},{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@8"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@9"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`)),"PacketGrammarGrammar"),Wot=dt(()=>kCe??(kCe=Jl(`{"$type":"Grammar","isDeclared":true,"name":"PieGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Pie","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"*"},{"$type":"Keyword","value":"pie"},{"$type":"Assignment","feature":"showData","operator":"?=","terminal":{"$type":"Keyword","value":"showData"},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"Assignment","feature":"sections","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PieSection","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Keyword","value":":"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"FLOAT_PIE","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/-?[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT_PIE","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/-?(0|[1-9][0-9]*)(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER_PIE","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@2"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@3"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@11"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@12"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`)),"PieGrammarGrammar"),Uot=dt(()=>CCe??(CCe=Jl(`{"$type":"Grammar","isDeclared":true,"name":"RadarGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Radar","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"Keyword","value":"radar-beta"},{"$type":"Keyword","value":"radar-beta:"},{"$type":"Group","elements":[{"$type":"Keyword","value":"radar-beta"},{"$type":"Keyword","value":":"}]}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Keyword","value":"axis"},{"$type":"Assignment","feature":"axes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"axes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"Keyword","value":"curve"},{"$type":"Assignment","feature":"curves","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"curves","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"options","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"options","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Label","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}},{"$type":"Keyword","value":"]"}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"Axis","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Curve","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[],"cardinality":"?"},{"$type":"Keyword","value":"{"},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},{"$type":"Keyword","value":"}"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Entries","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":","},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"},{"$type":"Assignment","feature":"entries","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"*"}]}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"DetailedEntry","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"axis","operator":"=","terminal":{"$type":"CrossReference","type":{"$ref":"#/rules@2"},"terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},"deprecatedSyntax":false,"isMulti":false}},{"$type":"Keyword","value":":","cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"NumberEntry","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Option","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"showLegend"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"ticks"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"max"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"min"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Keyword","value":"graticule"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"GRATICULE","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"circle"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"polygon"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@15"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@16"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[{"$type":"Interface","name":"Entry","attributes":[{"$type":"TypeAttribute","name":"axis","isOptional":true,"type":{"$type":"ReferenceType","referenceType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@2"}},"isMulti":false}},{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"number"},"isOptional":false}],"superTypes":[]}],"types":[]}`)),"RadarGrammarGrammar"),Hot=dt(()=>wCe??(wCe=Jl(`{"$type":"Grammar","isDeclared":true,"name":"TreemapGrammar","rules":[{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","entry":true,"name":"Treemap","returnType":{"$ref":"#/interfaces@4"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]},{"$type":"Assignment","feature":"TreemapRows","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"TREEMAP_KEYWORD","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"treemap-beta"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"treemap"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"CLASS_DEF","definition":{"$type":"RegexToken","regex":"/classDef\\\\s+([a-zA-Z_][a-zA-Z0-9_]+)(?:\\\\s+([^;\\\\r\\\\n]*))?(?:;)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STYLE_SEPARATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":":::"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"SEPARATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":":"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"COMMA","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":","},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INDENTATION","definition":{"$type":"RegexToken","regex":"/[ \\\\t]{1,}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WS","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ML_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\%\\\\%[^\\\\n]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"NL","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false},{"$type":"ParserRule","name":"TreemapRow","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"indent","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"item","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ClassDef","dataType":"string","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Item","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Section","returnType":{"$ref":"#/interfaces@1"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},{"$type":"Assignment","feature":"classSelector","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Leaf","returnType":{"$ref":"#/interfaces@2"},"definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[],"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[],"cardinality":"?"},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},{"$type":"Assignment","feature":"classSelector","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"ID2","definition":{"$type":"RegexToken","regex":"/[a-zA-Z_][a-zA-Z0-9_]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER2","definition":{"$type":"RegexToken","regex":"/[0-9_\\\\.\\\\,]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","name":"MyNumber","dataType":"number","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"STRING2","definition":{"$type":"RegexToken","regex":"/\\"[^\\"]*\\"|'[^']*'/","parenthesized":false},"fragment":false,"hidden":false}],"interfaces":[{"$type":"Interface","name":"Item","attributes":[{"$type":"TypeAttribute","name":"name","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"classSelector","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]},{"$type":"Interface","name":"Section","superTypes":[{"$ref":"#/interfaces@0"}],"attributes":[]},{"$type":"Interface","name":"Leaf","superTypes":[{"$ref":"#/interfaces@0"}],"attributes":[{"$type":"TypeAttribute","name":"value","type":{"$type":"SimpleType","primitiveType":"number"},"isOptional":false}]},{"$type":"Interface","name":"ClassDefStatement","attributes":[{"$type":"TypeAttribute","name":"className","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false},{"$type":"TypeAttribute","name":"styleText","type":{"$type":"SimpleType","primitiveType":"string"},"isOptional":false}],"superTypes":[]},{"$type":"Interface","name":"Treemap","attributes":[{"$type":"TypeAttribute","name":"TreemapRows","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@15"}}},"isOptional":false},{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]}],"imports":[],"types":[],"$comment":"/**\\n * Treemap grammar for Langium\\n * Converted from mindmap grammar\\n *\\n * The ML_COMMENT and NL hidden terminals handle whitespace, comments, and newlines\\n * before the treemap keyword, allowing for empty lines and comments before the\\n * treemap declaration.\\n */"}`)),"TreemapGrammarGrammar"),Yot=dt(()=>ECe??(ECe=Jl(`{"$type":"Grammar","isDeclared":true,"name":"TreeViewGrammar","rules":[{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"ParserRule","entry":true,"name":"TreeView","returnType":{"$ref":"#/interfaces@0"},"definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"treeView-beta"},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[],"cardinality":"?"},{"$type":"Assignment","feature":"nodes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]},"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@0"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"INDENTATION","definition":{"$type":"RegexToken","regex":"/[ \\\\t]{1,}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WS","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"ML_COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\%\\\\%[^\\\\n]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"NL","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false},{"$type":"ParserRule","name":"TreeNode","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"indent","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"STRING2","definition":{"$type":"RegexToken","regex":"/\\"[^\\"]*\\"|'[^']*'/","parenthesized":false},"fragment":false,"hidden":false}],"interfaces":[{"$type":"Interface","name":"TreeView","attributes":[{"$type":"TypeAttribute","name":"nodes","type":{"$type":"ArrayType","elementType":{"$type":"SimpleType","typeRef":{"$ref":"#/rules@9"}}},"isOptional":false},{"$type":"TypeAttribute","name":"title","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accTitle","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}},{"$type":"TypeAttribute","name":"accDescr","isOptional":true,"type":{"$type":"SimpleType","primitiveType":"string"}}],"superTypes":[]}],"imports":[],"types":[],"$comment":"/**\\n * TreeView grammar for Langium\\n * Converted from treemap grammar\\n *\\n * The ML_COMMENT and NL hidden terminals handle whitespace, comments, and newlines\\n * before the treemap keyword, allowing for empty lines and comments before the\\n * treeView declaration.\\n */"}`)),"TreeViewGrammarGrammar"),jot=dt(()=>SCe??(SCe=Jl(`{"$type":"Grammar","isDeclared":true,"name":"WardleyGrammar","imports":[],"rules":[{"$type":"ParserRule","entry":true,"name":"Wardley","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@42"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]}],"cardinality":"*"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"Statement","definition":{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"size","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]}},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]}},{"$type":"Assignment","feature":"anchors","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Assignment","feature":"components","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]}},{"$type":"Assignment","feature":"links","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]}},{"$type":"Assignment","feature":"evolves","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]}},{"$type":"Assignment","feature":"pipelines","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]}},{"$type":"Assignment","feature":"notes","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]}},{"$type":"Assignment","feature":"annotations","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]}},{"$type":"Assignment","feature":"annotation","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]}},{"$type":"Assignment","feature":"accelerators","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}},{"$type":"Assignment","feature":"deaccelerators","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}}]},"entry":false,"parameters":[]},{"$type":"ParserRule","name":"Size","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@26"},"arguments":[]},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"width","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"height","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Evolution","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@27"},"arguments":[]},{"$type":"Assignment","feature":"stages","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]},{"$type":"Assignment","feature":"stages","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}}],"cardinality":"+"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EvolutionStage","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"@"},{"$type":"Assignment","feature":"boundary","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}}],"cardinality":"?"},{"$type":"Group","elements":[{"$type":"Keyword","value":"/"},{"$type":"Assignment","feature":"secondName","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Anchor","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@28"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"visibility","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Component","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"visibility","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"decorator","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},"cardinality":"?"},{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"inertia","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@31"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"inertia","operator":"?=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@31"},"arguments":[]}},{"$type":"Keyword","value":")"}]}],"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Label","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"negX","operator":"?=","terminal":{"$type":"Keyword","value":"-"},"cardinality":"?"},{"$type":"Assignment","feature":"offsetX","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"negY","operator":"?=","terminal":{"$type":"Keyword","value":"-"},"cardinality":"?"},{"$type":"Assignment","feature":"offsetY","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":"]"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Decorator","definition":{"$type":"Group","elements":[{"$type":"Keyword","value":"("},{"$type":"Assignment","feature":"strategy","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]}},{"$type":"Keyword","value":")"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Link","definition":{"$type":"Group","elements":[{"$type":"Assignment","feature":"from","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Assignment","feature":"fromPort","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"arrow","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]}]},"cardinality":"?"},{"$type":"Assignment","feature":"to","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Assignment","feature":"toPort","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"linkLabel","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Evolve","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@32"},"arguments":[]},{"$type":"Assignment","feature":"component","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Assignment","feature":"target","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Pipeline","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@33"},"arguments":[]},{"$type":"Assignment","feature":"parent","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"{"},{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[],"cardinality":"+"},{"$type":"Assignment","feature":"components","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]},"cardinality":"+"},{"$type":"Keyword","value":"}"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PipelineComponent","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Note","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@34"},"arguments":[]},{"$type":"Assignment","feature":"text","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"visibility","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"evolution","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Annotations","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@35"},"arguments":[]},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Annotation","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@36"},"arguments":[]},{"$type":"Assignment","feature":"number","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"Assignment","feature":"text","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"CoordinateValue","dataType":"number","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Accelerator","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@37"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Deaccelerator","definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@38"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}]}},{"$type":"Keyword","value":"["},{"$type":"Assignment","feature":"x","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":","},{"$type":"Assignment","feature":"y","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]}},{"$type":"Keyword","value":"]"},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"WARDLEY_NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARROW","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"->"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LINK_PORT","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"+<>"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"+>"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"+<"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LINK_ARROW","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"-->"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"-.->"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":">"},"parenthesized":false}],"parenthesized":false},{"$type":"RegexToken","regex":"/\\\\+'[^']*'<>/","parenthesized":false}],"parenthesized":false},{"$type":"RegexToken","regex":"/\\\\+'[^']*'/","parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LINK_LABEL","definition":{"$type":"RegexToken","regex":"/;[^\\\\n\\\\r]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRATEGY","definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"build"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"buy"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"outsource"},"parenthesized":false}],"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"market"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_WARDLEY","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"wardley-beta"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_SIZE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"size"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_EVOLUTION","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"evolution"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ANCHOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"anchor"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_COMPONENT","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"component"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_LABEL","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"label"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_INERTIA","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"inertia"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_EVOLVE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"evolve"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_PIPELINE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"pipeline"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_NOTE","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"note"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ANNOTATIONS","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"annotations"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ANNOTATION","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"annotation"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_ACCELERATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"accelerator"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"KW_DEACCELERATOR","definition":{"$type":"CharacterRange","left":{"$type":"Keyword","value":"deaccelerator"},"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NAME_WITH_SPACES","definition":{"$type":"RegexToken","regex":"/(?!title\\\\s|accTitle|accDescr)[A-Za-z][A-Za-z0-9_()&]*(?:[ \\\\t]+[A-Za-z(][A-Za-z0-9_()&]*)*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WS","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+/","parenthesized":false},"fragment":false},{"$type":"ParserRule","name":"EOL","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[],"cardinality":"+"},{"$type":"EndOfFile"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","fragment":true,"name":"TitleAndAccessibilities","definition":{"$type":"Group","elements":[{"$type":"Alternatives","elements":[{"$type":"Assignment","feature":"accDescr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@44"},"arguments":[]}},{"$type":"Assignment","feature":"accTitle","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@45"},"arguments":[]}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@46"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}],"cardinality":"+"},"entry":false,"parameters":[]},{"$type":"TerminalRule","name":"BOOLEAN","type":{"$type":"ReturnType","name":"boolean"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"CharacterRange","left":{"$type":"Keyword","value":"true"},"parenthesized":false},{"$type":"CharacterRange","left":{"$type":"Keyword","value":"false"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_DESCR","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accDescr(?:[\\\\t ]*:([^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)|\\\\s*{([^}]*)})/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ACC_TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*accTitle[\\\\t ]*:(?:[^\\\\n\\\\r]*?(?=%%)|[^\\\\n\\\\r]*)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*title(?:[\\\\t ][^\\\\n\\\\r]*?(?=%%)|[\\\\t ][^\\\\n\\\\r]*|)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]+(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"RegexToken","regex":"/0|[1-9][0-9]*(?!\\\\.)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NUMBER","type":{"$type":"ReturnType","name":"number"},"definition":{"$type":"TerminalAlternatives","elements":[{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@47"},"parenthesized":false},{"$type":"TerminalRuleCall","rule":{"$ref":"#/rules@48"},"parenthesized":false}],"parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STRING","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/\\"([^\\"\\\\\\\\]|\\\\\\\\.)*\\"|'([^'\\\\\\\\]|\\\\\\\\.)*'/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","type":{"$type":"ReturnType","name":"string"},"definition":{"$type":"RegexToken","regex":"/[\\\\w]([-\\\\w]*\\\\w)?/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEWLINE","definition":{"$type":"RegexToken","regex":"/\\\\r?\\\\n/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WHITESPACE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"YAML","definition":{"$type":"RegexToken","regex":"/---[\\\\t ]*\\\\r?\\\\n(?:[\\\\S\\\\s]*?\\\\r?\\\\n)?---(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"DIRECTIVE","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%{[\\\\S\\\\s]*?}%%(?:\\\\r?\\\\n|(?!\\\\S))/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"SINGLE_LINE_COMMENT","definition":{"$type":"RegexToken","regex":"/[\\\\t ]*%%[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false}],"interfaces":[],"types":[]}`)),"WardleyGrammarGrammar"),Xot={languageId:"architecture",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},Kot={languageId:"gitGraph",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},Qot={languageId:"info",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},Zot={languageId:"packet",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},Jot={languageId:"pie",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},elt={languageId:"radar",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},tlt={languageId:"treemap",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},rlt={languageId:"treeView",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},ilt={languageId:"wardley",fileExtensions:[".mmd",".mermaid"],caseInsensitive:!1,mode:"production"},xa={AstReflection:dt(()=>new $Ce,"AstReflection")},Xq={Grammar:dt(()=>zot(),"Grammar"),LanguageMetaData:dt(()=>Xot,"LanguageMetaData"),parser:{}},Kq={Grammar:dt(()=>Got(),"Grammar"),LanguageMetaData:dt(()=>Kot,"LanguageMetaData"),parser:{}},Qq={Grammar:dt(()=>Vot(),"Grammar"),LanguageMetaData:dt(()=>Qot,"LanguageMetaData"),parser:{}},Zq={Grammar:dt(()=>qot(),"Grammar"),LanguageMetaData:dt(()=>Zot,"LanguageMetaData"),parser:{}},Jq={Grammar:dt(()=>Wot(),"Grammar"),LanguageMetaData:dt(()=>Jot,"LanguageMetaData"),parser:{}},eW={Grammar:dt(()=>Uot(),"Grammar"),LanguageMetaData:dt(()=>elt,"LanguageMetaData"),parser:{}},tW={Grammar:dt(()=>Hot(),"Grammar"),LanguageMetaData:dt(()=>tlt,"LanguageMetaData"),parser:{}},rW={Grammar:dt(()=>Yot(),"Grammar"),LanguageMetaData:dt(()=>rlt,"LanguageMetaData"),parser:{}},iW={Grammar:dt(()=>jot(),"Grammar"),LanguageMetaData:dt(()=>ilt,"LanguageMetaData"),parser:{}},nlt=/accDescr(?:[\t ]*:([^\n\r]*)|\s*{([^}]*)})/,alt=/accTitle[\t ]*:([^\n\r]*)/,slt=/title([\t ][^\n\r]*|)/,olt={ACC_DESCR:nlt,ACC_TITLE:alt,TITLE:slt},tc=class extends Fm{static{o(this,"AbstractMermaidValueConverter")}static{dt(this,"AbstractMermaidValueConverter")}runConverter(t,e,r){let i=this.runCommonConverter(t,e,r);return i===void 0&&(i=this.runCustomConverter(t,e,r)),i===void 0?super.runConverter(t,e,r):i}runCommonConverter(t,e,r){let i=olt[t.name];if(i===void 0)return;let n=i.exec(e);if(n!==null){if(n[1]!==void 0)return n[1].trim().replace(/[\t ]{2,}/gm," ");if(n[2]!==void 0)return n[2].replace(/^\s*/gm,"").replace(/\s+$/gm,"").replace(/[\t ]{2,}/gm," ").replace(/[\n\r]{2,}/gm,` +`)}}},yf=class extends tc{static{o(this,"CommonValueConverter")}static{dt(this,"CommonValueConverter")}runCustomConverter(t,e,r){}},Va=class extends mf{static{o(this,"AbstractMermaidTokenBuilder")}static{dt(this,"AbstractMermaidTokenBuilder")}constructor(t){super(),this.keywords=new Set(t)}buildKeywordTokens(t,e,r){let i=super.buildKeywordTokens(t,e,r);return i.forEach(n=>{this.keywords.has(n.name)&&n.PATTERN!==void 0&&(n.PATTERN=new RegExp(n.PATTERN.toString()+"(?:(?=%%)|(?!\\S))"))}),i}},llt=class extends Va{static{o(this,"CommonTokenBuilder")}static{dt(this,"CommonTokenBuilder")}}});function zCe(t){let e=t.validation.TreemapValidator,r=t.validation.ValidationRegistry;if(r){let i={Treemap:e.checkSingleRoot.bind(e)};r.register(i,e)}}function O7(t=Un){let e=ki(Wn(t),xa),r=ki(qn({shared:e}),tW,M7);return e.ServiceRegistry.register(r),zCe(r),{shared:e,Treemap:r}}var clt,ult,hlt,flt,M7,nW=P(()=>{"use strict";ia();to();clt=class extends Va{static{o(this,"TreemapTokenBuilder")}static{dt(this,"TreemapTokenBuilder")}constructor(){super(["treemap"])}},ult=/classDef\s+([A-Z_a-z]\w+)(?:\s+([^\n\r;]*))?;?/,hlt=class extends tc{static{o(this,"TreemapValueConverter")}static{dt(this,"TreemapValueConverter")}runCustomConverter(t,e,r){if(t.name==="NUMBER2")return parseFloat(e.replace(/,/g,""));if(t.name==="SEPARATOR")return e.substring(1,e.length-1);if(t.name==="STRING2")return e.substring(1,e.length-1);if(t.name==="INDENTATION")return e.length;if(t.name==="ClassDef"){if(typeof e!="string")return e;let i=ult.exec(e);if(i)return{$type:"ClassDefStatement",className:i[1],styleText:i[2]||void 0}}}};o(zCe,"registerValidationChecks");dt(zCe,"registerValidationChecks");flt=class{static{o(this,"TreemapValidator")}static{dt(this,"TreemapValidator")}checkSingleRoot(t,e){let r;for(let i of t.TreemapRows)i.item&&(r===void 0&&i.indent===void 0?r=0:i.indent===void 0?e("error","Multiple root nodes are not allowed in a treemap.",{node:i,property:"item"}):r!==void 0&&r>=parseInt(i.indent,10)&&e("error","Multiple root nodes are not allowed in a treemap.",{node:i,property:"item"}))}},M7={parser:{TokenBuilder:dt(()=>new clt,"TokenBuilder"),ValueConverter:dt(()=>new hlt,"ValueConverter")},validation:{TreemapValidator:dt(()=>new flt,"TreemapValidator")}};o(O7,"createTreemapServices");dt(O7,"createTreemapServices")});function B7(t=Un){let e=ki(Wn(t),xa),r=ki(qn({shared:e}),iW,P7);return e.ServiceRegistry.register(r),{shared:e,Wardley:r}}var dlt,P7,aW=P(()=>{"use strict";ia();to();dlt=class extends tc{static{o(this,"WardleyValueConverter")}static{dt(this,"WardleyValueConverter")}runCustomConverter(t,e,r){switch(t.name.toUpperCase()){case"LINK_LABEL":return e.substring(1).trim();default:return}}},P7={parser:{ValueConverter:dt(()=>new dlt,"ValueConverter")}};o(B7,"createWardleyServices");dt(B7,"createWardleyServices")});function $7(t=Un){let e=ki(Wn(t),xa),r=ki(qn({shared:e}),Kq,F7);return e.ServiceRegistry.register(r),{shared:e,GitGraph:r}}var plt,F7,sW=P(()=>{"use strict";ia();to();plt=class extends Va{static{o(this,"GitGraphTokenBuilder")}static{dt(this,"GitGraphTokenBuilder")}constructor(){super(["gitGraph"])}},F7={parser:{TokenBuilder:dt(()=>new plt,"TokenBuilder"),ValueConverter:dt(()=>new yf,"ValueConverter")}};o($7,"createGitGraphServices");dt($7,"createGitGraphServices")});function G7(t=Un){let e=ki(Wn(t),xa),r=ki(qn({shared:e}),Qq,z7);return e.ServiceRegistry.register(r),{shared:e,Info:r}}var mlt,z7,oW=P(()=>{"use strict";ia();to();mlt=class extends Va{static{o(this,"InfoTokenBuilder")}static{dt(this,"InfoTokenBuilder")}constructor(){super(["info","showInfo"])}},z7={parser:{TokenBuilder:dt(()=>new mlt,"TokenBuilder"),ValueConverter:dt(()=>new yf,"ValueConverter")}};o(G7,"createInfoServices");dt(G7,"createInfoServices")});function q7(t=Un){let e=ki(Wn(t),xa),r=ki(qn({shared:e}),Zq,V7);return e.ServiceRegistry.register(r),{shared:e,Packet:r}}var glt,V7,lW=P(()=>{"use strict";ia();to();glt=class extends Va{static{o(this,"PacketTokenBuilder")}static{dt(this,"PacketTokenBuilder")}constructor(){super(["packet"])}},V7={parser:{TokenBuilder:dt(()=>new glt,"TokenBuilder"),ValueConverter:dt(()=>new yf,"ValueConverter")}};o(q7,"createPacketServices");dt(q7,"createPacketServices")});function U7(t=Un){let e=ki(Wn(t),xa),r=ki(qn({shared:e}),Jq,W7);return e.ServiceRegistry.register(r),{shared:e,Pie:r}}var ylt,vlt,W7,cW=P(()=>{"use strict";ia();to();ylt=class extends Va{static{o(this,"PieTokenBuilder")}static{dt(this,"PieTokenBuilder")}constructor(){super(["pie","showData"])}},vlt=class extends tc{static{o(this,"PieValueConverter")}static{dt(this,"PieValueConverter")}runCustomConverter(t,e,r){if(t.name==="PIE_SECTION_LABEL")return e.replace(/"/g,"").trim()}},W7={parser:{TokenBuilder:dt(()=>new ylt,"TokenBuilder"),ValueConverter:dt(()=>new vlt,"ValueConverter")}};o(U7,"createPieServices");dt(U7,"createPieServices")});function Y7(t=Un){let e=ki(Wn(t),xa),r=ki(qn({shared:e}),rW,H7);return e.ServiceRegistry.register(r),{shared:e,TreeView:r}}var xlt,blt,H7,uW=P(()=>{"use strict";ia();to();xlt=class extends tc{static{o(this,"TreeViewValueConverter")}static{dt(this,"TreeViewValueConverter")}runCustomConverter(t,e,r){if(t.name==="INDENTATION")return e?.length||0;if(t.name==="STRING2")return e.substring(1,e.length-1)}},blt=class extends Va{static{o(this,"TreeViewTokenBuilder")}static{dt(this,"TreeViewTokenBuilder")}constructor(){super(["treeView-beta"])}},H7={parser:{TokenBuilder:dt(()=>new blt,"TokenBuilder"),ValueConverter:dt(()=>new xlt,"ValueConverter")}};o(Y7,"createTreeViewServices");dt(Y7,"createTreeViewServices")});function X7(t=Un){let e=ki(Wn(t),xa),r=ki(qn({shared:e}),Xq,j7);return e.ServiceRegistry.register(r),{shared:e,Architecture:r}}var Tlt,klt,j7,hW=P(()=>{"use strict";ia();to();Tlt=class extends Va{static{o(this,"ArchitectureTokenBuilder")}static{dt(this,"ArchitectureTokenBuilder")}constructor(){super(["architecture"])}},klt=class extends tc{static{o(this,"ArchitectureValueConverter")}static{dt(this,"ArchitectureValueConverter")}runCustomConverter(t,e,r){if(t.name==="ARCH_ICON")return e.replace(/[()]/g,"").trim();if(t.name==="ARCH_TEXT_ICON")return e.replace(/["()]/g,"");if(t.name==="ARCH_TITLE"){let i=e.replace(/^\[|]$/g,"").trim();return(i.startsWith('"')&&i.endsWith('"')||i.startsWith("'")&&i.endsWith("'"))&&(i=i.slice(1,-1),i=i.replace(/\\"/g,'"').replace(/\\'/g,"'")),i.trim()}}},j7={parser:{TokenBuilder:dt(()=>new Tlt,"TokenBuilder"),ValueConverter:dt(()=>new klt,"ValueConverter")}};o(X7,"createArchitectureServices");dt(X7,"createArchitectureServices")});function Q7(t=Un){let e=ki(Wn(t),xa),r=ki(qn({shared:e}),eW,K7);return e.ServiceRegistry.register(r),{shared:e,Radar:r}}var Clt,K7,fW=P(()=>{"use strict";ia();to();Clt=class extends Va{static{o(this,"RadarTokenBuilder")}static{dt(this,"RadarTokenBuilder")}constructor(){super(["radar-beta"])}},K7={parser:{TokenBuilder:dt(()=>new Clt,"TokenBuilder"),ValueConverter:dt(()=>new yf,"ValueConverter")}};o(Q7,"createRadarServices");dt(Q7,"createRadarServices")});var GCe={};ur(GCe,{InfoModule:()=>z7,createInfoServices:()=>G7});var VCe=P(()=>{"use strict";oW();ia()});var qCe={};ur(qCe,{PacketModule:()=>V7,createPacketServices:()=>q7});var WCe=P(()=>{"use strict";lW();ia()});var UCe={};ur(UCe,{PieModule:()=>W7,createPieServices:()=>U7});var HCe=P(()=>{"use strict";cW();ia()});var YCe={};ur(YCe,{TreeViewModule:()=>H7,createTreeViewServices:()=>Y7});var jCe=P(()=>{"use strict";uW();ia()});var XCe={};ur(XCe,{ArchitectureModule:()=>j7,createArchitectureServices:()=>X7});var KCe=P(()=>{"use strict";hW();ia()});var QCe={};ur(QCe,{GitGraphModule:()=>F7,createGitGraphServices:()=>$7});var ZCe=P(()=>{"use strict";sW();ia()});var JCe={};ur(JCe,{RadarModule:()=>K7,createRadarServices:()=>Q7});var e4e=P(()=>{"use strict";fW();ia()});var t4e={};ur(t4e,{TreemapModule:()=>M7,createTreemapServices:()=>O7});var r4e=P(()=>{"use strict";nW();ia()});var i4e={};ur(i4e,{WardleyModule:()=>P7,createWardleyServices:()=>B7});var n4e=P(()=>{"use strict";aW();ia()});async function ba(t,e){let r=wlt[t];if(!r)throw new Error(`Unknown diagram type: ${t}`);Yc[t]||await r();let n=Yc[t].parse(e);if(n.lexerErrors.length>0||n.parserErrors.length>0)throw new Elt(n);return n.value}var Yc,wlt,Elt,sh=P(()=>{"use strict";nW();aW();sW();oW();lW();cW();uW();hW();fW();ia();Yc={},wlt={info:dt(async()=>{let{createInfoServices:t}=await Promise.resolve().then(()=>(VCe(),GCe)),e=t().Info.parser.LangiumParser;Yc.info=e},"info"),packet:dt(async()=>{let{createPacketServices:t}=await Promise.resolve().then(()=>(WCe(),qCe)),e=t().Packet.parser.LangiumParser;Yc.packet=e},"packet"),pie:dt(async()=>{let{createPieServices:t}=await Promise.resolve().then(()=>(HCe(),UCe)),e=t().Pie.parser.LangiumParser;Yc.pie=e},"pie"),treeView:dt(async()=>{let{createTreeViewServices:t}=await Promise.resolve().then(()=>(jCe(),YCe)),e=t().TreeView.parser.LangiumParser;Yc.treeView=e},"treeView"),architecture:dt(async()=>{let{createArchitectureServices:t}=await Promise.resolve().then(()=>(KCe(),XCe)),e=t().Architecture.parser.LangiumParser;Yc.architecture=e},"architecture"),gitGraph:dt(async()=>{let{createGitGraphServices:t}=await Promise.resolve().then(()=>(ZCe(),QCe)),e=t().GitGraph.parser.LangiumParser;Yc.gitGraph=e},"gitGraph"),radar:dt(async()=>{let{createRadarServices:t}=await Promise.resolve().then(()=>(e4e(),JCe)),e=t().Radar.parser.LangiumParser;Yc.radar=e},"radar"),treemap:dt(async()=>{let{createTreemapServices:t}=await Promise.resolve().then(()=>(r4e(),t4e)),e=t().Treemap.parser.LangiumParser;Yc.treemap=e},"treemap"),wardley:dt(async()=>{let{createWardleyServices:t}=await Promise.resolve().then(()=>(n4e(),i4e)),e=t().Wardley.parser.LangiumParser;Yc.wardley=e},"wardley")};o(ba,"parse");dt(ba,"parse");Elt=class extends Error{static{o(this,"MermaidParseError")}constructor(t){let e=t.lexerErrors.map(i=>{let n=i.line!==void 0&&!isNaN(i.line)?i.line:"?",a=i.column!==void 0&&!isNaN(i.column)?i.column:"?";return`Lexer error on line ${n}, column ${a}: ${i.message}`}).join(` +`),r=t.parserErrors.map(i=>{let n=i.token.startLine!==void 0&&!isNaN(i.token.startLine)?i.token.startLine:"?",a=i.token.startColumn!==void 0&&!isNaN(i.token.startColumn)?i.token.startColumn:"?";return`Parse error on line ${n}, column ${a}: ${i.message}`}).join(` +`);super(`Parsing failed: ${e} ${r}`),this.result=t}static{dt(this,"MermaidParseError")}}});function Ss(t,e){t.accDescr&&e.setAccDescription?.(t.accDescr),t.accTitle&&e.setAccTitle?.(t.accTitle),t.title&&e.setDiagramTitle?.(t.title)}var vf=P(()=>{"use strict";o(Ss,"populateCommonDb")});var Ci,Z7=P(()=>{"use strict";Ci={NORMAL:0,REVERSE:1,HIGHLIGHT:2,MERGE:3,CHERRY_PICK:4}});var Cp,J7=P(()=>{"use strict";Cp=class{constructor(e){this.init=e;this.records=this.init()}static{o(this,"ImperativeState")}reset(){this.records=this.init()}}});function dW(){return TI({length:7})}function Alt(t,e){let r=Object.create(null);return t.reduce((i,n)=>{let a=e(n);return r[a]||(r[a]=!0,i.push(n)),i},[])}function a4e(t,e,r){let i=t.indexOf(e);i===-1?t.push(r):t.splice(i,1,r)}function o4e(t){let e=t.reduce((n,a)=>n.seq>a.seq?n:a,t[0]),r="";t.forEach(function(n){n===e?r+=" *":r+=" |"});let i=[r,e.id,e.seq];for(let n in Ot.records.branches)Ot.records.branches.get(n)===e.id&&i.push(n);if(Q.debug(i.join(" ")),e.parents&&e.parents.length==2&&e.parents[0]&&e.parents[1]){let n=Ot.records.commits.get(e.parents[0]);a4e(t,e,n),e.parents[1]&&t.push(Ot.records.commits.get(e.parents[1]))}else{if(e.parents.length==0)return;if(e.parents[0]){let n=Ot.records.commits.get(e.parents[0]);a4e(t,e,n)}}t=Alt(t,n=>n.id),o4e(t)}var Slt,ig,Ot,_lt,Dlt,Llt,Rlt,Nlt,Ilt,Mlt,s4e,Olt,Plt,Blt,Flt,$lt,l4e,zlt,Glt,Vlt,e_,pW=P(()=>{"use strict";bt();er();Sr();Vr();Ki();Z7();J7();wa();Slt=fr.gitGraph,ig=o(()=>fi({...Slt,...Lt().gitGraph}),"getConfig"),Ot=new Cp(()=>{let t=ig(),e=t.mainBranchName,r=t.mainBranchOrder;return{mainBranchName:e,commits:new Map,head:null,branchConfig:new Map([[e,{name:e,order:r}]]),branches:new Map([[e,null]]),currBranch:e,direction:"LR",seq:0,options:{}}});o(dW,"getID");o(Alt,"uniqBy");_lt=o(function(t){Ot.records.direction=t},"setDirection"),Dlt=o(function(t){Q.debug("options str",t),t=t?.trim(),t=t||"{}";try{Ot.records.options=JSON.parse(t)}catch(e){Q.error("error while parsing gitGraph options",e.message)}},"setOptions"),Llt=o(function(){return Ot.records.options},"getOptions"),Rlt=o(function(t){let e=t.msg,r=t.id,i=t.type,n=t.tags;Q.info("commit",e,r,i,n),Q.debug("Entering commit:",e,r,i,n);let a=ig();r=lt.sanitizeText(r,a),e=lt.sanitizeText(e,a),n=n?.map(l=>lt.sanitizeText(l,a));let s={id:r||Ot.records.seq+"-"+dW(),message:e,seq:Ot.records.seq++,type:i??Ci.NORMAL,tags:n??[],parents:Ot.records.head==null?[]:[Ot.records.head.id],branch:Ot.records.currBranch};Ot.records.head=s,Q.info("main branch",a.mainBranchName),Ot.records.commits.has(s.id)&&Q.warn(`Commit ID ${s.id} already exists`),Ot.records.commits.set(s.id,s),Ot.records.branches.set(Ot.records.currBranch,s.id),Q.debug("in pushCommit "+s.id)},"commit"),Nlt=o(function(t){let e=t.name,r=t.order;if(e=lt.sanitizeText(e,ig()),Ot.records.branches.has(e))throw new Error(`Trying to create an existing branch. (Help: Either use a new name if you want create a new branch or try using "checkout ${e}")`);Ot.records.branches.set(e,Ot.records.head!=null?Ot.records.head.id:null),Ot.records.branchConfig.set(e,{name:e,order:r}),s4e(e),Q.debug("in createBranch")},"branch"),Ilt=o(t=>{let e=t.branch,r=t.id,i=t.type,n=t.tags,a=ig();e=lt.sanitizeText(e,a),r&&(r=lt.sanitizeText(r,a));let s=Ot.records.branches.get(Ot.records.currBranch),l=Ot.records.branches.get(e),u=s?Ot.records.commits.get(s):void 0,h=l?Ot.records.commits.get(l):void 0;if(u&&h&&u.branch===e)throw new Error(`Cannot merge branch '${e}' into itself.`);if(Ot.records.currBranch===e){let p=new Error('Incorrect usage of "merge". Cannot merge a branch to itself');throw p.hash={text:`merge ${e}`,token:`merge ${e}`,expected:["branch abc"]},p}if(u===void 0||!u){let p=new Error(`Incorrect usage of "merge". Current branch (${Ot.records.currBranch})has no commits`);throw p.hash={text:`merge ${e}`,token:`merge ${e}`,expected:["commit"]},p}if(!Ot.records.branches.has(e)){let p=new Error('Incorrect usage of "merge". Branch to be merged ('+e+") does not exist");throw p.hash={text:`merge ${e}`,token:`merge ${e}`,expected:[`branch ${e}`]},p}if(h===void 0||!h){let p=new Error('Incorrect usage of "merge". Branch to be merged ('+e+") has no commits");throw p.hash={text:`merge ${e}`,token:`merge ${e}`,expected:['"commit"']},p}if(u===h){let p=new Error('Incorrect usage of "merge". Both branches have same head');throw p.hash={text:`merge ${e}`,token:`merge ${e}`,expected:["branch abc"]},p}if(r&&Ot.records.commits.has(r)){let p=new Error('Incorrect usage of "merge". Commit with id:'+r+" already exists, use different custom id");throw p.hash={text:`merge ${e} ${r} ${i} ${n?.join(" ")}`,token:`merge ${e} ${r} ${i} ${n?.join(" ")}`,expected:[`merge ${e} ${r}_UNIQUE ${i} ${n?.join(" ")}`]},p}let f=l||"",d={id:r||`${Ot.records.seq}-${dW()}`,message:`merged branch ${e} into ${Ot.records.currBranch}`,seq:Ot.records.seq++,parents:Ot.records.head==null?[]:[Ot.records.head.id,f],branch:Ot.records.currBranch,type:Ci.MERGE,customType:i,customId:!!r,tags:n??[]};Ot.records.head=d,Ot.records.commits.set(d.id,d),Ot.records.branches.set(Ot.records.currBranch,d.id),Q.debug(Ot.records.branches),Q.debug("in mergeBranch")},"merge"),Mlt=o(function(t){let e=t.id,r=t.targetId,i=t.tags,n=t.parent;Q.debug("Entering cherryPick:",e,r,i);let a=ig();if(e=lt.sanitizeText(e,a),r=lt.sanitizeText(r,a),i=i?.map(u=>lt.sanitizeText(u,a)),n=lt.sanitizeText(n,a),!e||!Ot.records.commits.has(e)){let u=new Error('Incorrect usage of "cherryPick". Source commit id should exist and provided');throw u.hash={text:`cherryPick ${e} ${r}`,token:`cherryPick ${e} ${r}`,expected:["cherry-pick abc"]},u}let s=Ot.records.commits.get(e);if(s===void 0||!s)throw new Error('Incorrect usage of "cherryPick". Source commit id should exist and provided');if(n&&!(Array.isArray(s.parents)&&s.parents.includes(n)))throw new Error("Invalid operation: The specified parent commit is not an immediate parent of the cherry-picked commit.");let l=s.branch;if(s.type===Ci.MERGE&&!n)throw new Error("Incorrect usage of cherry-pick: If the source commit is a merge commit, an immediate parent commit must be specified.");if(!r||!Ot.records.commits.has(r)){if(l===Ot.records.currBranch){let d=new Error('Incorrect usage of "cherryPick". Source commit is already on current branch');throw d.hash={text:`cherryPick ${e} ${r}`,token:`cherryPick ${e} ${r}`,expected:["cherry-pick abc"]},d}let u=Ot.records.branches.get(Ot.records.currBranch);if(u===void 0||!u){let d=new Error(`Incorrect usage of "cherry-pick". Current branch (${Ot.records.currBranch})has no commits`);throw d.hash={text:`cherryPick ${e} ${r}`,token:`cherryPick ${e} ${r}`,expected:["cherry-pick abc"]},d}let h=Ot.records.commits.get(u);if(h===void 0||!h){let d=new Error(`Incorrect usage of "cherry-pick". Current branch (${Ot.records.currBranch})has no commits`);throw d.hash={text:`cherryPick ${e} ${r}`,token:`cherryPick ${e} ${r}`,expected:["cherry-pick abc"]},d}let f={id:Ot.records.seq+"-"+dW(),message:`cherry-picked ${s?.message} into ${Ot.records.currBranch}`,seq:Ot.records.seq++,parents:Ot.records.head==null?[]:[Ot.records.head.id,s.id],branch:Ot.records.currBranch,type:Ci.CHERRY_PICK,tags:i?i.filter(Boolean):[`cherry-pick:${s.id}${s.type===Ci.MERGE?`|parent:${n}`:""}`]};Ot.records.head=f,Ot.records.commits.set(f.id,f),Ot.records.branches.set(Ot.records.currBranch,f.id),Q.debug(Ot.records.branches),Q.debug("in cherryPick")}},"cherryPick"),s4e=o(function(t){if(t=lt.sanitizeText(t,ig()),Ot.records.branches.has(t)){Ot.records.currBranch=t;let e=Ot.records.branches.get(Ot.records.currBranch);e===void 0||!e?Ot.records.head=null:Ot.records.head=Ot.records.commits.get(e)??null}else{let e=new Error(`Trying to checkout branch which is not yet created. (Help try using "branch ${t}")`);throw e.hash={text:`checkout ${t}`,token:`checkout ${t}`,expected:[`branch ${t}`]},e}},"checkout");o(a4e,"upsert");o(o4e,"prettyPrintCommitHistory");Olt=o(function(){Q.debug(Ot.records.commits);let t=l4e()[0];o4e([t])},"prettyPrint"),Plt=o(function(){Ot.reset(),wr()},"clear"),Blt=o(function(){return[...Ot.records.branchConfig.values()].map((e,r)=>e.order!==null&&e.order!==void 0?e:{...e,order:parseFloat(`0.${r}`)}).sort((e,r)=>(e.order??0)-(r.order??0)).map(({name:e})=>({name:e}))},"getBranchesAsObjArray"),Flt=o(function(){return Ot.records.branches},"getBranches"),$lt=o(function(){return Ot.records.commits},"getCommits"),l4e=o(function(){let t=[...Ot.records.commits.values()];return t.forEach(function(e){Q.debug(e.id)}),t.sort((e,r)=>e.seq-r.seq),t},"getCommitsArray"),zlt=o(function(){return Ot.records.currBranch},"getCurrentBranch"),Glt=o(function(){return Ot.records.direction},"getDirection"),Vlt=o(function(){return Ot.records.head},"getHead"),e_={commitType:Ci,getConfig:ig,setDirection:_lt,setOptions:Dlt,getOptions:Llt,commit:Rlt,branch:Nlt,merge:Ilt,cherryPick:Mlt,checkout:s4e,prettyPrint:Olt,clear:Plt,getBranchesAsObjArray:Blt,getBranches:Flt,getCommits:$lt,getCommitsArray:l4e,getCurrentBranch:zlt,getDirection:Glt,getHead:Vlt,setAccTitle:Ar,getAccTitle:Dr,getAccDescription:Rr,setAccDescription:Lr,setDiagramTitle:Mr,getDiagramTitle:Nr}});var qlt,Wlt,Ult,Hlt,Ylt,jlt,Xlt,c4e,u4e=P(()=>{"use strict";sh();bt();vf();pW();Z7();qlt=o((t,e)=>{Ss(t,e),t.dir&&e.setDirection(t.dir);for(let r of t.statements)Wlt(r,e)},"populate"),Wlt=o((t,e)=>{let i={Commit:o(n=>e.commit(Ult(n)),"Commit"),Branch:o(n=>e.branch(Hlt(n)),"Branch"),Merge:o(n=>e.merge(Ylt(n)),"Merge"),Checkout:o(n=>e.checkout(jlt(n)),"Checkout"),CherryPicking:o(n=>e.cherryPick(Xlt(n)),"CherryPicking")}[t.$type];i?i(t):Q.error(`Unknown statement type: ${t.$type}`)},"parseStatement"),Ult=o(t=>({id:t.id,msg:t.message??"",type:t.type!==void 0?Ci[t.type]:Ci.NORMAL,tags:t.tags??void 0}),"parseCommit"),Hlt=o(t=>({name:t.name,order:t.order??0}),"parseBranch"),Ylt=o(t=>({branch:t.branch,id:t.id??"",type:t.type!==void 0?Ci[t.type]:void 0,tags:t.tags??void 0}),"parseMerge"),jlt=o(t=>t.branch,"parseCheckout"),Xlt=o(t=>({id:t.id,targetId:"",tags:t.tags?.length===0?void 0:t.tags,parent:t.parent}),"parseCherryPicking"),c4e={parse:o(async t=>{let e=await ba("gitGraph",t);Q.debug(e),qlt(e,e_)},"parse")}});var wp,Ep,oh,xf,ng,i_,mW,gW,Klt,ag,zo,Go,t_,wC,r_,bf,Zr,Qlt,f4e,d4e,Zlt,Jlt,ect,tct,rct,ict,nct,act,sct,oct,lct,cct,h4e,uct,EC,hct,fct,dct,pct,mct,p4e,m4e=P(()=>{"use strict";Pr();Ut();bt();er();Z7();wp=10,Ep=40,oh=4,xf=2,ng=8,i_=new Set(["redux","redux-dark","redux-color","redux-dark-color"]),mW=12,gW=new Set(["redux-color","redux-dark-color"]),Klt=new Set(["dark","redux-dark","redux-dark-color","neo-dark"]),ag=o((t,e,r=!1)=>r&&t>0?(t-1)%(e-1)+1:t%e,"calcColorIndex"),zo=new Map,Go=new Map,t_=30,wC=new Map,r_=[],bf=0,Zr="LR",Qlt=o(()=>{zo.clear(),Go.clear(),wC.clear(),bf=0,r_=[],Zr="LR"},"clear"),f4e=o(t=>{let e=document.createElementNS("http://www.w3.org/2000/svg","text");return(typeof t=="string"?t.split(/\\n|\n|/gi):t).forEach(i=>{let n=document.createElementNS("http://www.w3.org/2000/svg","tspan");n.setAttributeNS("http://www.w3.org/XML/1998/namespace","xml:space","preserve"),n.setAttribute("dy","1em"),n.setAttribute("x","0"),n.setAttribute("class","row"),n.textContent=i.trim(),e.appendChild(n)}),e},"drawText"),d4e=o(t=>{let e,r,i;return Zr==="BT"?(r=o((n,a)=>n<=a,"comparisonFunc"),i=1/0):(r=o((n,a)=>n>=a,"comparisonFunc"),i=0),t.forEach(n=>{let a=Zr==="TB"||Zr=="BT"?Go.get(n)?.y:Go.get(n)?.x;a!==void 0&&r(a,i)&&(e=n,i=a)}),e},"findClosestParent"),Zlt=o(t=>{let e="",r=1/0;return t.forEach(i=>{let n=Go.get(i).y;n<=r&&(e=i,r=n)}),e||void 0},"findClosestParentBT"),Jlt=o((t,e,r)=>{let i=r,n=r,a=[];t.forEach(s=>{let l=e.get(s);if(!l)throw new Error(`Commit not found for key ${s}`);l.parents.length?(i=tct(l),n=Math.max(i,n)):a.push(l),rct(l,i)}),i=n,a.forEach(s=>{ict(s,i,r)}),t.forEach(s=>{let l=e.get(s);if(l?.parents.length){let u=Zlt(l.parents);i=Go.get(u).y-Ep,i<=n&&(n=i);let h=zo.get(l.branch).pos,f=i-wp;Go.set(l.id,{x:h,y:f})}})},"setParallelBTPos"),ect=o(t=>{let e=d4e(t.parents.filter(i=>i!==null));if(!e)throw new Error(`Closest parent not found for commit ${t.id}`);let r=Go.get(e)?.y;if(r===void 0)throw new Error(`Closest parent position not found for commit ${t.id}`);return r},"findClosestParentPos"),tct=o(t=>ect(t)+Ep,"calculateCommitPosition"),rct=o((t,e)=>{let r=zo.get(t.branch);if(!r)throw new Error(`Branch not found for commit ${t.id}`);let i=r.pos,n=e+wp;return Go.set(t.id,{x:i,y:n}),{x:i,y:n}},"setCommitPosition"),ict=o((t,e,r)=>{let i=zo.get(t.branch);if(!i)throw new Error(`Branch not found for commit ${t.id}`);let n=e+r,a=i.pos;Go.set(t.id,{x:a,y:n})},"setRootPosition"),nct=o((t,e,r,i,n,a)=>{let{theme:s}=ge(),l=i_.has(s??""),u=gW.has(s??""),h=Klt.has(s??"");if(a===Ci.HIGHLIGHT)t.append("rect").attr("x",r.x-10+(l?3:0)).attr("y",r.y-10+(l?3:0)).attr("width",l?14:20).attr("height",l?14:20).attr("class",`commit ${e.id} commit-highlight${ag(n,ng,u)} ${i}-outer`),t.append("rect").attr("x",r.x-6+(l?2:0)).attr("y",r.y-6+(l?2:0)).attr("width",l?8:12).attr("height",l?8:12).attr("class",`commit ${e.id} commit${ag(n,ng,u)} ${i}-inner`);else if(a===Ci.CHERRY_PICK)t.append("circle").attr("cx",r.x).attr("cy",r.y).attr("r",l?7:10).attr("class",`commit ${e.id} ${i}`),t.append("circle").attr("cx",r.x-3).attr("cy",r.y+2).attr("r",l?2.5:2.75).attr("fill",h?"#000000":"#fff").attr("class",`commit ${e.id} ${i}`),t.append("circle").attr("cx",r.x+3).attr("cy",r.y+2).attr("r",l?2.5:2.75).attr("fill",h?"#000000":"#fff").attr("class",`commit ${e.id} ${i}`),t.append("line").attr("x1",r.x+3).attr("y1",r.y+1).attr("x2",r.x).attr("y2",r.y-5).attr("stroke",h?"#000000":"#fff").attr("class",`commit ${e.id} ${i}`),t.append("line").attr("x1",r.x-3).attr("y1",r.y+1).attr("x2",r.x).attr("y2",r.y-5).attr("stroke",h?"#000000":"#fff").attr("class",`commit ${e.id} ${i}`);else{let f=t.append("circle");if(f.attr("cx",r.x),f.attr("cy",r.y),f.attr("r",l?7:10),f.attr("class",`commit ${e.id} commit${ag(n,ng,u)}`),a===Ci.MERGE){let d=t.append("circle");d.attr("cx",r.x),d.attr("cy",r.y),d.attr("r",l?5:6),d.attr("class",`commit ${i} ${e.id} commit${ag(n,ng,u)}`)}if(a===Ci.REVERSE){let d=t.append("path"),p=l?4:5;d.attr("d",`M ${r.x-p},${r.y-p}L${r.x+p},${r.y+p}M${r.x-p},${r.y+p}L${r.x+p},${r.y-p}`).attr("class",`commit ${i} ${e.id} commit${ag(n,ng,u)}`)}}},"drawCommitBullet"),act=o((t,e,r,i,n)=>{if(e.type!==Ci.CHERRY_PICK&&(e.customId&&e.type===Ci.MERGE||e.type!==Ci.MERGE)&&n.showCommitLabel){let a=t.append("g"),s=a.insert("rect").attr("class","commit-label-bkg"),l=a.append("text").attr("x",i).attr("y",r.y+25).attr("class","commit-label").text(e.id),u=l.node()?.getBBox();if(u&&(s.attr("x",r.posWithOffset-u.width/2-xf).attr("y",r.y+13.5).attr("width",u.width+2*xf).attr("height",u.height+2*xf),Zr==="TB"||Zr==="BT"?(s.attr("x",r.x-(u.width+4*oh+5)).attr("y",r.y-12),l.attr("x",r.x-(u.width+4*oh)).attr("y",r.y+u.height-12)):l.attr("x",r.posWithOffset-u.width/2),n.rotateCommitLabel))if(Zr==="TB"||Zr==="BT")l.attr("transform","rotate(-45, "+r.x+", "+r.y+")"),s.attr("transform","rotate(-45, "+r.x+", "+r.y+")");else{let h=-7.5-(u.width+10)/25*9.5,f=10+u.width/25*8.5;a.attr("transform","translate("+h+", "+f+") rotate(-45, "+i+", "+r.y+")")}}},"drawCommitLabel"),sct=o((t,e,r,i)=>{if(e.tags.length>0){let n=0,a=0,s=0,l=[];for(let u of e.tags.reverse()){let h=t.insert("polygon"),f=t.append("circle"),d=t.append("text").attr("y",r.y-16-n).attr("class","tag-label").text(u),p=d.node()?.getBBox();if(!p)throw new Error("Tag bbox not found");a=Math.max(a,p.width),s=Math.max(s,p.height),d.attr("x",r.posWithOffset-p.width/2),l.push({tag:d,hole:f,rect:h,yOffset:n}),n+=20}for(let{tag:u,hole:h,rect:f,yOffset:d}of l){let p=s/2,m=r.y-19.2-d;if(f.attr("class","tag-label-bkg").attr("points",` + ${i-a/2-oh/2},${m+xf} + ${i-a/2-oh/2},${m-xf} + ${r.posWithOffset-a/2-oh},${m-p-xf} + ${r.posWithOffset+a/2+oh},${m-p-xf} + ${r.posWithOffset+a/2+oh},${m+p+xf} + ${r.posWithOffset-a/2-oh},${m+p+xf}`),h.attr("cy",m).attr("cx",i-a/2+oh/2).attr("r",1.5).attr("class","tag-hole"),Zr==="TB"||Zr==="BT"){let g=i+d;f.attr("class","tag-label-bkg").attr("points",` + ${r.x},${g+2} + ${r.x},${g-2} + ${r.x+wp},${g-p-2} + ${r.x+wp+a+4},${g-p-2} + ${r.x+wp+a+4},${g+p+2} + ${r.x+wp},${g+p+2}`).attr("transform","translate(12,12) rotate(45, "+r.x+","+i+")"),h.attr("cx",r.x+oh/2).attr("cy",g).attr("transform","translate(12,12) rotate(45, "+r.x+","+i+")"),u.attr("x",r.x+5).attr("y",g+3).attr("transform","translate(14,14) rotate(45, "+r.x+","+i+")")}}}},"drawCommitTags"),oct=o(t=>{switch(t.customType??t.type){case Ci.NORMAL:return"commit-normal";case Ci.REVERSE:return"commit-reverse";case Ci.HIGHLIGHT:return"commit-highlight";case Ci.MERGE:return"commit-merge";case Ci.CHERRY_PICK:return"commit-cherry-pick";default:return"commit-normal"}},"getCommitClassType"),lct=o((t,e,r,i)=>{let n={x:0,y:0};if(t.parents.length>0){let a=d4e(t.parents);if(a){let s=i.get(a)??n;return e==="TB"?s.y+Ep:e==="BT"?(i.get(t.id)??n).y-Ep:s.x+Ep}}else return e==="TB"?t_:e==="BT"?(i.get(t.id)??n).y-Ep:0;return 0},"calculatePosition"),cct=o((t,e,r)=>{let i=Zr==="BT"&&r?e:e+wp,n=zo.get(t.branch)?.pos,a=Zr==="TB"||Zr==="BT"?zo.get(t.branch)?.pos:i;if(a===void 0||n===void 0)throw new Error(`Position were undefined for commit ${t.id}`);let s=i_.has(ge().theme??""),l=Zr==="TB"||Zr==="BT"?i:n+(s?mW/2+1:-2);return{x:a,y:l,posWithOffset:i}},"getCommitPosition"),h4e=o((t,e,r,i)=>{let n=t.append("g").attr("class","commit-bullets"),a=t.append("g").attr("class","commit-labels"),s=Zr==="TB"||Zr==="BT"?t_:0,l=[...e.keys()],u=i.parallelCommits??!1,h=o((d,p)=>{let m=e.get(d)?.seq,g=e.get(p)?.seq;return m!==void 0&&g!==void 0?m-g:0},"sortKeys"),f=l.sort(h);Zr==="BT"&&(u&&Jlt(f,e,s),f=f.reverse()),f.forEach(d=>{let p=e.get(d);if(!p)throw new Error(`Commit not found for key ${d}`);u&&(s=lct(p,Zr,s,Go));let m=cct(p,s,u);if(r){let g=oct(p),y=p.customType??p.type,v=zo.get(p.branch)?.index??0;nct(n,p,m,g,v,y),act(a,p,m,s,i),sct(a,p,m,s)}Zr==="TB"||Zr==="BT"?Go.set(p.id,{x:m.x,y:m.posWithOffset}):Go.set(p.id,{x:m.posWithOffset,y:m.y}),s=Zr==="BT"&&u?s+Ep:s+Ep+wp,s>bf&&(bf=s)})},"drawCommits"),uct=o((t,e,r,i,n)=>{let s=(Zr==="TB"||Zr==="BT"?r.xh.branch===s,"isOnBranchToGetCurve"),u=o(h=>h.seq>t.seq&&h.sequ(h)&&l(h))},"shouldRerouteArrow"),EC=o((t,e,r=0)=>{let i=t+Math.abs(t-e)/2;if(r>5)return i;if(r_.every(s=>Math.abs(s-i)>=10))return r_.push(i),i;let a=Math.abs(t-e);return EC(t,e-a/5,r+1)},"findLane"),hct=o((t,e,r,i)=>{let{theme:n}=ge(),a=gW.has(n??""),s=Go.get(e.id),l=Go.get(r.id);if(s===void 0||l===void 0)throw new Error(`Commit positions not found for commits ${e.id} and ${r.id}`);let u=uct(e,r,s,l,i),h="",f="",d=0,p=0,m=zo.get(r.branch)?.index;r.type===Ci.MERGE&&e.id!==r.parents[0]&&(m=zo.get(e.branch)?.index);let g;if(u){h="A 10 10, 0, 0, 0,",f="A 10 10, 0, 0, 1,",d=10,p=10;let y=s.yl.x&&(h="A 20 20, 0, 0, 0,",f="A 20 20, 0, 0, 1,",d=20,p=20,r.type===Ci.MERGE&&e.id!==r.parents[0]?g=`M ${s.x} ${s.y} L ${s.x} ${l.y-d} ${f} ${s.x-p} ${l.y} L ${l.x} ${l.y}`:g=`M ${s.x} ${s.y} L ${l.x+d} ${s.y} ${h} ${l.x} ${s.y+p} L ${l.x} ${l.y}`),s.x===l.x&&(g=`M ${s.x} ${s.y} L ${l.x} ${l.y}`)):Zr==="BT"?(s.xl.x&&(h="A 20 20, 0, 0, 0,",f="A 20 20, 0, 0, 1,",d=20,p=20,r.type===Ci.MERGE&&e.id!==r.parents[0]?g=`M ${s.x} ${s.y} L ${s.x} ${l.y+d} ${h} ${s.x-p} ${l.y} L ${l.x} ${l.y}`:g=`M ${s.x} ${s.y} L ${l.x+d} ${s.y} ${f} ${l.x} ${s.y-p} L ${l.x} ${l.y}`),s.x===l.x&&(g=`M ${s.x} ${s.y} L ${l.x} ${l.y}`)):(s.yl.y&&(r.type===Ci.MERGE&&e.id!==r.parents[0]?g=`M ${s.x} ${s.y} L ${l.x-d} ${s.y} ${h} ${l.x} ${s.y-p} L ${l.x} ${l.y}`:g=`M ${s.x} ${s.y} L ${s.x} ${l.y+d} ${f} ${s.x+p} ${l.y} L ${l.x} ${l.y}`),s.y===l.y&&(g=`M ${s.x} ${s.y} L ${l.x} ${l.y}`));if(g===void 0)throw new Error("Line definition not found");t.append("path").attr("d",g).attr("class","arrow arrow"+ag(m,ng,a))},"drawArrow"),fct=o((t,e)=>{let r=t.append("g").attr("class","commit-arrows");[...e.keys()].forEach(i=>{let n=e.get(i);n.parents&&n.parents.length>0&&n.parents.forEach(a=>{hct(r,e.get(a),n,e)})})},"drawArrows"),dct=o((t,e,r,i)=>{let{look:n,theme:a,themeVariables:s}=ge(),{dropShadow:l,THEME_COLOR_LIMIT:u}=s,h=i_.has(a??""),f=gW.has(a??""),d=t.append("g");e.forEach((p,m)=>{let g=ag(m,h?u:ng,f),y=zo.get(p.name)?.pos;if(y===void 0)throw new Error(`Position not found for branch ${p.name}`);let v=Zr==="TB"||Zr==="BT"?y:h?y+mW/2+1:y-2,x=d.append("line");x.attr("x1",0),x.attr("y1",v),x.attr("x2",bf),x.attr("y2",v),x.attr("class","branch branch"+g),Zr==="TB"?(x.attr("y1",t_),x.attr("x1",y),x.attr("y2",bf),x.attr("x2",y)):Zr==="BT"&&(x.attr("y1",bf),x.attr("x1",y),x.attr("y2",t_),x.attr("x2",y)),r_.push(v);let b=p.name,T=f4e(b),w=d.insert("rect"),C=d.insert("g").attr("class","branchLabel").insert("g").attr("class","label branch-label"+g);C.node().appendChild(T);let E=T.getBBox(),S=h?0:4,L=h?16:0,M=h?mW:0;n==="neo"&&w.attr("data-look","neo"),w.attr("class","branchLabelBkg label"+g).attr("style",n==="neo"?`filter:${h?`url(#${i}-drop-shadow)`:l}`:"").attr("rx",S).attr("ry",S).attr("x",-E.width-4-(r.rotateCommitLabel===!0?30:0)).attr("y",-E.height/2+10).attr("width",E.width+18+L).attr("height",E.height+4+M),C.attr("transform","translate("+(-E.width-14-(r.rotateCommitLabel===!0?30:0)+L/2)+", "+(v-E.height/2-2)+")"),Zr==="TB"?(w.attr("x",y-E.width/2-10).attr("y",0),C.attr("transform","translate("+(y-E.width/2-5)+", 0)"),h&&(w.attr("transform",`translate(${-L/2-3}, ${-M-10})`),C.attr("transform","translate("+(y-E.width/2-5)+", "+(-M*2+7)+")"))):Zr==="BT"?(w.attr("x",y-E.width/2-10).attr("y",bf),C.attr("transform","translate("+(y-E.width/2-5)+", "+bf+")"),h&&(w.attr("transform",`translate(${-L/2-3}, ${M+10})`),C.attr("transform","translate("+(y-E.width/2-5)+", "+(bf+M*2+4)+")"))):w.attr("transform","translate(-19, "+(v-12-M/2)+")")})},"drawBranches"),pct=o(function(t,e,r,i,n){return zo.set(t,{pos:e,index:r}),e+=50+(n?40:0)+(Zr==="TB"||Zr==="BT"?i.width/2:0),e},"setBranchPosition"),mct=o(function(t,e,r,i){Qlt(),Q.debug("in gitgraph renderer",t+` +`,"id:",e,r);let n=i.db;if(!n.getConfig){Q.error("getConfig method is not available on db");return}let a=n.getConfig(),s=a.rotateCommitLabel??!1;wC=n.getCommits();let l=n.getBranchesAsObjArray();Zr=n.getDirection();let u=Ze(`[id="${e}"]`),{look:h,theme:f,themeVariables:d}=ge(),{useGradient:p,gradientStart:m,gradientStop:g,filterColor:y}=d;if(p){let x=u.append("defs").append("linearGradient").attr("id",e+"-gradient").attr("gradientUnits","objectBoundingBox").attr("x1","0%").attr("y1","0%").attr("x2","100%").attr("y2","0%");x.append("stop").attr("offset","0%").attr("stop-color",m).attr("stop-opacity",1),x.append("stop").attr("offset","100%").attr("stop-color",g).attr("stop-opacity",1)}h==="neo"&&i_.has(f??"")&&u.append("defs").append("filter").attr("id",e+"-drop-shadow").attr("height","130%").attr("width","130%").append("feDropShadow").attr("dx","4").attr("dy","4").attr("stdDeviation",0).attr("flood-opacity","0.06").attr("flood-color",y);let v=0;l.forEach((x,b)=>{let T=f4e(x.name),w=u.append("g"),k=w.insert("g").attr("class","branchLabel"),C=k.insert("g").attr("class","label branch-label");C.node()?.appendChild(T);let E=T.getBBox();v=pct(x.name,v,b,E,s),C.remove(),k.remove(),w.remove()}),h4e(u,wC,!1,a),a.showBranches&&dct(u,l,a,e),fct(u,wC),h4e(u,wC,!0,a),Kt.insertTitle(u,"gitTitleText",a.titleTopMargin??0,n.getDiagramTitle()),yL(void 0,u,a.diagramPadding,a.useMaxWidth)},"draw"),p4e={draw:mct}});var g4e,y4e,gct,yct,vct,xct,bct,Tct,kct,Cct,v4e,x4e=P(()=>{"use strict";Sr();g4e=8,y4e=new Set(["redux","redux-dark","redux-color","redux-dark-color"]),gct=new Set(["redux-color","redux-dark-color"]),yct=new Set(["neo","neo-dark"]),vct=new Set(["dark","redux-dark","redux-dark-color","neo-dark"]),xct=new Set(["redux","redux-dark","redux-color","redux-dark-color","neo","neo-dark"]),bct=o(t=>{let{svgId:e}=t,r="";if(t.useGradient&&e)for(let i=0;i{let e=Lt(),{theme:r,themeVariables:i}=e,{borderColorArray:n}=i,a=y4e.has(r);if(yct.has(r)){let s="";for(let l=0;l`${Array.from({length:t.THEME_COLOR_LIMIT},(e,r)=>r).map(e=>{let r=e%g4e;return` + .branch-label${e} { fill: ${t["gitBranchLabel"+r]}; } + .commit${e} { stroke: ${t["git"+r]}; fill: ${t["git"+r]}; } + .commit-highlight${e} { stroke: ${t["gitInv"+r]}; fill: ${t["gitInv"+r]}; } + .label${e} { fill: ${t["git"+r]}; } + .arrow${e} { stroke: ${t["git"+r]}; } + `}).join(` +`)}`,"normalTheme"),Cct=o(t=>{let e=Lt(),{theme:r}=e,i=xct.has(r);return` + .commit-id, + .commit-msg, + .branch-label { + fill: lightgrey; + color: lightgrey; + font-family: 'trebuchet ms', verdana, arial, sans-serif; + font-family: var(--mermaid-font-family); + } + + ${i?Tct(t):kct(t)} + + .branch { + stroke-width: ${t.strokeWidth}; + stroke: ${t.commitLineColor??t.lineColor}; + stroke-dasharray: ${i?"4 2":"2"}; + } + .commit-label { font-size: ${t.commitLabelFontSize}; fill: ${i?t.nodeBorder:t.commitLabelColor}; ${i?`font-weight:${t.noteFontWeight};`:""}} + .commit-label-bkg { font-size: ${t.commitLabelFontSize}; fill: ${i?"transparent":t.commitLabelBackground}; opacity: ${i?"":.5}; } + .tag-label { font-size: ${t.tagLabelFontSize}; fill: ${t.tagLabelColor};} + .tag-label-bkg { fill: ${i?t.mainBkg:t.tagLabelBackground}; stroke: ${i?t.nodeBorder:t.tagLabelBorder}; ${i?`filter:${t.dropShadow}`:""} } + .tag-hole { fill: ${t.textColor}; } + + .commit-merge { + stroke: ${i?t.mainBkg:t.primaryColor}; + fill: ${i?t.mainBkg:t.primaryColor}; + } + .commit-reverse { + stroke: ${i?t.mainBkg:t.primaryColor}; + fill: ${i?t.mainBkg:t.primaryColor}; + stroke-width: ${i?t.strokeWidth:3}; + } + .commit-highlight-outer { + } + .commit-highlight-inner { + stroke: ${i?t.mainBkg:t.primaryColor}; + fill: ${i?t.mainBkg:t.primaryColor}; + } + + .arrow { + /* Intentional: neo themes keep the bold 8px arrow (like classic themes); only redux-geometry themes use the thinner options.strokeWidth. */ + stroke-width: ${y4e.has(r)?t.strokeWidth:8}; + stroke-linecap: round; + fill: none + } + .gitTitleText { + text-anchor: middle; + font-size: 18px; + fill: ${t.textColor}; + } +`},"getStyles"),v4e=Cct});var b4e={};ur(b4e,{diagram:()=>wct});var wct,T4e=P(()=>{"use strict";u4e();pW();m4e();x4e();wct={parser:c4e,db:e_,renderer:p4e,styles:v4e}});var yW,w4e,E4e=P(()=>{"use strict";yW=(function(){var t=o(function(_,D,N,R){for(N=N||{},R=_.length;R--;N[_[R]]=D);return N},"o"),e=[6,8,10,12,13,14,15,16,17,18,20,21,22,23,24,25,26,27,28,29,30,31,33,35,36,38,40],r=[1,26],i=[1,27],n=[1,28],a=[1,29],s=[1,30],l=[1,31],u=[1,32],h=[1,33],f=[1,34],d=[1,9],p=[1,10],m=[1,11],g=[1,12],y=[1,13],v=[1,14],x=[1,15],b=[1,16],T=[1,19],w=[1,20],k=[1,21],C=[1,22],E=[1,23],S=[1,25],L=[1,35],M={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,gantt:4,document:5,EOF:6,line:7,SPACE:8,statement:9,NL:10,weekday:11,weekday_monday:12,weekday_tuesday:13,weekday_wednesday:14,weekday_thursday:15,weekday_friday:16,weekday_saturday:17,weekday_sunday:18,weekend:19,weekend_friday:20,weekend_saturday:21,dateFormat:22,inclusiveEndDates:23,topAxis:24,axisFormat:25,tickInterval:26,excludes:27,includes:28,todayMarker:29,title:30,acc_title:31,acc_title_value:32,acc_descr:33,acc_descr_value:34,acc_descr_multiline_value:35,section:36,clickStatement:37,taskTxt:38,taskData:39,click:40,callbackname:41,callbackargs:42,href:43,clickStatementDebug:44,$accept:0,$end:1},terminals_:{2:"error",4:"gantt",6:"EOF",8:"SPACE",10:"NL",12:"weekday_monday",13:"weekday_tuesday",14:"weekday_wednesday",15:"weekday_thursday",16:"weekday_friday",17:"weekday_saturday",18:"weekday_sunday",20:"weekend_friday",21:"weekend_saturday",22:"dateFormat",23:"inclusiveEndDates",24:"topAxis",25:"axisFormat",26:"tickInterval",27:"excludes",28:"includes",29:"todayMarker",30:"title",31:"acc_title",32:"acc_title_value",33:"acc_descr",34:"acc_descr_value",35:"acc_descr_multiline_value",36:"section",38:"taskTxt",39:"taskData",40:"click",41:"callbackname",42:"callbackargs",43:"href"},productions_:[0,[3,3],[5,0],[5,2],[7,2],[7,1],[7,1],[7,1],[11,1],[11,1],[11,1],[11,1],[11,1],[11,1],[11,1],[19,1],[19,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,1],[9,2],[9,2],[9,1],[9,1],[9,1],[9,2],[37,2],[37,3],[37,3],[37,4],[37,3],[37,4],[37,2],[44,2],[44,3],[44,3],[44,4],[44,3],[44,4],[44,2]],performAction:o(function(D,N,R,B,O,$,z){var F=$.length-1;switch(O){case 1:return $[F-1];case 2:this.$=[];break;case 3:$[F-1].push($[F]),this.$=$[F-1];break;case 4:case 5:this.$=$[F];break;case 6:case 7:this.$=[];break;case 8:B.setWeekday("monday");break;case 9:B.setWeekday("tuesday");break;case 10:B.setWeekday("wednesday");break;case 11:B.setWeekday("thursday");break;case 12:B.setWeekday("friday");break;case 13:B.setWeekday("saturday");break;case 14:B.setWeekday("sunday");break;case 15:B.setWeekend("friday");break;case 16:B.setWeekend("saturday");break;case 17:B.setDateFormat($[F].substr(11)),this.$=$[F].substr(11);break;case 18:B.enableInclusiveEndDates(),this.$=$[F].substr(18);break;case 19:B.TopAxis(),this.$=$[F].substr(8);break;case 20:B.setAxisFormat($[F].substr(11)),this.$=$[F].substr(11);break;case 21:B.setTickInterval($[F].substr(13)),this.$=$[F].substr(13);break;case 22:B.setExcludes($[F].substr(9)),this.$=$[F].substr(9);break;case 23:B.setIncludes($[F].substr(9)),this.$=$[F].substr(9);break;case 24:B.setTodayMarker($[F].substr(12)),this.$=$[F].substr(12);break;case 27:B.setDiagramTitle($[F].substr(6)),this.$=$[F].substr(6);break;case 28:this.$=$[F].trim(),B.setAccTitle(this.$);break;case 29:case 30:this.$=$[F].trim(),B.setAccDescription(this.$);break;case 31:B.addSection($[F].substr(8)),this.$=$[F].substr(8);break;case 33:B.addTask($[F-1],$[F]),this.$="task";break;case 34:this.$=$[F-1],B.setClickEvent($[F-1],$[F],null);break;case 35:this.$=$[F-2],B.setClickEvent($[F-2],$[F-1],$[F]);break;case 36:this.$=$[F-2],B.setClickEvent($[F-2],$[F-1],null),B.setLink($[F-2],$[F]);break;case 37:this.$=$[F-3],B.setClickEvent($[F-3],$[F-2],$[F-1]),B.setLink($[F-3],$[F]);break;case 38:this.$=$[F-2],B.setClickEvent($[F-2],$[F],null),B.setLink($[F-2],$[F-1]);break;case 39:this.$=$[F-3],B.setClickEvent($[F-3],$[F-1],$[F]),B.setLink($[F-3],$[F-2]);break;case 40:this.$=$[F-1],B.setLink($[F-1],$[F]);break;case 41:case 47:this.$=$[F-1]+" "+$[F];break;case 42:case 43:case 45:this.$=$[F-2]+" "+$[F-1]+" "+$[F];break;case 44:case 46:this.$=$[F-3]+" "+$[F-2]+" "+$[F-1]+" "+$[F];break}},"anonymous"),table:[{3:1,4:[1,2]},{1:[3]},t(e,[2,2],{5:3}),{6:[1,4],7:5,8:[1,6],9:7,10:[1,8],11:17,12:r,13:i,14:n,15:a,16:s,17:l,18:u,19:18,20:h,21:f,22:d,23:p,24:m,25:g,26:y,27:v,28:x,29:b,30:T,31:w,33:k,35:C,36:E,37:24,38:S,40:L},t(e,[2,7],{1:[2,1]}),t(e,[2,3]),{9:36,11:17,12:r,13:i,14:n,15:a,16:s,17:l,18:u,19:18,20:h,21:f,22:d,23:p,24:m,25:g,26:y,27:v,28:x,29:b,30:T,31:w,33:k,35:C,36:E,37:24,38:S,40:L},t(e,[2,5]),t(e,[2,6]),t(e,[2,17]),t(e,[2,18]),t(e,[2,19]),t(e,[2,20]),t(e,[2,21]),t(e,[2,22]),t(e,[2,23]),t(e,[2,24]),t(e,[2,25]),t(e,[2,26]),t(e,[2,27]),{32:[1,37]},{34:[1,38]},t(e,[2,30]),t(e,[2,31]),t(e,[2,32]),{39:[1,39]},t(e,[2,8]),t(e,[2,9]),t(e,[2,10]),t(e,[2,11]),t(e,[2,12]),t(e,[2,13]),t(e,[2,14]),t(e,[2,15]),t(e,[2,16]),{41:[1,40],43:[1,41]},t(e,[2,4]),t(e,[2,28]),t(e,[2,29]),t(e,[2,33]),t(e,[2,34],{42:[1,42],43:[1,43]}),t(e,[2,40],{41:[1,44]}),t(e,[2,35],{43:[1,45]}),t(e,[2,36]),t(e,[2,38],{42:[1,46]}),t(e,[2,37]),t(e,[2,39])],defaultActions:{},parseError:o(function(D,N){if(N.recoverable)this.trace(D);else{var R=new Error(D);throw R.hash=N,R}},"parseError"),parse:o(function(D){var N=this,R=[0],B=[],O=[null],$=[],z=this.table,F="",V=0,H=0,X=0,W=2,Z=1,Y=$.slice.call(arguments,1),ae=Object.create(this.lexer),J={yy:{}};for(var ee in this.yy)Object.prototype.hasOwnProperty.call(this.yy,ee)&&(J.yy[ee]=this.yy[ee]);ae.setInput(D,J.yy),J.yy.lexer=ae,J.yy.parser=this,typeof ae.yylloc>"u"&&(ae.yylloc={});var re=ae.yylloc;$.push(re);var te=ae.options&&ae.options.ranges;typeof J.yy.parseError=="function"?this.parseError=J.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function be(Me){R.length=R.length-2*Me,O.length=O.length-Me,$.length=$.length-Me}o(be,"popStack");function de(){var Me;return Me=B.pop()||ae.lex()||Z,typeof Me!="number"&&(Me instanceof Array&&(B=Me,Me=B.pop()),Me=N.symbols_[Me]||Me),Me}o(de,"lex");for(var Ee,Ne,we,Te,De,$e,pe={},Je,Ce,Fe,Ue;;){if(we=R[R.length-1],this.defaultActions[we]?Te=this.defaultActions[we]:((Ee===null||typeof Ee>"u")&&(Ee=de()),Te=z[we]&&z[we][Ee]),typeof Te>"u"||!Te.length||!Te[0]){var qe="";Ue=[];for(Je in z[we])this.terminals_[Je]&&Je>W&&Ue.push("'"+this.terminals_[Je]+"'");ae.showPosition?qe="Parse error on line "+(V+1)+`: +`+ae.showPosition()+` +Expecting `+Ue.join(", ")+", got '"+(this.terminals_[Ee]||Ee)+"'":qe="Parse error on line "+(V+1)+": Unexpected "+(Ee==Z?"end of input":"'"+(this.terminals_[Ee]||Ee)+"'"),this.parseError(qe,{text:ae.match,token:this.terminals_[Ee]||Ee,line:ae.yylineno,loc:re,expected:Ue})}if(Te[0]instanceof Array&&Te.length>1)throw new Error("Parse Error: multiple actions possible at state: "+we+", token: "+Ee);switch(Te[0]){case 1:R.push(Ee),O.push(ae.yytext),$.push(ae.yylloc),R.push(Te[1]),Ee=null,Ne?(Ee=Ne,Ne=null):(H=ae.yyleng,F=ae.yytext,V=ae.yylineno,re=ae.yylloc,X>0&&X--);break;case 2:if(Ce=this.productions_[Te[1]][1],pe.$=O[O.length-Ce],pe._$={first_line:$[$.length-(Ce||1)].first_line,last_line:$[$.length-1].last_line,first_column:$[$.length-(Ce||1)].first_column,last_column:$[$.length-1].last_column},te&&(pe._$.range=[$[$.length-(Ce||1)].range[0],$[$.length-1].range[1]]),$e=this.performAction.apply(pe,[F,H,V,J.yy,Te[1],O,$].concat(Y)),typeof $e<"u")return $e;Ce&&(R=R.slice(0,-1*Ce*2),O=O.slice(0,-1*Ce),$=$.slice(0,-1*Ce)),R.push(this.productions_[Te[1]][0]),O.push(pe.$),$.push(pe._$),Fe=z[R[R.length-2]][R[R.length-1]],R.push(Fe);break;case 3:return!0}}return!0},"parse")},I=(function(){var _={EOF:1,parseError:o(function(N,R){if(this.yy.parser)this.yy.parser.parseError(N,R);else throw new Error(N)},"parseError"),setInput:o(function(D,N){return this.yy=N||this.yy||{},this._input=D,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var D=this._input[0];this.yytext+=D,this.yyleng++,this.offset++,this.match+=D,this.matched+=D;var N=D.match(/(?:\r\n?|\n).*/g);return N?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),D},"input"),unput:o(function(D){var N=D.length,R=D.split(/(?:\r\n?|\n)/g);this._input=D+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-N),this.offset-=N;var B=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),R.length-1&&(this.yylineno-=R.length-1);var O=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:R?(R.length===B.length?this.yylloc.first_column:0)+B[B.length-R.length].length-R[0].length:this.yylloc.first_column-N},this.options.ranges&&(this.yylloc.range=[O[0],O[0]+this.yyleng-N]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(D){this.unput(this.match.slice(D))},"less"),pastInput:o(function(){var D=this.matched.substr(0,this.matched.length-this.match.length);return(D.length>20?"...":"")+D.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var D=this.match;return D.length<20&&(D+=this._input.substr(0,20-D.length)),(D.substr(0,20)+(D.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var D=this.pastInput(),N=new Array(D.length+1).join("-");return D+this.upcomingInput()+` +`+N+"^"},"showPosition"),test_match:o(function(D,N){var R,B,O;if(this.options.backtrack_lexer&&(O={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(O.yylloc.range=this.yylloc.range.slice(0))),B=D[0].match(/(?:\r\n?|\n).*/g),B&&(this.yylineno+=B.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:B?B[B.length-1].length-B[B.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+D[0].length},this.yytext+=D[0],this.match+=D[0],this.matches=D,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(D[0].length),this.matched+=D[0],R=this.performAction.call(this,this.yy,this,N,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),R)return R;if(this._backtrack){for(var $ in O)this[$]=O[$];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var D,N,R,B;this._more||(this.yytext="",this.match="");for(var O=this._currentRules(),$=0;$N[0].length)){if(N=R,B=$,this.options.backtrack_lexer){if(D=this.test_match(R,O[$]),D!==!1)return D;if(this._backtrack){N=!1;continue}else return!1}else if(!this.options.flex)break}return N?(D=this.test_match(N,O[B]),D!==!1?D:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var N=this.next();return N||this.lex()},"lex"),begin:o(function(N){this.conditionStack.push(N)},"begin"),popState:o(function(){var N=this.conditionStack.length-1;return N>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(N){return N=this.conditionStack.length-1-Math.abs(N||0),N>=0?this.conditionStack[N]:"INITIAL"},"topState"),pushState:o(function(N){this.begin(N)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:o(function(N,R,B,O){var $=O;switch(B){case 0:return this.begin("open_directive"),"open_directive";break;case 1:return this.begin("acc_title"),31;break;case 2:return this.popState(),"acc_title_value";break;case 3:return this.begin("acc_descr"),33;break;case 4:return this.popState(),"acc_descr_value";break;case 5:this.begin("acc_descr_multiline");break;case 6:this.popState();break;case 7:return"acc_descr_multiline_value";case 8:break;case 9:break;case 10:break;case 11:return 10;case 12:break;case 13:break;case 14:this.begin("href");break;case 15:this.popState();break;case 16:return 43;case 17:this.begin("callbackname");break;case 18:this.popState();break;case 19:this.popState(),this.begin("callbackargs");break;case 20:return 41;case 21:this.popState();break;case 22:return 42;case 23:this.begin("click");break;case 24:this.popState();break;case 25:return 40;case 26:return 4;case 27:return 22;case 28:return 23;case 29:return 24;case 30:return 25;case 31:return 26;case 32:return 28;case 33:return 27;case 34:return 29;case 35:return 12;case 36:return 13;case 37:return 14;case 38:return 15;case 39:return 16;case 40:return 17;case 41:return 18;case 42:return 20;case 43:return 21;case 44:return"date";case 45:return 30;case 46:return"accDescription";case 47:return 36;case 48:return 38;case 49:return 39;case 50:return":";case 51:return 6;case 52:return"INVALID"}},"anonymous"),rules:[/^(?:%%\{)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:%%(?!\{)*[^\n]*)/i,/^(?:[^\}]%%*[^\n]*)/i,/^(?:%%*[^\n]*[\n]*)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:%[^\n]*)/i,/^(?:href[\s]+["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:call[\s]+)/i,/^(?:\([\s]*\))/i,/^(?:\()/i,/^(?:[^(]*)/i,/^(?:\))/i,/^(?:[^)]*)/i,/^(?:click[\s]+)/i,/^(?:[\s\n])/i,/^(?:[^\s\n]*)/i,/^(?:gantt\b)/i,/^(?:dateFormat\s[^#\n;]+)/i,/^(?:inclusiveEndDates\b)/i,/^(?:topAxis\b)/i,/^(?:axisFormat\s[^#\n;]+)/i,/^(?:tickInterval\s[^#\n;]+)/i,/^(?:includes\s[^#\n;]+)/i,/^(?:excludes\s[^#\n;]+)/i,/^(?:todayMarker\s[^\n;]+)/i,/^(?:weekday\s+monday\b)/i,/^(?:weekday\s+tuesday\b)/i,/^(?:weekday\s+wednesday\b)/i,/^(?:weekday\s+thursday\b)/i,/^(?:weekday\s+friday\b)/i,/^(?:weekday\s+saturday\b)/i,/^(?:weekday\s+sunday\b)/i,/^(?:weekend\s+friday\b)/i,/^(?:weekend\s+saturday\b)/i,/^(?:\d\d\d\d-\d\d-\d\d\b)/i,/^(?:title\s[^\n]+)/i,/^(?:accDescription\s[^#\n;]+)/i,/^(?:section\s[^\n]+)/i,/^(?:[^:\n]+)/i,/^(?::[^#\n;]+)/i,/^(?::)/i,/^(?:$)/i,/^(?:.)/i],conditions:{acc_descr_multiline:{rules:[6,7],inclusive:!1},acc_descr:{rules:[4],inclusive:!1},acc_title:{rules:[2],inclusive:!1},callbackargs:{rules:[21,22],inclusive:!1},callbackname:{rules:[18,19,20],inclusive:!1},href:{rules:[15,16],inclusive:!1},click:{rules:[24,25],inclusive:!1},INITIAL:{rules:[0,1,3,5,8,9,10,11,12,13,14,17,23,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52],inclusive:!0}}};return _})();M.lexer=I;function A(){this.yy={}}return o(A,"Parser"),A.prototype=M,M.Parser=A,new A})();yW.parser=yW;w4e=yW});var S4e=ar((vW,xW)=>{"use strict";(function(t,e){typeof vW=="object"&&typeof xW<"u"?xW.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs_plugin_isoWeek=e()})(vW,(function(){"use strict";var t="day";return function(e,r,i){var n=o(function(l){return l.add(4-l.isoWeekday(),t)},"a"),a=r.prototype;a.isoWeekYear=function(){return n(this).year()},a.isoWeek=function(l){if(!this.$utils().u(l))return this.add(7*(l-this.isoWeek()),t);var u,h,f,d,p=n(this),m=(u=this.isoWeekYear(),h=this.$u,f=(h?i.utc:i)().year(u).startOf("year"),d=4-f.isoWeekday(),f.isoWeekday()>4&&(d+=7),f.add(d,t));return p.diff(m,"week")+1},a.isoWeekday=function(l){return this.$utils().u(l)?this.day()||7:this.day(this.day()%7?l:l-7)};var s=a.startOf;a.startOf=function(l,u){var h=this.$utils(),f=!!h.u(u)||u;return h.p(l)==="isoweek"?f?this.date(this.date()-(this.isoWeekday()-1)).startOf("day"):this.date(this.date()-1-(this.isoWeekday()-1)+7).endOf("day"):s.bind(this)(l,u)}}}))});var A4e=ar((bW,TW)=>{"use strict";(function(t,e){typeof bW=="object"&&typeof TW<"u"?TW.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs_plugin_customParseFormat=e()})(bW,(function(){"use strict";var t={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"},e=/(\[[^[]*\])|([-_:/.,()\s]+)|(A|a|Q|YYYY|YY?|ww?|MM?M?M?|Do|DD?|hh?|HH?|mm?|ss?|S{1,3}|z|ZZ?)/g,r=/\d/,i=/\d\d/,n=/\d\d?/,a=/\d*[^-_:/,()\s\d]+/,s={},l=o(function(g){return(g=+g)+(g>68?1900:2e3)},"a"),u=o(function(g){return function(y){this[g]=+y}},"f"),h=[/[+-]\d\d:?(\d\d)?|Z/,function(g){(this.zone||(this.zone={})).offset=(function(y){if(!y||y==="Z")return 0;var v=y.match(/([+-]|\d\d)/g),x=60*v[1]+(+v[2]||0);return x===0?0:v[0]==="+"?-x:x})(g)}],f=o(function(g){var y=s[g];return y&&(y.indexOf?y:y.s.concat(y.f))},"u"),d=o(function(g,y){var v,x=s.meridiem;if(x){for(var b=1;b<=24;b+=1)if(g.indexOf(x(b,0,y))>-1){v=b>12;break}}else v=g===(y?"pm":"PM");return v},"d"),p={A:[a,function(g){this.afternoon=d(g,!1)}],a:[a,function(g){this.afternoon=d(g,!0)}],Q:[r,function(g){this.month=3*(g-1)+1}],S:[r,function(g){this.milliseconds=100*+g}],SS:[i,function(g){this.milliseconds=10*+g}],SSS:[/\d{3}/,function(g){this.milliseconds=+g}],s:[n,u("seconds")],ss:[n,u("seconds")],m:[n,u("minutes")],mm:[n,u("minutes")],H:[n,u("hours")],h:[n,u("hours")],HH:[n,u("hours")],hh:[n,u("hours")],D:[n,u("day")],DD:[i,u("day")],Do:[a,function(g){var y=s.ordinal,v=g.match(/\d+/);if(this.day=v[0],y)for(var x=1;x<=31;x+=1)y(x).replace(/\[|\]/g,"")===g&&(this.day=x)}],w:[n,u("week")],ww:[i,u("week")],M:[n,u("month")],MM:[i,u("month")],MMM:[a,function(g){var y=f("months"),v=(f("monthsShort")||y.map((function(x){return x.slice(0,3)}))).indexOf(g)+1;if(v<1)throw new Error;this.month=v%12||v}],MMMM:[a,function(g){var y=f("months").indexOf(g)+1;if(y<1)throw new Error;this.month=y%12||y}],Y:[/[+-]?\d+/,u("year")],YY:[i,function(g){this.year=l(g)}],YYYY:[/\d{4}/,u("year")],Z:h,ZZ:h};function m(g){var y,v;y=g,v=s&&s.formats;for(var x=(g=y.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,(function(S,L,M){var I=M&&M.toUpperCase();return L||v[M]||t[M]||v[I].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,(function(A,_,D){return _||D.slice(1)}))}))).match(e),b=x.length,T=0;T-1)return new Date((R==="X"?1e3:1)*N);var $=m(R)(N),z=$.year,F=$.month,V=$.day,H=$.hours,X=$.minutes,W=$.seconds,Z=$.milliseconds,Y=$.zone,ae=$.week,J=new Date,ee=V||(z||F?1:J.getDate()),re=z||J.getFullYear(),te=0;z&&!F||(te=F>0?F-1:J.getMonth());var be,de=H||0,Ee=X||0,Ne=W||0,we=Z||0;return Y?new Date(Date.UTC(re,te,ee,de,Ee,Ne,we+60*Y.offset*1e3)):B?new Date(Date.UTC(re,te,ee,de,Ee,Ne,we)):(be=new Date(re,te,ee,de,Ee,Ne,we),ae&&(be=O(be).week(ae).toDate()),be)}catch{return new Date("")}})(w,E,k,v),this.init(),I&&I!==!0&&(this.$L=this.locale(I).$L),M&&w!=this.format(E)&&(this.$d=new Date("")),s={}}else if(E instanceof Array)for(var A=E.length,_=1;_<=A;_+=1){C[1]=E[_-1];var D=v.apply(this,C);if(D.isValid()){this.$d=D.$d,this.$L=D.$L,this.init();break}_===A&&(this.$d=new Date(""))}else b.call(this,T)}}}))});var _4e=ar((kW,CW)=>{"use strict";(function(t,e){typeof kW=="object"&&typeof CW<"u"?CW.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs_plugin_advancedFormat=e()})(kW,(function(){"use strict";return function(t,e){var r=e.prototype,i=r.format;r.format=function(n){var a=this,s=this.$locale();if(!this.isValid())return i.bind(this)(n);var l=this.$utils(),u=(n||"YYYY-MM-DDTHH:mm:ssZ").replace(/\[([^\]]+)]|Q|wo|ww|w|WW|W|zzz|z|gggg|GGGG|Do|X|x|k{1,2}|S/g,(function(h){switch(h){case"Q":return Math.ceil((a.$M+1)/3);case"Do":return s.ordinal(a.$D);case"gggg":return a.weekYear();case"GGGG":return a.isoWeekYear();case"wo":return s.ordinal(a.week(),"W");case"w":case"ww":return l.s(a.week(),h==="w"?1:2,"0");case"W":case"WW":return l.s(a.isoWeek(),h==="W"?1:2,"0");case"k":case"kk":return l.s(String(a.$H===0?24:a.$H),h==="k"?1:2,"0");case"X":return Math.floor(a.$d.getTime()/1e3);case"x":return a.$d.getTime();case"z":return"["+a.offsetName()+"]";case"zzz":return"["+a.offsetName("long")+"]";default:return h}}));return i.bind(this)(u)}}}))});function W4e(t,e,r){let i=!0;for(;i;)i=!1,r.forEach(function(n){let a="^\\s*"+n+"\\s*$",s=new RegExp(a);t[0].match(s)&&(e[n]=!0,t.shift(1),i=!0)})}var R4e,fl,N4e,I4e,M4e,D4e,lh,AW,_W,DW,SC,AC,LW,RW,s_,Xv,NW,O4e,IW,Yv,_C,MW,OW,o_,wW,_ct,Dct,Lct,Rct,Nct,Ict,Mct,Oct,Pct,Bct,Fct,$ct,zct,Gct,Vct,qct,Wct,Uct,Hct,Yct,jct,Xct,Kct,Qct,P4e,Zct,Jct,eut,B4e,tut,EW,F4e,$4e,n_,jv,rut,iut,SW,a_,Ta,z4e,nut,sg,aut,L4e,sut,G4e,out,V4e,lut,cut,q4e,U4e=P(()=>{"use strict";R4e=Wa(s1(),1),fl=Wa(c4(),1),N4e=Wa(S4e(),1),I4e=Wa(A4e(),1),M4e=Wa(_4e(),1);bt();Ut();er();Ki();fl.default.extend(N4e.default);fl.default.extend(I4e.default);fl.default.extend(M4e.default);D4e={friday:5,saturday:6},lh="",AW="",DW="",SC=[],AC=[],LW=new Map,RW=[],s_=[],Xv="",NW="",O4e=["active","done","crit","milestone","vert"],IW=[],Yv="",_C=!1,MW=!1,OW="sunday",o_="saturday",wW=0,_ct=o(function(){RW=[],s_=[],Xv="",IW=[],n_=0,SW=void 0,a_=void 0,Ta=[],lh="",AW="",NW="",_W=void 0,DW="",SC=[],AC=[],_C=!1,MW=!1,wW=0,LW=new Map,Yv="",wr(),OW="sunday",o_="saturday"},"clear"),Dct=o(function(t){Yv=t},"setDiagramId"),Lct=o(function(t){AW=t},"setAxisFormat"),Rct=o(function(){return AW},"getAxisFormat"),Nct=o(function(t){_W=t},"setTickInterval"),Ict=o(function(){return _W},"getTickInterval"),Mct=o(function(t){DW=t},"setTodayMarker"),Oct=o(function(){return DW},"getTodayMarker"),Pct=o(function(t){lh=t},"setDateFormat"),Bct=o(function(){_C=!0},"enableInclusiveEndDates"),Fct=o(function(){return _C},"endDatesAreInclusive"),$ct=o(function(){MW=!0},"enableTopAxis"),zct=o(function(){return MW},"topAxisEnabled"),Gct=o(function(t){NW=t},"setDisplayMode"),Vct=o(function(){return NW},"getDisplayMode"),qct=o(function(){return lh},"getDateFormat"),Wct=o(function(t){SC=t.toLowerCase().split(/[\s,]+/)},"setIncludes"),Uct=o(function(){return SC},"getIncludes"),Hct=o(function(t){AC=t.toLowerCase().split(/[\s,]+/)},"setExcludes"),Yct=o(function(){return AC},"getExcludes"),jct=o(function(){return LW},"getLinks"),Xct=o(function(t){Xv=t,RW.push(t)},"addSection"),Kct=o(function(){return RW},"getSections"),Qct=o(function(){let t=L4e(),e=10,r=0;for(;!t&&r{let u=l.trim();return u==="x"||u==="X"},"isTimestampFormat")(e)&&/^\d+$/.test(r))return new Date(Number(r));let a=/^after\s+(?[\d\w- ]+)/.exec(r);if(a!==null){let l=null;for(let h of a.groups.ids.split(" ")){let f=sg(h);f!==void 0&&(!l||f.endTime>l.endTime)&&(l=f)}if(l)return l.endTime;let u=new Date;return u.setHours(0,0,0,0),u}let s=(0,fl.default)(r,e.trim(),!0);if(s.isValid())return s.toDate();{Q.debug("Invalid date:"+r),Q.debug("With date format:"+e.trim());let l=new Date(r);if(l===void 0||isNaN(l.getTime())||l.getFullYear()<-1e4||l.getFullYear()>1e4)throw new Error("Invalid date:"+r);return l}},"getStartDate"),F4e=o(function(t){let e=/^(\d+(?:\.\d+)?)([Mdhmswy]|ms)$/.exec(t.trim());return e!==null?[Number.parseFloat(e[1]),e[2]]:[NaN,"ms"]},"parseDuration"),$4e=o(function(t,e,r,i=!1){r=r.trim();let a=/^until\s+(?[\d\w- ]+)/.exec(r);if(a!==null){let f=null;for(let p of a.groups.ids.split(" ")){let m=sg(p);m!==void 0&&(!f||m.startTime{window.open(r,"_self")}),LW.set(i,r))}),G4e(t,"clickable")},"setLink"),G4e=o(function(t,e){t.split(",").forEach(function(r){let i=sg(r);i!==void 0&&i.classes.push(e)})},"setClass"),out=o(function(t,e,r){if(ge().securityLevel!=="loose"||e===void 0)return;let i=[];if(typeof r=="string"){i=r.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);for(let a=0;a{Kt.runFunc(e,...i)})},"setClickFun"),V4e=o(function(t,e){IW.push(function(){let r=Yv?`${Yv}-${t}`:t,i=document.querySelector(`[id="${r}"]`);i!==null&&i.addEventListener("click",function(){e()})},function(){let r=Yv?`${Yv}-${t}`:t,i=document.querySelector(`[id="${r}-text"]`);i!==null&&i.addEventListener("click",function(){e()})})},"pushFun"),lut=o(function(t,e,r){t.split(",").forEach(function(i){out(i,e,r)}),G4e(t,"clickable")},"setClickEvent"),cut=o(function(t){IW.forEach(function(e){e(t)})},"bindFunctions"),q4e={getConfig:o(()=>ge().gantt,"getConfig"),clear:_ct,setDateFormat:Pct,getDateFormat:qct,enableInclusiveEndDates:Bct,endDatesAreInclusive:Fct,enableTopAxis:$ct,topAxisEnabled:zct,setAxisFormat:Lct,getAxisFormat:Rct,setTickInterval:Nct,getTickInterval:Ict,setTodayMarker:Mct,getTodayMarker:Oct,setAccTitle:Ar,getAccTitle:Dr,setDiagramTitle:Mr,getDiagramTitle:Nr,setDiagramId:Dct,setDisplayMode:Gct,getDisplayMode:Vct,setAccDescription:Lr,getAccDescription:Rr,addSection:Xct,getSections:Kct,getTasks:Qct,addTask:nut,findTaskById:sg,addTaskOrg:aut,setIncludes:Wct,getIncludes:Uct,setExcludes:Hct,getExcludes:Yct,setClickEvent:lut,setLink:sut,getLinks:jct,bindFunctions:cut,parseDuration:F4e,isInvalidDate:P4e,setWeekday:Zct,getWeekday:Jct,setWeekend:eut};o(W4e,"getTaskTags")});var H4e=ar((PW,BW)=>{"use strict";(function(t,e){typeof PW=="object"&&typeof BW<"u"?BW.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).dayjs_plugin_duration=e()})(PW,(function(){"use strict";var t,e,r=1e3,i=6e4,n=36e5,a=864e5,s=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,l=31536e6,u=2628e6,h=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,f={years:l,months:u,days:a,hours:n,minutes:i,seconds:r,milliseconds:1,weeks:6048e5},d=o(function(w){return w instanceof b},"c"),p=o(function(w,k,C){return new b(w,C,k.$l)},"f"),m=o(function(w){return e.p(w)+"s"},"m"),g=o(function(w){return w<0},"l"),y=o(function(w){return g(w)?Math.ceil(w):Math.floor(w)},"$"),v=o(function(w){return Math.abs(w)},"y"),x=o(function(w,k){return w?g(w)?{negative:!0,format:""+v(w)+k}:{negative:!1,format:""+w+k}:{negative:!1,format:""}},"v"),b=(function(){function w(C,E,S){var L=this;if(this.$d={},this.$l=S,C===void 0&&(this.$ms=0,this.parseFromMilliseconds()),E)return p(C*f[m(E)],this);if(typeof C=="number")return this.$ms=C,this.parseFromMilliseconds(),this;if(typeof C=="object")return Object.keys(C).forEach((function(A){L.$d[m(A)]=C[A]})),this.calMilliseconds(),this;if(typeof C=="string"){var M=C.match(h);if(M){var I=M.slice(2).map((function(A){return A!=null?Number(A):0}));return this.$d.years=I[0],this.$d.months=I[1],this.$d.weeks=I[2],this.$d.days=I[3],this.$d.hours=I[4],this.$d.minutes=I[5],this.$d.seconds=I[6],this.calMilliseconds(),this}}return this}o(w,"l");var k=w.prototype;return k.calMilliseconds=function(){var C=this;this.$ms=Object.keys(this.$d).reduce((function(E,S){return E+(C.$d[S]||0)*f[S]}),0)},k.parseFromMilliseconds=function(){var C=this.$ms;this.$d.years=y(C/l),C%=l,this.$d.months=y(C/u),C%=u,this.$d.days=y(C/a),C%=a,this.$d.hours=y(C/n),C%=n,this.$d.minutes=y(C/i),C%=i,this.$d.seconds=y(C/r),C%=r,this.$d.milliseconds=C},k.toISOString=function(){var C=x(this.$d.years,"Y"),E=x(this.$d.months,"M"),S=+this.$d.days||0;this.$d.weeks&&(S+=7*this.$d.weeks);var L=x(S,"D"),M=x(this.$d.hours,"H"),I=x(this.$d.minutes,"M"),A=this.$d.seconds||0;this.$d.milliseconds&&(A+=this.$d.milliseconds/1e3,A=Math.round(1e3*A)/1e3);var _=x(A,"S"),D=C.negative||E.negative||L.negative||M.negative||I.negative||_.negative,N=M.format||I.format||_.format?"T":"",R=(D?"-":"")+"P"+C.format+E.format+L.format+N+M.format+I.format+_.format;return R==="P"||R==="-P"?"P0D":R},k.toJSON=function(){return this.toISOString()},k.format=function(C){var E=C||"YYYY-MM-DDTHH:mm:ss",S={Y:this.$d.years,YY:e.s(this.$d.years,2,"0"),YYYY:e.s(this.$d.years,4,"0"),M:this.$d.months,MM:e.s(this.$d.months,2,"0"),D:this.$d.days,DD:e.s(this.$d.days,2,"0"),H:this.$d.hours,HH:e.s(this.$d.hours,2,"0"),m:this.$d.minutes,mm:e.s(this.$d.minutes,2,"0"),s:this.$d.seconds,ss:e.s(this.$d.seconds,2,"0"),SSS:e.s(this.$d.milliseconds,3,"0")};return E.replace(s,(function(L,M){return M||String(S[L])}))},k.as=function(C){return this.$ms/f[m(C)]},k.get=function(C){var E=this.$ms,S=m(C);return S==="milliseconds"?E%=1e3:E=S==="weeks"?y(E/f[S]):this.$d[S],E||0},k.add=function(C,E,S){var L;return L=E?C*f[m(E)]:d(C)?C.$ms:p(C,this).$ms,p(this.$ms+L*(S?-1:1),this)},k.subtract=function(C,E){return this.add(C,E,!0)},k.locale=function(C){var E=this.clone();return E.$l=C,E},k.clone=function(){return p(this.$ms,this)},k.humanize=function(C){return t().add(this.$ms,"ms").locale(this.$l).fromNow(!C)},k.valueOf=function(){return this.asMilliseconds()},k.milliseconds=function(){return this.get("milliseconds")},k.asMilliseconds=function(){return this.as("milliseconds")},k.seconds=function(){return this.get("seconds")},k.asSeconds=function(){return this.as("seconds")},k.minutes=function(){return this.get("minutes")},k.asMinutes=function(){return this.as("minutes")},k.hours=function(){return this.get("hours")},k.asHours=function(){return this.as("hours")},k.days=function(){return this.get("days")},k.asDays=function(){return this.as("days")},k.weeks=function(){return this.get("weeks")},k.asWeeks=function(){return this.as("weeks")},k.months=function(){return this.get("months")},k.asMonths=function(){return this.as("months")},k.years=function(){return this.get("years")},k.asYears=function(){return this.as("years")},w})(),T=o(function(w,k,C){return w.add(k.years()*C,"y").add(k.months()*C,"M").add(k.days()*C,"d").add(k.hours()*C,"h").add(k.minutes()*C,"m").add(k.seconds()*C,"s").add(k.milliseconds()*C,"ms")},"p");return function(w,k,C){t=C,e=C().$utils(),C.duration=function(L,M){var I=C.locale();return p(L,{$l:I},M)},C.isDuration=d;var E=k.prototype.add,S=k.prototype.subtract;k.prototype.add=function(L,M){return d(L)?T(this,L,1):E.bind(this)(L,M)},k.prototype.subtract=function(L,M){return d(L)?T(this,L,-1):S.bind(this)(L,M)}}}))});var Kv,j4e,uut,Y4e,hut,Tf,FW,fut,X4e,K4e=P(()=>{"use strict";Kv=Wa(c4(),1),j4e=Wa(H4e(),1);bt();Pr();Vr();Ut();Xi();Kv.default.extend(j4e.default);uut=o(function(){Q.debug("Something is calling, setConf, remove the call")},"setConf"),Y4e={monday:jf,tuesday:Zw,wednesday:Jw,thursday:gu,friday:e3,saturday:t3,sunday:xc},hut=o((t,e)=>{let r=[...t].map(()=>-1/0),i=[...t].sort((a,s)=>a.startTime-s.startTime||a.order-s.order),n=0;for(let a of i)for(let s=0;s=r[s]){r[s]=a.endTime,a.order=s+e,s>n&&(n=s);break}return n},"getMaxIntersections"),FW=1e4,fut=o(function(t,e,r,i){let n=ge().gantt;i.db.setDiagramId(e);let a=ge().securityLevel,s;a==="sandbox"&&(s=Ze("#i"+e));let l=a==="sandbox"?Ze(s.nodes()[0].contentDocument.body):Ze("body"),u=a==="sandbox"?s.nodes()[0].contentDocument:document,h=u.getElementById(e);Tf=h.parentElement.offsetWidth,Tf===void 0&&(Tf=1200),n.useWidth!==void 0&&(Tf=n.useWidth);let f=i.db.getTasks(),d=[];for(let L of f)d.push(L.type);d=S(d);let p={},m=2*n.topPadding;if(i.db.getDisplayMode()==="compact"||n.displayMode==="compact"){let L={};for(let I of f)L[I.section]===void 0?L[I.section]=[I]:L[I.section].push(I);let M=0;for(let I of Object.keys(L)){let A=hut(L[I],M)+1;M+=A,m+=A*(n.barHeight+n.barGap),p[I]=A}}else{m+=f.length*(n.barHeight+n.barGap);for(let L of d)p[L]=f.filter(M=>M.type===L).length}h.setAttribute("viewBox","0 0 "+Tf+" "+m);let g=l.select(`[id="${e}"]`),y=n3().domain([cw(f,function(L){return L.startTime}),lw(f,function(L){return L.endTime})]).rangeRound([0,Tf-n.leftPadding-n.rightPadding]);function v(L,M){let I=L.startTime,A=M.startTime,_=0;return I>A?_=1:IF.vert===V.vert?0:F.vert?1:-1);let B=[...new Set(L.map(F=>F.order))].map(F=>L.find(V=>V.order===F));g.append("g").selectAll("rect").data(B).enter().append("rect").attr("x",0).attr("y",function(F,V){return V=F.order,V*M+I-2}).attr("width",function(){return N-n.rightPadding/2}).attr("height",M).attr("class",function(F){for(let[V,H]of d.entries())if(F.type===H)return"section section"+V%n.numberSectionStyles;return"section section0"}).enter();let O=g.append("g").selectAll("rect").data(L).enter(),$=i.db.getLinks();if(O.append("rect").attr("id",function(F){return e+"-"+F.id}).attr("rx",3).attr("ry",3).attr("x",function(F){return F.milestone?y(F.startTime)+A+.5*(y(F.endTime)-y(F.startTime))-.5*_:y(F.startTime)+A}).attr("y",function(F,V){return V=F.order,F.vert?n.gridLineStartPadding:V*M+I}).attr("width",function(F){return F.milestone?_:F.vert?.08*_:y(F.renderEndTime||F.endTime)-y(F.startTime)}).attr("height",function(F){return F.vert?f.length*(n.barHeight+n.barGap)+n.barHeight*2:_}).attr("transform-origin",function(F,V){return V=F.order,(y(F.startTime)+A+.5*(y(F.endTime)-y(F.startTime))).toString()+"px "+(V*M+I+.5*_).toString()+"px"}).attr("class",function(F){let V="task",H="";F.classes.length>0&&(H=F.classes.join(" "));let X=0;for(let[Z,Y]of d.entries())F.type===Y&&(X=Z%n.numberSectionStyles);let W="";return F.active?F.crit?W+=" activeCrit":W=" active":F.done?F.crit?W=" doneCrit":W=" done":F.crit&&(W+=" crit"),W.length===0&&(W=" task"),F.milestone&&(W=" milestone "+W),F.vert&&(W=" vert "+W),W+=X,W+=" "+H,V+W}),O.append("text").attr("id",function(F){return e+"-"+F.id+"-text"}).text(function(F){return F.task}).attr("font-size",n.fontSize).attr("x",function(F){let V=y(F.startTime),H=y(F.renderEndTime||F.endTime);if(F.milestone&&(V+=.5*(y(F.endTime)-y(F.startTime))-.5*_,H=V+_),F.vert)return y(F.startTime)+A;let X=this.getBBox().width;return X>H-V?H+X+1.5*n.leftPadding>N?V+A-5:H+A+5:(H-V)/2+V+A}).attr("y",function(F,V){return F.vert?n.gridLineStartPadding+f.length*(n.barHeight+n.barGap)+60:(V=F.order,V*M+n.barHeight/2+(n.fontSize/2-2)+I)}).attr("text-height",_).attr("class",function(F){let V=y(F.startTime),H=y(F.endTime);F.milestone&&(H=V+_);let X=this.getBBox().width,W="";F.classes.length>0&&(W=F.classes.join(" "));let Z=0;for(let[ae,J]of d.entries())F.type===J&&(Z=ae%n.numberSectionStyles);let Y="";return F.active&&(F.crit?Y="activeCritText"+Z:Y="activeText"+Z),F.done?F.crit?Y=Y+" doneCritText"+Z:Y=Y+" doneText"+Z:F.crit&&(Y=Y+" critText"+Z),F.milestone&&(Y+=" milestoneText"),F.vert&&(Y+=" vertText"),X>H-V?H+X+1.5*n.leftPadding>N?W+" taskTextOutsideLeft taskTextOutside"+Z+" "+Y:W+" taskTextOutsideRight taskTextOutside"+Z+" "+Y+" width-"+X:W+" taskText taskText"+Z+" "+Y+" width-"+X}),ge().securityLevel==="sandbox"){let F;F=Ze("#i"+e);let V=F.nodes()[0].contentDocument;O.filter(function(H){return $.has(H.id)}).each(function(H){var X=V.querySelector("#"+CSS.escape(e+"-"+H.id)),W=V.querySelector("#"+CSS.escape(e+"-"+H.id+"-text"));let Z=X.parentNode;var Y=V.createElement("a");Y.setAttribute("xlink:href",$.get(H.id)),Y.setAttribute("target","_top"),Z.appendChild(Y),Y.appendChild(X),Y.appendChild(W)})}}o(b,"drawRects");function T(L,M,I,A,_,D,N,R){if(N.length===0&&R.length===0)return;let B,O;for(let{startTime:X,endTime:W}of D)(B===void 0||XO)&&(O=W);if(!B||!O)return;if((0,Kv.default)(O).diff((0,Kv.default)(B),"year")>5){Q.warn("The difference between the min and max time is more than 5 years. This will cause performance issues. Skipping drawing exclude days.");return}let $=i.db.getDateFormat(),z=[],F=null,V=(0,Kv.default)(B);for(;V.valueOf()<=O;)i.db.isInvalidDate(V,$,N,R)?F?F.end=V:F={start:V,end:V}:F&&(z.push(F),F=null),V=V.add(1,"d");g.append("g").selectAll("rect").data(z).enter().append("rect").attr("id",X=>e+"-exclude-"+X.start.format("YYYY-MM-DD")).attr("x",X=>y(X.start.startOf("day"))+I).attr("y",n.gridLineStartPadding).attr("width",X=>y(X.end.endOf("day"))-y(X.start.startOf("day"))).attr("height",_-M-n.gridLineStartPadding).attr("transform-origin",function(X,W){return(y(X.start)+I+.5*(y(X.end)-y(X.start))).toString()+"px "+(W*L+.5*_).toString()+"px"}).attr("class","exclude-range")}o(T,"drawExcludeDays");function w(L,M,I,A){if(I<=0||L>M)return 1/0;let _=M-L,D=Kv.default.duration({[A??"day"]:I}).asMilliseconds();return D<=0?1/0:Math.ceil(_/D)}o(w,"getEstimatedTickCount");function k(L,M,I,A){let _=i.db.getDateFormat(),D=i.db.getAxisFormat(),N;D?N=D:_==="D"?N="%d":N=n.axisFormat??"%Y-%m-%d";let R=LL(y).tickSize(-A+M+n.gridLineStartPadding).tickFormat(p0(N)),O=/^([1-9]\d*)(millisecond|second|minute|hour|day|week|month)$/.exec(i.db.getTickInterval()||n.tickInterval);if(O!==null){let $=parseInt(O[1],10);if(isNaN($)||$<=0)Q.warn(`Invalid tick interval value: "${O[1]}". Skipping custom tick interval.`);else{let z=O[2],F=i.db.getWeekday()||n.weekday,V=y.domain(),H=V[0],X=V[1],W=w(H,X,$,z);if(W>FW)Q.warn(`The tick interval "${$}${z}" would generate ${W} ticks, which exceeds the maximum allowed (${FW}). This may indicate an invalid date or time range. Skipping custom tick interval.`);else switch(z){case"millisecond":R.ticks(pu.every($));break;case"second":R.ticks(Xo.every($));break;case"minute":R.ticks(Rh.every($));break;case"hour":R.ticks(Nh.every($));break;case"day":R.ticks(Sl.every($));break;case"week":R.ticks(Y4e[F].every($));break;case"month":R.ticks(Ih.every($));break}}}if(g.append("g").attr("class","grid").attr("transform","translate("+L+", "+(A-50)+")").call(R).selectAll("text").style("text-anchor","middle").attr("fill","#000").attr("stroke","none").attr("font-size",10).attr("dy","1em"),i.db.topAxisEnabled()||n.topAxis){let $=DL(y).tickSize(-A+M+n.gridLineStartPadding).tickFormat(p0(N));if(O!==null){let z=parseInt(O[1],10);if(isNaN(z)||z<=0)Q.warn(`Invalid tick interval value: "${O[1]}". Skipping custom tick interval.`);else{let F=O[2],V=i.db.getWeekday()||n.weekday,H=y.domain(),X=H[0],W=H[1];if(w(X,W,z,F)<=FW)switch(F){case"millisecond":$.ticks(pu.every(z));break;case"second":$.ticks(Xo.every(z));break;case"minute":$.ticks(Rh.every(z));break;case"hour":$.ticks(Nh.every(z));break;case"day":$.ticks(Sl.every(z));break;case"week":$.ticks(Y4e[V].every(z));break;case"month":$.ticks(Ih.every(z));break}}}g.append("g").attr("class","grid").attr("transform","translate("+L+", "+M+")").call($).selectAll("text").style("text-anchor","middle").attr("fill","#000").attr("stroke","none").attr("font-size",10)}}o(k,"makeGrid");function C(L,M){let I=0,A=Object.keys(p).map(_=>[_,p[_]]);g.append("g").selectAll("text").data(A).enter().append(function(_){let D=_[0].split(lt.lineBreakRegex),N=-(D.length-1)/2,R=u.createElementNS("http://www.w3.org/2000/svg","text");R.setAttribute("dy",N+"em");for(let[B,O]of D.entries()){let $=u.createElementNS("http://www.w3.org/2000/svg","tspan");$.setAttribute("alignment-baseline","central"),$.setAttribute("x","10"),B>0&&$.setAttribute("dy","1em"),$.textContent=O,R.appendChild($)}return R}).attr("x",10).attr("y",function(_,D){if(D>0)for(let N=0;N{"use strict";dut=o(t=>` + .mermaid-main-font { + font-family: ${t.fontFamily}; + } + + .exclude-range { + fill: ${t.excludeBkgColor}; + } + + .section { + stroke: none; + opacity: 0.2; + } + + .section0 { + fill: ${t.sectionBkgColor}; + } + + .section2 { + fill: ${t.sectionBkgColor2}; + } + + .section1, + .section3 { + fill: ${t.altSectionBkgColor}; + opacity: 0.2; + } + + .sectionTitle0 { + fill: ${t.titleColor}; + } + + .sectionTitle1 { + fill: ${t.titleColor}; + } + + .sectionTitle2 { + fill: ${t.titleColor}; + } + + .sectionTitle3 { + fill: ${t.titleColor}; + } + + .sectionTitle { + text-anchor: start; + font-family: ${t.fontFamily}; + } + + + /* Grid and axis */ + + .grid .tick { + stroke: ${t.gridColor}; + opacity: 0.8; + shape-rendering: crispEdges; + } + + .grid .tick text { + font-family: ${t.fontFamily}; + fill: ${t.textColor}; + } + + .grid path { + stroke-width: 0; + } + + + /* Today line */ + + .today { + fill: none; + stroke: ${t.todayLineColor}; + stroke-width: 2px; + } + + + /* Task styling */ + + /* Default task */ + + .task { + stroke-width: 2; + } + + .taskText { + text-anchor: middle; + font-family: ${t.fontFamily}; + } + + .taskTextOutsideRight { + fill: ${t.taskTextDarkColor}; + text-anchor: start; + font-family: ${t.fontFamily}; + } + + .taskTextOutsideLeft { + fill: ${t.taskTextDarkColor}; + text-anchor: end; + } + + + /* Special case clickable */ + + .task.clickable { + cursor: pointer; + } + + .taskText.clickable { + cursor: pointer; + fill: ${t.taskTextClickableColor} !important; + font-weight: bold; + } + + .taskTextOutsideLeft.clickable { + cursor: pointer; + fill: ${t.taskTextClickableColor} !important; + font-weight: bold; + } + + .taskTextOutsideRight.clickable { + cursor: pointer; + fill: ${t.taskTextClickableColor} !important; + font-weight: bold; + } + + + /* Specific task settings for the sections*/ + + .taskText0, + .taskText1, + .taskText2, + .taskText3 { + fill: ${t.taskTextColor}; + } + + .task0, + .task1, + .task2, + .task3 { + fill: ${t.taskBkgColor}; + stroke: ${t.taskBorderColor}; + } + + .taskTextOutside0, + .taskTextOutside2 + { + fill: ${t.taskTextOutsideColor}; + } + + .taskTextOutside1, + .taskTextOutside3 { + fill: ${t.taskTextOutsideColor}; + } + + + /* Active task */ + + .active0, + .active1, + .active2, + .active3 { + fill: ${t.activeTaskBkgColor}; + stroke: ${t.activeTaskBorderColor}; + } + + .activeText0, + .activeText1, + .activeText2, + .activeText3 { + fill: ${t.taskTextDarkColor} !important; + } + + + /* Completed task */ + + .done0, + .done1, + .done2, + .done3 { + stroke: ${t.doneTaskBorderColor}; + fill: ${t.doneTaskBkgColor}; + stroke-width: 2; + } + + .doneText0, + .doneText1, + .doneText2, + .doneText3 { + fill: ${t.taskTextDarkColor} !important; + } + + /* Done task text displayed outside the bar sits against the diagram background, + not against the done-task bar, so it must use the outside/contrast color. */ + .doneText0.taskTextOutsideLeft, + .doneText0.taskTextOutsideRight, + .doneText1.taskTextOutsideLeft, + .doneText1.taskTextOutsideRight, + .doneText2.taskTextOutsideLeft, + .doneText2.taskTextOutsideRight, + .doneText3.taskTextOutsideLeft, + .doneText3.taskTextOutsideRight { + fill: ${t.taskTextOutsideColor} !important; + } + + + /* Tasks on the critical line */ + + .crit0, + .crit1, + .crit2, + .crit3 { + stroke: ${t.critBorderColor}; + fill: ${t.critBkgColor}; + stroke-width: 2; + } + + .activeCrit0, + .activeCrit1, + .activeCrit2, + .activeCrit3 { + stroke: ${t.critBorderColor}; + fill: ${t.activeTaskBkgColor}; + stroke-width: 2; + } + + .doneCrit0, + .doneCrit1, + .doneCrit2, + .doneCrit3 { + stroke: ${t.critBorderColor}; + fill: ${t.doneTaskBkgColor}; + stroke-width: 2; + cursor: pointer; + shape-rendering: crispEdges; + } + + .milestone { + transform: rotate(45deg) scale(0.8,0.8); + } + + .milestoneText { + font-style: italic; + } + .doneCritText0, + .doneCritText1, + .doneCritText2, + .doneCritText3 { + fill: ${t.taskTextDarkColor} !important; + } + + /* Done-crit task text outside the bar \u2014 same reasoning as doneText above. */ + .doneCritText0.taskTextOutsideLeft, + .doneCritText0.taskTextOutsideRight, + .doneCritText1.taskTextOutsideLeft, + .doneCritText1.taskTextOutsideRight, + .doneCritText2.taskTextOutsideLeft, + .doneCritText2.taskTextOutsideRight, + .doneCritText3.taskTextOutsideLeft, + .doneCritText3.taskTextOutsideRight { + fill: ${t.taskTextOutsideColor} !important; + } + + .vert { + stroke: ${t.vertLineColor}; + } + + .vertText { + font-size: 15px; + text-anchor: middle; + fill: ${t.vertLineColor} !important; + } + + .activeCritText0, + .activeCritText1, + .activeCritText2, + .activeCritText3 { + fill: ${t.taskTextDarkColor} !important; + } + + .titleText { + text-anchor: middle; + font-size: 18px; + fill: ${t.titleColor||t.textColor}; + font-family: ${t.fontFamily}; + } +`,"getStyles"),Q4e=dut});var J4e={};ur(J4e,{diagram:()=>put});var put,ewe=P(()=>{"use strict";E4e();U4e();K4e();Z4e();put={parser:w4e,db:q4e,renderer:X4e,styles:Q4e}});var iwe,nwe=P(()=>{"use strict";sh();bt();iwe={parse:o(async t=>{let e=await ba("info",t);Q.debug(e)},"parse")}});var vut,xut,awe,swe=P(()=>{"use strict";vut={version:"11.14.0"},xut=o(()=>vut.version,"getVersion"),awe={getVersion:xut}});var Fi,ro=P(()=>{"use strict";Pr();Ut();Fi=o(t=>{let{securityLevel:e}=ge(),r=Ze("body");if(e==="sandbox"){let a=Ze(`#i${t}`).node()?.contentDocument??document;r=Ze(a.body)}return r.select(`#${t}`)},"selectSvgElement")});var but,owe,lwe=P(()=>{"use strict";bt();ro();Xi();but=o((t,e,r)=>{Q.debug(`rendering info diagram +`+t);let i=Fi(e);Hr(i,100,400,!0),i.append("g").append("text").attr("x",100).attr("y",40).attr("class","version").attr("font-size",32).style("text-anchor","middle").text(`v${r}`)},"draw"),owe={draw:but}});var cwe={};ur(cwe,{diagram:()=>Tut});var Tut,uwe=P(()=>{"use strict";nwe();swe();lwe();Tut={parser:iwe,db:awe,renderer:owe}});var dwe,$W,l_,zW,wut,Eut,Sut,Aut,_ut,Dut,Lut,c_,GW=P(()=>{"use strict";bt();Ki();wa();dwe=fr.pie,$W={sections:new Map,showData:!1,config:dwe},l_=$W.sections,zW=$W.showData,wut=structuredClone(dwe),Eut=o(()=>structuredClone(wut),"getConfig"),Sut=o(()=>{l_=new Map,zW=$W.showData,wr()},"clear"),Aut=o(({label:t,value:e})=>{if(e<0)throw new Error(`"${t}" has invalid value: ${e}. Negative values are not allowed in pie charts. All slice values must be >= 0.`);l_.has(t)||(l_.set(t,e),Q.debug(`added new section: ${t}, with value: ${e}`))},"addSection"),_ut=o(()=>l_,"getSections"),Dut=o(t=>{zW=t},"setShowData"),Lut=o(()=>zW,"getShowData"),c_={getConfig:Eut,clear:Sut,setDiagramTitle:Mr,getDiagramTitle:Nr,setAccTitle:Ar,getAccTitle:Dr,setAccDescription:Lr,getAccDescription:Rr,addSection:Aut,getSections:_ut,setShowData:Dut,getShowData:Lut}});var Rut,pwe,mwe=P(()=>{"use strict";sh();bt();vf();GW();Rut=o((t,e)=>{Ss(t,e),e.setShowData(t.showData),t.sections.map(e.addSection)},"populateDb"),pwe={parse:o(async t=>{let e=await ba("pie",t);Q.debug(e),Rut(e,c_)},"parse")}});var Nut,gwe,ywe=P(()=>{"use strict";Nut=o(t=>` + .pieCircle{ + stroke: ${t.pieStrokeColor}; + stroke-width : ${t.pieStrokeWidth}; + opacity : ${t.pieOpacity}; + } + .pieOuterCircle{ + stroke: ${t.pieOuterStrokeColor}; + stroke-width: ${t.pieOuterStrokeWidth}; + fill: none; + } + .pieTitleText { + text-anchor: middle; + font-size: ${t.pieTitleTextSize}; + fill: ${t.pieTitleTextColor}; + font-family: ${t.fontFamily}; + } + .slice { + font-family: ${t.fontFamily}; + fill: ${t.pieSectionTextColor}; + font-size:${t.pieSectionTextSize}; + // fill: white; + } + .legend text { + fill: ${t.pieLegendTextColor}; + font-family: ${t.fontFamily}; + font-size: ${t.pieLegendTextSize}; + } +`,"getStyles"),gwe=Nut});var Iut,Mut,vwe,xwe=P(()=>{"use strict";Pr();Ut();bt();ro();Xi();er();Iut=o(t=>{let e=[...t.values()].reduce((n,a)=>n+a,0),r=[...t.entries()].map(([n,a])=>({label:n,value:a})).filter(n=>n.value/e*100>=1);return u3().value(n=>n.value).sort(null)(r)},"createPieArcs"),Mut=o((t,e,r,i)=>{Q.debug(`rendering pie chart +`+t);let n=i.db,a=ge(),s=fi(n.getConfig(),a.pie),l=40,u=18,h=4,f=450,d=f,p=Fi(e),m=p.append("g");m.attr("transform","translate("+d/2+","+f/2+")");let{themeVariables:g}=a,[y]=$s(g.pieOuterStrokeWidth);y??=2;let v=s.textPosition,x=Math.min(d,f)/2-l,b=kc().innerRadius(0).outerRadius(x),T=kc().innerRadius(x*v).outerRadius(x*v);m.append("circle").attr("cx",0).attr("cy",0).attr("r",x+y/2).attr("class","pieOuterCircle");let w=n.getSections(),k=Iut(w),C=[g.pie1,g.pie2,g.pie3,g.pie4,g.pie5,g.pie6,g.pie7,g.pie8,g.pie9,g.pie10,g.pie11,g.pie12],E=0;w.forEach(F=>{E+=F});let S=k.filter(F=>(F.data.value/E*100).toFixed(0)!=="0"),L=jo(C).domain([...w.keys()]);m.selectAll("mySlices").data(S).enter().append("path").attr("d",b).attr("fill",F=>L(F.data.label)).attr("class","pieCircle"),m.selectAll("mySlices").data(S).enter().append("text").text(F=>(F.data.value/E*100).toFixed(0)+"%").attr("transform",F=>"translate("+T.centroid(F)+")").style("text-anchor","middle").attr("class","slice");let M=m.append("text").text(n.getDiagramTitle()).attr("x",0).attr("y",-(f-50)/2).attr("class","pieTitleText"),I=[...w.entries()].map(([F,V])=>({label:F,value:V})),A=m.selectAll(".legend").data(I).enter().append("g").attr("class","legend").attr("transform",(F,V)=>{let H=u+h,X=H*I.length/2,W=12*u,Z=V*H-X;return"translate("+W+","+Z+")"});A.append("rect").attr("width",u).attr("height",u).style("fill",F=>L(F.label)).style("stroke",F=>L(F.label)),A.append("text").attr("x",u+h).attr("y",u-h).text(F=>n.getShowData()?`${F.label} [${F.value}]`:F.label);let _=Math.max(...A.selectAll("text").nodes().map(F=>F?.getBoundingClientRect().width??0)),D=d+l+u+h+_,N=M.node()?.getBoundingClientRect().width??0,R=d/2-N/2,B=d/2+N/2,O=Math.min(0,R),z=Math.max(D,B)-O;p.attr("viewBox",`${O} 0 ${z} ${f}`),Hr(p,f,z,s.useMaxWidth)},"draw"),vwe={draw:Mut}});var bwe={};ur(bwe,{diagram:()=>Out});var Out,Twe=P(()=>{"use strict";mwe();GW();ywe();xwe();Out={parser:pwe,db:c_,renderer:vwe,styles:gwe}});var VW,Cwe,wwe=P(()=>{"use strict";VW=(function(){var t=o(function(ue,G,se,le){for(se=se||{},le=ue.length;le--;se[ue[le]]=G);return se},"o"),e=[1,3],r=[1,4],i=[1,5],n=[1,6],a=[1,7],s=[1,4,5,10,12,13,14,18,25,35,37,39,41,42,48,50,51,52,53,54,55,56,57,60,61,63,64,65,66,67],l=[1,4,5,10,12,13,14,18,25,28,35,37,39,41,42,48,50,51,52,53,54,55,56,57,60,61,63,64,65,66,67],u=[55,56,57],h=[2,36],f=[1,37],d=[1,36],p=[1,38],m=[1,35],g=[1,43],y=[1,41],v=[1,14],x=[1,23],b=[1,18],T=[1,19],w=[1,20],k=[1,21],C=[1,22],E=[1,24],S=[1,25],L=[1,26],M=[1,27],I=[1,28],A=[1,29],_=[1,32],D=[1,33],N=[1,34],R=[1,39],B=[1,40],O=[1,42],$=[1,44],z=[1,62],F=[1,61],V=[4,5,8,10,12,13,14,18,44,47,49,55,56,57,63,64,65,66,67],H=[1,65],X=[1,66],W=[1,67],Z=[1,68],Y=[1,69],ae=[1,70],J=[1,71],ee=[1,72],re=[1,73],te=[1,74],be=[1,75],de=[1,76],Ee=[4,5,6,7,8,9,10,11,12,13,14,15,18],Ne=[1,90],we=[1,91],Te=[1,92],De=[1,99],$e=[1,93],pe=[1,96],Je=[1,94],Ce=[1,95],Fe=[1,97],Ue=[1,98],qe=[1,102],Me=[10,55,56,57],He=[4,5,6,8,10,11,13,17,18,19,20,55,56,57],K={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,idStringToken:3,ALPHA:4,NUM:5,NODE_STRING:6,DOWN:7,MINUS:8,DEFAULT:9,COMMA:10,COLON:11,AMP:12,BRKT:13,MULT:14,UNICODE_TEXT:15,styleComponent:16,UNIT:17,SPACE:18,STYLE:19,PCT:20,idString:21,style:22,stylesOpt:23,classDefStatement:24,CLASSDEF:25,start:26,eol:27,QUADRANT:28,document:29,line:30,statement:31,axisDetails:32,quadrantDetails:33,points:34,title:35,title_value:36,acc_title:37,acc_title_value:38,acc_descr:39,acc_descr_value:40,acc_descr_multiline_value:41,section:42,text:43,point_start:44,point_x:45,point_y:46,class_name:47,"X-AXIS":48,"AXIS-TEXT-DELIMITER":49,"Y-AXIS":50,QUADRANT_1:51,QUADRANT_2:52,QUADRANT_3:53,QUADRANT_4:54,NEWLINE:55,SEMI:56,EOF:57,alphaNumToken:58,textNoTagsToken:59,STR:60,MD_STR:61,alphaNum:62,PUNCTUATION:63,PLUS:64,EQUALS:65,DOT:66,UNDERSCORE:67,$accept:0,$end:1},terminals_:{2:"error",4:"ALPHA",5:"NUM",6:"NODE_STRING",7:"DOWN",8:"MINUS",9:"DEFAULT",10:"COMMA",11:"COLON",12:"AMP",13:"BRKT",14:"MULT",15:"UNICODE_TEXT",17:"UNIT",18:"SPACE",19:"STYLE",20:"PCT",25:"CLASSDEF",28:"QUADRANT",35:"title",36:"title_value",37:"acc_title",38:"acc_title_value",39:"acc_descr",40:"acc_descr_value",41:"acc_descr_multiline_value",42:"section",44:"point_start",45:"point_x",46:"point_y",47:"class_name",48:"X-AXIS",49:"AXIS-TEXT-DELIMITER",50:"Y-AXIS",51:"QUADRANT_1",52:"QUADRANT_2",53:"QUADRANT_3",54:"QUADRANT_4",55:"NEWLINE",56:"SEMI",57:"EOF",60:"STR",61:"MD_STR",63:"PUNCTUATION",64:"PLUS",65:"EQUALS",66:"DOT",67:"UNDERSCORE"},productions_:[0,[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[3,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[16,1],[21,1],[21,2],[22,1],[22,2],[23,1],[23,3],[24,5],[26,2],[26,2],[26,2],[29,0],[29,2],[30,2],[31,0],[31,1],[31,2],[31,1],[31,1],[31,1],[31,2],[31,2],[31,2],[31,1],[31,1],[34,4],[34,5],[34,5],[34,6],[32,4],[32,3],[32,2],[32,4],[32,3],[32,2],[33,2],[33,2],[33,2],[33,2],[27,1],[27,1],[27,1],[43,1],[43,2],[43,1],[43,1],[62,1],[62,2],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[58,1],[59,1],[59,1],[59,1]],performAction:o(function(G,se,le,ke,me,ye,Re){var ve=ye.length-1;switch(me){case 23:this.$=ye[ve];break;case 24:this.$=ye[ve-1]+""+ye[ve];break;case 26:this.$=ye[ve-1]+ye[ve];break;case 27:this.$=[ye[ve].trim()];break;case 28:ye[ve-2].push(ye[ve].trim()),this.$=ye[ve-2];break;case 29:this.$=ye[ve-4],ke.addClass(ye[ve-2],ye[ve]);break;case 37:this.$=[];break;case 42:this.$=ye[ve].trim(),ke.setDiagramTitle(this.$);break;case 43:this.$=ye[ve].trim(),ke.setAccTitle(this.$);break;case 44:case 45:this.$=ye[ve].trim(),ke.setAccDescription(this.$);break;case 46:ke.addSection(ye[ve].substr(8)),this.$=ye[ve].substr(8);break;case 47:ke.addPoint(ye[ve-3],"",ye[ve-1],ye[ve],[]);break;case 48:ke.addPoint(ye[ve-4],ye[ve-3],ye[ve-1],ye[ve],[]);break;case 49:ke.addPoint(ye[ve-4],"",ye[ve-2],ye[ve-1],ye[ve]);break;case 50:ke.addPoint(ye[ve-5],ye[ve-4],ye[ve-2],ye[ve-1],ye[ve]);break;case 51:ke.setXAxisLeftText(ye[ve-2]),ke.setXAxisRightText(ye[ve]);break;case 52:ye[ve-1].text+=" \u27F6 ",ke.setXAxisLeftText(ye[ve-1]);break;case 53:ke.setXAxisLeftText(ye[ve]);break;case 54:ke.setYAxisBottomText(ye[ve-2]),ke.setYAxisTopText(ye[ve]);break;case 55:ye[ve-1].text+=" \u27F6 ",ke.setYAxisBottomText(ye[ve-1]);break;case 56:ke.setYAxisBottomText(ye[ve]);break;case 57:ke.setQuadrant1Text(ye[ve]);break;case 58:ke.setQuadrant2Text(ye[ve]);break;case 59:ke.setQuadrant3Text(ye[ve]);break;case 60:ke.setQuadrant4Text(ye[ve]);break;case 64:this.$={text:ye[ve],type:"text"};break;case 65:this.$={text:ye[ve-1].text+""+ye[ve],type:ye[ve-1].type};break;case 66:this.$={text:ye[ve],type:"text"};break;case 67:this.$={text:ye[ve],type:"markdown"};break;case 68:this.$=ye[ve];break;case 69:this.$=ye[ve-1]+""+ye[ve];break}},"anonymous"),table:[{18:e,26:1,27:2,28:r,55:i,56:n,57:a},{1:[3]},{18:e,26:8,27:2,28:r,55:i,56:n,57:a},{18:e,26:9,27:2,28:r,55:i,56:n,57:a},t(s,[2,33],{29:10}),t(l,[2,61]),t(l,[2,62]),t(l,[2,63]),{1:[2,30]},{1:[2,31]},t(u,h,{30:11,31:12,24:13,32:15,33:16,34:17,43:30,58:31,1:[2,32],4:f,5:d,10:p,12:m,13:g,14:y,18:v,25:x,35:b,37:T,39:w,41:k,42:C,48:E,50:S,51:L,52:M,53:I,54:A,60:_,61:D,63:N,64:R,65:B,66:O,67:$}),t(s,[2,34]),{27:45,55:i,56:n,57:a},t(u,[2,37]),t(u,h,{24:13,32:15,33:16,34:17,43:30,58:31,31:46,4:f,5:d,10:p,12:m,13:g,14:y,18:v,25:x,35:b,37:T,39:w,41:k,42:C,48:E,50:S,51:L,52:M,53:I,54:A,60:_,61:D,63:N,64:R,65:B,66:O,67:$}),t(u,[2,39]),t(u,[2,40]),t(u,[2,41]),{36:[1,47]},{38:[1,48]},{40:[1,49]},t(u,[2,45]),t(u,[2,46]),{18:[1,50]},{4:f,5:d,10:p,12:m,13:g,14:y,43:51,58:31,60:_,61:D,63:N,64:R,65:B,66:O,67:$},{4:f,5:d,10:p,12:m,13:g,14:y,43:52,58:31,60:_,61:D,63:N,64:R,65:B,66:O,67:$},{4:f,5:d,10:p,12:m,13:g,14:y,43:53,58:31,60:_,61:D,63:N,64:R,65:B,66:O,67:$},{4:f,5:d,10:p,12:m,13:g,14:y,43:54,58:31,60:_,61:D,63:N,64:R,65:B,66:O,67:$},{4:f,5:d,10:p,12:m,13:g,14:y,43:55,58:31,60:_,61:D,63:N,64:R,65:B,66:O,67:$},{4:f,5:d,10:p,12:m,13:g,14:y,43:56,58:31,60:_,61:D,63:N,64:R,65:B,66:O,67:$},{4:f,5:d,8:z,10:p,12:m,13:g,14:y,18:F,44:[1,57],47:[1,58],58:60,59:59,63:N,64:R,65:B,66:O,67:$},t(V,[2,64]),t(V,[2,66]),t(V,[2,67]),t(V,[2,70]),t(V,[2,71]),t(V,[2,72]),t(V,[2,73]),t(V,[2,74]),t(V,[2,75]),t(V,[2,76]),t(V,[2,77]),t(V,[2,78]),t(V,[2,79]),t(V,[2,80]),t(s,[2,35]),t(u,[2,38]),t(u,[2,42]),t(u,[2,43]),t(u,[2,44]),{3:64,4:H,5:X,6:W,7:Z,8:Y,9:ae,10:J,11:ee,12:re,13:te,14:be,15:de,21:63},t(u,[2,53],{59:59,58:60,4:f,5:d,8:z,10:p,12:m,13:g,14:y,18:F,49:[1,77],63:N,64:R,65:B,66:O,67:$}),t(u,[2,56],{59:59,58:60,4:f,5:d,8:z,10:p,12:m,13:g,14:y,18:F,49:[1,78],63:N,64:R,65:B,66:O,67:$}),t(u,[2,57],{59:59,58:60,4:f,5:d,8:z,10:p,12:m,13:g,14:y,18:F,63:N,64:R,65:B,66:O,67:$}),t(u,[2,58],{59:59,58:60,4:f,5:d,8:z,10:p,12:m,13:g,14:y,18:F,63:N,64:R,65:B,66:O,67:$}),t(u,[2,59],{59:59,58:60,4:f,5:d,8:z,10:p,12:m,13:g,14:y,18:F,63:N,64:R,65:B,66:O,67:$}),t(u,[2,60],{59:59,58:60,4:f,5:d,8:z,10:p,12:m,13:g,14:y,18:F,63:N,64:R,65:B,66:O,67:$}),{45:[1,79]},{44:[1,80]},t(V,[2,65]),t(V,[2,81]),t(V,[2,82]),t(V,[2,83]),{3:82,4:H,5:X,6:W,7:Z,8:Y,9:ae,10:J,11:ee,12:re,13:te,14:be,15:de,18:[1,81]},t(Ee,[2,23]),t(Ee,[2,1]),t(Ee,[2,2]),t(Ee,[2,3]),t(Ee,[2,4]),t(Ee,[2,5]),t(Ee,[2,6]),t(Ee,[2,7]),t(Ee,[2,8]),t(Ee,[2,9]),t(Ee,[2,10]),t(Ee,[2,11]),t(Ee,[2,12]),t(u,[2,52],{58:31,43:83,4:f,5:d,10:p,12:m,13:g,14:y,60:_,61:D,63:N,64:R,65:B,66:O,67:$}),t(u,[2,55],{58:31,43:84,4:f,5:d,10:p,12:m,13:g,14:y,60:_,61:D,63:N,64:R,65:B,66:O,67:$}),{46:[1,85]},{45:[1,86]},{4:Ne,5:we,6:Te,8:De,11:$e,13:pe,16:89,17:Je,18:Ce,19:Fe,20:Ue,22:88,23:87},t(Ee,[2,24]),t(u,[2,51],{59:59,58:60,4:f,5:d,8:z,10:p,12:m,13:g,14:y,18:F,63:N,64:R,65:B,66:O,67:$}),t(u,[2,54],{59:59,58:60,4:f,5:d,8:z,10:p,12:m,13:g,14:y,18:F,63:N,64:R,65:B,66:O,67:$}),t(u,[2,47],{22:88,16:89,23:100,4:Ne,5:we,6:Te,8:De,11:$e,13:pe,17:Je,18:Ce,19:Fe,20:Ue}),{46:[1,101]},t(u,[2,29],{10:qe}),t(Me,[2,27],{16:103,4:Ne,5:we,6:Te,8:De,11:$e,13:pe,17:Je,18:Ce,19:Fe,20:Ue}),t(He,[2,25]),t(He,[2,13]),t(He,[2,14]),t(He,[2,15]),t(He,[2,16]),t(He,[2,17]),t(He,[2,18]),t(He,[2,19]),t(He,[2,20]),t(He,[2,21]),t(He,[2,22]),t(u,[2,49],{10:qe}),t(u,[2,48],{22:88,16:89,23:104,4:Ne,5:we,6:Te,8:De,11:$e,13:pe,17:Je,18:Ce,19:Fe,20:Ue}),{4:Ne,5:we,6:Te,8:De,11:$e,13:pe,16:89,17:Je,18:Ce,19:Fe,20:Ue,22:105},t(He,[2,26]),t(u,[2,50],{10:qe}),t(Me,[2,28],{16:103,4:Ne,5:we,6:Te,8:De,11:$e,13:pe,17:Je,18:Ce,19:Fe,20:Ue})],defaultActions:{8:[2,30],9:[2,31]},parseError:o(function(G,se){if(se.recoverable)this.trace(G);else{var le=new Error(G);throw le.hash=se,le}},"parseError"),parse:o(function(G){var se=this,le=[0],ke=[],me=[null],ye=[],Re=this.table,ve="",Oe=0,We=0,Be=0,Qe=2,ce=1,it=ye.slice.call(arguments,1),fe=Object.create(this.lexer),ut={yy:{}};for(var Nt in this.yy)Object.prototype.hasOwnProperty.call(this.yy,Nt)&&(ut.yy[Nt]=this.yy[Nt]);fe.setInput(G,ut.yy),ut.yy.lexer=fe,ut.yy.parser=this,typeof fe.yylloc>"u"&&(fe.yylloc={});var Pt=fe.yylloc;ye.push(Pt);var St=fe.options&&fe.options.ranges;typeof ut.yy.parseError=="function"?this.parseError=ut.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function It(xt){le.length=le.length-2*xt,me.length=me.length-xt,ye.length=ye.length-xt}o(It,"popStack");function ot(){var xt;return xt=ke.pop()||fe.lex()||ce,typeof xt!="number"&&(xt instanceof Array&&(ke=xt,xt=ke.pop()),xt=se.symbols_[xt]||xt),xt}o(ot,"lex");for(var ct,Dt,kt,yt,jt,hr,Qt={},Er,dr,ir,pr;;){if(kt=le[le.length-1],this.defaultActions[kt]?yt=this.defaultActions[kt]:((ct===null||typeof ct>"u")&&(ct=ot()),yt=Re[kt]&&Re[kt][ct]),typeof yt>"u"||!yt.length||!yt[0]){var Ii="";pr=[];for(Er in Re[kt])this.terminals_[Er]&&Er>Qe&&pr.push("'"+this.terminals_[Er]+"'");fe.showPosition?Ii="Parse error on line "+(Oe+1)+`: +`+fe.showPosition()+` +Expecting `+pr.join(", ")+", got '"+(this.terminals_[ct]||ct)+"'":Ii="Parse error on line "+(Oe+1)+": Unexpected "+(ct==ce?"end of input":"'"+(this.terminals_[ct]||ct)+"'"),this.parseError(Ii,{text:fe.match,token:this.terminals_[ct]||ct,line:fe.yylineno,loc:Pt,expected:pr})}if(yt[0]instanceof Array&&yt.length>1)throw new Error("Parse Error: multiple actions possible at state: "+kt+", token: "+ct);switch(yt[0]){case 1:le.push(ct),me.push(fe.yytext),ye.push(fe.yylloc),le.push(yt[1]),ct=null,Dt?(ct=Dt,Dt=null):(We=fe.yyleng,ve=fe.yytext,Oe=fe.yylineno,Pt=fe.yylloc,Be>0&&Be--);break;case 2:if(dr=this.productions_[yt[1]][1],Qt.$=me[me.length-dr],Qt._$={first_line:ye[ye.length-(dr||1)].first_line,last_line:ye[ye.length-1].last_line,first_column:ye[ye.length-(dr||1)].first_column,last_column:ye[ye.length-1].last_column},St&&(Qt._$.range=[ye[ye.length-(dr||1)].range[0],ye[ye.length-1].range[1]]),hr=this.performAction.apply(Qt,[ve,We,Oe,ut.yy,yt[1],me,ye].concat(it)),typeof hr<"u")return hr;dr&&(le=le.slice(0,-1*dr*2),me=me.slice(0,-1*dr),ye=ye.slice(0,-1*dr)),le.push(this.productions_[yt[1]][0]),me.push(Qt.$),ye.push(Qt._$),ir=Re[le[le.length-2]][le[le.length-1]],le.push(ir);break;case 3:return!0}}return!0},"parse")},oe=(function(){var ue={EOF:1,parseError:o(function(se,le){if(this.yy.parser)this.yy.parser.parseError(se,le);else throw new Error(se)},"parseError"),setInput:o(function(G,se){return this.yy=se||this.yy||{},this._input=G,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var G=this._input[0];this.yytext+=G,this.yyleng++,this.offset++,this.match+=G,this.matched+=G;var se=G.match(/(?:\r\n?|\n).*/g);return se?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),G},"input"),unput:o(function(G){var se=G.length,le=G.split(/(?:\r\n?|\n)/g);this._input=G+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-se),this.offset-=se;var ke=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),le.length-1&&(this.yylineno-=le.length-1);var me=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:le?(le.length===ke.length?this.yylloc.first_column:0)+ke[ke.length-le.length].length-le[0].length:this.yylloc.first_column-se},this.options.ranges&&(this.yylloc.range=[me[0],me[0]+this.yyleng-se]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(G){this.unput(this.match.slice(G))},"less"),pastInput:o(function(){var G=this.matched.substr(0,this.matched.length-this.match.length);return(G.length>20?"...":"")+G.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var G=this.match;return G.length<20&&(G+=this._input.substr(0,20-G.length)),(G.substr(0,20)+(G.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var G=this.pastInput(),se=new Array(G.length+1).join("-");return G+this.upcomingInput()+` +`+se+"^"},"showPosition"),test_match:o(function(G,se){var le,ke,me;if(this.options.backtrack_lexer&&(me={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(me.yylloc.range=this.yylloc.range.slice(0))),ke=G[0].match(/(?:\r\n?|\n).*/g),ke&&(this.yylineno+=ke.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:ke?ke[ke.length-1].length-ke[ke.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+G[0].length},this.yytext+=G[0],this.match+=G[0],this.matches=G,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(G[0].length),this.matched+=G[0],le=this.performAction.call(this,this.yy,this,se,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),le)return le;if(this._backtrack){for(var ye in me)this[ye]=me[ye];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var G,se,le,ke;this._more||(this.yytext="",this.match="");for(var me=this._currentRules(),ye=0;yese[0].length)){if(se=le,ke=ye,this.options.backtrack_lexer){if(G=this.test_match(le,me[ye]),G!==!1)return G;if(this._backtrack){se=!1;continue}else return!1}else if(!this.options.flex)break}return se?(G=this.test_match(se,me[ke]),G!==!1?G:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var se=this.next();return se||this.lex()},"lex"),begin:o(function(se){this.conditionStack.push(se)},"begin"),popState:o(function(){var se=this.conditionStack.length-1;return se>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(se){return se=this.conditionStack.length-1-Math.abs(se||0),se>=0?this.conditionStack[se]:"INITIAL"},"topState"),pushState:o(function(se){this.begin(se)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:o(function(se,le,ke,me){var ye=me;switch(ke){case 0:break;case 1:break;case 2:return 55;case 3:break;case 4:return this.begin("title"),35;break;case 5:return this.popState(),"title_value";break;case 6:return this.begin("acc_title"),37;break;case 7:return this.popState(),"acc_title_value";break;case 8:return this.begin("acc_descr"),39;break;case 9:return this.popState(),"acc_descr_value";break;case 10:this.begin("acc_descr_multiline");break;case 11:this.popState();break;case 12:return"acc_descr_multiline_value";case 13:return 48;case 14:return 50;case 15:return 49;case 16:return 51;case 17:return 52;case 18:return 53;case 19:return 54;case 20:return 25;case 21:this.begin("md_string");break;case 22:return"MD_STR";case 23:this.popState();break;case 24:this.begin("string");break;case 25:this.popState();break;case 26:return"STR";case 27:this.begin("class_name");break;case 28:return this.popState(),47;break;case 29:return this.begin("point_start"),44;break;case 30:return this.begin("point_x"),45;break;case 31:this.popState();break;case 32:this.popState(),this.begin("point_y");break;case 33:return this.popState(),46;break;case 34:return 28;case 35:return 4;case 36:return 11;case 37:return 64;case 38:return 10;case 39:return 65;case 40:return 65;case 41:return 14;case 42:return 13;case 43:return 67;case 44:return 66;case 45:return 12;case 46:return 8;case 47:return 5;case 48:return 18;case 49:return 56;case 50:return 63;case 51:return 57}},"anonymous"),rules:[/^(?:%%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n\r]+)/i,/^(?:%%[^\n]*)/i,/^(?:title\b)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?: *x-axis *)/i,/^(?: *y-axis *)/i,/^(?: *--+> *)/i,/^(?: *quadrant-1 *)/i,/^(?: *quadrant-2 *)/i,/^(?: *quadrant-3 *)/i,/^(?: *quadrant-4 *)/i,/^(?:classDef\b)/i,/^(?:["][`])/i,/^(?:[^`"]+)/i,/^(?:[`]["])/i,/^(?:["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?::::)/i,/^(?:^\w+)/i,/^(?:\s*:\s*\[\s*)/i,/^(?:(1)|(0(.\d+)?))/i,/^(?:\s*\] *)/i,/^(?:\s*,\s*)/i,/^(?:(1)|(0(.\d+)?))/i,/^(?: *quadrantChart *)/i,/^(?:[A-Za-z]+)/i,/^(?::)/i,/^(?:\+)/i,/^(?:,)/i,/^(?:=)/i,/^(?:=)/i,/^(?:\*)/i,/^(?:#)/i,/^(?:[\_])/i,/^(?:\.)/i,/^(?:&)/i,/^(?:-)/i,/^(?:[0-9]+)/i,/^(?:\s)/i,/^(?:;)/i,/^(?:[!"#$%&'*+,-.`?\\_/])/i,/^(?:$)/i],conditions:{class_name:{rules:[28],inclusive:!1},point_y:{rules:[33],inclusive:!1},point_x:{rules:[32],inclusive:!1},point_start:{rules:[30,31],inclusive:!1},acc_descr_multiline:{rules:[11,12],inclusive:!1},acc_descr:{rules:[9],inclusive:!1},acc_title:{rules:[7],inclusive:!1},title:{rules:[5],inclusive:!1},md_string:{rules:[22,23],inclusive:!1},string:{rules:[25,26],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,6,8,10,13,14,15,16,17,18,19,20,21,24,27,29,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],inclusive:!0}}};return ue})();K.lexer=oe;function U(){this.yy={}}return o(U,"Parser"),U.prototype=K,K.Parser=U,new U})();VW.parser=VW;Cwe=VW});var io,u_,Ewe=P(()=>{"use strict";Pr();wa();bt();wg();io=Zc(),u_=class{constructor(){this.classes=new Map;this.config=this.getDefaultConfig(),this.themeConfig=this.getDefaultThemeConfig(),this.data=this.getDefaultData()}static{o(this,"QuadrantBuilder")}getDefaultData(){return{titleText:"",quadrant1Text:"",quadrant2Text:"",quadrant3Text:"",quadrant4Text:"",xAxisLeftText:"",xAxisRightText:"",yAxisBottomText:"",yAxisTopText:"",points:[]}}getDefaultConfig(){return{showXAxis:!0,showYAxis:!0,showTitle:!0,chartHeight:fr.quadrantChart?.chartWidth||500,chartWidth:fr.quadrantChart?.chartHeight||500,titlePadding:fr.quadrantChart?.titlePadding||10,titleFontSize:fr.quadrantChart?.titleFontSize||20,quadrantPadding:fr.quadrantChart?.quadrantPadding||5,xAxisLabelPadding:fr.quadrantChart?.xAxisLabelPadding||5,yAxisLabelPadding:fr.quadrantChart?.yAxisLabelPadding||5,xAxisLabelFontSize:fr.quadrantChart?.xAxisLabelFontSize||16,yAxisLabelFontSize:fr.quadrantChart?.yAxisLabelFontSize||16,quadrantLabelFontSize:fr.quadrantChart?.quadrantLabelFontSize||16,quadrantTextTopPadding:fr.quadrantChart?.quadrantTextTopPadding||5,pointTextPadding:fr.quadrantChart?.pointTextPadding||5,pointLabelFontSize:fr.quadrantChart?.pointLabelFontSize||12,pointRadius:fr.quadrantChart?.pointRadius||5,xAxisPosition:fr.quadrantChart?.xAxisPosition||"top",yAxisPosition:fr.quadrantChart?.yAxisPosition||"left",quadrantInternalBorderStrokeWidth:fr.quadrantChart?.quadrantInternalBorderStrokeWidth||1,quadrantExternalBorderStrokeWidth:fr.quadrantChart?.quadrantExternalBorderStrokeWidth||2}}getDefaultThemeConfig(){return{quadrant1Fill:io.quadrant1Fill,quadrant2Fill:io.quadrant2Fill,quadrant3Fill:io.quadrant3Fill,quadrant4Fill:io.quadrant4Fill,quadrant1TextFill:io.quadrant1TextFill,quadrant2TextFill:io.quadrant2TextFill,quadrant3TextFill:io.quadrant3TextFill,quadrant4TextFill:io.quadrant4TextFill,quadrantPointFill:io.quadrantPointFill,quadrantPointTextFill:io.quadrantPointTextFill,quadrantXAxisTextFill:io.quadrantXAxisTextFill,quadrantYAxisTextFill:io.quadrantYAxisTextFill,quadrantTitleFill:io.quadrantTitleFill,quadrantInternalBorderStrokeFill:io.quadrantInternalBorderStrokeFill,quadrantExternalBorderStrokeFill:io.quadrantExternalBorderStrokeFill}}clear(){this.config=this.getDefaultConfig(),this.themeConfig=this.getDefaultThemeConfig(),this.data=this.getDefaultData(),this.classes=new Map,Q.info("clear called")}setData(e){this.data={...this.data,...e}}addPoints(e){this.data.points=[...e,...this.data.points]}addClass(e,r){this.classes.set(e,r)}setConfig(e){Q.trace("setConfig called with: ",e),this.config={...this.config,...e}}setThemeConfig(e){Q.trace("setThemeConfig called with: ",e),this.themeConfig={...this.themeConfig,...e}}calculateSpace(e,r,i,n){let a=this.config.xAxisLabelPadding*2+this.config.xAxisLabelFontSize,s={top:e==="top"&&r?a:0,bottom:e==="bottom"&&r?a:0},l=this.config.yAxisLabelPadding*2+this.config.yAxisLabelFontSize,u={left:this.config.yAxisPosition==="left"&&i?l:0,right:this.config.yAxisPosition==="right"&&i?l:0},h=this.config.titleFontSize+this.config.titlePadding*2,f={top:n?h:0},d=this.config.quadrantPadding+u.left,p=this.config.quadrantPadding+s.top+f.top,m=this.config.chartWidth-this.config.quadrantPadding*2-u.left-u.right,g=this.config.chartHeight-this.config.quadrantPadding*2-s.top-s.bottom-f.top,y=m/2,v=g/2;return{xAxisSpace:s,yAxisSpace:u,titleSpace:f,quadrantSpace:{quadrantLeft:d,quadrantTop:p,quadrantWidth:m,quadrantHalfWidth:y,quadrantHeight:g,quadrantHalfHeight:v}}}getAxisLabels(e,r,i,n){let{quadrantSpace:a,titleSpace:s}=n,{quadrantHalfHeight:l,quadrantHeight:u,quadrantLeft:h,quadrantHalfWidth:f,quadrantTop:d,quadrantWidth:p}=a,m=!!this.data.xAxisRightText,g=!!this.data.yAxisTopText,y=[];return this.data.xAxisLeftText&&r&&y.push({text:this.data.xAxisLeftText,fill:this.themeConfig.quadrantXAxisTextFill,x:h+(m?f/2:0),y:e==="top"?this.config.xAxisLabelPadding+s.top:this.config.xAxisLabelPadding+d+u+this.config.quadrantPadding,fontSize:this.config.xAxisLabelFontSize,verticalPos:m?"center":"left",horizontalPos:"top",rotation:0}),this.data.xAxisRightText&&r&&y.push({text:this.data.xAxisRightText,fill:this.themeConfig.quadrantXAxisTextFill,x:h+f+(m?f/2:0),y:e==="top"?this.config.xAxisLabelPadding+s.top:this.config.xAxisLabelPadding+d+u+this.config.quadrantPadding,fontSize:this.config.xAxisLabelFontSize,verticalPos:m?"center":"left",horizontalPos:"top",rotation:0}),this.data.yAxisBottomText&&i&&y.push({text:this.data.yAxisBottomText,fill:this.themeConfig.quadrantYAxisTextFill,x:this.config.yAxisPosition==="left"?this.config.yAxisLabelPadding:this.config.yAxisLabelPadding+h+p+this.config.quadrantPadding,y:d+u-(g?l/2:0),fontSize:this.config.yAxisLabelFontSize,verticalPos:g?"center":"left",horizontalPos:"top",rotation:-90}),this.data.yAxisTopText&&i&&y.push({text:this.data.yAxisTopText,fill:this.themeConfig.quadrantYAxisTextFill,x:this.config.yAxisPosition==="left"?this.config.yAxisLabelPadding:this.config.yAxisLabelPadding+h+p+this.config.quadrantPadding,y:d+l-(g?l/2:0),fontSize:this.config.yAxisLabelFontSize,verticalPos:g?"center":"left",horizontalPos:"top",rotation:-90}),y}getQuadrants(e){let{quadrantSpace:r}=e,{quadrantHalfHeight:i,quadrantLeft:n,quadrantHalfWidth:a,quadrantTop:s}=r,l=[{text:{text:this.data.quadrant1Text,fill:this.themeConfig.quadrant1TextFill,x:0,y:0,fontSize:this.config.quadrantLabelFontSize,verticalPos:"center",horizontalPos:"middle",rotation:0},x:n+a,y:s,width:a,height:i,fill:this.themeConfig.quadrant1Fill},{text:{text:this.data.quadrant2Text,fill:this.themeConfig.quadrant2TextFill,x:0,y:0,fontSize:this.config.quadrantLabelFontSize,verticalPos:"center",horizontalPos:"middle",rotation:0},x:n,y:s,width:a,height:i,fill:this.themeConfig.quadrant2Fill},{text:{text:this.data.quadrant3Text,fill:this.themeConfig.quadrant3TextFill,x:0,y:0,fontSize:this.config.quadrantLabelFontSize,verticalPos:"center",horizontalPos:"middle",rotation:0},x:n,y:s+i,width:a,height:i,fill:this.themeConfig.quadrant3Fill},{text:{text:this.data.quadrant4Text,fill:this.themeConfig.quadrant4TextFill,x:0,y:0,fontSize:this.config.quadrantLabelFontSize,verticalPos:"center",horizontalPos:"middle",rotation:0},x:n+a,y:s+i,width:a,height:i,fill:this.themeConfig.quadrant4Fill}];for(let u of l)u.text.x=u.x+u.width/2,this.data.points.length===0?(u.text.y=u.y+u.height/2,u.text.horizontalPos="middle"):(u.text.y=u.y+this.config.quadrantTextTopPadding,u.text.horizontalPos="top");return l}getQuadrantPoints(e){let{quadrantSpace:r}=e,{quadrantHeight:i,quadrantLeft:n,quadrantTop:a,quadrantWidth:s}=r,l=vc().domain([0,1]).range([n,s+n]),u=vc().domain([0,1]).range([i+a,a]);return this.data.points.map(f=>{let d=this.classes.get(f.className);return d&&(f={...d,...f}),{x:l(f.x),y:u(f.y),fill:f.color??this.themeConfig.quadrantPointFill,radius:f.radius??this.config.pointRadius,text:{text:f.text,fill:this.themeConfig.quadrantPointTextFill,x:l(f.x),y:u(f.y)+this.config.pointTextPadding,verticalPos:"center",horizontalPos:"top",fontSize:this.config.pointLabelFontSize,rotation:0},strokeColor:f.strokeColor??this.themeConfig.quadrantPointFill,strokeWidth:f.strokeWidth??"0px"}})}getBorders(e){let r=this.config.quadrantExternalBorderStrokeWidth/2,{quadrantSpace:i}=e,{quadrantHalfHeight:n,quadrantHeight:a,quadrantLeft:s,quadrantHalfWidth:l,quadrantTop:u,quadrantWidth:h}=i;return[{strokeFill:this.themeConfig.quadrantExternalBorderStrokeFill,strokeWidth:this.config.quadrantExternalBorderStrokeWidth,x1:s-r,y1:u,x2:s+h+r,y2:u},{strokeFill:this.themeConfig.quadrantExternalBorderStrokeFill,strokeWidth:this.config.quadrantExternalBorderStrokeWidth,x1:s+h,y1:u+r,x2:s+h,y2:u+a-r},{strokeFill:this.themeConfig.quadrantExternalBorderStrokeFill,strokeWidth:this.config.quadrantExternalBorderStrokeWidth,x1:s-r,y1:u+a,x2:s+h+r,y2:u+a},{strokeFill:this.themeConfig.quadrantExternalBorderStrokeFill,strokeWidth:this.config.quadrantExternalBorderStrokeWidth,x1:s,y1:u+r,x2:s,y2:u+a-r},{strokeFill:this.themeConfig.quadrantInternalBorderStrokeFill,strokeWidth:this.config.quadrantInternalBorderStrokeWidth,x1:s+l,y1:u+r,x2:s+l,y2:u+a-r},{strokeFill:this.themeConfig.quadrantInternalBorderStrokeFill,strokeWidth:this.config.quadrantInternalBorderStrokeWidth,x1:s+r,y1:u+n,x2:s+h-r,y2:u+n}]}getTitle(e){if(e)return{text:this.data.titleText,fill:this.themeConfig.quadrantTitleFill,fontSize:this.config.titleFontSize,horizontalPos:"top",verticalPos:"center",rotation:0,y:this.config.titlePadding,x:this.config.chartWidth/2}}build(){let e=this.config.showXAxis&&!!(this.data.xAxisLeftText||this.data.xAxisRightText),r=this.config.showYAxis&&!!(this.data.yAxisTopText||this.data.yAxisBottomText),i=this.config.showTitle&&!!this.data.titleText,n=this.data.points.length>0?"bottom":this.config.xAxisPosition,a=this.calculateSpace(n,e,r,i);return{points:this.getQuadrantPoints(a),quadrants:this.getQuadrants(a),axisLabels:this.getAxisLabels(n,e,r,a),borderLines:this.getBorders(a),title:this.getTitle(i)}}}});function qW(t){return!/^#?([\dA-Fa-f]{6}|[\dA-Fa-f]{3})$/.test(t)}function Swe(t){return!/^\d+$/.test(t)}function Awe(t){return!/^\d+px$/.test(t)}var og,_we=P(()=>{"use strict";og=class extends Error{static{o(this,"InvalidStyleError")}constructor(e,r,i){super(`value for ${e} ${r} is invalid, please use a valid ${i}`),this.name="InvalidStyleError"}};o(qW,"validateHexCode");o(Swe,"validateNumber");o(Awe,"validateSizeInPixels")});function kf(t){return Tr(t.trim(),Fut)}function $ut(t){ss.setData({quadrant1Text:kf(t.text)})}function zut(t){ss.setData({quadrant2Text:kf(t.text)})}function Gut(t){ss.setData({quadrant3Text:kf(t.text)})}function Vut(t){ss.setData({quadrant4Text:kf(t.text)})}function qut(t){ss.setData({xAxisLeftText:kf(t.text)})}function Wut(t){ss.setData({xAxisRightText:kf(t.text)})}function Uut(t){ss.setData({yAxisTopText:kf(t.text)})}function Hut(t){ss.setData({yAxisBottomText:kf(t.text)})}function WW(t){let e={};for(let r of t){let[i,n]=r.trim().split(/\s*:\s*/);if(i==="radius"){if(Swe(n))throw new og(i,n,"number");e.radius=parseInt(n)}else if(i==="color"){if(qW(n))throw new og(i,n,"hex code");e.color=n}else if(i==="stroke-color"){if(qW(n))throw new og(i,n,"hex code");e.strokeColor=n}else if(i==="stroke-width"){if(Awe(n))throw new og(i,n,"number of pixels (eg. 10px)");e.strokeWidth=n}else throw new Error(`style named ${i} is not supported.`)}return e}function Yut(t,e,r,i,n){let a=WW(n);ss.addPoints([{x:r,y:i,text:kf(t.text),className:e,...a}])}function jut(t,e){ss.addClass(t,WW(e))}function Xut(t){ss.setConfig({chartWidth:t})}function Kut(t){ss.setConfig({chartHeight:t})}function Qut(){let t=ge(),{themeVariables:e,quadrantChart:r}=t;return r&&ss.setConfig(r),ss.setThemeConfig({quadrant1Fill:e.quadrant1Fill,quadrant2Fill:e.quadrant2Fill,quadrant3Fill:e.quadrant3Fill,quadrant4Fill:e.quadrant4Fill,quadrant1TextFill:e.quadrant1TextFill,quadrant2TextFill:e.quadrant2TextFill,quadrant3TextFill:e.quadrant3TextFill,quadrant4TextFill:e.quadrant4TextFill,quadrantPointFill:e.quadrantPointFill,quadrantPointTextFill:e.quadrantPointTextFill,quadrantXAxisTextFill:e.quadrantXAxisTextFill,quadrantYAxisTextFill:e.quadrantYAxisTextFill,quadrantExternalBorderStrokeFill:e.quadrantExternalBorderStrokeFill,quadrantInternalBorderStrokeFill:e.quadrantInternalBorderStrokeFill,quadrantTitleFill:e.quadrantTitleFill}),ss.setData({titleText:Nr()}),ss.build()}var Fut,ss,Zut,Dwe,Lwe=P(()=>{"use strict";Ut();Vr();Ki();Ewe();_we();Fut=ge();o(kf,"textSanitizer");ss=new u_;o($ut,"setQuadrant1Text");o(zut,"setQuadrant2Text");o(Gut,"setQuadrant3Text");o(Vut,"setQuadrant4Text");o(qut,"setXAxisLeftText");o(Wut,"setXAxisRightText");o(Uut,"setYAxisTopText");o(Hut,"setYAxisBottomText");o(WW,"parseStyles");o(Yut,"addPoint");o(jut,"addClass");o(Xut,"setWidth");o(Kut,"setHeight");o(Qut,"getQuadrantData");Zut=o(function(){ss.clear(),wr()},"clear"),Dwe={setWidth:Xut,setHeight:Kut,setQuadrant1Text:$ut,setQuadrant2Text:zut,setQuadrant3Text:Gut,setQuadrant4Text:Vut,setXAxisLeftText:qut,setXAxisRightText:Wut,setYAxisTopText:Uut,setYAxisBottomText:Hut,parseStyles:WW,addPoint:Yut,addClass:jut,getQuadrantData:Qut,clear:Zut,setAccTitle:Ar,getAccTitle:Dr,setDiagramTitle:Mr,getDiagramTitle:Nr,getAccDescription:Rr,setAccDescription:Lr}});var Jut,Rwe,Nwe=P(()=>{"use strict";Pr();Ut();bt();Xi();Jut=o((t,e,r,i)=>{function n(S){return S==="top"?"hanging":"middle"}o(n,"getDominantBaseLine");function a(S){return S==="left"?"start":"middle"}o(a,"getTextAnchor");function s(S){return`translate(${S.x}, ${S.y}) rotate(${S.rotation||0})`}o(s,"getTransformation");let l=ge();Q.debug(`Rendering quadrant chart +`+t);let u=l.securityLevel,h;u==="sandbox"&&(h=Ze("#i"+e));let d=(u==="sandbox"?Ze(h.nodes()[0].contentDocument.body):Ze("body")).select(`[id="${e}"]`),p=d.append("g").attr("class","main"),m=l.quadrantChart?.chartWidth??500,g=l.quadrantChart?.chartHeight??500;Hr(d,g,m,l.quadrantChart?.useMaxWidth??!0),d.attr("viewBox","0 0 "+m+" "+g),i.db.setHeight(g),i.db.setWidth(m);let y=i.db.getQuadrantData(),v=p.append("g").attr("class","quadrants"),x=p.append("g").attr("class","border"),b=p.append("g").attr("class","data-points"),T=p.append("g").attr("class","labels"),w=p.append("g").attr("class","title");y.title&&w.append("text").attr("x",0).attr("y",0).attr("fill",y.title.fill).attr("font-size",y.title.fontSize).attr("dominant-baseline",n(y.title.horizontalPos)).attr("text-anchor",a(y.title.verticalPos)).attr("transform",s(y.title)).text(y.title.text),y.borderLines&&x.selectAll("line").data(y.borderLines).enter().append("line").attr("x1",S=>S.x1).attr("y1",S=>S.y1).attr("x2",S=>S.x2).attr("y2",S=>S.y2).style("stroke",S=>S.strokeFill).style("stroke-width",S=>S.strokeWidth);let k=v.selectAll("g.quadrant").data(y.quadrants).enter().append("g").attr("class","quadrant");k.append("rect").attr("x",S=>S.x).attr("y",S=>S.y).attr("width",S=>S.width).attr("height",S=>S.height).attr("fill",S=>S.fill),k.append("text").attr("x",0).attr("y",0).attr("fill",S=>S.text.fill).attr("font-size",S=>S.text.fontSize).attr("dominant-baseline",S=>n(S.text.horizontalPos)).attr("text-anchor",S=>a(S.text.verticalPos)).attr("transform",S=>s(S.text)).text(S=>S.text.text),T.selectAll("g.label").data(y.axisLabels).enter().append("g").attr("class","label").append("text").attr("x",0).attr("y",0).text(S=>S.text).attr("fill",S=>S.fill).attr("font-size",S=>S.fontSize).attr("dominant-baseline",S=>n(S.horizontalPos)).attr("text-anchor",S=>a(S.verticalPos)).attr("transform",S=>s(S));let E=b.selectAll("g.data-point").data(y.points).enter().append("g").attr("class","data-point");E.append("circle").attr("cx",S=>S.x).attr("cy",S=>S.y).attr("r",S=>S.radius).attr("fill",S=>S.fill).attr("stroke",S=>S.strokeColor).attr("stroke-width",S=>S.strokeWidth),E.append("text").attr("x",0).attr("y",0).text(S=>S.text.text).attr("fill",S=>S.text.fill).attr("font-size",S=>S.text.fontSize).attr("dominant-baseline",S=>n(S.text.horizontalPos)).attr("text-anchor",S=>a(S.text.verticalPos)).attr("transform",S=>s(S.text))},"draw"),Rwe={draw:Jut}});var Iwe={};ur(Iwe,{diagram:()=>eht});var eht,Mwe=P(()=>{"use strict";wwe();Lwe();Nwe();eht={parser:Cwe,db:Dwe,renderer:Rwe,styles:o(()=>"","styles")}});var UW,Bwe,Fwe=P(()=>{"use strict";UW=(function(){var t=o(function(N,R,B,O){for(B=B||{},O=N.length;O--;B[N[O]]=R);return B},"o"),e=[1,10,12,14,16,18,19,21,23],r=[2,6],i=[1,3],n=[1,5],a=[1,6],s=[1,7],l=[1,5,10,12,14,16,18,19,21,23,34,35,36],u=[1,25],h=[1,26],f=[1,28],d=[1,29],p=[1,30],m=[1,31],g=[1,32],y=[1,33],v=[1,34],x=[1,35],b=[1,36],T=[1,37],w=[1,43],k=[1,42],C=[1,47],E=[1,50],S=[1,10,12,14,16,18,19,21,23,34,35,36],L=[1,10,12,14,16,18,19,21,23,24,26,27,28,34,35,36],M=[1,10,12,14,16,18,19,21,23,24,26,27,28,34,35,36,41,42,43,44,45,46,47,48,49,50],I=[1,64],A={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,eol:4,XYCHART:5,chartConfig:6,document:7,CHART_ORIENTATION:8,statement:9,title:10,text:11,X_AXIS:12,parseXAxis:13,Y_AXIS:14,parseYAxis:15,LINE:16,plotData:17,BAR:18,acc_title:19,acc_title_value:20,acc_descr:21,acc_descr_value:22,acc_descr_multiline_value:23,SQUARE_BRACES_START:24,commaSeparatedNumbers:25,SQUARE_BRACES_END:26,NUMBER_WITH_DECIMAL:27,COMMA:28,xAxisData:29,bandData:30,ARROW_DELIMITER:31,commaSeparatedTexts:32,yAxisData:33,NEWLINE:34,SEMI:35,EOF:36,alphaNum:37,STR:38,MD_STR:39,alphaNumToken:40,AMP:41,NUM:42,ALPHA:43,PLUS:44,EQUALS:45,MULT:46,DOT:47,BRKT:48,MINUS:49,UNDERSCORE:50,$accept:0,$end:1},terminals_:{2:"error",5:"XYCHART",8:"CHART_ORIENTATION",10:"title",12:"X_AXIS",14:"Y_AXIS",16:"LINE",18:"BAR",19:"acc_title",20:"acc_title_value",21:"acc_descr",22:"acc_descr_value",23:"acc_descr_multiline_value",24:"SQUARE_BRACES_START",26:"SQUARE_BRACES_END",27:"NUMBER_WITH_DECIMAL",28:"COMMA",31:"ARROW_DELIMITER",34:"NEWLINE",35:"SEMI",36:"EOF",38:"STR",39:"MD_STR",41:"AMP",42:"NUM",43:"ALPHA",44:"PLUS",45:"EQUALS",46:"MULT",47:"DOT",48:"BRKT",49:"MINUS",50:"UNDERSCORE"},productions_:[0,[3,2],[3,3],[3,2],[3,1],[6,1],[7,0],[7,2],[9,2],[9,2],[9,2],[9,2],[9,2],[9,3],[9,2],[9,3],[9,2],[9,2],[9,1],[17,3],[25,3],[25,1],[13,1],[13,2],[13,1],[29,1],[29,3],[30,3],[32,3],[32,1],[15,1],[15,2],[15,1],[33,3],[4,1],[4,1],[4,1],[11,1],[11,1],[11,1],[37,1],[37,2],[40,1],[40,1],[40,1],[40,1],[40,1],[40,1],[40,1],[40,1],[40,1],[40,1]],performAction:o(function(R,B,O,$,z,F,V){var H=F.length-1;switch(z){case 5:$.setOrientation(F[H]);break;case 9:$.setDiagramTitle(F[H].text.trim());break;case 12:$.setLineData({text:"",type:"text"},F[H]);break;case 13:$.setLineData(F[H-1],F[H]);break;case 14:$.setBarData({text:"",type:"text"},F[H]);break;case 15:$.setBarData(F[H-1],F[H]);break;case 16:this.$=F[H].trim(),$.setAccTitle(this.$);break;case 17:case 18:this.$=F[H].trim(),$.setAccDescription(this.$);break;case 19:this.$=F[H-1];break;case 20:this.$=[Number(F[H-2]),...F[H]];break;case 21:this.$=[Number(F[H])];break;case 22:$.setXAxisTitle(F[H]);break;case 23:$.setXAxisTitle(F[H-1]);break;case 24:$.setXAxisTitle({type:"text",text:""});break;case 25:$.setXAxisBand(F[H]);break;case 26:$.setXAxisRangeData(Number(F[H-2]),Number(F[H]));break;case 27:this.$=F[H-1];break;case 28:this.$=[F[H-2],...F[H]];break;case 29:this.$=[F[H]];break;case 30:$.setYAxisTitle(F[H]);break;case 31:$.setYAxisTitle(F[H-1]);break;case 32:$.setYAxisTitle({type:"text",text:""});break;case 33:$.setYAxisRangeData(Number(F[H-2]),Number(F[H]));break;case 37:this.$={text:F[H],type:"text"};break;case 38:this.$={text:F[H],type:"text"};break;case 39:this.$={text:F[H],type:"markdown"};break;case 40:this.$=F[H];break;case 41:this.$=F[H-1]+""+F[H];break}},"anonymous"),table:[t(e,r,{3:1,4:2,7:4,5:i,34:n,35:a,36:s}),{1:[3]},t(e,r,{4:2,7:4,3:8,5:i,34:n,35:a,36:s}),t(e,r,{4:2,7:4,6:9,3:10,5:i,8:[1,11],34:n,35:a,36:s}),{1:[2,4],9:12,10:[1,13],12:[1,14],14:[1,15],16:[1,16],18:[1,17],19:[1,18],21:[1,19],23:[1,20]},t(l,[2,34]),t(l,[2,35]),t(l,[2,36]),{1:[2,1]},t(e,r,{4:2,7:4,3:21,5:i,34:n,35:a,36:s}),{1:[2,3]},t(l,[2,5]),t(e,[2,7],{4:22,34:n,35:a,36:s}),{11:23,37:24,38:u,39:h,40:27,41:f,42:d,43:p,44:m,45:g,46:y,47:v,48:x,49:b,50:T},{11:39,13:38,24:w,27:k,29:40,30:41,37:24,38:u,39:h,40:27,41:f,42:d,43:p,44:m,45:g,46:y,47:v,48:x,49:b,50:T},{11:45,15:44,27:C,33:46,37:24,38:u,39:h,40:27,41:f,42:d,43:p,44:m,45:g,46:y,47:v,48:x,49:b,50:T},{11:49,17:48,24:E,37:24,38:u,39:h,40:27,41:f,42:d,43:p,44:m,45:g,46:y,47:v,48:x,49:b,50:T},{11:52,17:51,24:E,37:24,38:u,39:h,40:27,41:f,42:d,43:p,44:m,45:g,46:y,47:v,48:x,49:b,50:T},{20:[1,53]},{22:[1,54]},t(S,[2,18]),{1:[2,2]},t(S,[2,8]),t(S,[2,9]),t(L,[2,37],{40:55,41:f,42:d,43:p,44:m,45:g,46:y,47:v,48:x,49:b,50:T}),t(L,[2,38]),t(L,[2,39]),t(M,[2,40]),t(M,[2,42]),t(M,[2,43]),t(M,[2,44]),t(M,[2,45]),t(M,[2,46]),t(M,[2,47]),t(M,[2,48]),t(M,[2,49]),t(M,[2,50]),t(M,[2,51]),t(S,[2,10]),t(S,[2,22],{30:41,29:56,24:w,27:k}),t(S,[2,24]),t(S,[2,25]),{31:[1,57]},{11:59,32:58,37:24,38:u,39:h,40:27,41:f,42:d,43:p,44:m,45:g,46:y,47:v,48:x,49:b,50:T},t(S,[2,11]),t(S,[2,30],{33:60,27:C}),t(S,[2,32]),{31:[1,61]},t(S,[2,12]),{17:62,24:E},{25:63,27:I},t(S,[2,14]),{17:65,24:E},t(S,[2,16]),t(S,[2,17]),t(M,[2,41]),t(S,[2,23]),{27:[1,66]},{26:[1,67]},{26:[2,29],28:[1,68]},t(S,[2,31]),{27:[1,69]},t(S,[2,13]),{26:[1,70]},{26:[2,21],28:[1,71]},t(S,[2,15]),t(S,[2,26]),t(S,[2,27]),{11:59,32:72,37:24,38:u,39:h,40:27,41:f,42:d,43:p,44:m,45:g,46:y,47:v,48:x,49:b,50:T},t(S,[2,33]),t(S,[2,19]),{25:73,27:I},{26:[2,28]},{26:[2,20]}],defaultActions:{8:[2,1],10:[2,3],21:[2,2],72:[2,28],73:[2,20]},parseError:o(function(R,B){if(B.recoverable)this.trace(R);else{var O=new Error(R);throw O.hash=B,O}},"parseError"),parse:o(function(R){var B=this,O=[0],$=[],z=[null],F=[],V=this.table,H="",X=0,W=0,Z=0,Y=2,ae=1,J=F.slice.call(arguments,1),ee=Object.create(this.lexer),re={yy:{}};for(var te in this.yy)Object.prototype.hasOwnProperty.call(this.yy,te)&&(re.yy[te]=this.yy[te]);ee.setInput(R,re.yy),re.yy.lexer=ee,re.yy.parser=this,typeof ee.yylloc>"u"&&(ee.yylloc={});var be=ee.yylloc;F.push(be);var de=ee.options&&ee.options.ranges;typeof re.yy.parseError=="function"?this.parseError=re.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function Ee(K){O.length=O.length-2*K,z.length=z.length-K,F.length=F.length-K}o(Ee,"popStack");function Ne(){var K;return K=$.pop()||ee.lex()||ae,typeof K!="number"&&(K instanceof Array&&($=K,K=$.pop()),K=B.symbols_[K]||K),K}o(Ne,"lex");for(var we,Te,De,$e,pe,Je,Ce={},Fe,Ue,qe,Me;;){if(De=O[O.length-1],this.defaultActions[De]?$e=this.defaultActions[De]:((we===null||typeof we>"u")&&(we=Ne()),$e=V[De]&&V[De][we]),typeof $e>"u"||!$e.length||!$e[0]){var He="";Me=[];for(Fe in V[De])this.terminals_[Fe]&&Fe>Y&&Me.push("'"+this.terminals_[Fe]+"'");ee.showPosition?He="Parse error on line "+(X+1)+`: +`+ee.showPosition()+` +Expecting `+Me.join(", ")+", got '"+(this.terminals_[we]||we)+"'":He="Parse error on line "+(X+1)+": Unexpected "+(we==ae?"end of input":"'"+(this.terminals_[we]||we)+"'"),this.parseError(He,{text:ee.match,token:this.terminals_[we]||we,line:ee.yylineno,loc:be,expected:Me})}if($e[0]instanceof Array&&$e.length>1)throw new Error("Parse Error: multiple actions possible at state: "+De+", token: "+we);switch($e[0]){case 1:O.push(we),z.push(ee.yytext),F.push(ee.yylloc),O.push($e[1]),we=null,Te?(we=Te,Te=null):(W=ee.yyleng,H=ee.yytext,X=ee.yylineno,be=ee.yylloc,Z>0&&Z--);break;case 2:if(Ue=this.productions_[$e[1]][1],Ce.$=z[z.length-Ue],Ce._$={first_line:F[F.length-(Ue||1)].first_line,last_line:F[F.length-1].last_line,first_column:F[F.length-(Ue||1)].first_column,last_column:F[F.length-1].last_column},de&&(Ce._$.range=[F[F.length-(Ue||1)].range[0],F[F.length-1].range[1]]),Je=this.performAction.apply(Ce,[H,W,X,re.yy,$e[1],z,F].concat(J)),typeof Je<"u")return Je;Ue&&(O=O.slice(0,-1*Ue*2),z=z.slice(0,-1*Ue),F=F.slice(0,-1*Ue)),O.push(this.productions_[$e[1]][0]),z.push(Ce.$),F.push(Ce._$),qe=V[O[O.length-2]][O[O.length-1]],O.push(qe);break;case 3:return!0}}return!0},"parse")},_=(function(){var N={EOF:1,parseError:o(function(B,O){if(this.yy.parser)this.yy.parser.parseError(B,O);else throw new Error(B)},"parseError"),setInput:o(function(R,B){return this.yy=B||this.yy||{},this._input=R,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var R=this._input[0];this.yytext+=R,this.yyleng++,this.offset++,this.match+=R,this.matched+=R;var B=R.match(/(?:\r\n?|\n).*/g);return B?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),R},"input"),unput:o(function(R){var B=R.length,O=R.split(/(?:\r\n?|\n)/g);this._input=R+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-B),this.offset-=B;var $=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),O.length-1&&(this.yylineno-=O.length-1);var z=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:O?(O.length===$.length?this.yylloc.first_column:0)+$[$.length-O.length].length-O[0].length:this.yylloc.first_column-B},this.options.ranges&&(this.yylloc.range=[z[0],z[0]+this.yyleng-B]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(R){this.unput(this.match.slice(R))},"less"),pastInput:o(function(){var R=this.matched.substr(0,this.matched.length-this.match.length);return(R.length>20?"...":"")+R.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var R=this.match;return R.length<20&&(R+=this._input.substr(0,20-R.length)),(R.substr(0,20)+(R.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var R=this.pastInput(),B=new Array(R.length+1).join("-");return R+this.upcomingInput()+` +`+B+"^"},"showPosition"),test_match:o(function(R,B){var O,$,z;if(this.options.backtrack_lexer&&(z={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(z.yylloc.range=this.yylloc.range.slice(0))),$=R[0].match(/(?:\r\n?|\n).*/g),$&&(this.yylineno+=$.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:$?$[$.length-1].length-$[$.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+R[0].length},this.yytext+=R[0],this.match+=R[0],this.matches=R,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(R[0].length),this.matched+=R[0],O=this.performAction.call(this,this.yy,this,B,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),O)return O;if(this._backtrack){for(var F in z)this[F]=z[F];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var R,B,O,$;this._more||(this.yytext="",this.match="");for(var z=this._currentRules(),F=0;FB[0].length)){if(B=O,$=F,this.options.backtrack_lexer){if(R=this.test_match(O,z[F]),R!==!1)return R;if(this._backtrack){B=!1;continue}else return!1}else if(!this.options.flex)break}return B?(R=this.test_match(B,z[$]),R!==!1?R:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var B=this.next();return B||this.lex()},"lex"),begin:o(function(B){this.conditionStack.push(B)},"begin"),popState:o(function(){var B=this.conditionStack.length-1;return B>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(B){return B=this.conditionStack.length-1-Math.abs(B||0),B>=0?this.conditionStack[B]:"INITIAL"},"topState"),pushState:o(function(B){this.begin(B)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:o(function(B,O,$,z){var F=z;switch($){case 0:break;case 1:break;case 2:return this.popState(),34;break;case 3:return this.popState(),34;break;case 4:return 34;case 5:break;case 6:return 10;case 7:return this.pushState("acc_title"),19;break;case 8:return this.popState(),"acc_title_value";break;case 9:return this.pushState("acc_descr"),21;break;case 10:return this.popState(),"acc_descr_value";break;case 11:this.pushState("acc_descr_multiline");break;case 12:this.popState();break;case 13:return"acc_descr_multiline_value";case 14:return 5;case 15:return 5;case 16:return 8;case 17:return this.pushState("axis_data"),"X_AXIS";break;case 18:return this.pushState("axis_data"),"Y_AXIS";break;case 19:return this.pushState("axis_band_data"),24;break;case 20:return 31;case 21:return this.pushState("data"),16;break;case 22:return this.pushState("data"),18;break;case 23:return this.pushState("data_inner"),24;break;case 24:return 27;case 25:return this.popState(),26;break;case 26:this.popState();break;case 27:this.pushState("string");break;case 28:this.popState();break;case 29:return"STR";case 30:return 24;case 31:return 26;case 32:return 43;case 33:return"COLON";case 34:return 44;case 35:return 28;case 36:return 45;case 37:return 46;case 38:return 48;case 39:return 50;case 40:return 47;case 41:return 41;case 42:return 49;case 43:return 42;case 44:break;case 45:return 35;case 46:return 36}},"anonymous"),rules:[/^(?:%%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:(\r?\n))/i,/^(?:(\r?\n))/i,/^(?:[\n\r]+)/i,/^(?:%%[^\n]*)/i,/^(?:title\b)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:\})/i,/^(?:[^\}]*)/i,/^(?:xychart-beta\b)/i,/^(?:xychart\b)/i,/^(?:(?:vertical|horizontal))/i,/^(?:x-axis\b)/i,/^(?:y-axis\b)/i,/^(?:\[)/i,/^(?:-->)/i,/^(?:line\b)/i,/^(?:bar\b)/i,/^(?:\[)/i,/^(?:[+-]?(?:\d+(?:\.\d+)?|\.\d+))/i,/^(?:\])/i,/^(?:(?:`\) \{ this\.pushState\(md_string\); \}\n\(\?:\(\?!`"\)\.\)\+ \{ return MD_STR; \}\n\(\?:`))/i,/^(?:["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:\[)/i,/^(?:\])/i,/^(?:[A-Za-z]+)/i,/^(?::)/i,/^(?:\+)/i,/^(?:,)/i,/^(?:=)/i,/^(?:\*)/i,/^(?:#)/i,/^(?:[\_])/i,/^(?:\.)/i,/^(?:&)/i,/^(?:-)/i,/^(?:[0-9]+)/i,/^(?:\s+)/i,/^(?:;)/i,/^(?:$)/i],conditions:{data_inner:{rules:[0,1,4,5,6,7,9,11,14,15,16,17,18,21,22,24,25,26,27,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],inclusive:!0},data:{rules:[0,1,3,4,5,6,7,9,11,14,15,16,17,18,21,22,23,26,27,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],inclusive:!0},axis_band_data:{rules:[0,1,4,5,6,7,9,11,14,15,16,17,18,21,22,25,26,27,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],inclusive:!0},axis_data:{rules:[0,1,2,4,5,6,7,9,11,14,15,16,17,18,19,20,21,22,24,26,27,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],inclusive:!0},acc_descr_multiline:{rules:[12,13],inclusive:!1},acc_descr:{rules:[10],inclusive:!1},acc_title:{rules:[8],inclusive:!1},title:{rules:[],inclusive:!1},md_string:{rules:[],inclusive:!1},string:{rules:[28,29],inclusive:!1},INITIAL:{rules:[0,1,4,5,6,7,9,11,14,15,16,17,18,21,22,26,27,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46],inclusive:!0}}};return N})();A.lexer=_;function D(){this.yy={}}return o(D,"Parser"),D.prototype=A,A.Parser=D,new D})();UW.parser=UW;Bwe=UW});function HW(t){return t.type==="bar"}function h_(t){return t.type==="band"}function Qv(t){return t.type==="linear"}var f_=P(()=>{"use strict";o(HW,"isBarPlot");o(h_,"isBandAxisData");o(Qv,"isLinearAxisData")});var Zv,YW=P(()=>{"use strict";To();Zv=class{constructor(e){this.parentGroup=e}static{o(this,"TextDimensionCalculatorWithFont")}getMaxDimension(e,r){if(!this.parentGroup)return{width:e.reduce((a,s)=>Math.max(s.length,a),0)*r,height:r};let i={width:0,height:0},n=this.parentGroup.append("g").attr("visibility","hidden").attr("font-size",r);for(let a of e){let s=zae(n,1,a),l=s?s.width:a.length*r,u=s?s.height:r;i.width=Math.max(i.width,l),i.height=Math.max(i.height,u)}return n.remove(),i}}});var Jv,jW=P(()=>{"use strict";Jv=class{constructor(e,r,i,n){this.axisConfig=e;this.title=r;this.textDimensionCalculator=i;this.axisThemeConfig=n;this.boundingRect={x:0,y:0,width:0,height:0};this.axisPosition="left";this.showTitle=!1;this.showLabel=!1;this.showTick=!1;this.showAxisLine=!1;this.outerPadding=0;this.titleTextHeight=0;this.labelTextHeight=0;this.range=[0,10],this.boundingRect={x:0,y:0,width:0,height:0},this.axisPosition="left"}static{o(this,"BaseAxis")}setRange(e){this.range=e,this.axisPosition==="left"||this.axisPosition==="right"?this.boundingRect.height=e[1]-e[0]:this.boundingRect.width=e[1]-e[0],this.recalculateScale()}getRange(){return[this.range[0]+this.outerPadding,this.range[1]-this.outerPadding]}setAxisPosition(e){this.axisPosition=e,this.setRange(this.range)}getTickDistance(){let e=this.getRange();return Math.abs(e[0]-e[1])/this.getTickValues().length}getAxisOuterPadding(){return this.outerPadding}getLabelDimension(){return this.textDimensionCalculator.getMaxDimension(this.getTickValues().map(e=>e.toString()),this.axisConfig.labelFontSize)}recalculateOuterPaddingToDrawBar(){.7*this.getTickDistance()>this.outerPadding*2&&(this.outerPadding=Math.floor(.7*this.getTickDistance()/2)),this.recalculateScale()}calculateSpaceIfDrawnHorizontally(e){let r=e.height;if(this.axisConfig.showAxisLine&&r>this.axisConfig.axisLineWidth&&(r-=this.axisConfig.axisLineWidth,this.showAxisLine=!0),this.axisConfig.showLabel){let i=this.getLabelDimension(),n=.2*e.width;this.outerPadding=Math.min(i.width/2,n);let a=i.height+this.axisConfig.labelPadding*2;this.labelTextHeight=i.height,a<=r&&(r-=a,this.showLabel=!0)}if(this.axisConfig.showTick&&r>=this.axisConfig.tickLength&&(this.showTick=!0,r-=this.axisConfig.tickLength),this.axisConfig.showTitle&&this.title){let i=this.textDimensionCalculator.getMaxDimension([this.title],this.axisConfig.titleFontSize),n=i.height+this.axisConfig.titlePadding*2;this.titleTextHeight=i.height,n<=r&&(r-=n,this.showTitle=!0)}this.boundingRect.width=e.width,this.boundingRect.height=e.height-r}calculateSpaceIfDrawnVertical(e){let r=e.width;if(this.axisConfig.showAxisLine&&r>this.axisConfig.axisLineWidth&&(r-=this.axisConfig.axisLineWidth,this.showAxisLine=!0),this.axisConfig.showLabel){let i=this.getLabelDimension(),n=.2*e.height;this.outerPadding=Math.min(i.height/2,n);let a=i.width+this.axisConfig.labelPadding*2;a<=r&&(r-=a,this.showLabel=!0)}if(this.axisConfig.showTick&&r>=this.axisConfig.tickLength&&(this.showTick=!0,r-=this.axisConfig.tickLength),this.axisConfig.showTitle&&this.title){let i=this.textDimensionCalculator.getMaxDimension([this.title],this.axisConfig.titleFontSize),n=i.height+this.axisConfig.titlePadding*2;this.titleTextHeight=i.height,n<=r&&(r-=n,this.showTitle=!0)}this.boundingRect.width=e.width-r,this.boundingRect.height=e.height}calculateSpace(e){return this.axisPosition==="left"||this.axisPosition==="right"?this.calculateSpaceIfDrawnVertical(e):this.calculateSpaceIfDrawnHorizontally(e),this.recalculateScale(),{width:this.boundingRect.width,height:this.boundingRect.height}}setBoundingBoxXY(e){this.boundingRect.x=e.x,this.boundingRect.y=e.y}getDrawableElementsForLeftAxis(){let e=[];if(this.showAxisLine){let r=this.boundingRect.x+this.boundingRect.width-this.axisConfig.axisLineWidth/2;e.push({type:"path",groupTexts:["left-axis","axisl-line"],data:[{path:`M ${r},${this.boundingRect.y} L ${r},${this.boundingRect.y+this.boundingRect.height} `,strokeFill:this.axisThemeConfig.axisLineColor,strokeWidth:this.axisConfig.axisLineWidth}]})}if(this.showLabel&&e.push({type:"text",groupTexts:["left-axis","label"],data:this.getTickValues().map(r=>({text:r.toString(),x:this.boundingRect.x+this.boundingRect.width-(this.showLabel?this.axisConfig.labelPadding:0)-(this.showTick?this.axisConfig.tickLength:0)-(this.showAxisLine?this.axisConfig.axisLineWidth:0),y:this.getScaleValue(r),fill:this.axisThemeConfig.labelColor,fontSize:this.axisConfig.labelFontSize,rotation:0,verticalPos:"middle",horizontalPos:"right"}))}),this.showTick){let r=this.boundingRect.x+this.boundingRect.width-(this.showAxisLine?this.axisConfig.axisLineWidth:0);e.push({type:"path",groupTexts:["left-axis","ticks"],data:this.getTickValues().map(i=>({path:`M ${r},${this.getScaleValue(i)} L ${r-this.axisConfig.tickLength},${this.getScaleValue(i)}`,strokeFill:this.axisThemeConfig.tickColor,strokeWidth:this.axisConfig.tickWidth}))})}return this.showTitle&&e.push({type:"text",groupTexts:["left-axis","title"],data:[{text:this.title,x:this.boundingRect.x+this.axisConfig.titlePadding,y:this.boundingRect.y+this.boundingRect.height/2,fill:this.axisThemeConfig.titleColor,fontSize:this.axisConfig.titleFontSize,rotation:270,verticalPos:"top",horizontalPos:"center"}]}),e}getDrawableElementsForBottomAxis(){let e=[];if(this.showAxisLine){let r=this.boundingRect.y+this.axisConfig.axisLineWidth/2;e.push({type:"path",groupTexts:["bottom-axis","axis-line"],data:[{path:`M ${this.boundingRect.x},${r} L ${this.boundingRect.x+this.boundingRect.width},${r}`,strokeFill:this.axisThemeConfig.axisLineColor,strokeWidth:this.axisConfig.axisLineWidth}]})}if(this.showLabel&&e.push({type:"text",groupTexts:["bottom-axis","label"],data:this.getTickValues().map(r=>({text:r.toString(),x:this.getScaleValue(r),y:this.boundingRect.y+this.axisConfig.labelPadding+(this.showTick?this.axisConfig.tickLength:0)+(this.showAxisLine?this.axisConfig.axisLineWidth:0),fill:this.axisThemeConfig.labelColor,fontSize:this.axisConfig.labelFontSize,rotation:0,verticalPos:"top",horizontalPos:"center"}))}),this.showTick){let r=this.boundingRect.y+(this.showAxisLine?this.axisConfig.axisLineWidth:0);e.push({type:"path",groupTexts:["bottom-axis","ticks"],data:this.getTickValues().map(i=>({path:`M ${this.getScaleValue(i)},${r} L ${this.getScaleValue(i)},${r+this.axisConfig.tickLength}`,strokeFill:this.axisThemeConfig.tickColor,strokeWidth:this.axisConfig.tickWidth}))})}return this.showTitle&&e.push({type:"text",groupTexts:["bottom-axis","title"],data:[{text:this.title,x:this.range[0]+(this.range[1]-this.range[0])/2,y:this.boundingRect.y+this.boundingRect.height-this.axisConfig.titlePadding-this.titleTextHeight,fill:this.axisThemeConfig.titleColor,fontSize:this.axisConfig.titleFontSize,rotation:0,verticalPos:"top",horizontalPos:"center"}]}),e}getDrawableElementsForTopAxis(){let e=[];if(this.showAxisLine){let r=this.boundingRect.y+this.boundingRect.height-this.axisConfig.axisLineWidth/2;e.push({type:"path",groupTexts:["top-axis","axis-line"],data:[{path:`M ${this.boundingRect.x},${r} L ${this.boundingRect.x+this.boundingRect.width},${r}`,strokeFill:this.axisThemeConfig.axisLineColor,strokeWidth:this.axisConfig.axisLineWidth}]})}if(this.showLabel&&e.push({type:"text",groupTexts:["top-axis","label"],data:this.getTickValues().map(r=>({text:r.toString(),x:this.getScaleValue(r),y:this.boundingRect.y+(this.showTitle?this.titleTextHeight+this.axisConfig.titlePadding*2:0)+this.axisConfig.labelPadding,fill:this.axisThemeConfig.labelColor,fontSize:this.axisConfig.labelFontSize,rotation:0,verticalPos:"top",horizontalPos:"center"}))}),this.showTick){let r=this.boundingRect.y;e.push({type:"path",groupTexts:["top-axis","ticks"],data:this.getTickValues().map(i=>({path:`M ${this.getScaleValue(i)},${r+this.boundingRect.height-(this.showAxisLine?this.axisConfig.axisLineWidth:0)} L ${this.getScaleValue(i)},${r+this.boundingRect.height-this.axisConfig.tickLength-(this.showAxisLine?this.axisConfig.axisLineWidth:0)}`,strokeFill:this.axisThemeConfig.tickColor,strokeWidth:this.axisConfig.tickWidth}))})}return this.showTitle&&e.push({type:"text",groupTexts:["top-axis","title"],data:[{text:this.title,x:this.boundingRect.x+this.boundingRect.width/2,y:this.boundingRect.y+this.axisConfig.titlePadding,fill:this.axisThemeConfig.titleColor,fontSize:this.axisConfig.titleFontSize,rotation:0,verticalPos:"top",horizontalPos:"center"}]}),e}getDrawableElements(){if(this.axisPosition==="left")return this.getDrawableElementsForLeftAxis();if(this.axisPosition==="right")throw Error("Drawing of right axis is not implemented");return this.axisPosition==="bottom"?this.getDrawableElementsForBottomAxis():this.axisPosition==="top"?this.getDrawableElementsForTopAxis():[]}}});var d_,$we=P(()=>{"use strict";Pr();bt();jW();d_=class extends Jv{static{o(this,"BandAxis")}constructor(e,r,i,n,a){super(e,n,a,r),this.categories=i,this.scale=Kg().domain(this.categories).range(this.getRange())}setRange(e){super.setRange(e)}recalculateScale(){this.scale=Kg().domain(this.categories).range(this.getRange()).paddingInner(1).paddingOuter(0).align(.5),Q.trace("BandAxis axis final categories, range: ",this.categories,this.getRange())}getTickValues(){return this.categories}getScaleValue(e){return this.scale(e)??this.getRange()[0]}}});var p_,zwe=P(()=>{"use strict";Pr();jW();p_=class extends Jv{static{o(this,"LinearAxis")}constructor(e,r,i,n,a){super(e,n,a,r),this.domain=i,this.scale=vc().domain(this.domain).range(this.getRange())}getTickValues(){return this.scale.ticks()}recalculateScale(){let e=[...this.domain];this.axisPosition==="left"&&e.reverse(),this.scale=vc().domain(e).range(this.getRange())}getScaleValue(e){return this.scale(e)}}});function XW(t,e,r,i){let n=new Zv(i);return h_(t)?new d_(e,r,t.categories,t.title,n):new p_(e,r,[t.min,t.max],t.title,n)}var Gwe=P(()=>{"use strict";f_();YW();$we();zwe();o(XW,"getAxis")});function Vwe(t,e,r,i){let n=new Zv(i);return new KW(n,t,e,r)}var KW,qwe=P(()=>{"use strict";YW();KW=class{constructor(e,r,i,n){this.textDimensionCalculator=e;this.chartConfig=r;this.chartData=i;this.chartThemeConfig=n;this.boundingRect={x:0,y:0,width:0,height:0},this.showChartTitle=!1}static{o(this,"ChartTitle")}setBoundingBoxXY(e){this.boundingRect.x=e.x,this.boundingRect.y=e.y}calculateSpace(e){let r=this.textDimensionCalculator.getMaxDimension([this.chartData.title],this.chartConfig.titleFontSize),i=Math.max(r.width,e.width),n=r.height+2*this.chartConfig.titlePadding;return r.width<=i&&r.height<=n&&this.chartConfig.showTitle&&this.chartData.title&&(this.boundingRect.width=i,this.boundingRect.height=n,this.showChartTitle=!0),{width:this.boundingRect.width,height:this.boundingRect.height}}getDrawableElements(){let e=[];return this.showChartTitle&&e.push({groupTexts:["chart-title"],type:"text",data:[{fontSize:this.chartConfig.titleFontSize,text:this.chartData.title,verticalPos:"middle",horizontalPos:"center",x:this.boundingRect.x+this.boundingRect.width/2,y:this.boundingRect.y+this.boundingRect.height/2,fill:this.chartThemeConfig.titleColor,rotation:0}]}),e}};o(Vwe,"getChartTitleComponent")});var m_,Wwe=P(()=>{"use strict";Pr();m_=class{constructor(e,r,i,n,a){this.plotData=e;this.xAxis=r;this.yAxis=i;this.orientation=n;this.plotIndex=a}static{o(this,"LinePlot")}getDrawableElement(){let e=this.plotData.data.map(i=>[this.xAxis.getScaleValue(i[0]),this.yAxis.getScaleValue(i[1])]),r;return this.orientation==="horizontal"?r=Cc().y(i=>i[0]).x(i=>i[1])(e):r=Cc().x(i=>i[0]).y(i=>i[1])(e),r?[{groupTexts:["plot",`line-plot-${this.plotIndex}`],type:"path",data:[{path:r,strokeFill:this.plotData.strokeFill,strokeWidth:this.plotData.strokeWidth}]}]:[]}}});var g_,Uwe=P(()=>{"use strict";g_=class{constructor(e,r,i,n,a,s){this.barData=e;this.boundingRect=r;this.xAxis=i;this.yAxis=n;this.orientation=a;this.plotIndex=s}static{o(this,"BarPlot")}getDrawableElement(){let e=this.barData.data.map(a=>[this.xAxis.getScaleValue(a[0]),this.yAxis.getScaleValue(a[1])]),i=Math.min(this.xAxis.getAxisOuterPadding()*2,this.xAxis.getTickDistance())*(1-.05),n=i/2;return this.orientation==="horizontal"?[{groupTexts:["plot",`bar-plot-${this.plotIndex}`],type:"rect",data:e.map(a=>({x:this.boundingRect.x,y:a[0]-n,height:i,width:a[1]-this.boundingRect.x,fill:this.barData.fill,strokeWidth:0,strokeFill:this.barData.fill}))}]:[{groupTexts:["plot",`bar-plot-${this.plotIndex}`],type:"rect",data:e.map(a=>({x:a[0]-n,y:a[1],width:i,height:this.boundingRect.y+this.boundingRect.height-a[1],fill:this.barData.fill,strokeWidth:0,strokeFill:this.barData.fill}))}]}}});function Hwe(t,e,r){return new QW(t,e,r)}var QW,Ywe=P(()=>{"use strict";Wwe();Uwe();QW=class{constructor(e,r,i){this.chartConfig=e;this.chartData=r;this.chartThemeConfig=i;this.boundingRect={x:0,y:0,width:0,height:0}}static{o(this,"BasePlot")}setAxes(e,r){this.xAxis=e,this.yAxis=r}setBoundingBoxXY(e){this.boundingRect.x=e.x,this.boundingRect.y=e.y}calculateSpace(e){return this.boundingRect.width=e.width,this.boundingRect.height=e.height,{width:this.boundingRect.width,height:this.boundingRect.height}}getDrawableElements(){if(!(this.xAxis&&this.yAxis))throw Error("Axes must be passed to render Plots");let e=[];for(let[r,i]of this.chartData.plots.entries())switch(i.type){case"line":{let n=new m_(i,this.xAxis,this.yAxis,this.chartConfig.chartOrientation,r);e.push(...n.getDrawableElement())}break;case"bar":{let n=new g_(i,this.boundingRect,this.xAxis,this.yAxis,this.chartConfig.chartOrientation,r);e.push(...n.getDrawableElement())}break}return e}};o(Hwe,"getPlotComponent")});var y_,jwe=P(()=>{"use strict";Gwe();qwe();Ywe();f_();y_=class{constructor(e,r,i,n){this.chartConfig=e;this.chartData=r;this.componentStore={title:Vwe(e,r,i,n),plot:Hwe(e,r,i),xAxis:XW(r.xAxis,e.xAxis,{titleColor:i.xAxisTitleColor,labelColor:i.xAxisLabelColor,tickColor:i.xAxisTickColor,axisLineColor:i.xAxisLineColor},n),yAxis:XW(r.yAxis,e.yAxis,{titleColor:i.yAxisTitleColor,labelColor:i.yAxisLabelColor,tickColor:i.yAxisTickColor,axisLineColor:i.yAxisLineColor},n)}}static{o(this,"Orchestrator")}calculateVerticalSpace(){let e=this.chartConfig.width,r=this.chartConfig.height,i=0,n=0,a=Math.floor(e*this.chartConfig.plotReservedSpacePercent/100),s=Math.floor(r*this.chartConfig.plotReservedSpacePercent/100),l=this.componentStore.plot.calculateSpace({width:a,height:s});e-=l.width,r-=l.height,l=this.componentStore.title.calculateSpace({width:this.chartConfig.width,height:r}),n=l.height,r-=l.height,this.componentStore.xAxis.setAxisPosition("bottom"),l=this.componentStore.xAxis.calculateSpace({width:e,height:r}),r-=l.height,this.componentStore.yAxis.setAxisPosition("left"),l=this.componentStore.yAxis.calculateSpace({width:e,height:r}),i=l.width,e-=l.width,e>0&&(a+=e,e=0),r>0&&(s+=r,r=0),this.componentStore.plot.calculateSpace({width:a,height:s}),this.componentStore.plot.setBoundingBoxXY({x:i,y:n}),this.componentStore.xAxis.setRange([i,i+a]),this.componentStore.xAxis.setBoundingBoxXY({x:i,y:n+s}),this.componentStore.yAxis.setRange([n,n+s]),this.componentStore.yAxis.setBoundingBoxXY({x:0,y:n}),this.chartData.plots.some(u=>HW(u))&&this.componentStore.xAxis.recalculateOuterPaddingToDrawBar()}calculateHorizontalSpace(){let e=this.chartConfig.width,r=this.chartConfig.height,i=0,n=0,a=0,s=Math.floor(e*this.chartConfig.plotReservedSpacePercent/100),l=Math.floor(r*this.chartConfig.plotReservedSpacePercent/100),u=this.componentStore.plot.calculateSpace({width:s,height:l});e-=u.width,r-=u.height,u=this.componentStore.title.calculateSpace({width:this.chartConfig.width,height:r}),i=u.height,r-=u.height,this.componentStore.xAxis.setAxisPosition("left"),u=this.componentStore.xAxis.calculateSpace({width:e,height:r}),e-=u.width,n=u.width,this.componentStore.yAxis.setAxisPosition("top"),u=this.componentStore.yAxis.calculateSpace({width:e,height:r}),r-=u.height,a=i+u.height,e>0&&(s+=e,e=0),r>0&&(l+=r,r=0),this.componentStore.plot.calculateSpace({width:s,height:l}),this.componentStore.plot.setBoundingBoxXY({x:n,y:a}),this.componentStore.yAxis.setRange([n,n+s]),this.componentStore.yAxis.setBoundingBoxXY({x:n,y:i}),this.componentStore.xAxis.setRange([a,a+l]),this.componentStore.xAxis.setBoundingBoxXY({x:0,y:a}),this.chartData.plots.some(h=>HW(h))&&this.componentStore.xAxis.recalculateOuterPaddingToDrawBar()}calculateSpace(){this.chartConfig.chartOrientation==="horizontal"?this.calculateHorizontalSpace():this.calculateVerticalSpace()}getDrawableElement(){this.calculateSpace();let e=[];this.componentStore.plot.setAxes(this.componentStore.xAxis,this.componentStore.yAxis);for(let r of Object.values(this.componentStore))e.push(...r.getDrawableElements());return e}}});var v_,Xwe=P(()=>{"use strict";jwe();v_=class{static{o(this,"XYChartBuilder")}static build(e,r,i,n){return new y_(e,r,i,n).getDrawableElement()}}});function Qwe(){let t=Zc(),e=Lt();return fi(t.xyChart,e.themeVariables.xyChart)}function Zwe(){let t=Lt();return fi(fr.xyChart,t.xyChart)}function Jwe(){return{yAxis:{type:"linear",title:"",min:1/0,max:-1/0},xAxis:{type:"band",title:"",categories:[]},title:"",plots:[]}}function eU(t){let e=Lt();return Tr(t.trim(),e)}function nht(t){Kwe=t}function aht(t){t==="horizontal"?LC.chartOrientation="horizontal":LC.chartOrientation="vertical"}function sht(t){Ni.xAxis.title=eU(t.text)}function e3e(t,e){Ni.xAxis={type:"linear",title:Ni.xAxis.title,min:t,max:e},x_=!0}function oht(t){Ni.xAxis={type:"band",title:Ni.xAxis.title,categories:t.map(e=>eU(e.text))},x_=!0}function lht(t){Ni.yAxis.title=eU(t.text)}function cht(t,e){Ni.yAxis={type:"linear",title:Ni.yAxis.title,min:t,max:e},JW=!0}function uht(t){let e=Math.min(...t),r=Math.max(...t),i=Qv(Ni.yAxis)?Ni.yAxis.min:1/0,n=Qv(Ni.yAxis)?Ni.yAxis.max:-1/0;Ni.yAxis={type:"linear",title:Ni.yAxis.title,min:Math.min(i,e),max:Math.max(n,r)}}function t3e(t){let e=[];if(t.length===0)return e;if(!x_){let r=Qv(Ni.xAxis)?Ni.xAxis.min:1/0,i=Qv(Ni.xAxis)?Ni.xAxis.max:-1/0;e3e(Math.min(r,1),Math.max(i,t.length))}if(JW||uht(t),h_(Ni.xAxis)&&(e=Ni.xAxis.categories.map((r,i)=>[r,t[i]])),Qv(Ni.xAxis)){let r=Ni.xAxis.min,i=Ni.xAxis.max,n=(i-r)/(t.length-1),a=[];for(let s=r;s<=i;s+=n)a.push(`${s}`);e=a.map((s,l)=>[s,t[l]])}return e}function r3e(t){return ZW[t===0?0:t%ZW.length]}function hht(t,e){let r=t3e(e);Ni.plots.push({type:"line",strokeFill:r3e(DC),strokeWidth:2,data:r}),DC++}function fht(t,e){let r=t3e(e);Ni.plots.push({type:"bar",fill:r3e(DC),data:r}),DC++}function dht(){if(Ni.plots.length===0)throw Error("No Plot to render, please provide a plot with some data");return Ni.title=Nr(),v_.build(LC,Ni,RC,Kwe)}function pht(){return RC}function mht(){return LC}function ght(){return Ni}var DC,Kwe,LC,RC,Ni,ZW,x_,JW,yht,i3e,n3e=P(()=>{"use strict";Sr();wa();wg();er();Vr();Ki();Xwe();f_();DC=0,LC=Zwe(),RC=Qwe(),Ni=Jwe(),ZW=RC.plotColorPalette.split(",").map(t=>t.trim()),x_=!1,JW=!1;o(Qwe,"getChartDefaultThemeConfig");o(Zwe,"getChartDefaultConfig");o(Jwe,"getChartDefaultData");o(eU,"textSanitizer");o(nht,"setTmpSVGG");o(aht,"setOrientation");o(sht,"setXAxisTitle");o(e3e,"setXAxisRangeData");o(oht,"setXAxisBand");o(lht,"setYAxisTitle");o(cht,"setYAxisRangeData");o(uht,"setYAxisRangeFromPlotData");o(t3e,"transformDataWithoutCategory");o(r3e,"getPlotColorFromPalette");o(hht,"setLineData");o(fht,"setBarData");o(dht,"getDrawableElem");o(pht,"getChartThemeConfig");o(mht,"getChartConfig");o(ght,"getXYChartData");yht=o(function(){wr(),DC=0,LC=Zwe(),Ni=Jwe(),RC=Qwe(),ZW=RC.plotColorPalette.split(",").map(t=>t.trim()),x_=!1,JW=!1},"clear"),i3e={getDrawableElem:dht,clear:yht,setAccTitle:Ar,getAccTitle:Dr,setDiagramTitle:Mr,getDiagramTitle:Nr,getAccDescription:Rr,setAccDescription:Lr,setOrientation:aht,setXAxisTitle:sht,setXAxisRangeData:e3e,setXAxisBand:oht,setYAxisTitle:lht,setYAxisRangeData:cht,setLineData:hht,setBarData:fht,setTmpSVGG:nht,getChartThemeConfig:pht,getChartConfig:mht,getXYChartData:ght}});var vht,a3e,s3e=P(()=>{"use strict";bt();ro();Xi();vht=o((t,e,r,i)=>{let n=i.db,a=n.getChartThemeConfig(),s=n.getChartConfig(),l=n.getXYChartData().plots[0].data.map(T=>T[1]);function u(T){return T==="top"?"text-before-edge":"middle"}o(u,"getDominantBaseLine");function h(T){return T==="left"?"start":T==="right"?"end":"middle"}o(h,"getTextAnchor");function f(T){return`translate(${T.x}, ${T.y}) rotate(${T.rotation||0})`}o(f,"getTextTransformation"),Q.debug(`Rendering xychart chart +`+t);let d=Fi(e),p=d.append("g").attr("class","main"),m=p.append("rect").attr("width",s.width).attr("height",s.height).attr("class","background");Hr(d,s.height,s.width,!0),d.attr("viewBox",`0 0 ${s.width} ${s.height}`),m.attr("fill",a.backgroundColor),n.setTmpSVGG(d.append("g").attr("class","mermaid-tmp-group"));let g=n.getDrawableElem(),y={};function v(T){let w=p,k="";for(let[C]of T.entries()){let E=p;C>0&&y[k]&&(E=y[k]),k+=T[C],w=y[k],w||(w=y[k]=E.append("g").attr("class",T[C]))}return w}o(v,"getGroup");for(let T of g){if(T.data.length===0)continue;let w=v(T.groupTexts);switch(T.type){case"rect":if(w.selectAll("rect").data(T.data).enter().append("rect").attr("x",k=>k.x).attr("y",k=>k.y).attr("width",k=>k.width).attr("height",k=>k.height).attr("fill",k=>k.fill).attr("stroke",k=>k.strokeFill).attr("stroke-width",k=>k.strokeWidth),s.showDataLabel){let k=s.showDataLabelOutsideBar;if(s.chartOrientation==="horizontal"){let L=function(_,D){let{data:N,label:R}=_;return D*R.length*.7<=N.width-10};var x=L;o(L,"fitsHorizontally");let C=.7,E=10,S=T.data.map((_,D)=>({data:_,label:l[D].toString()})).filter(_=>_.data.width>0&&_.data.height>0),M=S.map(_=>{let{data:D}=_,N=D.height*.7;for(;!L(_,N)&&N>0;)N-=1;return N}),I=Math.floor(Math.min(...M)),A=o(_=>k?_.data.x+_.data.width+10:_.data.x+_.data.width-10,"determineLabelXPosition");w.selectAll("text").data(S).enter().append("text").attr("x",A).attr("y",_=>_.data.y+_.data.height/2).attr("text-anchor",k?"start":"end").attr("dominant-baseline","middle").attr("fill",a.dataLabelColor).attr("font-size",`${I}px`).text(_=>_.label)}else{let S=function(A,_,D){let{data:N,label:R}=A,O=_*R.length*.7,$=N.x+N.width/2,z=$-O/2,F=$+O/2,V=z>=N.x&&F<=N.x+N.width,H=N.y+D+_<=N.y+N.height;return V&&H};var b=S;o(S,"fitsInBar");let C=10,E=T.data.map((A,_)=>({data:A,label:l[_].toString()})).filter(A=>A.data.width>0&&A.data.height>0),L=E.map(A=>{let{data:_,label:D}=A,N=_.width/(D.length*.7);for(;!S(A,N,10)&&N>0;)N-=1;return N}),M=Math.floor(Math.min(...L)),I=o(A=>k?A.data.y-10:A.data.y+10,"determineLabelYPosition");w.selectAll("text").data(E).enter().append("text").attr("x",A=>A.data.x+A.data.width/2).attr("y",I).attr("text-anchor","middle").attr("dominant-baseline",k?"auto":"hanging").attr("fill",a.dataLabelColor).attr("font-size",`${M}px`).text(A=>A.label)}}break;case"text":w.selectAll("text").data(T.data).enter().append("text").attr("x",0).attr("y",0).attr("fill",k=>k.fill).attr("font-size",k=>k.fontSize).attr("dominant-baseline",k=>u(k.verticalPos)).attr("text-anchor",k=>h(k.horizontalPos)).attr("transform",k=>f(k)).text(k=>k.text);break;case"path":w.selectAll("path").data(T.data).enter().append("path").attr("d",k=>k.path).attr("fill",k=>k.fill?k.fill:"none").attr("stroke",k=>k.strokeFill).attr("stroke-width",k=>k.strokeWidth);break}}},"draw"),a3e={draw:vht}});var o3e={};ur(o3e,{diagram:()=>xht});var xht,l3e=P(()=>{"use strict";Fwe();n3e();s3e();xht={parser:Bwe,db:i3e,renderer:a3e}});var tU,h3e,f3e=P(()=>{"use strict";tU=(function(){var t=o(function(K,oe,U,ue){for(U=U||{},ue=K.length;ue--;U[K[ue]]=oe);return U},"o"),e=[1,3],r=[1,4],i=[1,5],n=[1,6],a=[5,6,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,77,89,90],s=[1,22],l=[2,7],u=[1,26],h=[1,27],f=[1,28],d=[1,29],p=[1,33],m=[1,34],g=[1,35],y=[1,36],v=[1,37],x=[1,38],b=[1,24],T=[1,31],w=[1,32],k=[1,30],C=[1,39],E=[1,40],S=[5,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,77,89,90],L=[1,61],M=[89,90],I=[5,8,9,11,13,21,22,23,24,27,29,41,42,43,44,45,46,54,61,63,72,74,75,76,77,80,81,82,83,84,85,86,87,88,89,90],A=[27,29],_=[1,70],D=[1,71],N=[1,72],R=[1,73],B=[1,74],O=[1,75],$=[1,76],z=[1,83],F=[1,80],V=[1,84],H=[1,85],X=[1,86],W=[1,87],Z=[1,88],Y=[1,89],ae=[1,90],J=[1,91],ee=[1,92],re=[5,8,9,11,13,21,22,23,24,27,41,42,43,44,45,46,54,72,74,75,76,77,80,81,82,83,84,85,86,87,88,89,90],te=[63,64],be=[1,101],de=[5,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,76,77,89,90],Ee=[5,8,9,11,13,21,22,23,24,41,42,43,44,45,46,54,72,74,75,76,77,80,81,82,83,84,85,86,87,88,89,90],Ne=[1,110],we=[1,106],Te=[1,107],De=[1,108],$e=[1,109],pe=[1,111],Je=[1,116],Ce=[1,117],Fe=[1,114],Ue=[1,115],qe={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,directive:4,NEWLINE:5,RD:6,diagram:7,EOF:8,acc_title:9,acc_title_value:10,acc_descr:11,acc_descr_value:12,acc_descr_multiline_value:13,requirementDef:14,elementDef:15,relationshipDef:16,direction:17,styleStatement:18,classDefStatement:19,classStatement:20,direction_tb:21,direction_bt:22,direction_rl:23,direction_lr:24,requirementType:25,requirementName:26,STRUCT_START:27,requirementBody:28,STYLE_SEPARATOR:29,idList:30,ID:31,COLONSEP:32,id:33,TEXT:34,text:35,RISK:36,riskLevel:37,VERIFYMTHD:38,verifyType:39,STRUCT_STOP:40,REQUIREMENT:41,FUNCTIONAL_REQUIREMENT:42,INTERFACE_REQUIREMENT:43,PERFORMANCE_REQUIREMENT:44,PHYSICAL_REQUIREMENT:45,DESIGN_CONSTRAINT:46,LOW_RISK:47,MED_RISK:48,HIGH_RISK:49,VERIFY_ANALYSIS:50,VERIFY_DEMONSTRATION:51,VERIFY_INSPECTION:52,VERIFY_TEST:53,ELEMENT:54,elementName:55,elementBody:56,TYPE:57,type:58,DOCREF:59,ref:60,END_ARROW_L:61,relationship:62,LINE:63,END_ARROW_R:64,CONTAINS:65,COPIES:66,DERIVES:67,SATISFIES:68,VERIFIES:69,REFINES:70,TRACES:71,CLASSDEF:72,stylesOpt:73,CLASS:74,ALPHA:75,COMMA:76,STYLE:77,style:78,styleComponent:79,NUM:80,COLON:81,UNIT:82,SPACE:83,BRKT:84,PCT:85,MINUS:86,LABEL:87,SEMICOLON:88,unqString:89,qString:90,$accept:0,$end:1},terminals_:{2:"error",5:"NEWLINE",6:"RD",8:"EOF",9:"acc_title",10:"acc_title_value",11:"acc_descr",12:"acc_descr_value",13:"acc_descr_multiline_value",21:"direction_tb",22:"direction_bt",23:"direction_rl",24:"direction_lr",27:"STRUCT_START",29:"STYLE_SEPARATOR",31:"ID",32:"COLONSEP",34:"TEXT",36:"RISK",38:"VERIFYMTHD",40:"STRUCT_STOP",41:"REQUIREMENT",42:"FUNCTIONAL_REQUIREMENT",43:"INTERFACE_REQUIREMENT",44:"PERFORMANCE_REQUIREMENT",45:"PHYSICAL_REQUIREMENT",46:"DESIGN_CONSTRAINT",47:"LOW_RISK",48:"MED_RISK",49:"HIGH_RISK",50:"VERIFY_ANALYSIS",51:"VERIFY_DEMONSTRATION",52:"VERIFY_INSPECTION",53:"VERIFY_TEST",54:"ELEMENT",57:"TYPE",59:"DOCREF",61:"END_ARROW_L",63:"LINE",64:"END_ARROW_R",65:"CONTAINS",66:"COPIES",67:"DERIVES",68:"SATISFIES",69:"VERIFIES",70:"REFINES",71:"TRACES",72:"CLASSDEF",74:"CLASS",75:"ALPHA",76:"COMMA",77:"STYLE",80:"NUM",81:"COLON",82:"UNIT",83:"SPACE",84:"BRKT",85:"PCT",86:"MINUS",87:"LABEL",88:"SEMICOLON",89:"unqString",90:"qString"},productions_:[0,[3,3],[3,2],[3,4],[4,2],[4,2],[4,1],[7,0],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[7,2],[17,1],[17,1],[17,1],[17,1],[14,5],[14,7],[28,5],[28,5],[28,5],[28,5],[28,2],[28,1],[25,1],[25,1],[25,1],[25,1],[25,1],[25,1],[37,1],[37,1],[37,1],[39,1],[39,1],[39,1],[39,1],[15,5],[15,7],[56,5],[56,5],[56,2],[56,1],[16,5],[16,5],[62,1],[62,1],[62,1],[62,1],[62,1],[62,1],[62,1],[19,3],[20,3],[20,3],[30,1],[30,3],[30,1],[30,3],[18,3],[73,1],[73,3],[78,1],[78,2],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[79,1],[26,1],[26,1],[33,1],[33,1],[35,1],[35,1],[55,1],[55,1],[58,1],[58,1],[60,1],[60,1]],performAction:o(function(oe,U,ue,G,se,le,ke){var me=le.length-1;switch(se){case 4:this.$=le[me].trim(),G.setAccTitle(this.$);break;case 5:case 6:this.$=le[me].trim(),G.setAccDescription(this.$);break;case 7:this.$=[];break;case 17:G.setDirection("TB");break;case 18:G.setDirection("BT");break;case 19:G.setDirection("RL");break;case 20:G.setDirection("LR");break;case 21:G.addRequirement(le[me-3],le[me-4]);break;case 22:G.addRequirement(le[me-5],le[me-6]),G.setClass([le[me-5]],le[me-3]);break;case 23:G.setNewReqId(le[me-2]);break;case 24:G.setNewReqText(le[me-2]);break;case 25:G.setNewReqRisk(le[me-2]);break;case 26:G.setNewReqVerifyMethod(le[me-2]);break;case 29:this.$=G.RequirementType.REQUIREMENT;break;case 30:this.$=G.RequirementType.FUNCTIONAL_REQUIREMENT;break;case 31:this.$=G.RequirementType.INTERFACE_REQUIREMENT;break;case 32:this.$=G.RequirementType.PERFORMANCE_REQUIREMENT;break;case 33:this.$=G.RequirementType.PHYSICAL_REQUIREMENT;break;case 34:this.$=G.RequirementType.DESIGN_CONSTRAINT;break;case 35:this.$=G.RiskLevel.LOW_RISK;break;case 36:this.$=G.RiskLevel.MED_RISK;break;case 37:this.$=G.RiskLevel.HIGH_RISK;break;case 38:this.$=G.VerifyType.VERIFY_ANALYSIS;break;case 39:this.$=G.VerifyType.VERIFY_DEMONSTRATION;break;case 40:this.$=G.VerifyType.VERIFY_INSPECTION;break;case 41:this.$=G.VerifyType.VERIFY_TEST;break;case 42:G.addElement(le[me-3]);break;case 43:G.addElement(le[me-5]),G.setClass([le[me-5]],le[me-3]);break;case 44:G.setNewElementType(le[me-2]);break;case 45:G.setNewElementDocRef(le[me-2]);break;case 48:G.addRelationship(le[me-2],le[me],le[me-4]);break;case 49:G.addRelationship(le[me-2],le[me-4],le[me]);break;case 50:this.$=G.Relationships.CONTAINS;break;case 51:this.$=G.Relationships.COPIES;break;case 52:this.$=G.Relationships.DERIVES;break;case 53:this.$=G.Relationships.SATISFIES;break;case 54:this.$=G.Relationships.VERIFIES;break;case 55:this.$=G.Relationships.REFINES;break;case 56:this.$=G.Relationships.TRACES;break;case 57:this.$=le[me-2],G.defineClass(le[me-1],le[me]);break;case 58:G.setClass(le[me-1],le[me]);break;case 59:G.setClass([le[me-2]],le[me]);break;case 60:case 62:this.$=[le[me]];break;case 61:case 63:this.$=le[me-2].concat([le[me]]);break;case 64:this.$=le[me-2],G.setCssStyle(le[me-1],le[me]);break;case 65:this.$=[le[me]];break;case 66:le[me-2].push(le[me]),this.$=le[me-2];break;case 68:this.$=le[me-1]+le[me];break}},"anonymous"),table:[{3:1,4:2,6:e,9:r,11:i,13:n},{1:[3]},{3:8,4:2,5:[1,7],6:e,9:r,11:i,13:n},{5:[1,9]},{10:[1,10]},{12:[1,11]},t(a,[2,6]),{3:12,4:2,6:e,9:r,11:i,13:n},{1:[2,2]},{4:17,5:s,7:13,8:l,9:r,11:i,13:n,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:u,22:h,23:f,24:d,25:23,33:25,41:p,42:m,43:g,44:y,45:v,46:x,54:b,72:T,74:w,77:k,89:C,90:E},t(a,[2,4]),t(a,[2,5]),{1:[2,1]},{8:[1,41]},{4:17,5:s,7:42,8:l,9:r,11:i,13:n,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:u,22:h,23:f,24:d,25:23,33:25,41:p,42:m,43:g,44:y,45:v,46:x,54:b,72:T,74:w,77:k,89:C,90:E},{4:17,5:s,7:43,8:l,9:r,11:i,13:n,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:u,22:h,23:f,24:d,25:23,33:25,41:p,42:m,43:g,44:y,45:v,46:x,54:b,72:T,74:w,77:k,89:C,90:E},{4:17,5:s,7:44,8:l,9:r,11:i,13:n,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:u,22:h,23:f,24:d,25:23,33:25,41:p,42:m,43:g,44:y,45:v,46:x,54:b,72:T,74:w,77:k,89:C,90:E},{4:17,5:s,7:45,8:l,9:r,11:i,13:n,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:u,22:h,23:f,24:d,25:23,33:25,41:p,42:m,43:g,44:y,45:v,46:x,54:b,72:T,74:w,77:k,89:C,90:E},{4:17,5:s,7:46,8:l,9:r,11:i,13:n,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:u,22:h,23:f,24:d,25:23,33:25,41:p,42:m,43:g,44:y,45:v,46:x,54:b,72:T,74:w,77:k,89:C,90:E},{4:17,5:s,7:47,8:l,9:r,11:i,13:n,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:u,22:h,23:f,24:d,25:23,33:25,41:p,42:m,43:g,44:y,45:v,46:x,54:b,72:T,74:w,77:k,89:C,90:E},{4:17,5:s,7:48,8:l,9:r,11:i,13:n,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:u,22:h,23:f,24:d,25:23,33:25,41:p,42:m,43:g,44:y,45:v,46:x,54:b,72:T,74:w,77:k,89:C,90:E},{4:17,5:s,7:49,8:l,9:r,11:i,13:n,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:u,22:h,23:f,24:d,25:23,33:25,41:p,42:m,43:g,44:y,45:v,46:x,54:b,72:T,74:w,77:k,89:C,90:E},{4:17,5:s,7:50,8:l,9:r,11:i,13:n,14:14,15:15,16:16,17:18,18:19,19:20,20:21,21:u,22:h,23:f,24:d,25:23,33:25,41:p,42:m,43:g,44:y,45:v,46:x,54:b,72:T,74:w,77:k,89:C,90:E},{26:51,89:[1,52],90:[1,53]},{55:54,89:[1,55],90:[1,56]},{29:[1,59],61:[1,57],63:[1,58]},t(S,[2,17]),t(S,[2,18]),t(S,[2,19]),t(S,[2,20]),{30:60,33:62,75:L,89:C,90:E},{30:63,33:62,75:L,89:C,90:E},{30:64,33:62,75:L,89:C,90:E},t(M,[2,29]),t(M,[2,30]),t(M,[2,31]),t(M,[2,32]),t(M,[2,33]),t(M,[2,34]),t(I,[2,81]),t(I,[2,82]),{1:[2,3]},{8:[2,8]},{8:[2,9]},{8:[2,10]},{8:[2,11]},{8:[2,12]},{8:[2,13]},{8:[2,14]},{8:[2,15]},{8:[2,16]},{27:[1,65],29:[1,66]},t(A,[2,79]),t(A,[2,80]),{27:[1,67],29:[1,68]},t(A,[2,85]),t(A,[2,86]),{62:69,65:_,66:D,67:N,68:R,69:B,70:O,71:$},{62:77,65:_,66:D,67:N,68:R,69:B,70:O,71:$},{30:78,33:62,75:L,89:C,90:E},{73:79,75:z,76:F,78:81,79:82,80:V,81:H,82:X,83:W,84:Z,85:Y,86:ae,87:J,88:ee},t(re,[2,60]),t(re,[2,62]),{73:93,75:z,76:F,78:81,79:82,80:V,81:H,82:X,83:W,84:Z,85:Y,86:ae,87:J,88:ee},{30:94,33:62,75:L,76:F,89:C,90:E},{5:[1,95]},{30:96,33:62,75:L,89:C,90:E},{5:[1,97]},{30:98,33:62,75:L,89:C,90:E},{63:[1,99]},t(te,[2,50]),t(te,[2,51]),t(te,[2,52]),t(te,[2,53]),t(te,[2,54]),t(te,[2,55]),t(te,[2,56]),{64:[1,100]},t(S,[2,59],{76:F}),t(S,[2,64],{76:be}),{33:103,75:[1,102],89:C,90:E},t(de,[2,65],{79:104,75:z,80:V,81:H,82:X,83:W,84:Z,85:Y,86:ae,87:J,88:ee}),t(Ee,[2,67]),t(Ee,[2,69]),t(Ee,[2,70]),t(Ee,[2,71]),t(Ee,[2,72]),t(Ee,[2,73]),t(Ee,[2,74]),t(Ee,[2,75]),t(Ee,[2,76]),t(Ee,[2,77]),t(Ee,[2,78]),t(S,[2,57],{76:be}),t(S,[2,58],{76:F}),{5:Ne,28:105,31:we,34:Te,36:De,38:$e,40:pe},{27:[1,112],76:F},{5:Je,40:Ce,56:113,57:Fe,59:Ue},{27:[1,118],76:F},{33:119,89:C,90:E},{33:120,89:C,90:E},{75:z,78:121,79:82,80:V,81:H,82:X,83:W,84:Z,85:Y,86:ae,87:J,88:ee},t(re,[2,61]),t(re,[2,63]),t(Ee,[2,68]),t(S,[2,21]),{32:[1,122]},{32:[1,123]},{32:[1,124]},{32:[1,125]},{5:Ne,28:126,31:we,34:Te,36:De,38:$e,40:pe},t(S,[2,28]),{5:[1,127]},t(S,[2,42]),{32:[1,128]},{32:[1,129]},{5:Je,40:Ce,56:130,57:Fe,59:Ue},t(S,[2,47]),{5:[1,131]},t(S,[2,48]),t(S,[2,49]),t(de,[2,66],{79:104,75:z,80:V,81:H,82:X,83:W,84:Z,85:Y,86:ae,87:J,88:ee}),{33:132,89:C,90:E},{35:133,89:[1,134],90:[1,135]},{37:136,47:[1,137],48:[1,138],49:[1,139]},{39:140,50:[1,141],51:[1,142],52:[1,143],53:[1,144]},t(S,[2,27]),{5:Ne,28:145,31:we,34:Te,36:De,38:$e,40:pe},{58:146,89:[1,147],90:[1,148]},{60:149,89:[1,150],90:[1,151]},t(S,[2,46]),{5:Je,40:Ce,56:152,57:Fe,59:Ue},{5:[1,153]},{5:[1,154]},{5:[2,83]},{5:[2,84]},{5:[1,155]},{5:[2,35]},{5:[2,36]},{5:[2,37]},{5:[1,156]},{5:[2,38]},{5:[2,39]},{5:[2,40]},{5:[2,41]},t(S,[2,22]),{5:[1,157]},{5:[2,87]},{5:[2,88]},{5:[1,158]},{5:[2,89]},{5:[2,90]},t(S,[2,43]),{5:Ne,28:159,31:we,34:Te,36:De,38:$e,40:pe},{5:Ne,28:160,31:we,34:Te,36:De,38:$e,40:pe},{5:Ne,28:161,31:we,34:Te,36:De,38:$e,40:pe},{5:Ne,28:162,31:we,34:Te,36:De,38:$e,40:pe},{5:Je,40:Ce,56:163,57:Fe,59:Ue},{5:Je,40:Ce,56:164,57:Fe,59:Ue},t(S,[2,23]),t(S,[2,24]),t(S,[2,25]),t(S,[2,26]),t(S,[2,44]),t(S,[2,45])],defaultActions:{8:[2,2],12:[2,1],41:[2,3],42:[2,8],43:[2,9],44:[2,10],45:[2,11],46:[2,12],47:[2,13],48:[2,14],49:[2,15],50:[2,16],134:[2,83],135:[2,84],137:[2,35],138:[2,36],139:[2,37],141:[2,38],142:[2,39],143:[2,40],144:[2,41],147:[2,87],148:[2,88],150:[2,89],151:[2,90]},parseError:o(function(oe,U){if(U.recoverable)this.trace(oe);else{var ue=new Error(oe);throw ue.hash=U,ue}},"parseError"),parse:o(function(oe){var U=this,ue=[0],G=[],se=[null],le=[],ke=this.table,me="",ye=0,Re=0,ve=0,Oe=2,We=1,Be=le.slice.call(arguments,1),Qe=Object.create(this.lexer),ce={yy:{}};for(var it in this.yy)Object.prototype.hasOwnProperty.call(this.yy,it)&&(ce.yy[it]=this.yy[it]);Qe.setInput(oe,ce.yy),ce.yy.lexer=Qe,ce.yy.parser=this,typeof Qe.yylloc>"u"&&(Qe.yylloc={});var fe=Qe.yylloc;le.push(fe);var ut=Qe.options&&Qe.options.ranges;typeof ce.yy.parseError=="function"?this.parseError=ce.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function Nt(ir){ue.length=ue.length-2*ir,se.length=se.length-ir,le.length=le.length-ir}o(Nt,"popStack");function Pt(){var ir;return ir=G.pop()||Qe.lex()||We,typeof ir!="number"&&(ir instanceof Array&&(G=ir,ir=G.pop()),ir=U.symbols_[ir]||ir),ir}o(Pt,"lex");for(var St,It,ot,ct,Dt,kt,yt={},jt,hr,Qt,Er;;){if(ot=ue[ue.length-1],this.defaultActions[ot]?ct=this.defaultActions[ot]:((St===null||typeof St>"u")&&(St=Pt()),ct=ke[ot]&&ke[ot][St]),typeof ct>"u"||!ct.length||!ct[0]){var dr="";Er=[];for(jt in ke[ot])this.terminals_[jt]&&jt>Oe&&Er.push("'"+this.terminals_[jt]+"'");Qe.showPosition?dr="Parse error on line "+(ye+1)+`: +`+Qe.showPosition()+` +Expecting `+Er.join(", ")+", got '"+(this.terminals_[St]||St)+"'":dr="Parse error on line "+(ye+1)+": Unexpected "+(St==We?"end of input":"'"+(this.terminals_[St]||St)+"'"),this.parseError(dr,{text:Qe.match,token:this.terminals_[St]||St,line:Qe.yylineno,loc:fe,expected:Er})}if(ct[0]instanceof Array&&ct.length>1)throw new Error("Parse Error: multiple actions possible at state: "+ot+", token: "+St);switch(ct[0]){case 1:ue.push(St),se.push(Qe.yytext),le.push(Qe.yylloc),ue.push(ct[1]),St=null,It?(St=It,It=null):(Re=Qe.yyleng,me=Qe.yytext,ye=Qe.yylineno,fe=Qe.yylloc,ve>0&&ve--);break;case 2:if(hr=this.productions_[ct[1]][1],yt.$=se[se.length-hr],yt._$={first_line:le[le.length-(hr||1)].first_line,last_line:le[le.length-1].last_line,first_column:le[le.length-(hr||1)].first_column,last_column:le[le.length-1].last_column},ut&&(yt._$.range=[le[le.length-(hr||1)].range[0],le[le.length-1].range[1]]),kt=this.performAction.apply(yt,[me,Re,ye,ce.yy,ct[1],se,le].concat(Be)),typeof kt<"u")return kt;hr&&(ue=ue.slice(0,-1*hr*2),se=se.slice(0,-1*hr),le=le.slice(0,-1*hr)),ue.push(this.productions_[ct[1]][0]),se.push(yt.$),le.push(yt._$),Qt=ke[ue[ue.length-2]][ue[ue.length-1]],ue.push(Qt);break;case 3:return!0}}return!0},"parse")},Me=(function(){var K={EOF:1,parseError:o(function(U,ue){if(this.yy.parser)this.yy.parser.parseError(U,ue);else throw new Error(U)},"parseError"),setInput:o(function(oe,U){return this.yy=U||this.yy||{},this._input=oe,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var oe=this._input[0];this.yytext+=oe,this.yyleng++,this.offset++,this.match+=oe,this.matched+=oe;var U=oe.match(/(?:\r\n?|\n).*/g);return U?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),oe},"input"),unput:o(function(oe){var U=oe.length,ue=oe.split(/(?:\r\n?|\n)/g);this._input=oe+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-U),this.offset-=U;var G=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),ue.length-1&&(this.yylineno-=ue.length-1);var se=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:ue?(ue.length===G.length?this.yylloc.first_column:0)+G[G.length-ue.length].length-ue[0].length:this.yylloc.first_column-U},this.options.ranges&&(this.yylloc.range=[se[0],se[0]+this.yyleng-U]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(oe){this.unput(this.match.slice(oe))},"less"),pastInput:o(function(){var oe=this.matched.substr(0,this.matched.length-this.match.length);return(oe.length>20?"...":"")+oe.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var oe=this.match;return oe.length<20&&(oe+=this._input.substr(0,20-oe.length)),(oe.substr(0,20)+(oe.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var oe=this.pastInput(),U=new Array(oe.length+1).join("-");return oe+this.upcomingInput()+` +`+U+"^"},"showPosition"),test_match:o(function(oe,U){var ue,G,se;if(this.options.backtrack_lexer&&(se={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(se.yylloc.range=this.yylloc.range.slice(0))),G=oe[0].match(/(?:\r\n?|\n).*/g),G&&(this.yylineno+=G.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:G?G[G.length-1].length-G[G.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+oe[0].length},this.yytext+=oe[0],this.match+=oe[0],this.matches=oe,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(oe[0].length),this.matched+=oe[0],ue=this.performAction.call(this,this.yy,this,U,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),ue)return ue;if(this._backtrack){for(var le in se)this[le]=se[le];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var oe,U,ue,G;this._more||(this.yytext="",this.match="");for(var se=this._currentRules(),le=0;leU[0].length)){if(U=ue,G=le,this.options.backtrack_lexer){if(oe=this.test_match(ue,se[le]),oe!==!1)return oe;if(this._backtrack){U=!1;continue}else return!1}else if(!this.options.flex)break}return U?(oe=this.test_match(U,se[G]),oe!==!1?oe:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var U=this.next();return U||this.lex()},"lex"),begin:o(function(U){this.conditionStack.push(U)},"begin"),popState:o(function(){var U=this.conditionStack.length-1;return U>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(U){return U=this.conditionStack.length-1-Math.abs(U||0),U>=0?this.conditionStack[U]:"INITIAL"},"topState"),pushState:o(function(U){this.begin(U)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:o(function(U,ue,G,se){var le=se;switch(G){case 0:return"title";case 1:return this.begin("acc_title"),9;break;case 2:return this.popState(),"acc_title_value";break;case 3:return this.begin("acc_descr"),11;break;case 4:return this.popState(),"acc_descr_value";break;case 5:this.begin("acc_descr_multiline");break;case 6:this.popState();break;case 7:return"acc_descr_multiline_value";case 8:return 21;case 9:return 22;case 10:return 23;case 11:return 24;case 12:return 5;case 13:break;case 14:break;case 15:break;case 16:return 8;case 17:return 6;case 18:return 27;case 19:return 40;case 20:return 29;case 21:return 32;case 22:return 31;case 23:return 34;case 24:return 36;case 25:return 38;case 26:return 41;case 27:return 42;case 28:return 43;case 29:return 44;case 30:return 45;case 31:return 46;case 32:return 47;case 33:return 48;case 34:return 49;case 35:return 50;case 36:return 51;case 37:return 52;case 38:return 53;case 39:return 54;case 40:return 65;case 41:return 66;case 42:return 67;case 43:return 68;case 44:return 69;case 45:return 70;case 46:return 71;case 47:return 57;case 48:return 59;case 49:return this.begin("style"),77;break;case 50:return 75;case 51:return 81;case 52:return 88;case 53:return"PERCENT";case 54:return 86;case 55:return 84;case 56:break;case 57:this.begin("string");break;case 58:this.popState();break;case 59:return this.begin("style"),72;break;case 60:return this.begin("style"),74;break;case 61:return 61;case 62:return 64;case 63:return 63;case 64:this.begin("string");break;case 65:this.popState();break;case 66:return"qString";case 67:return ue.yytext=ue.yytext.trim(),89;break;case 68:return 75;case 69:return 80;case 70:return 76}},"anonymous"),rules:[/^(?:title\s[^#\n;]+)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:(\r?\n)+)/i,/^(?:\s+)/i,/^(?:#[^\n]*)/i,/^(?:%[^\n]*)/i,/^(?:$)/i,/^(?:requirementDiagram\b)/i,/^(?:\{)/i,/^(?:\})/i,/^(?::{3})/i,/^(?::)/i,/^(?:id\b)/i,/^(?:text\b)/i,/^(?:risk\b)/i,/^(?:verifyMethod\b)/i,/^(?:requirement\b)/i,/^(?:functionalRequirement\b)/i,/^(?:interfaceRequirement\b)/i,/^(?:performanceRequirement\b)/i,/^(?:physicalRequirement\b)/i,/^(?:designConstraint\b)/i,/^(?:low\b)/i,/^(?:medium\b)/i,/^(?:high\b)/i,/^(?:analysis\b)/i,/^(?:demonstration\b)/i,/^(?:inspection\b)/i,/^(?:test\b)/i,/^(?:element\b)/i,/^(?:contains\b)/i,/^(?:copies\b)/i,/^(?:derives\b)/i,/^(?:satisfies\b)/i,/^(?:verifies\b)/i,/^(?:refines\b)/i,/^(?:traces\b)/i,/^(?:type\b)/i,/^(?:docref\b)/i,/^(?:style\b)/i,/^(?:\w+)/i,/^(?::)/i,/^(?:;)/i,/^(?:%)/i,/^(?:-)/i,/^(?:#)/i,/^(?: )/i,/^(?:["])/i,/^(?:\n)/i,/^(?:classDef\b)/i,/^(?:class\b)/i,/^(?:<-)/i,/^(?:->)/i,/^(?:-)/i,/^(?:["])/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[\w][^:,\r\n\{\<\>\-\=]*)/i,/^(?:\w+)/i,/^(?:[0-9]+)/i,/^(?:,)/i],conditions:{acc_descr_multiline:{rules:[6,7,68,69,70],inclusive:!1},acc_descr:{rules:[4,68,69,70],inclusive:!1},acc_title:{rules:[2,68,69,70],inclusive:!1},style:{rules:[50,51,52,53,54,55,56,57,58,68,69,70],inclusive:!1},unqString:{rules:[68,69,70],inclusive:!1},token:{rules:[68,69,70],inclusive:!1},string:{rules:[65,66,68,69,70],inclusive:!1},INITIAL:{rules:[0,1,3,5,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,59,60,61,62,63,64,67,68,69,70],inclusive:!0}}};return K})();qe.lexer=Me;function He(){this.yy={}}return o(He,"Parser"),He.prototype=qe,qe.Parser=He,new He})();tU.parser=tU;h3e=tU});var b_,d3e=P(()=>{"use strict";Ut();bt();Ki();b_=class{constructor(){this.relations=[];this.latestRequirement=this.getInitialRequirement();this.requirements=new Map;this.latestElement=this.getInitialElement();this.elements=new Map;this.classes=new Map;this.direction="TB";this.RequirementType={REQUIREMENT:"Requirement",FUNCTIONAL_REQUIREMENT:"Functional Requirement",INTERFACE_REQUIREMENT:"Interface Requirement",PERFORMANCE_REQUIREMENT:"Performance Requirement",PHYSICAL_REQUIREMENT:"Physical Requirement",DESIGN_CONSTRAINT:"Design Constraint"};this.RiskLevel={LOW_RISK:"Low",MED_RISK:"Medium",HIGH_RISK:"High"};this.VerifyType={VERIFY_ANALYSIS:"Analysis",VERIFY_DEMONSTRATION:"Demonstration",VERIFY_INSPECTION:"Inspection",VERIFY_TEST:"Test"};this.Relationships={CONTAINS:"contains",COPIES:"copies",DERIVES:"derives",SATISFIES:"satisfies",VERIFIES:"verifies",REFINES:"refines",TRACES:"traces"};this.setAccTitle=Ar;this.getAccTitle=Dr;this.setAccDescription=Lr;this.getAccDescription=Rr;this.setDiagramTitle=Mr;this.getDiagramTitle=Nr;this.getConfig=o(()=>ge().requirement,"getConfig");this.clear(),this.setDirection=this.setDirection.bind(this),this.addRequirement=this.addRequirement.bind(this),this.setNewReqId=this.setNewReqId.bind(this),this.setNewReqRisk=this.setNewReqRisk.bind(this),this.setNewReqText=this.setNewReqText.bind(this),this.setNewReqVerifyMethod=this.setNewReqVerifyMethod.bind(this),this.addElement=this.addElement.bind(this),this.setNewElementType=this.setNewElementType.bind(this),this.setNewElementDocRef=this.setNewElementDocRef.bind(this),this.addRelationship=this.addRelationship.bind(this),this.setCssStyle=this.setCssStyle.bind(this),this.setClass=this.setClass.bind(this),this.defineClass=this.defineClass.bind(this),this.setAccTitle=this.setAccTitle.bind(this),this.setAccDescription=this.setAccDescription.bind(this)}static{o(this,"RequirementDB")}getDirection(){return this.direction}setDirection(e){this.direction=e}resetLatestRequirement(){this.latestRequirement=this.getInitialRequirement()}resetLatestElement(){this.latestElement=this.getInitialElement()}getInitialRequirement(){return{requirementId:"",text:"",risk:"",verifyMethod:"",name:"",type:"",cssStyles:[],classes:["default"]}}getInitialElement(){return{name:"",type:"",docRef:"",cssStyles:[],classes:["default"]}}addRequirement(e,r){return this.requirements.has(e)||this.requirements.set(e,{name:e,type:r,requirementId:this.latestRequirement.requirementId,text:this.latestRequirement.text,risk:this.latestRequirement.risk,verifyMethod:this.latestRequirement.verifyMethod,cssStyles:[],classes:["default"]}),this.resetLatestRequirement(),this.requirements.get(e)}getRequirements(){return this.requirements}setNewReqId(e){this.latestRequirement!==void 0&&(this.latestRequirement.requirementId=e)}setNewReqText(e){this.latestRequirement!==void 0&&(this.latestRequirement.text=e)}setNewReqRisk(e){this.latestRequirement!==void 0&&(this.latestRequirement.risk=e)}setNewReqVerifyMethod(e){this.latestRequirement!==void 0&&(this.latestRequirement.verifyMethod=e)}addElement(e){return this.elements.has(e)||(this.elements.set(e,{name:e,type:this.latestElement.type,docRef:this.latestElement.docRef,cssStyles:[],classes:["default"]}),Q.info("Added new element: ",e)),this.resetLatestElement(),this.elements.get(e)}getElements(){return this.elements}setNewElementType(e){this.latestElement!==void 0&&(this.latestElement.type=e)}setNewElementDocRef(e){this.latestElement!==void 0&&(this.latestElement.docRef=e)}addRelationship(e,r,i){this.relations.push({type:e,src:r,dst:i})}getRelationships(){return this.relations}clear(){this.relations=[],this.resetLatestRequirement(),this.requirements=new Map,this.resetLatestElement(),this.elements=new Map,this.classes=new Map,wr()}setCssStyle(e,r){for(let i of e){let n=this.requirements.get(i)??this.elements.get(i);if(!r||!n)return;for(let a of r)a.includes(",")?n.cssStyles.push(...a.split(",")):n.cssStyles.push(a)}}setClass(e,r){for(let i of e){let n=this.requirements.get(i)??this.elements.get(i);if(n)for(let a of r){n.classes.push(a);let s=this.classes.get(a)?.styles;s&&n.cssStyles.push(...s)}}}defineClass(e,r){for(let i of e){let n=this.classes.get(i);n===void 0&&(n={id:i,styles:[],textStyles:[]},this.classes.set(i,n)),r&&r.forEach(function(a){if(/color/.exec(a)){let s=a.replace("fill","bgFill");n.textStyles.push(s)}n.styles.push(a)}),this.requirements.forEach(a=>{a.classes.includes(i)&&a.cssStyles.push(...r.flatMap(s=>s.split(",")))}),this.elements.forEach(a=>{a.classes.includes(i)&&a.cssStyles.push(...r.flatMap(s=>s.split(",")))})}}getClasses(){return this.classes}getData(){let e=ge(),r=[],i=[];for(let n of this.requirements.values()){let a=n;a.id=n.name,a.cssStyles=n.cssStyles,a.cssClasses=n.classes.join(" "),a.shape="requirementBox",a.look=e.look,a.colorIndex=r.length,r.push(a)}for(let n of this.elements.values()){let a=n;a.shape="requirementBox",a.look=e.look,a.id=n.name,a.cssStyles=n.cssStyles,a.cssClasses=n.classes.join(" "),a.colorIndex=r.length,r.push(a)}for(let n of this.relations){let a=0,s=n.type===this.Relationships.CONTAINS,l={id:`${n.src}-${n.dst}-${a}`,start:this.requirements.get(n.src)?.name??this.elements.get(n.src)?.name,end:this.requirements.get(n.dst)?.name??this.elements.get(n.dst)?.name,label:`<<${n.type}>>`,classes:"relationshipLine",style:["fill:none",s?"":"stroke-dasharray: 10,7"],labelpos:"c",thickness:"normal",type:"normal",pattern:s?"normal":"dashed",arrowTypeStart:s?"requirement_contains":"",arrowTypeEnd:s?"":"requirement_arrow",look:e.look,labelType:"markdown"};i.push(l),a++}return{nodes:r,edges:i,other:{},config:e,direction:this.getDirection()}}}});var Cht,wht,p3e,m3e=P(()=>{"use strict";Sr();Cht=o(t=>{let e=Lt(),{themeVariables:r,look:i}=e,{bkgColorArray:n,borderColorArray:a}=r;if(!a?.length)return"";let s="";for(let l=0;l{let e=Lt(),{look:r,themeVariables:i}=e,{requirementEdgeLabelBackground:n}=i;return` + ${Cht(t)} + marker { + fill: ${t.relationColor}; + stroke: ${t.relationColor}; + } + + marker.cross { + stroke: ${t.lineColor}; + } + + svg { + font-family: ${t.fontFamily}; + font-size: ${t.fontSize}; + } + + .reqBox { + fill: ${t.requirementBackground}; + fill-opacity: 1.0; + stroke: ${t.requirementBorderColor}; + stroke-width: ${t.requirementBorderSize}; + } + + .reqTitle, .reqLabel{ + fill: ${t.requirementTextColor}; + } + .reqLabelBox { + fill: ${t.relationLabelBackground}; + fill-opacity: 1.0; + } + + .req-title-line { + stroke: ${t.requirementBorderColor}; + stroke-width: ${t.requirementBorderSize}; + } + .relationshipLine { + stroke: ${t.relationColor}; + stroke-width: ${r==="neo"?t.strokeWidth:"1px"}; + } + .relationshipLabel { + fill: ${t.relationLabelColor}; + } + .edgeLabel { + background-color: ${t.edgeLabelBackground}; + } + .edgeLabel .label rect { + fill: ${t.edgeLabelBackground}; + } + .edgeLabel .label text { + fill: ${t.relationLabelColor}; + } + .divider { + stroke: ${t.nodeBorder}; + stroke-width: 1; + } + .label { + font-family: ${t.fontFamily}; + color: ${t.nodeTextColor||t.textColor}; + } + .label text,span { + fill: ${t.nodeTextColor||t.textColor}; + color: ${t.nodeTextColor||t.textColor}; + } + .labelBkg { + background-color: ${n??t.edgeLabelBackground}; + } + +`},"getStyles"),p3e=wht});var rU={};ur(rU,{draw:()=>Eht});var Eht,g3e=P(()=>{"use strict";Ut();bt();I0();Wd();Ud();er();Eht=o(async function(t,e,r,i){Q.info("REF0:"),Q.info("Drawing requirement diagram (unified)",e);let{securityLevel:n,state:a,layout:s,look:l}=ge(),u=i.db.getData(),h=Ol(e,n);u.type=i.type,u.layoutAlgorithm=Vu(s),u.nodeSpacing=a?.nodeSpacing??50,u.rankSpacing=a?.rankSpacing??50,u.markers=l==="neo"?["requirement_contains_neo","requirement_arrow_neo"]:["requirement_contains","requirement_arrow"],u.diagramId=e,await Ul(u,h);let f=8;Kt.insertTitle(h,"requirementDiagramTitleText",a?.titleTopMargin??25,i.db.getDiagramTitle()),Ro(h,f,"requirementDiagram",a?.useMaxWidth??!0)},"draw")});var y3e={};ur(y3e,{diagram:()=>Sht});var Sht,v3e=P(()=>{"use strict";f3e();d3e();m3e();g3e();Sht={parser:h3e,get db(){return new b_},renderer:rU,styles:p3e}});var iU,T3e,k3e=P(()=>{"use strict";iU=(function(){var t=o(function(Re,ve,Oe,We){for(Oe=Oe||{},We=Re.length;We--;Oe[Re[We]]=ve);return Oe},"o"),e=[1,2],r=[1,3],i=[1,4],n=[2,4],a=[1,9],s=[1,11],l=[1,12],u=[1,14],h=[1,15],f=[1,17],d=[1,18],p=[1,19],m=[1,25],g=[1,26],y=[1,27],v=[1,28],x=[1,29],b=[1,30],T=[1,31],w=[1,32],k=[1,33],C=[1,34],E=[1,35],S=[1,36],L=[1,37],M=[1,38],I=[1,39],A=[1,40],_=[1,42],D=[1,43],N=[1,44],R=[1,45],B=[1,46],O=[1,47],$=[1,4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,48,49,50,51,53,54,56,61,62,63,64,73],z=[1,74],F=[1,80],V=[1,81],H=[1,82],X=[1,83],W=[1,84],Z=[1,85],Y=[1,86],ae=[1,87],J=[1,88],ee=[1,89],re=[1,90],te=[1,91],be=[1,92],de=[1,93],Ee=[1,94],Ne=[1,95],we=[1,96],Te=[1,97],De=[1,98],$e=[1,99],pe=[1,100],Je=[1,101],Ce=[1,102],Fe=[1,103],Ue=[1,104],qe=[1,105],Me=[2,78],He=[4,5,17,51,53,54],K=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,51,53,54,56,61,62,63,64,73],oe=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,50,51,53,54,56,61,62,63,64,73],U=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,49,51,53,54,56,61,62,63,64,73],ue=[4,5,10,14,15,17,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,48,51,53,54,56,61,62,63,64,73],G=[5,52],se=[70,71,72,73],le=[1,151],ke={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,SPACE:4,NEWLINE:5,SD:6,document:7,line:8,statement:9,INVALID:10,box_section:11,box_line:12,participant_statement:13,create:14,box:15,restOfLine:16,end:17,signal:18,autonumber:19,NUM:20,off:21,activate:22,actor:23,deactivate:24,note_statement:25,links_statement:26,link_statement:27,properties_statement:28,details_statement:29,title:30,legacy_title:31,acc_title:32,acc_title_value:33,acc_descr:34,acc_descr_value:35,acc_descr_multiline_value:36,loop:37,rect:38,opt:39,alt:40,else_sections:41,par:42,par_sections:43,par_over:44,critical:45,option_sections:46,break:47,option:48,and:49,else:50,participant:51,AS:52,participant_actor:53,destroy:54,actor_with_config:55,note:56,placement:57,text2:58,over:59,actor_pair:60,links:61,link:62,properties:63,details:64,spaceList:65,",":66,left_of:67,right_of:68,signaltype:69,"+":70,"-":71,"()":72,ACTOR:73,config_object:74,CONFIG_START:75,CONFIG_CONTENT:76,CONFIG_END:77,SOLID_OPEN_ARROW:78,DOTTED_OPEN_ARROW:79,SOLID_ARROW:80,SOLID_ARROW_TOP:81,SOLID_ARROW_BOTTOM:82,STICK_ARROW_TOP:83,STICK_ARROW_BOTTOM:84,SOLID_ARROW_TOP_DOTTED:85,SOLID_ARROW_BOTTOM_DOTTED:86,STICK_ARROW_TOP_DOTTED:87,STICK_ARROW_BOTTOM_DOTTED:88,SOLID_ARROW_TOP_REVERSE:89,SOLID_ARROW_BOTTOM_REVERSE:90,STICK_ARROW_TOP_REVERSE:91,STICK_ARROW_BOTTOM_REVERSE:92,SOLID_ARROW_TOP_REVERSE_DOTTED:93,SOLID_ARROW_BOTTOM_REVERSE_DOTTED:94,STICK_ARROW_TOP_REVERSE_DOTTED:95,STICK_ARROW_BOTTOM_REVERSE_DOTTED:96,BIDIRECTIONAL_SOLID_ARROW:97,DOTTED_ARROW:98,BIDIRECTIONAL_DOTTED_ARROW:99,SOLID_CROSS:100,DOTTED_CROSS:101,SOLID_POINT:102,DOTTED_POINT:103,TXT:104,$accept:0,$end:1},terminals_:{2:"error",4:"SPACE",5:"NEWLINE",6:"SD",10:"INVALID",14:"create",15:"box",16:"restOfLine",17:"end",19:"autonumber",20:"NUM",21:"off",22:"activate",24:"deactivate",30:"title",31:"legacy_title",32:"acc_title",33:"acc_title_value",34:"acc_descr",35:"acc_descr_value",36:"acc_descr_multiline_value",37:"loop",38:"rect",39:"opt",40:"alt",42:"par",44:"par_over",45:"critical",47:"break",48:"option",49:"and",50:"else",51:"participant",52:"AS",53:"participant_actor",54:"destroy",56:"note",59:"over",61:"links",62:"link",63:"properties",64:"details",66:",",67:"left_of",68:"right_of",70:"+",71:"-",72:"()",73:"ACTOR",75:"CONFIG_START",76:"CONFIG_CONTENT",77:"CONFIG_END",78:"SOLID_OPEN_ARROW",79:"DOTTED_OPEN_ARROW",80:"SOLID_ARROW",81:"SOLID_ARROW_TOP",82:"SOLID_ARROW_BOTTOM",83:"STICK_ARROW_TOP",84:"STICK_ARROW_BOTTOM",85:"SOLID_ARROW_TOP_DOTTED",86:"SOLID_ARROW_BOTTOM_DOTTED",87:"STICK_ARROW_TOP_DOTTED",88:"STICK_ARROW_BOTTOM_DOTTED",89:"SOLID_ARROW_TOP_REVERSE",90:"SOLID_ARROW_BOTTOM_REVERSE",91:"STICK_ARROW_TOP_REVERSE",92:"STICK_ARROW_BOTTOM_REVERSE",93:"SOLID_ARROW_TOP_REVERSE_DOTTED",94:"SOLID_ARROW_BOTTOM_REVERSE_DOTTED",95:"STICK_ARROW_TOP_REVERSE_DOTTED",96:"STICK_ARROW_BOTTOM_REVERSE_DOTTED",97:"BIDIRECTIONAL_SOLID_ARROW",98:"DOTTED_ARROW",99:"BIDIRECTIONAL_DOTTED_ARROW",100:"SOLID_CROSS",101:"DOTTED_CROSS",102:"SOLID_POINT",103:"DOTTED_POINT",104:"TXT"},productions_:[0,[3,2],[3,2],[3,2],[7,0],[7,2],[8,2],[8,1],[8,1],[8,1],[11,0],[11,2],[12,2],[12,1],[12,1],[9,1],[9,2],[9,4],[9,2],[9,4],[9,3],[9,3],[9,2],[9,3],[9,3],[9,2],[9,2],[9,2],[9,2],[9,2],[9,1],[9,1],[9,2],[9,2],[9,1],[9,4],[9,4],[9,4],[9,4],[9,4],[9,4],[9,4],[9,4],[46,1],[46,4],[43,1],[43,4],[41,1],[41,4],[13,5],[13,3],[13,5],[13,3],[13,3],[13,5],[13,3],[13,5],[13,3],[25,4],[25,4],[26,3],[27,3],[28,3],[29,3],[65,2],[65,1],[60,3],[60,1],[57,1],[57,1],[18,5],[18,5],[18,5],[18,5],[18,6],[18,4],[55,2],[74,3],[23,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[69,1],[58,1]],performAction:o(function(ve,Oe,We,Be,Qe,ce,it){var fe=ce.length-1;switch(Qe){case 3:return Be.apply(ce[fe]),ce[fe];break;case 4:case 10:this.$=[];break;case 5:case 11:ce[fe-1].push(ce[fe]),this.$=ce[fe-1];break;case 6:case 7:case 12:case 13:this.$=ce[fe];break;case 8:case 9:case 14:this.$=[];break;case 16:ce[fe].type="createParticipant",this.$=ce[fe];break;case 17:ce[fe-1].unshift({type:"boxStart",boxData:Be.parseBoxData(ce[fe-2])}),ce[fe-1].push({type:"boxEnd",boxText:ce[fe-2]}),this.$=ce[fe-1];break;case 19:this.$={type:"sequenceIndex",sequenceIndex:Number(ce[fe-2]),sequenceIndexStep:Number(ce[fe-1]),sequenceVisible:!0,signalType:Be.LINETYPE.AUTONUMBER};break;case 20:this.$={type:"sequenceIndex",sequenceIndex:Number(ce[fe-1]),sequenceIndexStep:1,sequenceVisible:!0,signalType:Be.LINETYPE.AUTONUMBER};break;case 21:this.$={type:"sequenceIndex",sequenceVisible:!1,signalType:Be.LINETYPE.AUTONUMBER};break;case 22:this.$={type:"sequenceIndex",sequenceVisible:!0,signalType:Be.LINETYPE.AUTONUMBER};break;case 23:this.$={type:"activeStart",signalType:Be.LINETYPE.ACTIVE_START,actor:ce[fe-1].actor};break;case 24:this.$={type:"activeEnd",signalType:Be.LINETYPE.ACTIVE_END,actor:ce[fe-1].actor};break;case 30:Be.setDiagramTitle(ce[fe].substring(6)),this.$=ce[fe].substring(6);break;case 31:Be.setDiagramTitle(ce[fe].substring(7)),this.$=ce[fe].substring(7);break;case 32:this.$=ce[fe].trim(),Be.setAccTitle(this.$);break;case 33:case 34:this.$=ce[fe].trim(),Be.setAccDescription(this.$);break;case 35:ce[fe-1].unshift({type:"loopStart",loopText:Be.parseMessage(ce[fe-2]),signalType:Be.LINETYPE.LOOP_START}),ce[fe-1].push({type:"loopEnd",loopText:ce[fe-2],signalType:Be.LINETYPE.LOOP_END}),this.$=ce[fe-1];break;case 36:ce[fe-1].unshift({type:"rectStart",color:Be.parseMessage(ce[fe-2]),signalType:Be.LINETYPE.RECT_START}),ce[fe-1].push({type:"rectEnd",color:Be.parseMessage(ce[fe-2]),signalType:Be.LINETYPE.RECT_END}),this.$=ce[fe-1];break;case 37:ce[fe-1].unshift({type:"optStart",optText:Be.parseMessage(ce[fe-2]),signalType:Be.LINETYPE.OPT_START}),ce[fe-1].push({type:"optEnd",optText:Be.parseMessage(ce[fe-2]),signalType:Be.LINETYPE.OPT_END}),this.$=ce[fe-1];break;case 38:ce[fe-1].unshift({type:"altStart",altText:Be.parseMessage(ce[fe-2]),signalType:Be.LINETYPE.ALT_START}),ce[fe-1].push({type:"altEnd",signalType:Be.LINETYPE.ALT_END}),this.$=ce[fe-1];break;case 39:ce[fe-1].unshift({type:"parStart",parText:Be.parseMessage(ce[fe-2]),signalType:Be.LINETYPE.PAR_START}),ce[fe-1].push({type:"parEnd",signalType:Be.LINETYPE.PAR_END}),this.$=ce[fe-1];break;case 40:ce[fe-1].unshift({type:"parStart",parText:Be.parseMessage(ce[fe-2]),signalType:Be.LINETYPE.PAR_OVER_START}),ce[fe-1].push({type:"parEnd",signalType:Be.LINETYPE.PAR_END}),this.$=ce[fe-1];break;case 41:ce[fe-1].unshift({type:"criticalStart",criticalText:Be.parseMessage(ce[fe-2]),signalType:Be.LINETYPE.CRITICAL_START}),ce[fe-1].push({type:"criticalEnd",signalType:Be.LINETYPE.CRITICAL_END}),this.$=ce[fe-1];break;case 42:ce[fe-1].unshift({type:"breakStart",breakText:Be.parseMessage(ce[fe-2]),signalType:Be.LINETYPE.BREAK_START}),ce[fe-1].push({type:"breakEnd",optText:Be.parseMessage(ce[fe-2]),signalType:Be.LINETYPE.BREAK_END}),this.$=ce[fe-1];break;case 44:this.$=ce[fe-3].concat([{type:"option",optionText:Be.parseMessage(ce[fe-1]),signalType:Be.LINETYPE.CRITICAL_OPTION},ce[fe]]);break;case 46:this.$=ce[fe-3].concat([{type:"and",parText:Be.parseMessage(ce[fe-1]),signalType:Be.LINETYPE.PAR_AND},ce[fe]]);break;case 48:this.$=ce[fe-3].concat([{type:"else",altText:Be.parseMessage(ce[fe-1]),signalType:Be.LINETYPE.ALT_ELSE},ce[fe]]);break;case 49:ce[fe-3].draw="participant",ce[fe-3].type="addParticipant",ce[fe-3].description=Be.parseMessage(ce[fe-1]),this.$=ce[fe-3];break;case 50:ce[fe-1].draw="participant",ce[fe-1].type="addParticipant",this.$=ce[fe-1];break;case 51:ce[fe-3].draw="actor",ce[fe-3].type="addParticipant",ce[fe-3].description=Be.parseMessage(ce[fe-1]),this.$=ce[fe-3];break;case 52:case 57:ce[fe-1].draw="actor",ce[fe-1].type="addParticipant",this.$=ce[fe-1];break;case 53:ce[fe-1].type="destroyParticipant",this.$=ce[fe-1];break;case 54:ce[fe-3].draw="participant",ce[fe-3].type="addParticipant",ce[fe-3].description=Be.parseMessage(ce[fe-1]),this.$=ce[fe-3];break;case 55:ce[fe-1].draw="participant",ce[fe-1].type="addParticipant",this.$=ce[fe-1];break;case 56:ce[fe-3].draw="actor",ce[fe-3].type="addParticipant",ce[fe-3].description=Be.parseMessage(ce[fe-1]),this.$=ce[fe-3];break;case 58:this.$=[ce[fe-1],{type:"addNote",placement:ce[fe-2],actor:ce[fe-1].actor,text:ce[fe]}];break;case 59:ce[fe-2]=[].concat(ce[fe-1],ce[fe-1]).slice(0,2),ce[fe-2][0]=ce[fe-2][0].actor,ce[fe-2][1]=ce[fe-2][1].actor,this.$=[ce[fe-1],{type:"addNote",placement:Be.PLACEMENT.OVER,actor:ce[fe-2].slice(0,2),text:ce[fe]}];break;case 60:this.$=[ce[fe-1],{type:"addLinks",actor:ce[fe-1].actor,text:ce[fe]}];break;case 61:this.$=[ce[fe-1],{type:"addALink",actor:ce[fe-1].actor,text:ce[fe]}];break;case 62:this.$=[ce[fe-1],{type:"addProperties",actor:ce[fe-1].actor,text:ce[fe]}];break;case 63:this.$=[ce[fe-1],{type:"addDetails",actor:ce[fe-1].actor,text:ce[fe]}];break;case 66:this.$=[ce[fe-2],ce[fe]];break;case 67:this.$=ce[fe];break;case 68:this.$=Be.PLACEMENT.LEFTOF;break;case 69:this.$=Be.PLACEMENT.RIGHTOF;break;case 70:this.$=[ce[fe-4],ce[fe-1],{type:"addMessage",from:ce[fe-4].actor,to:ce[fe-1].actor,signalType:ce[fe-3],msg:ce[fe],activate:!0},{type:"activeStart",signalType:Be.LINETYPE.ACTIVE_START,actor:ce[fe-1].actor}];break;case 71:this.$=[ce[fe-4],ce[fe-1],{type:"addMessage",from:ce[fe-4].actor,to:ce[fe-1].actor,signalType:ce[fe-3],msg:ce[fe]},{type:"activeEnd",signalType:Be.LINETYPE.ACTIVE_END,actor:ce[fe-4].actor}];break;case 72:this.$=[ce[fe-4],ce[fe-1],{type:"addMessage",from:ce[fe-4].actor,to:ce[fe-1].actor,signalType:ce[fe-3],msg:ce[fe],activate:!0,centralConnection:Be.LINETYPE.CENTRAL_CONNECTION},{type:"centralConnection",signalType:Be.LINETYPE.CENTRAL_CONNECTION,actor:ce[fe-1].actor}];break;case 73:this.$=[ce[fe-4],ce[fe-1],{type:"addMessage",from:ce[fe-4].actor,to:ce[fe-1].actor,signalType:ce[fe-2],msg:ce[fe],activate:!1,centralConnection:Be.LINETYPE.CENTRAL_CONNECTION_REVERSE},{type:"centralConnectionReverse",signalType:Be.LINETYPE.CENTRAL_CONNECTION_REVERSE,actor:ce[fe-4].actor}];break;case 74:this.$=[ce[fe-5],ce[fe-1],{type:"addMessage",from:ce[fe-5].actor,to:ce[fe-1].actor,signalType:ce[fe-3],msg:ce[fe],activate:!0,centralConnection:Be.LINETYPE.CENTRAL_CONNECTION_DUAL},{type:"centralConnection",signalType:Be.LINETYPE.CENTRAL_CONNECTION,actor:ce[fe-1].actor},{type:"centralConnectionReverse",signalType:Be.LINETYPE.CENTRAL_CONNECTION_REVERSE,actor:ce[fe-5].actor}];break;case 75:this.$=[ce[fe-3],ce[fe-1],{type:"addMessage",from:ce[fe-3].actor,to:ce[fe-1].actor,signalType:ce[fe-2],msg:ce[fe]}];break;case 76:this.$={type:"addParticipant",actor:ce[fe-1],config:ce[fe]};break;case 77:this.$=ce[fe-1].trim();break;case 78:this.$={type:"addParticipant",actor:ce[fe]};break;case 79:this.$=Be.LINETYPE.SOLID_OPEN;break;case 80:this.$=Be.LINETYPE.DOTTED_OPEN;break;case 81:this.$=Be.LINETYPE.SOLID;break;case 82:this.$=Be.LINETYPE.SOLID_TOP;break;case 83:this.$=Be.LINETYPE.SOLID_BOTTOM;break;case 84:this.$=Be.LINETYPE.STICK_TOP;break;case 85:this.$=Be.LINETYPE.STICK_BOTTOM;break;case 86:this.$=Be.LINETYPE.SOLID_TOP_DOTTED;break;case 87:this.$=Be.LINETYPE.SOLID_BOTTOM_DOTTED;break;case 88:this.$=Be.LINETYPE.STICK_TOP_DOTTED;break;case 89:this.$=Be.LINETYPE.STICK_BOTTOM_DOTTED;break;case 90:this.$=Be.LINETYPE.SOLID_ARROW_TOP_REVERSE;break;case 91:this.$=Be.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE;break;case 92:this.$=Be.LINETYPE.STICK_ARROW_TOP_REVERSE;break;case 93:this.$=Be.LINETYPE.STICK_ARROW_BOTTOM_REVERSE;break;case 94:this.$=Be.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED;break;case 95:this.$=Be.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED;break;case 96:this.$=Be.LINETYPE.STICK_ARROW_TOP_REVERSE_DOTTED;break;case 97:this.$=Be.LINETYPE.STICK_ARROW_BOTTOM_REVERSE_DOTTED;break;case 98:this.$=Be.LINETYPE.BIDIRECTIONAL_SOLID;break;case 99:this.$=Be.LINETYPE.DOTTED;break;case 100:this.$=Be.LINETYPE.BIDIRECTIONAL_DOTTED;break;case 101:this.$=Be.LINETYPE.SOLID_CROSS;break;case 102:this.$=Be.LINETYPE.DOTTED_CROSS;break;case 103:this.$=Be.LINETYPE.SOLID_POINT;break;case 104:this.$=Be.LINETYPE.DOTTED_POINT;break;case 105:this.$=Be.parseMessage(ce[fe].trim().substring(1));break}},"anonymous"),table:[{3:1,4:e,5:r,6:i},{1:[3]},{3:5,4:e,5:r,6:i},{3:6,4:e,5:r,6:i},t([1,4,5,10,14,15,19,22,24,30,31,32,34,36,37,38,39,40,42,44,45,47,51,53,54,56,61,62,63,64,73],n,{7:7}),{1:[2,1]},{1:[2,2]},{1:[2,3],4:a,5:s,8:8,9:10,10:l,13:13,14:u,15:h,18:16,19:f,22:d,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:g,32:y,34:v,36:x,37:b,38:T,39:w,40:k,42:C,44:E,45:S,47:L,51:M,53:I,54:A,56:_,61:D,62:N,63:R,64:B,73:O},t($,[2,5]),{9:48,13:13,14:u,15:h,18:16,19:f,22:d,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:g,32:y,34:v,36:x,37:b,38:T,39:w,40:k,42:C,44:E,45:S,47:L,51:M,53:I,54:A,56:_,61:D,62:N,63:R,64:B,73:O},t($,[2,7]),t($,[2,8]),t($,[2,9]),t($,[2,15]),{13:49,51:M,53:I,54:A},{16:[1,50]},{5:[1,51]},{5:[1,54],20:[1,52],21:[1,53]},{23:55,73:O},{23:56,73:O},{5:[1,57]},{5:[1,58]},{5:[1,59]},{5:[1,60]},{5:[1,61]},t($,[2,30]),t($,[2,31]),{33:[1,62]},{35:[1,63]},t($,[2,34]),{16:[1,64]},{16:[1,65]},{16:[1,66]},{16:[1,67]},{16:[1,68]},{16:[1,69]},{16:[1,70]},{16:[1,71]},{23:72,55:73,73:z},{23:75,55:76,73:z},{23:77,73:O},{69:78,72:[1,79],78:F,79:V,80:H,81:X,82:W,83:Z,84:Y,85:ae,86:J,87:ee,88:re,89:te,90:be,91:de,92:Ee,93:Ne,94:we,95:Te,96:De,97:$e,98:pe,99:Je,100:Ce,101:Fe,102:Ue,103:qe},{57:106,59:[1,107],67:[1,108],68:[1,109]},{23:110,73:O},{23:111,73:O},{23:112,73:O},{23:113,73:O},t([5,66,72,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104],Me),t($,[2,6]),t($,[2,16]),t(He,[2,10],{11:114}),t($,[2,18]),{5:[1,116],20:[1,115]},{5:[1,117]},t($,[2,22]),{5:[1,118]},{5:[1,119]},t($,[2,25]),t($,[2,26]),t($,[2,27]),t($,[2,28]),t($,[2,29]),t($,[2,32]),t($,[2,33]),t(K,n,{7:120}),t(K,n,{7:121}),t(K,n,{7:122}),t(oe,n,{41:123,7:124}),t(U,n,{43:125,7:126}),t(U,n,{7:126,43:127}),t(ue,n,{46:128,7:129}),t(K,n,{7:130}),{5:[1,132],52:[1,131]},{5:[1,134],52:[1,133]},t(G,Me,{74:135,75:[1,136]}),{5:[1,138],52:[1,137]},{5:[1,140],52:[1,139]},{5:[1,141]},{23:145,70:[1,142],71:[1,143],72:[1,144],73:O},{69:146,78:F,79:V,80:H,81:X,82:W,83:Z,84:Y,85:ae,86:J,87:ee,88:re,89:te,90:be,91:de,92:Ee,93:Ne,94:we,95:Te,96:De,97:$e,98:pe,99:Je,100:Ce,101:Fe,102:Ue,103:qe},t(se,[2,79]),t(se,[2,80]),t(se,[2,81]),t(se,[2,82]),t(se,[2,83]),t(se,[2,84]),t(se,[2,85]),t(se,[2,86]),t(se,[2,87]),t(se,[2,88]),t(se,[2,89]),t(se,[2,90]),t(se,[2,91]),t(se,[2,92]),t(se,[2,93]),t(se,[2,94]),t(se,[2,95]),t(se,[2,96]),t(se,[2,97]),t(se,[2,98]),t(se,[2,99]),t(se,[2,100]),t(se,[2,101]),t(se,[2,102]),t(se,[2,103]),t(se,[2,104]),{23:147,73:O},{23:149,60:148,73:O},{73:[2,68]},{73:[2,69]},{58:150,104:le},{58:152,104:le},{58:153,104:le},{58:154,104:le},{4:[1,157],5:[1,159],12:156,13:158,17:[1,155],51:M,53:I,54:A},{5:[1,160]},t($,[2,20]),t($,[2,21]),t($,[2,23]),t($,[2,24]),{4:a,5:s,8:8,9:10,10:l,13:13,14:u,15:h,17:[1,161],18:16,19:f,22:d,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:g,32:y,34:v,36:x,37:b,38:T,39:w,40:k,42:C,44:E,45:S,47:L,51:M,53:I,54:A,56:_,61:D,62:N,63:R,64:B,73:O},{4:a,5:s,8:8,9:10,10:l,13:13,14:u,15:h,17:[1,162],18:16,19:f,22:d,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:g,32:y,34:v,36:x,37:b,38:T,39:w,40:k,42:C,44:E,45:S,47:L,51:M,53:I,54:A,56:_,61:D,62:N,63:R,64:B,73:O},{4:a,5:s,8:8,9:10,10:l,13:13,14:u,15:h,17:[1,163],18:16,19:f,22:d,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:g,32:y,34:v,36:x,37:b,38:T,39:w,40:k,42:C,44:E,45:S,47:L,51:M,53:I,54:A,56:_,61:D,62:N,63:R,64:B,73:O},{17:[1,164]},{4:a,5:s,8:8,9:10,10:l,13:13,14:u,15:h,17:[2,47],18:16,19:f,22:d,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:g,32:y,34:v,36:x,37:b,38:T,39:w,40:k,42:C,44:E,45:S,47:L,50:[1,165],51:M,53:I,54:A,56:_,61:D,62:N,63:R,64:B,73:O},{17:[1,166]},{4:a,5:s,8:8,9:10,10:l,13:13,14:u,15:h,17:[2,45],18:16,19:f,22:d,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:g,32:y,34:v,36:x,37:b,38:T,39:w,40:k,42:C,44:E,45:S,47:L,49:[1,167],51:M,53:I,54:A,56:_,61:D,62:N,63:R,64:B,73:O},{17:[1,168]},{17:[1,169]},{4:a,5:s,8:8,9:10,10:l,13:13,14:u,15:h,17:[2,43],18:16,19:f,22:d,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:g,32:y,34:v,36:x,37:b,38:T,39:w,40:k,42:C,44:E,45:S,47:L,48:[1,170],51:M,53:I,54:A,56:_,61:D,62:N,63:R,64:B,73:O},{4:a,5:s,8:8,9:10,10:l,13:13,14:u,15:h,17:[1,171],18:16,19:f,22:d,23:41,24:p,25:20,26:21,27:22,28:23,29:24,30:m,31:g,32:y,34:v,36:x,37:b,38:T,39:w,40:k,42:C,44:E,45:S,47:L,51:M,53:I,54:A,56:_,61:D,62:N,63:R,64:B,73:O},{16:[1,172]},t($,[2,50]),{16:[1,173]},t($,[2,55]),t(G,[2,76]),{76:[1,174]},{16:[1,175]},t($,[2,52]),{16:[1,176]},t($,[2,57]),t($,[2,53]),{23:177,73:O},{23:178,73:O},{23:179,73:O},{58:180,104:le},{23:181,72:[1,182],73:O},{58:183,104:le},{58:184,104:le},{66:[1,185],104:[2,67]},{5:[2,60]},{5:[2,105]},{5:[2,61]},{5:[2,62]},{5:[2,63]},t($,[2,17]),t(He,[2,11]),{13:186,51:M,53:I,54:A},t(He,[2,13]),t(He,[2,14]),t($,[2,19]),t($,[2,35]),t($,[2,36]),t($,[2,37]),t($,[2,38]),{16:[1,187]},t($,[2,39]),{16:[1,188]},t($,[2,40]),t($,[2,41]),{16:[1,189]},t($,[2,42]),{5:[1,190]},{5:[1,191]},{77:[1,192]},{5:[1,193]},{5:[1,194]},{58:195,104:le},{58:196,104:le},{58:197,104:le},{5:[2,75]},{58:198,104:le},{23:199,73:O},{5:[2,58]},{5:[2,59]},{23:200,73:O},t(He,[2,12]),t(oe,n,{7:124,41:201}),t(U,n,{7:126,43:202}),t(ue,n,{7:129,46:203}),t($,[2,49]),t($,[2,54]),t(G,[2,77]),t($,[2,51]),t($,[2,56]),{5:[2,70]},{5:[2,71]},{5:[2,72]},{5:[2,73]},{58:204,104:le},{104:[2,66]},{17:[2,48]},{17:[2,46]},{17:[2,44]},{5:[2,74]}],defaultActions:{5:[2,1],6:[2,2],108:[2,68],109:[2,69],150:[2,60],151:[2,105],152:[2,61],153:[2,62],154:[2,63],180:[2,75],183:[2,58],184:[2,59],195:[2,70],196:[2,71],197:[2,72],198:[2,73],200:[2,66],201:[2,48],202:[2,46],203:[2,44],204:[2,74]},parseError:o(function(ve,Oe){if(Oe.recoverable)this.trace(ve);else{var We=new Error(ve);throw We.hash=Oe,We}},"parseError"),parse:o(function(ve){var Oe=this,We=[0],Be=[],Qe=[null],ce=[],it=this.table,fe="",ut=0,Nt=0,Pt=0,St=2,It=1,ot=ce.slice.call(arguments,1),ct=Object.create(this.lexer),Dt={yy:{}};for(var kt in this.yy)Object.prototype.hasOwnProperty.call(this.yy,kt)&&(Dt.yy[kt]=this.yy[kt]);ct.setInput(ve,Dt.yy),Dt.yy.lexer=ct,Dt.yy.parser=this,typeof ct.yylloc>"u"&&(ct.yylloc={});var yt=ct.yylloc;ce.push(yt);var jt=ct.options&&ct.options.ranges;typeof Dt.yy.parseError=="function"?this.parseError=Dt.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function hr(Ir){We.length=We.length-2*Ir,Qe.length=Qe.length-Ir,ce.length=ce.length-Ir}o(hr,"popStack");function Qt(){var Ir;return Ir=Be.pop()||ct.lex()||It,typeof Ir!="number"&&(Ir instanceof Array&&(Be=Ir,Ir=Be.pop()),Ir=Oe.symbols_[Ir]||Ir),Ir}o(Qt,"lex");for(var Er,dr,ir,pr,Ii,xt,Ie={},ft,_t,zr,ri;;){if(ir=We[We.length-1],this.defaultActions[ir]?pr=this.defaultActions[ir]:((Er===null||typeof Er>"u")&&(Er=Qt()),pr=it[ir]&&it[ir][Er]),typeof pr>"u"||!pr.length||!pr[0]){var ci="";ri=[];for(ft in it[ir])this.terminals_[ft]&&ft>St&&ri.push("'"+this.terminals_[ft]+"'");ct.showPosition?ci="Parse error on line "+(ut+1)+`: +`+ct.showPosition()+` +Expecting `+ri.join(", ")+", got '"+(this.terminals_[Er]||Er)+"'":ci="Parse error on line "+(ut+1)+": Unexpected "+(Er==It?"end of input":"'"+(this.terminals_[Er]||Er)+"'"),this.parseError(ci,{text:ct.match,token:this.terminals_[Er]||Er,line:ct.yylineno,loc:yt,expected:ri})}if(pr[0]instanceof Array&&pr.length>1)throw new Error("Parse Error: multiple actions possible at state: "+ir+", token: "+Er);switch(pr[0]){case 1:We.push(Er),Qe.push(ct.yytext),ce.push(ct.yylloc),We.push(pr[1]),Er=null,dr?(Er=dr,dr=null):(Nt=ct.yyleng,fe=ct.yytext,ut=ct.yylineno,yt=ct.yylloc,Pt>0&&Pt--);break;case 2:if(_t=this.productions_[pr[1]][1],Ie.$=Qe[Qe.length-_t],Ie._$={first_line:ce[ce.length-(_t||1)].first_line,last_line:ce[ce.length-1].last_line,first_column:ce[ce.length-(_t||1)].first_column,last_column:ce[ce.length-1].last_column},jt&&(Ie._$.range=[ce[ce.length-(_t||1)].range[0],ce[ce.length-1].range[1]]),xt=this.performAction.apply(Ie,[fe,Nt,ut,Dt.yy,pr[1],Qe,ce].concat(ot)),typeof xt<"u")return xt;_t&&(We=We.slice(0,-1*_t*2),Qe=Qe.slice(0,-1*_t),ce=ce.slice(0,-1*_t)),We.push(this.productions_[pr[1]][0]),Qe.push(Ie.$),ce.push(Ie._$),zr=it[We[We.length-2]][We[We.length-1]],We.push(zr);break;case 3:return!0}}return!0},"parse")},me=(function(){var Re={EOF:1,parseError:o(function(Oe,We){if(this.yy.parser)this.yy.parser.parseError(Oe,We);else throw new Error(Oe)},"parseError"),setInput:o(function(ve,Oe){return this.yy=Oe||this.yy||{},this._input=ve,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var ve=this._input[0];this.yytext+=ve,this.yyleng++,this.offset++,this.match+=ve,this.matched+=ve;var Oe=ve.match(/(?:\r\n?|\n).*/g);return Oe?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),ve},"input"),unput:o(function(ve){var Oe=ve.length,We=ve.split(/(?:\r\n?|\n)/g);this._input=ve+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-Oe),this.offset-=Oe;var Be=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),We.length-1&&(this.yylineno-=We.length-1);var Qe=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:We?(We.length===Be.length?this.yylloc.first_column:0)+Be[Be.length-We.length].length-We[0].length:this.yylloc.first_column-Oe},this.options.ranges&&(this.yylloc.range=[Qe[0],Qe[0]+this.yyleng-Oe]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(ve){this.unput(this.match.slice(ve))},"less"),pastInput:o(function(){var ve=this.matched.substr(0,this.matched.length-this.match.length);return(ve.length>20?"...":"")+ve.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var ve=this.match;return ve.length<20&&(ve+=this._input.substr(0,20-ve.length)),(ve.substr(0,20)+(ve.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var ve=this.pastInput(),Oe=new Array(ve.length+1).join("-");return ve+this.upcomingInput()+` +`+Oe+"^"},"showPosition"),test_match:o(function(ve,Oe){var We,Be,Qe;if(this.options.backtrack_lexer&&(Qe={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(Qe.yylloc.range=this.yylloc.range.slice(0))),Be=ve[0].match(/(?:\r\n?|\n).*/g),Be&&(this.yylineno+=Be.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:Be?Be[Be.length-1].length-Be[Be.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+ve[0].length},this.yytext+=ve[0],this.match+=ve[0],this.matches=ve,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(ve[0].length),this.matched+=ve[0],We=this.performAction.call(this,this.yy,this,Oe,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),We)return We;if(this._backtrack){for(var ce in Qe)this[ce]=Qe[ce];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var ve,Oe,We,Be;this._more||(this.yytext="",this.match="");for(var Qe=this._currentRules(),ce=0;ceOe[0].length)){if(Oe=We,Be=ce,this.options.backtrack_lexer){if(ve=this.test_match(We,Qe[ce]),ve!==!1)return ve;if(this._backtrack){Oe=!1;continue}else return!1}else if(!this.options.flex)break}return Oe?(ve=this.test_match(Oe,Qe[Be]),ve!==!1?ve:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var Oe=this.next();return Oe||this.lex()},"lex"),begin:o(function(Oe){this.conditionStack.push(Oe)},"begin"),popState:o(function(){var Oe=this.conditionStack.length-1;return Oe>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(Oe){return Oe=this.conditionStack.length-1-Math.abs(Oe||0),Oe>=0?this.conditionStack[Oe]:"INITIAL"},"topState"),pushState:o(function(Oe){this.begin(Oe)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:o(function(Oe,We,Be,Qe){var ce=Qe;switch(Be){case 0:return 5;case 1:break;case 2:break;case 3:break;case 4:break;case 5:break;case 6:return 20;case 7:return this.begin("CONFIG"),75;break;case 8:return 76;case 9:return this.popState(),this.begin("ALIAS"),77;break;case 10:return this.popState(),this.popState(),77;break;case 11:return We.yytext=We.yytext.trim(),73;break;case 12:return We.yytext=We.yytext.trim(),this.begin("ALIAS"),73;break;case 13:return We.yytext=We.yytext.trim(),this.popState(),73;break;case 14:return this.popState(),10;break;case 15:return We.yytext=We.yytext.trim(),this.popState(),10;break;case 16:return this.begin("LINE"),15;break;case 17:return this.begin("ID"),51;break;case 18:return this.begin("ID"),53;break;case 19:return 14;case 20:return this.begin("ID"),54;break;case 21:return this.popState(),this.popState(),this.begin("LINE"),52;break;case 22:return this.popState(),this.popState(),5;break;case 23:return this.begin("LINE"),37;break;case 24:return this.begin("LINE"),38;break;case 25:return this.begin("LINE"),39;break;case 26:return this.begin("LINE"),40;break;case 27:return this.begin("LINE"),50;break;case 28:return this.begin("LINE"),42;break;case 29:return this.begin("LINE"),44;break;case 30:return this.begin("LINE"),49;break;case 31:return this.begin("LINE"),45;break;case 32:return this.begin("LINE"),48;break;case 33:return this.begin("LINE"),47;break;case 34:return this.popState(),16;break;case 35:return 17;case 36:return 67;case 37:return 68;case 38:return 61;case 39:return 62;case 40:return 63;case 41:return 64;case 42:return 59;case 43:return 56;case 44:return this.begin("ID"),22;break;case 45:return this.begin("ID"),24;break;case 46:return 30;case 47:return 31;case 48:return this.begin("acc_title"),32;break;case 49:return this.popState(),"acc_title_value";break;case 50:return this.begin("acc_descr"),34;break;case 51:return this.popState(),"acc_descr_value";break;case 52:this.begin("acc_descr_multiline");break;case 53:this.popState();break;case 54:return"acc_descr_multiline_value";case 55:return 6;case 56:return 19;case 57:return 21;case 58:return 66;case 59:return 5;case 60:return We.yytext=We.yytext.trim(),73;break;case 61:return 80;case 62:return 97;case 63:return 98;case 64:return 99;case 65:return 78;case 66:return 79;case 67:return 100;case 68:return 101;case 69:return 102;case 70:return 103;case 71:return 85;case 72:return 86;case 73:return 87;case 74:return 88;case 75:return 93;case 76:return 94;case 77:return 95;case 78:return 96;case 79:return 81;case 80:return 82;case 81:return 83;case 82:return 84;case 83:return 89;case 84:return 90;case 85:return 91;case 86:return 92;case 87:return 104;case 88:return 104;case 89:return 70;case 90:return 71;case 91:return 72;case 92:return 5;case 93:return 10}},"anonymous"),rules:[/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:((?!\n)\s)+)/i,/^(?:#[^\n]*)/i,/^(?:%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[0-9]+(?=[ \n]+))/i,/^(?:@\{)/i,/^(?:[^\}]+)/i,/^(?:\}(?=\s+as\s))/i,/^(?:\})/i,/^(?:[^\<->\->:\n,;@\s]+(?=@\{))/i,/^(?:[^<>:\n,;@\s]+(?=\s+as\s))/i,/^(?:[^<>:\n,;@]+(?=\s*[\n;#]|$))/i,/^(?:[^<>:\n,;@]*<[^\n]*)/i,/^(?:[^\n]+)/i,/^(?:box\b)/i,/^(?:participant\b)/i,/^(?:actor\b)/i,/^(?:create\b)/i,/^(?:destroy\b)/i,/^(?:as\b)/i,/^(?:(?:))/i,/^(?:loop\b)/i,/^(?:rect\b)/i,/^(?:opt\b)/i,/^(?:alt\b)/i,/^(?:else\b)/i,/^(?:par\b)/i,/^(?:par_over\b)/i,/^(?:and\b)/i,/^(?:critical\b)/i,/^(?:option\b)/i,/^(?:break\b)/i,/^(?:(?:[:]?(?:no)?wrap)?[^#\n;]*)/i,/^(?:end\b)/i,/^(?:left of\b)/i,/^(?:right of\b)/i,/^(?:links\b)/i,/^(?:link\b)/i,/^(?:properties\b)/i,/^(?:details\b)/i,/^(?:over\b)/i,/^(?:note\b)/i,/^(?:activate\b)/i,/^(?:deactivate\b)/i,/^(?:title\s[^#\n;]+)/i,/^(?:title:\s[^#\n;]+)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:sequenceDiagram\b)/i,/^(?:autonumber\b)/i,/^(?:off\b)/i,/^(?:,)/i,/^(?:;)/i,/^(?:[^\/\\\+\()\+<\->\->:\n,;]+((?!(-x|--x|-\)|--\)|-\|\\|-\\|-\/|-\/\/|-\|\/|\/\|-|\\\|-|\/\/-|\\\\-|\/\|-|--\|\\|--|\(\)))[\-]*[^\+<\->\->:\n,;]+)*)/i,/^(?:->>)/i,/^(?:<<->>)/i,/^(?:-->>)/i,/^(?:<<-->>)/i,/^(?:->)/i,/^(?:-->)/i,/^(?:-[x])/i,/^(?:--[x])/i,/^(?:-[\)])/i,/^(?:--[\)])/i,/^(?:--\|\\)/i,/^(?:--\|\/)/i,/^(?:--\\\\)/i,/^(?:--\/\/)/i,/^(?:\/\|--)/i,/^(?:\\\|--)/i,/^(?:\/\/--)/i,/^(?:\\\\--)/i,/^(?:-\|\\)/i,/^(?:-\|\/)/i,/^(?:-\\\\)/i,/^(?:-\/\/)/i,/^(?:\/\|-)/i,/^(?:\\\|-)/i,/^(?:\/\/-)/i,/^(?:\\\\-)/i,/^(?::(?:(?:no)?wrap)?[^#\n;]*)/i,/^(?::)/i,/^(?:\+)/i,/^(?:-)/i,/^(?:\(\))/i,/^(?:$)/i,/^(?:.)/i],conditions:{acc_descr_multiline:{rules:[53,54],inclusive:!1},acc_descr:{rules:[51],inclusive:!1},acc_title:{rules:[49],inclusive:!1},ID:{rules:[2,3,7,11,12,13,14,15],inclusive:!1},ALIAS:{rules:[2,3,21,22],inclusive:!1},LINE:{rules:[2,3,34],inclusive:!1},CONFIG:{rules:[8,9,10],inclusive:!1},CONFIG_DATA:{rules:[],inclusive:!1},INITIAL:{rules:[0,1,3,4,5,6,16,17,18,19,20,23,24,25,26,27,28,29,30,31,32,33,35,36,37,38,39,40,41,42,43,44,45,46,47,48,50,52,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93],inclusive:!0}}};return Re})();ke.lexer=me;function ye(){this.yy={}}return o(ye,"Parser"),ye.prototype=ke,ke.Parser=ye,new ye})();iU.parser=iU;T3e=iU});var Lht,Rht,Nht,NC,T_,nU=P(()=>{"use strict";Ut();xb();bt();J7();Vr();Ki();Lht={SOLID:0,DOTTED:1,NOTE:2,SOLID_CROSS:3,DOTTED_CROSS:4,SOLID_OPEN:5,DOTTED_OPEN:6,LOOP_START:10,LOOP_END:11,ALT_START:12,ALT_ELSE:13,ALT_END:14,OPT_START:15,OPT_END:16,ACTIVE_START:17,ACTIVE_END:18,PAR_START:19,PAR_AND:20,PAR_END:21,RECT_START:22,RECT_END:23,SOLID_POINT:24,DOTTED_POINT:25,AUTONUMBER:26,CRITICAL_START:27,CRITICAL_OPTION:28,CRITICAL_END:29,BREAK_START:30,BREAK_END:31,PAR_OVER_START:32,BIDIRECTIONAL_SOLID:33,BIDIRECTIONAL_DOTTED:34,SOLID_TOP:41,SOLID_BOTTOM:42,STICK_TOP:43,STICK_BOTTOM:44,SOLID_ARROW_TOP_REVERSE:45,SOLID_ARROW_BOTTOM_REVERSE:46,STICK_ARROW_TOP_REVERSE:47,STICK_ARROW_BOTTOM_REVERSE:48,SOLID_TOP_DOTTED:51,SOLID_BOTTOM_DOTTED:52,STICK_TOP_DOTTED:53,STICK_BOTTOM_DOTTED:54,SOLID_ARROW_TOP_REVERSE_DOTTED:55,SOLID_ARROW_BOTTOM_REVERSE_DOTTED:56,STICK_ARROW_TOP_REVERSE_DOTTED:57,STICK_ARROW_BOTTOM_REVERSE_DOTTED:58,CENTRAL_CONNECTION:59,CENTRAL_CONNECTION_REVERSE:60,CENTRAL_CONNECTION_DUAL:61},Rht={FILLED:0,OPEN:1},Nht={LEFTOF:0,RIGHTOF:1,OVER:2},NC={ACTOR:"actor",BOUNDARY:"boundary",COLLECTIONS:"collections",CONTROL:"control",DATABASE:"database",ENTITY:"entity",PARTICIPANT:"participant",QUEUE:"queue"},T_=class{constructor(){this.state=new Cp(()=>({prevActor:void 0,actors:new Map,createdActors:new Map,destroyedActors:new Map,boxes:[],messages:[],notes:[],sequenceNumbersEnabled:!1,wrapEnabled:void 0,currentBox:void 0,lastCreated:void 0,lastDestroyed:void 0}));this.setAccTitle=Ar;this.setAccDescription=Lr;this.setDiagramTitle=Mr;this.getAccTitle=Dr;this.getAccDescription=Rr;this.getDiagramTitle=Nr;this.apply=this.apply.bind(this),this.parseBoxData=this.parseBoxData.bind(this),this.parseMessage=this.parseMessage.bind(this),this.clear(),this.setWrap(ge().wrap),this.LINETYPE=Lht,this.ARROWTYPE=Rht,this.PLACEMENT=Nht}static{o(this,"SequenceDB")}addBox(e){this.state.records.boxes.push({name:e.text,wrap:e.wrap??this.autoWrap(),fill:e.color,actorKeys:[]}),this.state.records.currentBox=this.state.records.boxes.slice(-1)[0]}addActor(e,r,i,n,a){let s=this.state.records.currentBox,l;if(a!==void 0){let h;a.includes(` +`)?h=a+` +`:h=`{ +`+a+` +}`,l=ud(h,{schema:cd})}n=l?.type??n,l?.alias&&(!i||i.text===r)&&(i={text:l.alias,wrap:i?.wrap,type:n});let u=this.state.records.actors.get(e);if(u){if(this.state.records.currentBox&&u.box&&this.state.records.currentBox!==u.box)throw new Error(`A same participant should only be defined in one Box: ${u.name} can't be in '${u.box.name}' and in '${this.state.records.currentBox.name}' at the same time.`);if(s=u.box?u.box:this.state.records.currentBox,u.box=s,u&&r===u.name&&i==null)return}if(i?.text==null&&(i={text:r,type:n}),(n==null||i.text==null)&&(i={text:r,type:n}),this.state.records.actors.set(e,{box:s,name:r,description:i.text,wrap:i.wrap??this.autoWrap(),prevActor:this.state.records.prevActor,links:{},properties:{},actorCnt:null,rectData:null,type:n??"participant"}),this.state.records.prevActor){let h=this.state.records.actors.get(this.state.records.prevActor);h&&(h.nextActor=e)}this.state.records.currentBox&&this.state.records.currentBox.actorKeys.push(e),this.state.records.prevActor=e}activationCount(e){let r,i=0;if(!e)return 0;for(r=0;r>-",token:"->>-",line:"1",loc:{first_line:1,last_line:1,first_column:1,last_column:1},expected:["'ACTIVE_PARTICIPANT'"]},u}return this.state.records.messages.push({id:this.state.records.messages.length.toString(),from:e,to:r,message:i?.text??"",wrap:i?.wrap??this.autoWrap(),type:n,activate:a,centralConnection:s??0}),!0}hasAtLeastOneBox(){return this.state.records.boxes.length>0}hasAtLeastOneBoxWithTitle(){return this.state.records.boxes.some(e=>e.name)}getMessages(){return this.state.records.messages}getBoxes(){return this.state.records.boxes}getActors(){return this.state.records.actors}getCreatedActors(){return this.state.records.createdActors}getDestroyedActors(){return this.state.records.destroyedActors}getActor(e){return this.state.records.actors.get(e)}getActorKeys(){return[...this.state.records.actors.keys()]}enableSequenceNumbers(){this.state.records.sequenceNumbersEnabled=!0}disableSequenceNumbers(){this.state.records.sequenceNumbersEnabled=!1}showSequenceNumbers(){return this.state.records.sequenceNumbersEnabled}setWrap(e){this.state.records.wrapEnabled=e}extractWrap(e){if(e===void 0)return{};e=e.trim();let r=/^:?wrap:/.exec(e)!==null?!0:/^:?nowrap:/.exec(e)!==null?!1:void 0;return{cleanedText:(r===void 0?e:e.replace(/^:?(?:no)?wrap:/,"")).trim(),wrap:r}}autoWrap(){return this.state.records.wrapEnabled!==void 0?this.state.records.wrapEnabled:ge().sequence?.wrap??!1}clear(){this.state.reset(),wr()}parseMessage(e){let r=e.trim(),{wrap:i,cleanedText:n}=this.extractWrap(r),a={text:n,wrap:i};return Q.debug(`parseMessage: ${JSON.stringify(a)}`),a}parseBoxData(e){let r=/^((?:rgba?|hsla?)\s*\(.*\)|\w*)(.*)$/.exec(e),i=r?.[1]?r[1].trim():"transparent",n=r?.[2]?r[2].trim():void 0;if(window?.CSS)window.CSS.supports("color",i)||(i="transparent",n=e.trim());else{let l=new Option().style;l.color=i,l.color!==i&&(i="transparent",n=e.trim())}let{wrap:a,cleanedText:s}=this.extractWrap(n);return{text:s?Tr(s,ge()):void 0,color:i,wrap:a}}addNote(e,r,i){let n={actor:e,placement:r,message:i.text,wrap:i.wrap??this.autoWrap()},a=[].concat(e,e);this.state.records.notes.push(n),this.state.records.messages.push({id:this.state.records.messages.length.toString(),from:a[0],to:a[1],message:i.text,wrap:i.wrap??this.autoWrap(),type:this.LINETYPE.NOTE,placement:r})}addLinks(e,r){let i=this.getActor(e);try{let n=Tr(r.text,ge());n=n.replace(/=/g,"="),n=n.replace(/&/g,"&");let a=JSON.parse(n);this.insertLinks(i,a)}catch(n){Q.error("error while parsing actor link text",n)}}addALink(e,r){let i=this.getActor(e);try{let n={},a=Tr(r.text,ge()),s=a.indexOf("@");a=a.replace(/=/g,"="),a=a.replace(/&/g,"&");let l=a.slice(0,s-1).trim(),u=a.slice(s+1).trim();n[l]=u,this.insertLinks(i,n)}catch(n){Q.error("error while parsing actor link text",n)}}insertLinks(e,r){if(e.links==null)e.links=r;else for(let i in r)e.links[i]=r[i]}addProperties(e,r){let i=this.getActor(e);try{let n=Tr(r.text,ge()),a=JSON.parse(n);this.insertProperties(i,a)}catch(n){Q.error("error while parsing actor properties text",n)}}insertProperties(e,r){if(e.properties==null)e.properties=r;else for(let i in r)e.properties[i]=r[i]}boxEnd(){this.state.records.currentBox=void 0}addDetails(e,r){let i=this.getActor(e),n=document.getElementById(r.text);try{let a=n.innerHTML,s=JSON.parse(a);s.properties&&this.insertProperties(i,s.properties),s.links&&this.insertLinks(i,s.links)}catch(a){Q.error("error while parsing actor details text",a)}}getActorProperty(e,r){if(e?.properties!==void 0)return e.properties[r]}apply(e){if(Array.isArray(e))e.forEach(r=>{this.apply(r)});else switch(e.type){case"sequenceIndex":this.state.records.messages.push({id:this.state.records.messages.length.toString(),from:void 0,to:void 0,message:{start:e.sequenceIndex,step:e.sequenceIndexStep,visible:e.sequenceVisible},wrap:!1,type:e.signalType});break;case"addParticipant":this.addActor(e.actor,e.actor,e.description,e.draw,e.config);break;case"createParticipant":if(this.state.records.actors.has(e.actor))throw new Error("It is not possible to have actors with the same id, even if one is destroyed before the next is created. Use 'AS' aliases to simulate the behavior");this.state.records.lastCreated=e.actor,this.addActor(e.actor,e.actor,e.description,e.draw,e.config),this.state.records.createdActors.set(e.actor,this.state.records.messages.length);break;case"destroyParticipant":this.state.records.lastDestroyed=e.actor,this.state.records.destroyedActors.set(e.actor,this.state.records.messages.length);break;case"activeStart":this.addSignal(e.actor,void 0,void 0,e.signalType);break;case"centralConnection":this.addSignal(e.actor,void 0,void 0,e.signalType);break;case"centralConnectionReverse":this.addSignal(e.actor,void 0,void 0,e.signalType);break;case"activeEnd":this.addSignal(e.actor,void 0,void 0,e.signalType);break;case"addNote":this.addNote(e.actor,e.placement,e.text);break;case"addLinks":this.addLinks(e.actor,e.text);break;case"addALink":this.addALink(e.actor,e.text);break;case"addProperties":this.addProperties(e.actor,e.text);break;case"addDetails":this.addDetails(e.actor,e.text);break;case"addMessage":if(this.state.records.lastCreated){if(e.to!==this.state.records.lastCreated)throw new Error("The created participant "+this.state.records.lastCreated.name+" does not have an associated creating message after its declaration. Please check the sequence diagram.");this.state.records.lastCreated=void 0}else if(this.state.records.lastDestroyed){if(e.to!==this.state.records.lastDestroyed&&e.from!==this.state.records.lastDestroyed)throw new Error("The destroyed participant "+this.state.records.lastDestroyed.name+" does not have an associated destroying message after its declaration. Please check the sequence diagram.");this.state.records.lastDestroyed=void 0}this.addSignal(e.from,e.to,e.msg,e.signalType,e.activate,e.centralConnection);break;case"boxStart":this.addBox(e.boxData);break;case"boxEnd":this.boxEnd();break;case"loopStart":this.addSignal(void 0,void 0,e.loopText,e.signalType);break;case"loopEnd":this.addSignal(void 0,void 0,void 0,e.signalType);break;case"rectStart":this.addSignal(void 0,void 0,e.color,e.signalType);break;case"rectEnd":this.addSignal(void 0,void 0,void 0,e.signalType);break;case"optStart":this.addSignal(void 0,void 0,e.optText,e.signalType);break;case"optEnd":this.addSignal(void 0,void 0,void 0,e.signalType);break;case"altStart":this.addSignal(void 0,void 0,e.altText,e.signalType);break;case"else":this.addSignal(void 0,void 0,e.altText,e.signalType);break;case"altEnd":this.addSignal(void 0,void 0,void 0,e.signalType);break;case"setAccTitle":Ar(e.text);break;case"parStart":this.addSignal(void 0,void 0,e.parText,e.signalType);break;case"and":this.addSignal(void 0,void 0,e.parText,e.signalType);break;case"parEnd":this.addSignal(void 0,void 0,void 0,e.signalType);break;case"criticalStart":this.addSignal(void 0,void 0,e.criticalText,e.signalType);break;case"option":this.addSignal(void 0,void 0,e.optionText,e.signalType);break;case"criticalEnd":this.addSignal(void 0,void 0,void 0,e.signalType);break;case"breakStart":this.addSignal(void 0,void 0,e.breakText,e.signalType);break;case"breakEnd":this.addSignal(void 0,void 0,void 0,e.signalType);break}}getConfig(){return ge().sequence}}});var Iht,C3e,w3e=P(()=>{"use strict";Ut();Iht=o(t=>{let e=t.dropShadow??"none",{look:r}=ge();return`.actor { + stroke: ${t.actorBorder}; + fill: ${t.actorBkg}; + stroke-width: ${t.strokeWidth??1}; + } + + rect.actor.outer-path[data-look="neo"] { + filter: ${e}; + } + + rect.note[data-look="neo"] { + stroke:${t.noteBorderColor}; + fill:${t.noteBkgColor}; + filter: ${e}; + } + + text.actor > tspan { + fill: ${t.actorTextColor}; + stroke: none; + } + + .actor-line { + stroke: ${t.actorLineColor}; + } + + .innerArc { + stroke-width: 1.5; + stroke-dasharray: none; + } + + .messageLine0 { + stroke-width: 1.5; + stroke-dasharray: none; + stroke: ${t.signalColor}; + } + + .messageLine1 { + stroke-width: 1.5; + stroke-dasharray: 2, 2; + stroke: ${t.signalColor}; + } + + [id$="-arrowhead"] path { + fill: ${t.signalColor}; + stroke: ${t.signalColor}; + } + + .sequenceNumber { + fill: ${t.sequenceNumberColor}; + } + + [id$="-sequencenumber"] { + fill: ${t.signalColor}; + } + + [id$="-crosshead"] path { + fill: ${t.signalColor}; + stroke: ${t.signalColor}; + } + + .messageText { + fill: ${t.signalTextColor}; + stroke: none; + } + + .labelBox { + stroke: ${t.labelBoxBorderColor}; + fill: ${t.labelBoxBkgColor}; + filter: ${r==="neo"?e:"none"}; + } + + .labelText, .labelText > tspan { + fill: ${t.labelTextColor}; + stroke: none; + } + + .loopText, .loopText > tspan { + fill: ${t.loopTextColor}; + stroke: none; + } + + .loopLine { + stroke-width: 2px; + stroke-dasharray: 2, 2; + stroke: ${t.labelBoxBorderColor}; + fill: ${t.labelBoxBorderColor}; + } + + .note { + //stroke: #decc93; + stroke: ${t.noteBorderColor}; + fill: ${t.noteBkgColor}; + } + + .noteText, .noteText > tspan { + fill: ${t.noteTextColor}; + stroke: none; + ${t.noteFontWeight?`font-weight: ${t.noteFontWeight};`:""} + } + + .activation0 { + fill: ${t.activationBkgColor}; + stroke: ${t.activationBorderColor}; + } + + .activation1 { + fill: ${t.activationBkgColor}; + stroke: ${t.activationBorderColor}; + } + + .activation2 { + fill: ${t.activationBkgColor}; + stroke: ${t.activationBorderColor}; + } + + .actorPopupMenu { + position: absolute; + } + + .actorPopupMenuPanel { + position: absolute; + fill: ${t.actorBkg}; + box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); + filter: drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4)); +} + .actor-man circle, line { + fill: ${t.actorBkg}; + stroke-width: 2px; + } + + g rect.rect { + filter: ${e}; + stroke: ${t.nodeBorder}; + } +`},"getStyles"),C3e=Iht});var aU,Sp,Ap,_p,k_,lg,Cf,IC,Mht,C_,MC,cg,E3e,ei,sU,Oht,Pht,Bht,Fht,$ht,zht,Ght,Vht,qht,Wht,Uht,Hht,Yht,S3e,jht,Xht,Kht,Qht,Zht,Jht,eft,tft,A3e,rft,wf,ift,nft,aft,sft,oft,Hi,_3e=P(()=>{"use strict";aU=Wa(s1(),1);Sr();er();Vr();y0();Sp=36,Ap="actor-top",_p="actor-bottom",k_="actor-box",lg="actor-man",Cf=new Set(["redux-color","redux-dark-color"]),IC=o(function(t,e){let r=g0(t,e);return Lt().look==="neo"&&r.attr("data-look","neo"),r},"drawRect"),Mht=o(function(t,e,r,i,n){if(e.links===void 0||e.links===null||Object.keys(e.links).length===0)return{height:0,width:0};let a=e.links,s=e.actorCnt,l=e.rectData;var u="none";n&&(u="block !important");let h=t.append("g");h.attr("id","actor"+s+"_popup"),h.attr("class","actorPopupMenu"),h.attr("display",u);var f="";l.class!==void 0&&(f=" "+l.class);let d=l.width>r?l.width:r,p=h.append("rect");if(p.attr("class","actorPopupMenuPanel"+f),p.attr("x",l.x),p.attr("y",l.height),p.attr("fill",l.fill),p.attr("stroke",l.stroke),p.attr("width",d),p.attr("height",l.height),p.attr("rx",l.rx),p.attr("ry",l.ry),a!=null){var m=20;for(let v in a){var g=h.append("a"),y=(0,aU.sanitizeUrl)(a[v]);g.attr("xlink:href",y),g.attr("target","_blank"),ift(i)(v,g,l.x+10,l.height+m,d,20,{class:"actor"},i),m+=30}}return p.attr("height",m),{height:l.height+m,width:d}},"drawPopup"),C_=o(function(t){return"var pu = document.getElementById('"+t+"'); if (pu != null) { pu.style.display = pu.style.display == 'block' ? 'none' : 'block'; }"},"popupMenuToggle"),MC=o(async function(t,e,r=null){let i=t.append("foreignObject"),n=await Rg(e.text,Lt()),s=i.append("xhtml:div").attr("style","width: fit-content;").attr("xmlns","http://www.w3.org/1999/xhtml").html(n).node().getBoundingClientRect();if(i.attr("height",Math.round(s.height)).attr("width",Math.round(s.width)),e.class==="noteText"){let l=t.node().firstChild;l.setAttribute("height",s.height+2*e.textMargin);let u=l.getBBox();i.attr("x",Math.round(u.x+u.width/2-s.width/2)).attr("y",Math.round(u.y+u.height/2-s.height/2))}else if(r){let{startx:l,stopx:u,starty:h}=r;if(l>u){let f=l;l=u,u=f}i.attr("x",Math.round(l+Math.abs(l-u)/2-s.width/2)),e.class==="loopText"?i.attr("y",Math.round(h)):i.attr("y",Math.round(h-s.height))}return[i]},"drawKatex"),cg=o(function(t,e){let r=0,i=0,n=e.text.split(lt.lineBreakRegex),[a,s]=$s(e.fontSize),l=[],u=0,h=o(()=>e.y,"yfunc");if(e.valign!==void 0&&e.textMargin!==void 0&&e.textMargin>0)switch(e.valign){case"top":case"start":h=o(()=>Math.round(e.y+e.textMargin),"yfunc");break;case"middle":case"center":h=o(()=>Math.round(e.y+(r+i+e.textMargin)/2),"yfunc");break;case"bottom":case"end":h=o(()=>Math.round(e.y+(r+i+2*e.textMargin)-e.textMargin),"yfunc");break}if(e.anchor!==void 0&&e.textMargin!==void 0&&e.width!==void 0)switch(e.anchor){case"left":case"start":e.x=Math.round(e.x+e.textMargin),e.anchor="start",e.dominantBaseline="middle",e.alignmentBaseline="middle";break;case"middle":case"center":e.x=Math.round(e.x+e.width/2),e.anchor="middle",e.dominantBaseline="middle",e.alignmentBaseline="middle";break;case"right":case"end":e.x=Math.round(e.x+e.width-e.textMargin),e.anchor="end",e.dominantBaseline="middle",e.alignmentBaseline="middle";break}for(let[f,d]of n.entries()){e.textMargin!==void 0&&e.textMargin===0&&a!==void 0&&(u=f*a);let p=t.append("text");p.attr("x",e.x),p.attr("y",h()),e.anchor!==void 0&&p.attr("text-anchor",e.anchor).attr("dominant-baseline",e.dominantBaseline).attr("alignment-baseline",e.alignmentBaseline),e.fontFamily!==void 0&&p.style("font-family",e.fontFamily),s!==void 0&&p.style("font-size",s),e.fontWeight!==void 0&&p.style("font-weight",e.fontWeight),e.fill!==void 0&&p.attr("fill",e.fill),e.class!==void 0&&p.attr("class",e.class),e.dy!==void 0?p.attr("dy",e.dy):u!==0&&p.attr("dy",u);let m=d||gI;if(e.tspan){let g=p.append("tspan");g.attr("x",e.x),e.fill!==void 0&&g.attr("fill",e.fill),g.text(m)}else p.text(m);e.valign!==void 0&&e.textMargin!==void 0&&e.textMargin>0&&(i+=(p._groups||p)[0][0].getBBox().height,r=i),l.push(p)}return l},"drawText"),E3e=o(function(t,e){function r(n,a,s,l,u){return n+","+a+" "+(n+s)+","+a+" "+(n+s)+","+(a+l-u)+" "+(n+s-u*1.2)+","+(a+l)+" "+n+","+(a+l)}o(r,"genPoints");let i=t.append("polygon");return i.attr("points",r(e.x,e.y,e.width,e.height,7)),i.attr("class","labelBox"),e.y=e.y+e.height/2,cg(t,e),i},"drawLabel"),ei=-1,sU=o((t,e,r,i)=>{t.select&&r.forEach(n=>{let a=e.get(n),s=t.select("#actor"+a.actorCnt);!i.mirrorActors&&a.stopy?s.attr("y2",a.stopy+a.height/2):i.mirrorActors&&s.attr("y2",a.stopy)})},"fixLifeLineHeights"),Oht=o(function(t,e,r,i,n){let a=i?e.stopy:e.starty,s=e.x+e.width/2,l=a+e.height,{look:u,theme:h,themeVariables:f}=r,{bkgColorArray:d,borderColorArray:p}=f,m=t.append("g").lower();var g=m;i||(ei++,Object.keys(e.links||{}).length&&!r.forceMenus&&g.attr("onclick",C_(`actor${ei}_popup`)).attr("cursor","pointer"),g.append("line").attr("id","actor"+ei).attr("x1",s).attr("y1",l).attr("x2",s).attr("y2",2e3).attr("class","actor-line 200").attr("stroke-width","0.5px").attr("stroke","#999").attr("name",e.name).attr("data-et","life-line").attr("data-id",e.name),g=m.append("g"),e.actorCnt=ei,e.links!=null&&g.attr("id","root-"+ei),u==="neo"&&g.attr("data-look","neo"));let y=ja();var v="actor";e.properties?.class?v=e.properties.class:y.fill="#eaeaea",i?v+=` ${_p}`:v+=` ${Ap}`,y.x=e.x,y.y=a,y.width=e.width,y.height=e.height,y.class=v,y.rx=3,y.ry=3,y.name=e.name,u==="neo"&&(y.rx=6,y.ry=6);let x=IC(g,y),b=n.get(e.name)??0;if(Cf.has(h)&&(x.style("stroke",p[b%p.length]),x.style("fill",d[b%p.length])),u==="neo"&&x.attr("filter","url(#drop-shadow)"),e.rectData=y,e.properties?.icon){let w=e.properties.icon.trim();w.charAt(0)==="@"?w3(g,y.x+y.width-20,y.y+10,w.substr(1)):C3(g,y.x+y.width-20,y.y+10,w)}i||(g.attr("data-et","participant"),g.attr("data-type","participant"),g.attr("data-id",e.name)),wf(r,sn(e.description))(e.description,g,y.x,y.y,y.width,y.height,{class:`actor ${k_}`},r);let T=e.height;if(x.node){let w=x.node().getBBox();e.height=w.height,T=w.height}return T},"drawActorTypeParticipant"),Pht=o(function(t,e,r,i,n){let a=i?e.stopy:e.starty,s=e.x+e.width/2,l=a+e.height,{look:u,theme:h,themeVariables:f}=r,{bkgColorArray:d,borderColorArray:p}=f,m=t.append("g").lower();var g=m;i||(ei++,Object.keys(e.links||{}).length&&!r.forceMenus&&g.attr("onclick",C_(`actor${ei}_popup`)).attr("cursor","pointer"),g.append("line").attr("id","actor"+ei).attr("x1",s).attr("y1",l).attr("x2",s).attr("y2",2e3).attr("class","actor-line 200").attr("stroke-width","0.5px").attr("stroke","#999").attr("name",e.name).attr("data-et","life-line").attr("data-id",e.name),g=m.append("g"),e.actorCnt=ei,e.links!=null&&g.attr("id","root-"+ei),u==="neo"&&g.attr("data-look","neo"));let y=ja();var v="actor";e.properties?.class?v=e.properties.class:y.fill="#eaeaea",i?v+=` ${_p}`:v+=` ${Ap}`,y.x=e.x,y.y=a,y.width=e.width,y.height=e.height,y.class=v,y.name=e.name;let x=6,b={...y,x:y.x+-x,y:y.y+ +x,class:"actor"},T=IC(g,y),w=IC(g,b);e.rectData=y,u==="neo"&&g.attr("filter","url(#drop-shadow)");let k=n.get(e.name)??0;if(Cf.has(h)&&(T.style("stroke",p[k%p.length]),T.style("fill",d[k%p.length]),w.style("stroke",p[k%p.length]),w.style("fill",d[k%p.length])),e.properties?.icon){let E=e.properties.icon.trim();E.charAt(0)==="@"?w3(g,y.x+y.width-20,y.y+10,E.substr(1)):C3(g,y.x+y.width-20,y.y+10,E)}wf(r,sn(e.description))(e.description,g,y.x-x,y.y+x,y.width,y.height,{class:`actor ${k_}`},r);let C=e.height;if(T.node){let E=T.node().getBBox();e.height=E.height,C=E.height}return i||(g.attr("data-et","participant"),g.attr("data-type","collections"),g.attr("data-id",e.name)),C},"drawActorTypeCollections"),Bht=o(function(t,e,r,i,n){let a=i?e.stopy:e.starty,s=e.x+e.width/2,l=a+e.height,{look:u,theme:h,themeVariables:f}=r,{bkgColorArray:d,borderColorArray:p}=f,m=t.append("g").lower(),g=m;i||(ei++,Object.keys(e.links||{}).length&&!r.forceMenus&&g.attr("onclick",C_(`actor${ei}_popup`)).attr("cursor","pointer"),g.append("line").attr("id","actor"+ei).attr("x1",s).attr("y1",l).attr("x2",s).attr("y2",2e3).attr("class","actor-line 200").attr("stroke-width","0.5px").attr("stroke","#999").attr("name",e.name).attr("data-et","life-line").attr("data-id",e.name),g=m.append("g"),e.actorCnt=ei,e.links!=null&&g.attr("id","root-"+ei),u==="neo"&&g.attr("data-look","neo"));let y=ja(),v="actor";e.properties?.class?v=e.properties.class:y.fill="#eaeaea",i?v+=` ${_p}`:v+=` ${Ap}`,g.attr("class",v),y.x=e.x,y.y=a,y.width=e.width,y.height=e.height,y.name=e.name;let x=y.height/2,b=x/(2.5+y.height/50),T=g.append("g"),w=g.append("g"),k=`M ${y.x},${y.y+x} + a ${b},${x} 0 0 0 0,${y.height} + h ${y.width-2*b} + a ${b},${x} 0 0 0 0,-${y.height} + Z + `;T.append("path").attr("d",k),w.append("path").attr("d",`M ${y.x},${y.y+x} + a ${b},${x} 0 0 0 0,${y.height}`),T.attr("transform",`translate(${b}, ${-(y.height/2)})`),w.attr("transform",`translate(${y.width-b}, ${-y.height/2})`),e.rectData=y,u==="neo"&&T.attr("filter","url(#drop-shadow)");let C=n.get(e.name)??0;if(Cf.has(h)&&(T.style("stroke",p[C%p.length]),T.style("fill",d[C%p.length]),w.style("stroke",p[C%p.length]),w.style("fill",d[C%p.length])),e.properties?.icon){let L=e.properties.icon.trim(),M=y.x+y.width-20,I=y.y+10;L.charAt(0)==="@"?w3(g,M,I,L.substr(1)):C3(g,M,I,L)}wf(r,sn(e.description))(e.description,g,y.x,y.y,y.width,y.height,{class:`actor ${k_}`},r);let E=e.height,S=T.select("path:last-child");if(S.node()){let L=S.node().getBBox();e.height=L.height,E=L.height}return i||(g.attr("data-et","participant"),g.attr("data-type","queue"),g.attr("data-id",e.name)),E},"drawActorTypeQueue"),Fht=o(function(t,e,r,i,n,a){let s=i?e.stopy:e.starty,l=e.x+e.width/2,u=s+75,{look:h,theme:f,themeVariables:d}=r,{bkgColorArray:p,borderColorArray:m,actorBorder:g,actorBkg:y}=d,v=t.append("g").lower();i||(ei++,v.append("line").attr("id","actor"+ei).attr("x1",l).attr("y1",u).attr("x2",l).attr("y2",2e3).attr("class","actor-line 200").attr("stroke-width","0.5px").attr("stroke","#999").attr("name",e.name).attr("data-et","life-line").attr("data-id",e.name),e.actorCnt=ei);let x=t.append("g"),b=lg;i?b+=` ${_p}`:b+=` ${Ap}`,x.attr("class",b),x.attr("name",e.name);let T=ja();T.x=e.x,T.y=s,T.fill="#eaeaea",T.width=e.width,T.height=e.height,T.class="actor";let w=e.x+e.width/2,k=s+32,C=22;x.append("defs").append("marker").attr("id",n+"-filled-head-control").attr("refX",11).attr("refY",5.8).attr("markerWidth",20).attr("markerHeight",28).attr("orient","172.5").attr("stroke-width",1.2).append("path").attr("d","M 14.4 5.6 L 7.2 10.4 L 8.8 5.6 L 7.2 0.8 Z"),x.append("circle").attr("cx",w).attr("cy",k).attr("r",C).attr("filter",`${h==="neo"?"url(#drop-shadow)":""}`),x.append("line").attr("marker-end","url(#"+n+"-filled-head-control)").attr("transform",`translate(${w}, ${k-C})`);let E=a.get(e.name)??0;Cf.has(f)?(x.style("stroke",m[E%m.length]),x.style("fill",p[E%m.length])):(x.style("stroke",g),x.style("fill",y));let S=x.node().getBBox();return e.height=S.height+2*(r?.sequence?.labelBoxHeight??0),wf(r,sn(e.description))(e.description,x,T.x,T.y+C+(i?5:12),T.width,T.height,{class:`actor ${lg}`},r),i||(x.attr("data-et","participant"),x.attr("data-type","control"),x.attr("data-id",e.name)),e.height},"drawActorTypeControl"),$ht=o(function(t,e,r,i,n){let a=i?e.stopy:e.starty,s=e.x+e.width/2,l=a+75,{look:u,theme:h,themeVariables:f}=r,{bkgColorArray:d,borderColorArray:p}=f,m=t.append("g").lower(),g=t.append("g"),y="actor";i?y+=` ${_p}`:y+=` ${Ap}`,g.attr("class",y),g.attr("name",e.name);let v=ja();v.x=e.x,v.y=a,v.fill="#eaeaea",v.width=e.width,v.height=e.height,v.class="actor";let x=e.x+e.width/2,b=a+(i?10:25),T=22;g.append("circle").attr("cx",x).attr("cy",b).attr("r",T).attr("width",e.width).attr("height",e.height),g.append("line").attr("x1",x-T).attr("x2",x+T).attr("y1",b+T).attr("y2",b+T).attr("stroke-width",2),u==="neo"&&g.attr("filter","url(#drop-shadow)");let w=n.get(e.name)??0;Cf.has(h)&&(g.style("stroke",p[w%p.length]),g.style("fill",d[w%p.length]));let k=g.node().getBBox();return e.height=k.height+(r?.sequence?.labelBoxHeight??0),i||(ei++,m.append("line").attr("id","actor"+ei).attr("x1",s).attr("y1",l).attr("x2",s).attr("y2",2e3).attr("class","actor-line 200").attr("stroke-width","0.5px").attr("stroke","#999").attr("name",e.name).attr("data-et","life-line").attr("data-id",e.name),e.actorCnt=ei),wf(r,sn(e.description))(e.description,g,v.x,v.y+(i?15:30),v.width,v.height,{class:`actor ${lg}`},r),i?g.attr("transform",`translate(0, ${T})`):(g.attr("transform",`translate(0, ${T/2-5})`),g.attr("data-et","participant"),g.attr("data-type","entity"),g.attr("data-id",e.name)),e.height},"drawActorTypeEntity"),zht=o(function(t,e,r,i,n){let a=i?e.stopy:e.starty,s=e.x+e.width/2,l=a+e.height+2*r.boxTextMargin,{theme:u,themeVariables:h,look:f}=r,{bkgColorArray:d,borderColorArray:p,actorBorder:m}=h,g=t.append("g").lower(),y=g;i||(ei++,Object.keys(e.links||{}).length&&!r.forceMenus&&y.attr("onclick",C_(`actor${ei}_popup`)).attr("cursor","pointer"),y.append("line").attr("id","actor"+ei).attr("x1",s).attr("y1",l).attr("x2",s).attr("y2",2e3).attr("class","actor-line 200").attr("stroke-width","0.5px").attr("stroke","#999").attr("name",e.name).attr("data-et","life-line").attr("data-id",e.name),y=g.append("g"),e.actorCnt=ei,e.links!=null&&y.attr("id","root-"+ei),f==="neo"&&y.attr("data-look","neo"));let v=ja(),x="actor";e.properties?.class?x=e.properties.class:v.fill="#eaeaea",i?x+=` ${_p}`:x+=` ${Ap}`,v.x=e.x,v.y=a,v.width=e.width,v.height=e.height,v.class=x,v.name=e.name,v.x=e.x,v.y=a;let b=v.width/3,T=v.width/3,w=b/2,k=w/(2.5+b/50),C=y.append("g");C.attr("class",x);let E=` + M ${v.x},${v.y+k} + a ${w},${k} 0 0 0 ${b},0 + a ${w},${k} 0 0 0 -${b},0 + l 0,${T-2*k} + a ${w},${k} 0 0 0 ${b},0 + l 0,-${T-2*k} +`;C.append("path").attr("d",E),f==="neo"&&C.attr("filter","url(#drop-shadow)");let S=n.get(e.name)??0;Cf.has(u)?(C.style("stroke",p[S%p.length]),C.style("fill",d[S%p.length])):C.style("stroke",m),C.attr("transform",`translate(${b}, ${k})`),e.rectData=v,wf(r,sn(e.description))(e.description,y,v.x,v.y+35,v.width,v.height,{class:`actor ${k_}`},r);let L=C.select("path:last-child");if(L.node()){let M=L.node().getBBox();e.height=M.height+(r.sequence.labelBoxHeight??0)}return i||(y.attr("data-et","participant"),y.attr("data-type","database"),y.attr("data-id",e.name)),e.height},"drawActorTypeDatabase"),Ght=o(function(t,e,r,i,n){let a=i?e.stopy:e.starty,s=e.x+e.width/2,l=a+80,u=22,h=t.append("g").lower(),{look:f,theme:d,themeVariables:p}=r,{bkgColorArray:m,borderColorArray:g,actorBorder:y}=p;i||(ei++,h.append("line").attr("id","actor"+ei).attr("x1",s).attr("y1",l).attr("x2",s).attr("y2",2e3).attr("class","actor-line 200").attr("stroke-width","0.5px").attr("stroke","#999").attr("name",e.name).attr("data-et","life-line").attr("data-id",e.name),e.actorCnt=ei);let v=t.append("g"),x=lg;i?x+=` ${_p}`:x+=` ${Ap}`,v.attr("class",x),v.attr("name",e.name);let b=ja();b.x=e.x,b.y=a,b.fill="#eaeaea",b.width=e.width,b.height=e.height,b.class="actor",v.append("line").attr("id","actor-man-torso"+ei).attr("x1",e.x+e.width/2-u*2.5).attr("y1",a+12).attr("x2",e.x+e.width/2-15).attr("y2",a+12),v.append("line").attr("id","actor-man-arms"+ei).attr("x1",e.x+e.width/2-u*2.5).attr("y1",a+2).attr("x2",e.x+e.width/2-u*2.5).attr("y2",a+22),v.append("circle").attr("cx",e.x+e.width/2).attr("cy",a+12).attr("r",u),f==="neo"&&v.attr("filter","url(#drop-shadow)");let T=n.get(e.name)??0;Cf.has(d)?(v.style("stroke",g[T%g.length]),v.style("fill",m[T%g.length])):v.style("stroke",y);let w=v.node().getBBox();return e.height=w.height+(r.sequence.labelBoxHeight??0),wf(r,sn(e.description))(e.description,v,b.x,b.y+15,b.width,b.height,{class:`actor ${lg}`},r),v.attr("transform",`translate(0,${u/2+10})`),i||(v.attr("data-et","participant"),v.attr("data-type","boundary"),v.attr("data-id",e.name)),e.height},"drawActorTypeBoundary"),Vht=o(function(t,e,r,i,n){let a=i?e.stopy:e.starty,s=e.x+e.width/2,l=a+80,{look:u,theme:h,themeVariables:f}=r,{bkgColorArray:d,borderColorArray:p,actorBorder:m}=f,g=t.append("g").lower();i||(ei++,g.append("line").attr("id","actor"+ei).attr("x1",s).attr("y1",l).attr("x2",s).attr("y2",2e3).attr("class","actor-line 200").attr("stroke-width","0.5px").attr("stroke","#999").attr("name",e.name).attr("data-et","life-line").attr("data-id",e.name),e.actorCnt=ei);let y=t.append("g"),v=lg;i?v+=` ${_p}`:v+=` ${Ap}`,y.attr("class",v),y.attr("name",e.name),i||y.attr("data-et","participant").attr("data-type","actor").attr("data-id",e.name);let x=u==="neo"?.5:1,b=u==="neo"?a+(1-x)*30:a;y.append("line").attr("id","actor-man-torso"+ei).attr("x1",s).attr("y1",b+25*x).attr("x2",s).attr("y2",b+45*x),y.append("line").attr("id","actor-man-arms"+ei).attr("x1",s-Sp/2*x).attr("y1",b+33*x).attr("x2",s+Sp/2*x).attr("y2",b+33*x),y.append("line").attr("x1",s-Sp/2*x).attr("y1",b+60*x).attr("x2",s).attr("y2",b+45*x),y.append("line").attr("x1",s).attr("y1",b+45*x).attr("x2",s+(Sp/2-2)*x).attr("y2",b+60*x);let T=y.append("circle");T.attr("cx",e.x+e.width/2),T.attr("cy",b+10*x),T.attr("r",15*x),T.attr("width",e.width*x),T.attr("height",e.height*x);let w=y.node().getBBox();e.height=w.height;let k=ja();k.x=e.x,k.y=b,k.fill="#eaeaea",k.width=e.width,k.height=e.height/x,k.class="actor",k.rx=3,k.ry=3;let C=n.get(e.name)??0;return Cf.has(h)?(y.style("stroke",p[C%p.length]),y.style("fill",d[C%p.length])):y.style("stroke",m),wf(r,sn(e.description))(e.description,y,k.x,b+35*x-(u==="neo"?10:0),k.width,k.height,{class:`actor ${lg}`},r),e.height},"drawActorTypeActor"),qht=o(async function(t,e,r,i,n,a,s){let l=s??new Map([...a.db.getActors().values()].map((u,h)=>[u.name,h]));switch(e.type){case"actor":return await Vht(t,e,r,i,l);case"participant":return await Oht(t,e,r,i,l);case"boundary":return await Ght(t,e,r,i,l);case"control":return await Fht(t,e,r,i,n,l);case"entity":return await $ht(t,e,r,i,l);case"database":return await zht(t,e,r,i,l);case"collections":return await Pht(t,e,r,i,l);case"queue":return await Bht(t,e,r,i,l)}},"drawActor"),Wht=o(function(t,e,r){let n=t.append("g");S3e(n,e),e.name&&wf(r)(e.name,n,e.x,e.y+r.boxTextMargin+(e.textMaxHeight||0)/2,e.width,0,{class:"text"},r),n.lower()},"drawBox"),Uht=o(function(t){return t.append("g")},"anchorElement"),Hht=o(function(t,e,r,i,n,a,s){let{theme:l,themeVariables:u}=i,{bkgColorArray:h,borderColorArray:f,mainBkg:d}=u,p=ja(),m=e.anchored,g=e.actor;p.x=e.startx,p.y=e.starty,p.class="activation"+n%3,p.width=e.stopx-e.startx,p.height=r-e.starty;let y=IC(m,p),x=(s??new Map([...a.db.getActors().values()].map((b,T)=>[b.name,T]))).get(g)??0;Cf.has(l)&&(y.style("stroke",f[x%f.length]),y.style("fill",h[x%f.length]??d))},"drawActivation"),Yht=o(async function(t,e,r,i,n){let{boxMargin:a,boxTextMargin:s,labelBoxHeight:l,labelBoxWidth:u,messageFontFamily:h,messageFontSize:f,messageFontWeight:d}=i,p=t.append("g").attr("data-et","control-structure").attr("data-id","i"+n.id),m=o(function(v,x,b,T){return p.append("line").attr("x1",v).attr("y1",x).attr("x2",b).attr("y2",T).attr("class","loopLine")},"drawLoopLine");m(e.startx,e.starty,e.stopx,e.starty),m(e.stopx,e.starty,e.stopx,e.stopy),m(e.startx,e.stopy,e.stopx,e.stopy),m(e.startx,e.starty,e.startx,e.stopy),e.sections!==void 0&&e.sections.forEach(function(v){m(e.startx,v.y,e.stopx,v.y).style("stroke-dasharray","3, 3")});let g=J2();g.text=r,g.x=e.startx,g.y=e.starty,g.fontFamily=h,g.fontSize=f,g.fontWeight=d,g.anchor="middle",g.valign="middle",g.tspan=!1,g.width=Math.max(u??0,50),g.height=l+(i.look==="neo"?15:0)||20,g.textMargin=s,g.class="labelText",E3e(p,g),g=A3e(),g.text=e.title,g.x=e.startx+u/2+(e.stopx-e.startx)/2,g.y=e.starty+a+s,g.anchor="middle",g.valign="middle",g.textMargin=s,g.class="loopText",g.fontFamily=h,g.fontSize=f,g.fontWeight=d,g.wrap=!0;let y=sn(g.text)?await MC(p,g,e):cg(p,g);if(e.sectionTitles!==void 0){for(let[v,x]of Object.entries(e.sectionTitles))if(x.message){g.text=x.message,g.x=e.startx+(e.stopx-e.startx)/2,g.y=e.sections[v].y+a+s,g.class="loopText",g.anchor="middle",g.valign="middle",g.tspan=!1,g.fontFamily=h,g.fontSize=f,g.fontWeight=d,g.wrap=e.wrap,sn(g.text)?(e.starty=e.sections[v].y,await MC(p,g,e)):cg(p,g);let b=Math.round(y.map(T=>(T._groups||T)[0][0].getBBox().height).reduce((T,w)=>T+w));e.sections[v].height+=b-(a+s)}}return e.height=Math.round(e.stopy-e.starty),p},"drawLoop"),S3e=o(function(t,e){k3(t,e)},"drawBackgroundRect"),jht=o(function(t,e){t.append("defs").append("symbol").attr("id",e+"-database").attr("fill-rule","evenodd").attr("clip-rule","evenodd").append("path").attr("transform","scale(.5)").attr("d","M12.258.001l.256.004.255.005.253.008.251.01.249.012.247.015.246.016.242.019.241.02.239.023.236.024.233.027.231.028.229.031.225.032.223.034.22.036.217.038.214.04.211.041.208.043.205.045.201.046.198.048.194.05.191.051.187.053.183.054.18.056.175.057.172.059.168.06.163.061.16.063.155.064.15.066.074.033.073.033.071.034.07.034.069.035.068.035.067.035.066.035.064.036.064.036.062.036.06.036.06.037.058.037.058.037.055.038.055.038.053.038.052.038.051.039.05.039.048.039.047.039.045.04.044.04.043.04.041.04.04.041.039.041.037.041.036.041.034.041.033.042.032.042.03.042.029.042.027.042.026.043.024.043.023.043.021.043.02.043.018.044.017.043.015.044.013.044.012.044.011.045.009.044.007.045.006.045.004.045.002.045.001.045v17l-.001.045-.002.045-.004.045-.006.045-.007.045-.009.044-.011.045-.012.044-.013.044-.015.044-.017.043-.018.044-.02.043-.021.043-.023.043-.024.043-.026.043-.027.042-.029.042-.03.042-.032.042-.033.042-.034.041-.036.041-.037.041-.039.041-.04.041-.041.04-.043.04-.044.04-.045.04-.047.039-.048.039-.05.039-.051.039-.052.038-.053.038-.055.038-.055.038-.058.037-.058.037-.06.037-.06.036-.062.036-.064.036-.064.036-.066.035-.067.035-.068.035-.069.035-.07.034-.071.034-.073.033-.074.033-.15.066-.155.064-.16.063-.163.061-.168.06-.172.059-.175.057-.18.056-.183.054-.187.053-.191.051-.194.05-.198.048-.201.046-.205.045-.208.043-.211.041-.214.04-.217.038-.22.036-.223.034-.225.032-.229.031-.231.028-.233.027-.236.024-.239.023-.241.02-.242.019-.246.016-.247.015-.249.012-.251.01-.253.008-.255.005-.256.004-.258.001-.258-.001-.256-.004-.255-.005-.253-.008-.251-.01-.249-.012-.247-.015-.245-.016-.243-.019-.241-.02-.238-.023-.236-.024-.234-.027-.231-.028-.228-.031-.226-.032-.223-.034-.22-.036-.217-.038-.214-.04-.211-.041-.208-.043-.204-.045-.201-.046-.198-.048-.195-.05-.19-.051-.187-.053-.184-.054-.179-.056-.176-.057-.172-.059-.167-.06-.164-.061-.159-.063-.155-.064-.151-.066-.074-.033-.072-.033-.072-.034-.07-.034-.069-.035-.068-.035-.067-.035-.066-.035-.064-.036-.063-.036-.062-.036-.061-.036-.06-.037-.058-.037-.057-.037-.056-.038-.055-.038-.053-.038-.052-.038-.051-.039-.049-.039-.049-.039-.046-.039-.046-.04-.044-.04-.043-.04-.041-.04-.04-.041-.039-.041-.037-.041-.036-.041-.034-.041-.033-.042-.032-.042-.03-.042-.029-.042-.027-.042-.026-.043-.024-.043-.023-.043-.021-.043-.02-.043-.018-.044-.017-.043-.015-.044-.013-.044-.012-.044-.011-.045-.009-.044-.007-.045-.006-.045-.004-.045-.002-.045-.001-.045v-17l.001-.045.002-.045.004-.045.006-.045.007-.045.009-.044.011-.045.012-.044.013-.044.015-.044.017-.043.018-.044.02-.043.021-.043.023-.043.024-.043.026-.043.027-.042.029-.042.03-.042.032-.042.033-.042.034-.041.036-.041.037-.041.039-.041.04-.041.041-.04.043-.04.044-.04.046-.04.046-.039.049-.039.049-.039.051-.039.052-.038.053-.038.055-.038.056-.038.057-.037.058-.037.06-.037.061-.036.062-.036.063-.036.064-.036.066-.035.067-.035.068-.035.069-.035.07-.034.072-.034.072-.033.074-.033.151-.066.155-.064.159-.063.164-.061.167-.06.172-.059.176-.057.179-.056.184-.054.187-.053.19-.051.195-.05.198-.048.201-.046.204-.045.208-.043.211-.041.214-.04.217-.038.22-.036.223-.034.226-.032.228-.031.231-.028.234-.027.236-.024.238-.023.241-.02.243-.019.245-.016.247-.015.249-.012.251-.01.253-.008.255-.005.256-.004.258-.001.258.001zm-9.258 20.499v.01l.001.021.003.021.004.022.005.021.006.022.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.023.018.024.019.024.021.024.022.025.023.024.024.025.052.049.056.05.061.051.066.051.07.051.075.051.079.052.084.052.088.052.092.052.097.052.102.051.105.052.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.048.144.049.147.047.152.047.155.047.16.045.163.045.167.043.171.043.176.041.178.041.183.039.187.039.19.037.194.035.197.035.202.033.204.031.209.03.212.029.216.027.219.025.222.024.226.021.23.02.233.018.236.016.24.015.243.012.246.01.249.008.253.005.256.004.259.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.021.224-.024.22-.026.216-.027.212-.028.21-.031.205-.031.202-.034.198-.034.194-.036.191-.037.187-.039.183-.04.179-.04.175-.042.172-.043.168-.044.163-.045.16-.046.155-.046.152-.047.148-.048.143-.049.139-.049.136-.05.131-.05.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.053.083-.051.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.05.023-.024.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.023.01-.022.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.127l-.077.055-.08.053-.083.054-.085.053-.087.052-.09.052-.093.051-.095.05-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.045-.118.044-.12.043-.122.042-.124.042-.126.041-.128.04-.13.04-.132.038-.134.038-.135.037-.138.037-.139.035-.142.035-.143.034-.144.033-.147.032-.148.031-.15.03-.151.03-.153.029-.154.027-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.01-.179.008-.179.008-.181.006-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.006-.179-.008-.179-.008-.178-.01-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.027-.153-.029-.151-.03-.15-.03-.148-.031-.146-.032-.145-.033-.143-.034-.141-.035-.14-.035-.137-.037-.136-.037-.134-.038-.132-.038-.13-.04-.128-.04-.126-.041-.124-.042-.122-.042-.12-.044-.117-.043-.116-.045-.113-.045-.112-.046-.109-.047-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.05-.093-.052-.09-.051-.087-.052-.085-.053-.083-.054-.08-.054-.077-.054v4.127zm0-5.654v.011l.001.021.003.021.004.021.005.022.006.022.007.022.009.022.01.022.011.023.012.023.013.023.015.024.016.023.017.024.018.024.019.024.021.024.022.024.023.025.024.024.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.052.11.051.114.051.119.052.123.05.127.051.131.05.135.049.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.044.171.042.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.022.23.02.233.018.236.016.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.012.241-.015.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.048.139-.05.136-.049.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.051.051-.049.023-.025.023-.024.021-.025.02-.024.019-.024.018-.024.017-.024.015-.023.014-.023.013-.024.012-.022.01-.023.01-.023.008-.022.006-.022.006-.022.004-.021.004-.022.001-.021.001-.021v-4.139l-.077.054-.08.054-.083.054-.085.052-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.044-.118.044-.12.044-.122.042-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.035-.143.033-.144.033-.147.033-.148.031-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.009-.179.009-.179.007-.181.007-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.007-.179-.007-.179-.009-.178-.009-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.031-.146-.033-.145-.033-.143-.033-.141-.035-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.04-.126-.041-.124-.042-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.051-.093-.051-.09-.051-.087-.053-.085-.052-.083-.054-.08-.054-.077-.054v4.139zm0-5.666v.011l.001.02.003.022.004.021.005.022.006.021.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.024.018.023.019.024.021.025.022.024.023.024.024.025.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.051.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.043.171.043.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.021.23.02.233.018.236.017.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.013.241-.014.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.049.139-.049.136-.049.131-.051.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.049.023-.025.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.022.01-.023.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.153l-.077.054-.08.054-.083.053-.085.053-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.048-.105.048-.106.048-.109.046-.111.046-.114.046-.115.044-.118.044-.12.043-.122.043-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.034-.143.034-.144.033-.147.032-.148.032-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.024-.161.024-.162.023-.163.023-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.01-.178.01-.179.009-.179.007-.181.006-.182.006-.182.004-.184.003-.184.001-.185.001-.185-.001-.184-.001-.184-.003-.182-.004-.182-.006-.181-.006-.179-.007-.179-.009-.178-.01-.176-.01-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.023-.162-.023-.161-.024-.159-.024-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.032-.146-.032-.145-.033-.143-.034-.141-.034-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.041-.126-.041-.124-.041-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.048-.105-.048-.102-.048-.1-.05-.097-.049-.095-.051-.093-.051-.09-.052-.087-.052-.085-.053-.083-.053-.08-.054-.077-.054v4.153zm8.74-8.179l-.257.004-.254.005-.25.008-.247.011-.244.012-.241.014-.237.016-.233.018-.231.021-.226.022-.224.023-.22.026-.216.027-.212.028-.21.031-.205.032-.202.033-.198.034-.194.036-.191.038-.187.038-.183.04-.179.041-.175.042-.172.043-.168.043-.163.045-.16.046-.155.046-.152.048-.148.048-.143.048-.139.049-.136.05-.131.05-.126.051-.123.051-.118.051-.114.052-.11.052-.106.052-.101.052-.096.052-.092.052-.088.052-.083.052-.079.052-.074.051-.07.052-.065.051-.06.05-.056.05-.051.05-.023.025-.023.024-.021.024-.02.025-.019.024-.018.024-.017.023-.015.024-.014.023-.013.023-.012.023-.01.023-.01.022-.008.022-.006.023-.006.021-.004.022-.004.021-.001.021-.001.021.001.021.001.021.004.021.004.022.006.021.006.023.008.022.01.022.01.023.012.023.013.023.014.023.015.024.017.023.018.024.019.024.02.025.021.024.023.024.023.025.051.05.056.05.06.05.065.051.07.052.074.051.079.052.083.052.088.052.092.052.096.052.101.052.106.052.11.052.114.052.118.051.123.051.126.051.131.05.136.05.139.049.143.048.148.048.152.048.155.046.16.046.163.045.168.043.172.043.175.042.179.041.183.04.187.038.191.038.194.036.198.034.202.033.205.032.21.031.212.028.216.027.22.026.224.023.226.022.231.021.233.018.237.016.241.014.244.012.247.011.25.008.254.005.257.004.26.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.022.224-.023.22-.026.216-.027.212-.028.21-.031.205-.032.202-.033.198-.034.194-.036.191-.038.187-.038.183-.04.179-.041.175-.042.172-.043.168-.043.163-.045.16-.046.155-.046.152-.048.148-.048.143-.048.139-.049.136-.05.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.05.051-.05.023-.025.023-.024.021-.024.02-.025.019-.024.018-.024.017-.023.015-.024.014-.023.013-.023.012-.023.01-.023.01-.022.008-.022.006-.023.006-.021.004-.022.004-.021.001-.021.001-.021-.001-.021-.001-.021-.004-.021-.004-.022-.006-.021-.006-.023-.008-.022-.01-.022-.01-.023-.012-.023-.013-.023-.014-.023-.015-.024-.017-.023-.018-.024-.019-.024-.02-.025-.021-.024-.023-.024-.023-.025-.051-.05-.056-.05-.06-.05-.065-.051-.07-.052-.074-.051-.079-.052-.083-.052-.088-.052-.092-.052-.096-.052-.101-.052-.106-.052-.11-.052-.114-.052-.118-.051-.123-.051-.126-.051-.131-.05-.136-.05-.139-.049-.143-.048-.148-.048-.152-.048-.155-.046-.16-.046-.163-.045-.168-.043-.172-.043-.175-.042-.179-.041-.183-.04-.187-.038-.191-.038-.194-.036-.198-.034-.202-.033-.205-.032-.21-.031-.212-.028-.216-.027-.22-.026-.224-.023-.226-.022-.231-.021-.233-.018-.237-.016-.241-.014-.244-.012-.247-.011-.25-.008-.254-.005-.257-.004-.26-.001-.26.001z")},"insertDatabaseIcon"),Xht=o(function(t,e){t.append("defs").append("symbol").attr("id",e+"-computer").attr("width","24").attr("height","24").append("path").attr("transform","scale(.5)").attr("d","M2 2v13h20v-13h-20zm18 11h-16v-9h16v9zm-10.228 6l.466-1h3.524l.467 1h-4.457zm14.228 3h-24l2-6h2.104l-1.33 4h18.45l-1.297-4h2.073l2 6zm-5-10h-14v-7h14v7z")},"insertComputerIcon"),Kht=o(function(t,e){t.append("defs").append("symbol").attr("id",e+"-clock").attr("width","24").attr("height","24").append("path").attr("transform","scale(.5)").attr("d","M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm5.848 12.459c.202.038.202.333.001.372-1.907.361-6.045 1.111-6.547 1.111-.719 0-1.301-.582-1.301-1.301 0-.512.77-5.447 1.125-7.445.034-.192.312-.181.343.014l.985 6.238 5.394 1.011z")},"insertClockIcon"),Qht=o(function(t,e){t.append("defs").append("marker").attr("id",e+"-arrowhead").attr("refX",7.9).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto-start-reverse").append("path").attr("d","M -1 0 L 10 5 L 0 10 z")},"insertArrowHead"),Zht=o(function(t,e){t.append("defs").append("marker").attr("id",e+"-filled-head").attr("refX",15.5).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L14,7 L9,1 Z")},"insertArrowFilledHead"),Jht=o(function(t,e){t.append("defs").append("marker").attr("id",e+"-sequencenumber").attr("refX",15).attr("refY",15).attr("markerWidth",60).attr("markerHeight",40).attr("orient","auto").append("circle").attr("cx",15).attr("cy",15).attr("r",6)},"insertSequenceNumber"),eft=o(function(t,e){t.append("defs").append("marker").attr("id",e+"-crosshead").attr("markerWidth",15).attr("markerHeight",8).attr("orient","auto").attr("refX",4).attr("refY",4.5).append("path").attr("fill","none").attr("stroke","#000000").style("stroke-dasharray","0, 0").attr("stroke-width","1pt").attr("d","M 1,2 L 6,7 M 6,2 L 1,7")},"insertArrowCrossHead"),tft=o(function(t,e){let{theme:r}=e;t.append("defs").append("filter").attr("id","drop-shadow").attr("height","130%").attr("width","130%").append("feDropShadow").attr("dx","4").attr("dy","4").attr("stdDeviation",0).attr("flood-opacity","0.06").attr("flood-color",`${r==="redux"||r==="redux-color"?"#000000":"#FFFFFF"}`)},"insertDropShadow"),A3e=o(function(){return{x:0,y:0,fill:void 0,anchor:void 0,style:"#666",width:void 0,height:void 0,textMargin:0,rx:0,ry:0,tspan:!0,valign:void 0}},"getTextObj"),rft=o(function(){return{x:0,y:0,fill:"#EDF2AE",stroke:"#666",width:100,anchor:"start",height:100,rx:0,ry:0}},"getNoteRect"),wf=(function(){function t(a,s,l,u,h,f,d){let p=s.append("text").attr("x",l+h/2).attr("y",u+f/2+5).style("text-anchor","middle").text(a);n(p,d)}o(t,"byText");function e(a,s,l,u,h,f,d,p){let{actorFontSize:m,actorFontFamily:g,actorFontWeight:y}=p,[v,x]=$s(m),b=a.split(lt.lineBreakRegex);for(let T=0;T{let s=ug(Ve),l=a.actorKeys.reduce((d,p)=>d+=t.get(p).width+(t.get(p).margin||0),0),u=Ve.boxMargin*8;l+=u,l-=2*Ve.boxTextMargin,a.wrap&&(a.name=Kt.wrapLabel(a.name,l-2*Ve.wrapPadding,s));let h=Kt.calculateTextDimensions(a.name,s);n=lt.getMax(h.height,n);let f=lt.getMax(l,h.width+2*Ve.wrapPadding);if(a.margin=Ve.boxTextMargin,la.textMaxHeight=n),lt.getMax(i,Ve.height)}var Ve,pt,lft,D3e,ug,ex,lU,uft,hft,cU,R3e,N3e,w_,L3e,dft,mft,yft,vft,xft,oU,bft,I3e,Tft,kft,Cft,M3e,O3e=P(()=>{"use strict";Pr();_3e();bt();Vr();Vr();y0();Ut();kg();er();Xi();nU();Ve={},pt={data:{startx:void 0,stopx:void 0,starty:void 0,stopy:void 0},verticalPos:0,sequenceItems:[],activations:[],models:{getHeight:o(function(){return Math.max.apply(null,this.actors.length===0?[0]:this.actors.map(t=>t.height||0))+(this.loops.length===0?0:this.loops.map(t=>t.height||0).reduce((t,e)=>t+e))+(this.messages.length===0?0:this.messages.map(t=>t.height||0).reduce((t,e)=>t+e))+(this.notes.length===0?0:this.notes.map(t=>t.height||0).reduce((t,e)=>t+e))},"getHeight"),clear:o(function(){this.actors=[],this.boxes=[],this.loops=[],this.messages=[],this.notes=[]},"clear"),addBox:o(function(t){this.boxes.push(t)},"addBox"),addActor:o(function(t){this.actors.push(t)},"addActor"),addLoop:o(function(t){this.loops.push(t)},"addLoop"),addMessage:o(function(t){this.messages.push(t)},"addMessage"),addNote:o(function(t){this.notes.push(t)},"addNote"),lastActor:o(function(){return this.actors[this.actors.length-1]},"lastActor"),lastLoop:o(function(){return this.loops[this.loops.length-1]},"lastLoop"),lastMessage:o(function(){return this.messages[this.messages.length-1]},"lastMessage"),lastNote:o(function(){return this.notes[this.notes.length-1]},"lastNote"),actors:[],boxes:[],loops:[],messages:[],notes:[]},init:o(function(){this.sequenceItems=[],this.activations=[],this.models.clear(),this.data={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0},this.verticalPos=0,N3e(ge())},"init"),updateVal:o(function(t,e,r,i){t[e]===void 0?t[e]=r:t[e]=i(r,t[e])},"updateVal"),updateBounds:o(function(t,e,r,i){let n=this,a=0;function s(l){return o(function(h){a++;let f=n.sequenceItems.length-a+1;n.updateVal(h,"starty",e-f*Ve.boxMargin,Math.min),n.updateVal(h,"stopy",i+f*Ve.boxMargin,Math.max),n.updateVal(pt.data,"startx",t-f*Ve.boxMargin,Math.min),n.updateVal(pt.data,"stopx",r+f*Ve.boxMargin,Math.max),l!=="activation"&&(n.updateVal(h,"startx",t-f*Ve.boxMargin,Math.min),n.updateVal(h,"stopx",r+f*Ve.boxMargin,Math.max),n.updateVal(pt.data,"starty",e-f*Ve.boxMargin,Math.min),n.updateVal(pt.data,"stopy",i+f*Ve.boxMargin,Math.max))},"updateItemBounds")}o(s,"updateFn"),this.sequenceItems.forEach(s()),this.activations.forEach(s("activation"))},"updateBounds"),insert:o(function(t,e,r,i){let n=lt.getMin(t,r),a=lt.getMax(t,r),s=lt.getMin(e,i),l=lt.getMax(e,i);this.updateVal(pt.data,"startx",n,Math.min),this.updateVal(pt.data,"starty",s,Math.min),this.updateVal(pt.data,"stopx",a,Math.max),this.updateVal(pt.data,"stopy",l,Math.max),this.updateBounds(n,s,a,l)},"insert"),newActivation:o(function(t,e,r){let i=r.get(t.from),n=w_(t.from).length||0,a=i.x+i.width/2+(n-1)*Ve.activationWidth/2;this.activations.push({startx:a,starty:this.verticalPos+2,stopx:a+Ve.activationWidth,stopy:void 0,actor:t.from,anchored:Hi.anchorElement(e)})},"newActivation"),endActivation:o(function(t){let e=this.activations.map(function(r){return r.actor}).lastIndexOf(t.from);return this.activations.splice(e,1)[0]},"endActivation"),createLoop:o(function(t={message:void 0,wrap:!1,width:void 0},e){return{startx:void 0,starty:this.verticalPos,stopx:void 0,stopy:void 0,title:t.message,wrap:t.wrap,width:t.width,height:0,fill:e}},"createLoop"),newLoop:o(function(t={message:void 0,wrap:!1,width:void 0},e){this.sequenceItems.push(this.createLoop(t,e))},"newLoop"),endLoop:o(function(){return this.sequenceItems.pop()},"endLoop"),isLoopOverlap:o(function(){return this.sequenceItems.length?this.sequenceItems[this.sequenceItems.length-1].overlap:!1},"isLoopOverlap"),addSectionToLoop:o(function(t){let e=this.sequenceItems.pop();e.sections=e.sections||[],e.sectionTitles=e.sectionTitles||[],e.sections.push({y:pt.getVerticalPos(),height:0}),e.sectionTitles.push(t),this.sequenceItems.push(e)},"addSectionToLoop"),saveVerticalPos:o(function(){this.isLoopOverlap()&&(this.savedVerticalPos=this.verticalPos)},"saveVerticalPos"),resetVerticalPos:o(function(){this.isLoopOverlap()&&(this.verticalPos=this.savedVerticalPos)},"resetVerticalPos"),bumpVerticalPos:o(function(t){this.verticalPos=this.verticalPos+t,this.data.stopy=lt.getMax(this.data.stopy,this.verticalPos)},"bumpVerticalPos"),getVerticalPos:o(function(){return this.verticalPos},"getVerticalPos"),getBounds:o(function(){return{bounds:this.data,models:this.models}},"getBounds")},lft=o(async function(t,e,r){pt.bumpVerticalPos(Ve.boxMargin),e.height=Ve.boxMargin,e.starty=pt.getVerticalPos();let i=ja();i.x=e.startx,i.y=e.starty,i.width=e.width||Ve.width,i.class="note";let n=t.append("g");n.attr("data-et","note"),n.attr("data-id","i"+r);let a=Hi.drawRect(n,i),s=J2();s.x=e.startx,s.y=e.starty,s.width=i.width,s.dy="1em",s.text=e.message,s.class="noteText",s.fontFamily=Ve.noteFontFamily,s.fontSize=Ve.noteFontSize,s.fontWeight=Ve.noteFontWeight,s.anchor=Ve.noteAlign,s.textMargin=Ve.noteMargin,s.valign="center";let l=sn(s.text)?await MC(n,s):cg(n,s),u=Math.round(l.map(h=>(h._groups||h)[0][0].getBBox().height).reduce((h,f)=>h+f));a.attr("height",u+2*Ve.noteMargin),e.height+=u+2*Ve.noteMargin,pt.bumpVerticalPos(u+2*Ve.noteMargin),e.stopy=e.starty+u+2*Ve.noteMargin,e.stopx=e.startx+i.width,pt.insert(e.startx,e.starty,e.stopx,e.stopy),pt.models.addNote(e)},"drawNote"),D3e=o(function(t,e,r,i,n,a,s){let l=i.db.getActors(),u=l.get(e.from),h=l.get(e.to),f=r.sequenceVisible,d=u.x+u.width/2,p=h.x+h.width/2,m=d<=p,g=I3e(e,i),y=t.append("g"),v=16.5,x=o((C,E)=>{let S=C?v:-v;return E?-S:S},"getCircleOffset"),b=o(C=>{y.append("circle").attr("cx",C).attr("cy",s).attr("r",5).attr("width",10).attr("height",10)},"drawCircle"),{CENTRAL_CONNECTION:T,CENTRAL_CONNECTION_REVERSE:w,CENTRAL_CONNECTION_DUAL:k}=i.db.LINETYPE;if(f)switch(e.centralConnection){case T:g&&(p+=x(m,!0));break;case w:g||(d+=x(m,!1));break;case k:g?p+=x(m,!0):d+=x(m,!1);break}switch(e.centralConnection){case T:b(p);break;case w:b(d);break;case k:b(d),b(p);break}},"drawCentralConnection"),ug=o(t=>({fontFamily:t.messageFontFamily,fontSize:t.messageFontSize,fontWeight:t.messageFontWeight}),"messageFont"),ex=o(t=>({fontFamily:t.noteFontFamily,fontSize:t.noteFontSize,fontWeight:t.noteFontWeight}),"noteFont"),lU=o(t=>({fontFamily:t.actorFontFamily,fontSize:t.actorFontSize,fontWeight:t.actorFontWeight}),"actorFont");o(cft,"boundMessage");uft=o(async function(t,e,r,i,n,a){let{startx:s,stopx:l,starty:u,message:h,type:f,sequenceIndex:d,sequenceVisible:p}=e,m=Kt.calculateTextDimensions(h,ug(Ve)),g=J2();g.x=s,g.y=u+10,g.width=l-s,g.class="messageText",g.dy="1em",g.text=h,g.fontFamily=Ve.messageFontFamily,g.fontSize=Ve.messageFontSize,g.fontWeight=Ve.messageFontWeight,g.anchor=Ve.messageAlign,g.valign="center",g.textMargin=Ve.wrapPadding,g.tspan=!1,sn(g.text)?await MC(t,g,{startx:s,stopx:l,starty:r}):cg(t,g);let y=m.width,v;if(s===l){let b=p||Ve.showSequenceNumbers,T=I3e(n,i),w=Tft(n,i),k=s+(b&&(T||w)?10:0);Ve.rightAngles?v=t.append("path").attr("d",`M ${k},${r} H ${s+lt.getMax(Ve.width/2,y/2)} V ${r+25} H ${s}`):v=t.append("path").attr("d","M "+k+","+r+" C "+(k+60)+","+(r-10)+" "+(s+60)+","+(r+30)+" "+s+","+(r+20)),oU(n,i)&&D3e(t,n,e,i,s,l,r)}else v=t.append("line"),v.attr("x1",s),v.attr("y1",r),v.attr("x2",l),v.attr("y2",r),oU(n,i)&&D3e(t,n,e,i,s,l,r);f===i.db.LINETYPE.DOTTED||f===i.db.LINETYPE.DOTTED_CROSS||f===i.db.LINETYPE.DOTTED_POINT||f===i.db.LINETYPE.DOTTED_OPEN||f===i.db.LINETYPE.BIDIRECTIONAL_DOTTED||f===i.db.LINETYPE.SOLID_TOP_DOTTED||f===i.db.LINETYPE.SOLID_BOTTOM_DOTTED||f===i.db.LINETYPE.STICK_TOP_DOTTED||f===i.db.LINETYPE.STICK_BOTTOM_DOTTED||f===i.db.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED||f===i.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED||f===i.db.LINETYPE.STICK_ARROW_TOP_REVERSE_DOTTED||f===i.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE_DOTTED?(v.style("stroke-dasharray","3, 3"),v.attr("class","messageLine1")):v.attr("class","messageLine0"),v.attr("data-et","message"),v.attr("data-id","i"+e.id),v.attr("data-from",e.from),v.attr("data-to",e.to);let x="";if(Ve.arrowMarkerAbsolute&&(x=Yp(!0)),v.attr("stroke-width",2),v.attr("stroke","none"),v.style("fill","none"),(f===i.db.LINETYPE.SOLID_TOP||f===i.db.LINETYPE.SOLID_TOP_DOTTED)&&v.attr("marker-end","url("+x+"#"+a+"-solidTopArrowHead)"),(f===i.db.LINETYPE.SOLID_BOTTOM||f===i.db.LINETYPE.SOLID_BOTTOM_DOTTED)&&v.attr("marker-end","url("+x+"#"+a+"-solidBottomArrowHead)"),(f===i.db.LINETYPE.STICK_TOP||f===i.db.LINETYPE.STICK_TOP_DOTTED)&&v.attr("marker-end","url("+x+"#"+a+"-stickTopArrowHead)"),(f===i.db.LINETYPE.STICK_BOTTOM||f===i.db.LINETYPE.STICK_BOTTOM_DOTTED)&&v.attr("marker-end","url("+x+"#"+a+"-stickBottomArrowHead)"),(f===i.db.LINETYPE.SOLID_ARROW_TOP_REVERSE||f===i.db.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED)&&v.attr("marker-start","url("+x+"#"+a+"-solidBottomArrowHead)"),(f===i.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE||f===i.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED)&&v.attr("marker-start","url("+x+"#"+a+"-solidTopArrowHead)"),(f===i.db.LINETYPE.STICK_ARROW_TOP_REVERSE||f===i.db.LINETYPE.STICK_ARROW_TOP_REVERSE_DOTTED)&&v.attr("marker-start","url("+x+"#"+a+"-stickBottomArrowHead)"),(f===i.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE||f===i.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE_DOTTED)&&v.attr("marker-start","url("+x+"#"+a+"-stickTopArrowHead)"),(f===i.db.LINETYPE.SOLID||f===i.db.LINETYPE.DOTTED)&&v.attr("marker-end","url("+x+"#"+a+"-arrowhead)"),(f===i.db.LINETYPE.BIDIRECTIONAL_SOLID||f===i.db.LINETYPE.BIDIRECTIONAL_DOTTED)&&(v.attr("marker-start","url("+x+"#"+a+"-arrowhead)"),v.attr("marker-end","url("+x+"#"+a+"-arrowhead)")),(f===i.db.LINETYPE.SOLID_POINT||f===i.db.LINETYPE.DOTTED_POINT)&&v.attr("marker-end","url("+x+"#"+a+"-filled-head)"),(f===i.db.LINETYPE.SOLID_CROSS||f===i.db.LINETYPE.DOTTED_CROSS)&&v.attr("marker-end","url("+x+"#"+a+"-crosshead)"),p||Ve.showSequenceNumbers){let b=f===i.db.LINETYPE.BIDIRECTIONAL_SOLID||f===i.db.LINETYPE.BIDIRECTIONAL_DOTTED,T=f===i.db.LINETYPE.SOLID_ARROW_TOP_REVERSE||f===i.db.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED||f===i.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE||f===i.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED||f===i.db.LINETYPE.STICK_ARROW_TOP_REVERSE||f===i.db.LINETYPE.STICK_ARROW_TOP_REVERSE_DOTTED||f===i.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE||f===i.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE_DOTTED,w=6,k=oU(n,i),C=s,E=l;b?(ss?E=l-2*w:(E=l-w,C+=n?.centralConnection===i.db.LINETYPE.CENTRAL_CONNECTION_DUAL||n?.centralConnection===i.db.LINETYPE.CENTRAL_CONNECTION_REVERSE?-7.5:0),E+=k?15:0,v.attr("x2",E),v.attr("x1",C)):v.attr("x1",s+w);let S=0,L=s===l,M=s<=l;L?S=e.fromBounds+1:T?S=M?e.toBounds-1:e.fromBounds+1:S=M?e.fromBounds+1:e.toBounds-1,t.append("line").attr("x1",S).attr("y1",r).attr("x2",S).attr("y2",r).attr("stroke-width",0).attr("marker-start","url("+x+"#"+a+"-sequencenumber)"),t.append("text").attr("x",S).attr("y",r+4).attr("font-family","sans-serif").attr("font-size","12px").attr("text-anchor","middle").attr("class","sequenceNumber").text(d)}},"drawMessage"),hft=o(function(t,e,r,i,n,a,s){let l=0,u=0,h,f=0;for(let d of i){let p=e.get(d),m=p.box;h&&h!=m&&(s||pt.models.addBox(h),u+=Ve.boxMargin+h.margin),m&&m!=h&&(s||(m.x=l+u,m.y=n),u+=m.margin),p.width=lt.getMax(p.width||Ve.width,Ve.width),p.height=lt.getMax(p.height||Ve.height,Ve.height),p.margin=p.margin||Ve.actorMargin,f=lt.getMax(f,p.height),r.get(p.name)&&(u+=p.width/2),p.x=l+u,p.starty=pt.getVerticalPos(),pt.insert(p.x,n,p.x+p.width,p.height),l+=p.width+u,p.box&&(p.box.width=l+m.margin-p.box.x),u=p.margin,h=p.box,pt.models.addActor(p)}h&&!s&&pt.models.addBox(h),pt.bumpVerticalPos(f)},"addActorRenderingData"),cU=o(async function(t,e,r,i,n,a,s){if(i){let l=0;pt.bumpVerticalPos(Ve.boxMargin*2);for(let u of r){let h=e.get(u);h.stopy||(h.stopy=pt.getVerticalPos());let f=await Hi.drawActor(t,h,Ve,!0,n,a,s);l=lt.getMax(l,f)}pt.bumpVerticalPos(l+Ve.boxMargin)}else for(let l of r){let u=e.get(l);await Hi.drawActor(t,u,Ve,!1,n,a,s)}},"drawActors"),R3e=o(function(t,e,r,i){let n=0,a=0;for(let s of r){let l=e.get(s),u=mft(l),h=Hi.drawPopup(t,l,u,Ve,Ve.forceMenus,i);h.height>n&&(n=h.height),h.width+l.x>a&&(a=h.width+l.x)}return{maxHeight:n,maxWidth:a}},"drawActorsPopup"),N3e=o(function(t){Yi(Ve,t),t.fontFamily&&(Ve.actorFontFamily=Ve.noteFontFamily=Ve.messageFontFamily=t.fontFamily),t.fontSize&&(Ve.actorFontSize=Ve.noteFontSize=Ve.messageFontSize=t.fontSize),t.fontWeight&&(Ve.actorFontWeight=Ve.noteFontWeight=Ve.messageFontWeight=t.fontWeight)},"setConf"),w_=o(function(t){return pt.activations.filter(function(e){return e.actor===t})},"actorActivations"),L3e=o(function(t,e){let r=e.get(t),i=w_(t),n=i.reduce(function(s,l){return lt.getMin(s,l.startx)},r.x+r.width/2-1),a=i.reduce(function(s,l){return lt.getMax(s,l.stopx)},r.x+r.width/2+1);return[n,a]},"activationBounds");o(ch,"adjustLoopHeightForWrap");o(fft,"adjustCreatedDestroyedData");dft=o(async function(t,e,r,i){let{securityLevel:n,sequence:a,look:s}=ge();Ve=a;let l;n==="sandbox"&&(l=Ze("#i"+e));let u=n==="sandbox"?Ze(l.nodes()[0].contentDocument.body):Ze("body"),h=n==="sandbox"?l.nodes()[0].contentDocument:document;pt.init(),Q.debug(i.db);let f=n==="sandbox"?u.select(`[id="${e}"]`):Ze(`[id="${e}"]`),d=i.db.getActors(),p=i.db.getCreatedActors(),m=i.db.getDestroyedActors(),g=i.db.getBoxes(),y=i.db.getActorKeys(),v=i.db.getMessages(),x=i.db.getDiagramTitle(),b=i.db.hasAtLeastOneBox(),T=i.db.hasAtLeastOneBoxWithTitle(),w=await pft(d,v,i);if(Ve.height=await gft(d,w,g),Hi.insertComputerIcon(f,e),Hi.insertDatabaseIcon(f,e),Hi.insertClockIcon(f,e),b&&(pt.bumpVerticalPos(Ve.boxMargin),T&&pt.bumpVerticalPos(g[0].textMaxHeight)),Ve.hideUnusedParticipants===!0){let F=new Set;v.forEach(V=>{F.add(V.from),F.add(V.to)}),y=y.filter(V=>F.has(V))}let k=new Map(y.map((F,V)=>[d.get(F)?.name??F,V]));hft(f,d,p,y,0,v,!1);let C=await Cft(v,d,w,i);Hi.insertArrowHead(f,e),Hi.insertArrowCrossHead(f,e),Hi.insertArrowFilledHead(f,e),Hi.insertSequenceNumber(f,e),Hi.insertSolidTopArrowHead(f,e),Hi.insertSolidBottomArrowHead(f,e),Hi.insertStickTopArrowHead(f,e),Hi.insertStickBottomArrowHead(f,e),s==="neo"&&Hi.insertDropShadow(f,Ve);function E(F,V){let H=pt.endActivation(F);H.starty+18>V&&(H.starty=V-6,V+=12),Hi.drawActivation(f,H,V,Ve,w_(F.from).length,i,k),pt.insert(H.startx,V-10,H.stopx,V)}o(E,"activeEnd");let S=1,L=1,M=[],I=[],A=0;for(let F of v){let V,H,X;switch(F.type){case i.db.LINETYPE.NOTE:pt.resetVerticalPos(),H=F.noteModel,await lft(f,H,F.id);break;case i.db.LINETYPE.ACTIVE_START:pt.newActivation(F,f,d);break;case i.db.LINETYPE.CENTRAL_CONNECTION:pt.newActivation(F,f,d);break;case i.db.LINETYPE.CENTRAL_CONNECTION_REVERSE:pt.newActivation(F,f,d);break;case i.db.LINETYPE.ACTIVE_END:E(F,pt.getVerticalPos());break;case i.db.LINETYPE.LOOP_START:ch(C,F,Ve.boxMargin,Ve.boxMargin+Ve.boxTextMargin,W=>pt.newLoop(W));break;case i.db.LINETYPE.LOOP_END:V=pt.endLoop(),await Hi.drawLoop(f,V,"loop",Ve,F),pt.bumpVerticalPos(V.stopy-pt.getVerticalPos()),pt.models.addLoop(V);break;case i.db.LINETYPE.RECT_START:ch(C,F,Ve.boxMargin,Ve.boxMargin,W=>pt.newLoop(void 0,W.message));break;case i.db.LINETYPE.RECT_END:V=pt.endLoop(),I.push(V),pt.models.addLoop(V),pt.bumpVerticalPos(V.stopy-pt.getVerticalPos());break;case i.db.LINETYPE.OPT_START:ch(C,F,Ve.boxMargin,Ve.boxMargin+Ve.boxTextMargin,W=>pt.newLoop(W));break;case i.db.LINETYPE.OPT_END:V=pt.endLoop(),await Hi.drawLoop(f,V,"opt",Ve,F),pt.bumpVerticalPos(V.stopy-pt.getVerticalPos()),pt.models.addLoop(V);break;case i.db.LINETYPE.ALT_START:ch(C,F,Ve.boxMargin,Ve.boxMargin+Ve.boxTextMargin,W=>pt.newLoop(W));break;case i.db.LINETYPE.ALT_ELSE:ch(C,F,Ve.boxMargin+Ve.boxTextMargin,Ve.boxMargin,W=>pt.addSectionToLoop(W));break;case i.db.LINETYPE.ALT_END:V=pt.endLoop(),await Hi.drawLoop(f,V,"alt",Ve,F),pt.bumpVerticalPos(V.stopy-pt.getVerticalPos()),pt.models.addLoop(V);break;case i.db.LINETYPE.PAR_START:case i.db.LINETYPE.PAR_OVER_START:ch(C,F,Ve.boxMargin,Ve.boxMargin+Ve.boxTextMargin,W=>pt.newLoop(W)),pt.saveVerticalPos();break;case i.db.LINETYPE.PAR_AND:ch(C,F,Ve.boxMargin+Ve.boxTextMargin,Ve.boxMargin,W=>pt.addSectionToLoop(W));break;case i.db.LINETYPE.PAR_END:V=pt.endLoop(),await Hi.drawLoop(f,V,"par",Ve,F),pt.bumpVerticalPos(V.stopy-pt.getVerticalPos()),pt.models.addLoop(V);break;case i.db.LINETYPE.AUTONUMBER:S=F.message.start||S,L=F.message.step||L,F.message.visible?i.db.enableSequenceNumbers():i.db.disableSequenceNumbers();break;case i.db.LINETYPE.CRITICAL_START:ch(C,F,Ve.boxMargin,Ve.boxMargin+Ve.boxTextMargin,W=>pt.newLoop(W));break;case i.db.LINETYPE.CRITICAL_OPTION:ch(C,F,Ve.boxMargin+Ve.boxTextMargin,Ve.boxMargin,W=>pt.addSectionToLoop(W));break;case i.db.LINETYPE.CRITICAL_END:V=pt.endLoop(),await Hi.drawLoop(f,V,"critical",Ve,F),pt.bumpVerticalPos(V.stopy-pt.getVerticalPos()),pt.models.addLoop(V);break;case i.db.LINETYPE.BREAK_START:ch(C,F,Ve.boxMargin,Ve.boxMargin+Ve.boxTextMargin,W=>pt.newLoop(W));break;case i.db.LINETYPE.BREAK_END:V=pt.endLoop(),await Hi.drawLoop(f,V,"break",Ve,F),pt.bumpVerticalPos(V.stopy-pt.getVerticalPos()),pt.models.addLoop(V);break;default:try{X=F.msgModel,X.starty=pt.getVerticalPos(),X.sequenceIndex=S,X.sequenceVisible=i.db.showSequenceNumbers(),X.id=F.id,X.from=F.from,X.to=F.to;let W=await cft(f,X);fft(F,X,W,A,d,p,m),M.push({messageModel:X,lineStartY:W,msg:F}),pt.models.addMessage(X)}catch(W){Q.error("error while drawing message",W)}}[i.db.LINETYPE.SOLID_OPEN,i.db.LINETYPE.DOTTED_OPEN,i.db.LINETYPE.SOLID,i.db.LINETYPE.SOLID_TOP,i.db.LINETYPE.SOLID_BOTTOM,i.db.LINETYPE.STICK_TOP,i.db.LINETYPE.STICK_BOTTOM,i.db.LINETYPE.SOLID_TOP_DOTTED,i.db.LINETYPE.SOLID_BOTTOM_DOTTED,i.db.LINETYPE.STICK_TOP_DOTTED,i.db.LINETYPE.STICK_BOTTOM_DOTTED,i.db.LINETYPE.SOLID_ARROW_TOP_REVERSE,i.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE,i.db.LINETYPE.STICK_ARROW_TOP_REVERSE,i.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE,i.db.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED,i.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED,i.db.LINETYPE.STICK_ARROW_TOP_REVERSE_DOTTED,i.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE_DOTTED,i.db.LINETYPE.DOTTED,i.db.LINETYPE.SOLID_CROSS,i.db.LINETYPE.DOTTED_CROSS,i.db.LINETYPE.SOLID_POINT,i.db.LINETYPE.DOTTED_POINT,i.db.LINETYPE.BIDIRECTIONAL_SOLID,i.db.LINETYPE.BIDIRECTIONAL_DOTTED].includes(F.type)&&(S=S+L),A++}Q.debug("createdActors",p),Q.debug("destroyedActors",m),await cU(f,d,y,!1,e,i,k);for(let F of M)await uft(f,F.messageModel,F.lineStartY,i,F.msg,e);Ve.mirrorActors&&await cU(f,d,y,!0,e,i,k),I.forEach(F=>Hi.drawBackgroundRect(f,F)),sU(f,d,y,Ve);for(let F of pt.models.boxes){F.height=pt.getVerticalPos()-F.y,pt.insert(F.x,F.y,F.x+F.width,F.height);let V=Ve.boxMargin*2;F.startx=F.x-V,F.starty=F.y-V*.25,F.stopx=F.startx+F.width+2*V,F.stopy=F.starty+F.height+V*.75,F.stroke="rgb(0,0,0, 0.5)",Hi.drawBox(f,F,Ve)}b&&pt.bumpVerticalPos(Ve.boxMargin);let _=R3e(f,d,y,h),{bounds:D}=pt.getBounds();D.startx===void 0&&(D.startx=0),D.starty===void 0&&(D.starty=0),D.stopx===void 0&&(D.stopx=0),D.stopy===void 0&&(D.stopy=0);let N=D.stopy-D.starty;N<_.maxHeight&&(N=_.maxHeight);let R=N+2*Ve.diagramMarginY;Ve.mirrorActors&&(R=R-Ve.boxMargin+Ve.bottomMarginAdj);let B=D.stopx-D.startx;B<_.maxWidth&&(B=_.maxWidth);let O=B+2*Ve.diagramMarginX;x&&f.append("text").text(x).attr("x",(D.stopx-D.startx)/2-2*Ve.diagramMarginX).attr("y",-25),Hr(f,R,O,Ve.useMaxWidth);let $=x?40:0,z=d.size&&s==="neo"?30:0;f.attr("viewBox",D.startx-Ve.diagramMarginX+" -"+(Ve.diagramMarginY+$)+" "+O+" "+(R+$+z)),Q.debug("models:",pt.models)},"draw");o(pft,"getMaxMessageWidthPerActor");mft=o(function(t){let e=0,r=lU(Ve);for(let i in t.links){let a=Kt.calculateTextDimensions(i,r).width+2*Ve.wrapPadding+2*Ve.boxMargin;e2,p=o(v=>u?-v:v,"adjustValue");t.from===t.to?f=h:(t.activate&&!d&&(f+=p(Ve.activationWidth/2-1)),[r.db.LINETYPE.SOLID_OPEN,r.db.LINETYPE.DOTTED_OPEN,r.db.LINETYPE.STICK_TOP,r.db.LINETYPE.STICK_BOTTOM,r.db.LINETYPE.STICK_TOP_DOTTED,r.db.LINETYPE.STICK_BOTTOM_DOTTED,r.db.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED,r.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED,r.db.LINETYPE.STICK_ARROW_TOP_REVERSE,r.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE,r.db.LINETYPE.STICK_ARROW_TOP_REVERSE_DOTTED,r.db.LINETYPE.STICK_ARROW_BOTTOM_REVERSE_DOTTED,r.db.LINETYPE.SOLID_ARROW_TOP_REVERSE,r.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE].includes(t.type)||(f+=p(3)),[r.db.LINETYPE.BIDIRECTIONAL_SOLID,r.db.LINETYPE.BIDIRECTIONAL_DOTTED,r.db.LINETYPE.SOLID_ARROW_TOP_REVERSE_DOTTED,r.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE_DOTTED,r.db.LINETYPE.SOLID_ARROW_TOP_REVERSE,r.db.LINETYPE.SOLID_ARROW_BOTTOM_REVERSE].includes(t.type)&&(h-=p(3)));let m=[n,a,s,l],g=Math.abs(h-f);t.wrap&&t.message&&(t.message=Kt.wrapLabel(t.message,lt.getMax(g+2*Ve.wrapPadding,Ve.width),ug(Ve)));let y=Kt.calculateTextDimensions(t.message,ug(Ve));return{width:lt.getMax(t.wrap?0:y.width+2*Ve.wrapPadding,g+2*Ve.wrapPadding,Ve.width),height:0,startx:h,stopx:f,starty:0,stopy:0,message:t.message,type:t.type,wrap:t.wrap,fromBounds:Math.min.apply(null,m),toBounds:Math.max.apply(null,m)}},"buildMessageModel"),Cft=o(async function(t,e,r,i){let n={},a=[],s,l,u;for(let h of t){switch(h.type){case i.db.LINETYPE.LOOP_START:case i.db.LINETYPE.ALT_START:case i.db.LINETYPE.OPT_START:case i.db.LINETYPE.PAR_START:case i.db.LINETYPE.PAR_OVER_START:case i.db.LINETYPE.CRITICAL_START:case i.db.LINETYPE.BREAK_START:a.push({id:h.id,msg:h.message,from:Number.MAX_SAFE_INTEGER,to:Number.MIN_SAFE_INTEGER,width:0});break;case i.db.LINETYPE.ALT_ELSE:case i.db.LINETYPE.PAR_AND:case i.db.LINETYPE.CRITICAL_OPTION:h.message&&(s=a.pop(),n[s.id]=s,n[h.id]=s,a.push(s));break;case i.db.LINETYPE.LOOP_END:case i.db.LINETYPE.ALT_END:case i.db.LINETYPE.OPT_END:case i.db.LINETYPE.PAR_END:case i.db.LINETYPE.CRITICAL_END:case i.db.LINETYPE.BREAK_END:s=a.pop(),n[s.id]=s;break;case i.db.LINETYPE.ACTIVE_START:{let d=e.get(h.from?h.from:h.to.actor),p=w_(h.from?h.from:h.to.actor).length,m=d.x+d.width/2+(p-1)*Ve.activationWidth/2,g={startx:m,stopx:m+Ve.activationWidth,actor:h.from,enabled:!0};pt.activations.push(g)}break;case i.db.LINETYPE.ACTIVE_END:{let d=pt.activations.map(p=>p.actor).lastIndexOf(h.from);pt.activations.splice(d,1).splice(0,1)}break}h.placement!==void 0?(l=await yft(h,e,i),h.noteModel=l,a.forEach(d=>{s=d,s.from=lt.getMin(s.from,l.startx),s.to=lt.getMax(s.to,l.startx+l.width),s.width=lt.getMax(s.width,Math.abs(s.from-s.to))-Ve.labelBoxWidth})):(u=kft(h,e,i),h.msgModel=u,u.startx&&u.stopx&&a.length>0&&a.forEach(d=>{if(s=d,u.startx===u.stopx){let p=e.get(h.from),m=e.get(h.to);s.from=lt.getMin(p.x-u.width/2,p.x-p.width/2,s.from),s.to=lt.getMax(m.x+u.width/2,m.x+p.width/2,s.to),s.width=lt.getMax(s.width,Math.abs(s.to-s.from))-Ve.labelBoxWidth}else s.from=lt.getMin(u.startx,s.from),s.to=lt.getMax(u.stopx,s.to),s.width=lt.getMax(s.width,u.width)-Ve.labelBoxWidth}))}return pt.activations=[],Q.debug("Loop type widths:",n),n},"calculateLoopBounds"),M3e={bounds:pt,drawActors:cU,drawActorsPopup:R3e,setConf:N3e,draw:dft}});var P3e={};ur(P3e,{diagram:()=>wft});var wft,B3e=P(()=>{"use strict";k3e();nU();w3e();Ut();O3e();wft={parser:T3e,get db(){return new T_},renderer:M3e,styles:C3e,init:o(t=>{t.sequence||(t.sequence={}),t.wrap&&(t.sequence.wrap=t.wrap,t2({sequence:{wrap:t.wrap}}))},"init")}});var uU,E_,hU=P(()=>{"use strict";uU=(function(){var t=o(function(Ue,qe,Me,He){for(Me=Me||{},He=Ue.length;He--;Me[Ue[He]]=qe);return Me},"o"),e=[1,18],r=[1,19],i=[1,20],n=[1,41],a=[1,26],s=[1,42],l=[1,24],u=[1,25],h=[1,32],f=[1,33],d=[1,34],p=[1,45],m=[1,35],g=[1,36],y=[1,37],v=[1,38],x=[1,27],b=[1,28],T=[1,29],w=[1,30],k=[1,31],C=[1,44],E=[1,46],S=[1,43],L=[1,47],M=[1,9],I=[1,8,9],A=[1,58],_=[1,59],D=[1,60],N=[1,61],R=[1,62],B=[1,63],O=[1,64],$=[1,8,9,41],z=[1,77],F=[1,8,9,12,13,22,39,41,44,46,68,69,70,71,72,73,74,79,81],V=[1,8,9,12,13,18,20,22,39,41,44,46,47,60,68,69,70,71,72,73,74,79,81,86,100,102,103],H=[13,60,86,100,102,103],X=[13,60,73,74,86,100,102,103],W=[13,60,68,69,70,71,72,86,100,102,103],Z=[1,102],Y=[1,120],ae=[1,116],J=[1,112],ee=[1,118],re=[1,113],te=[1,114],be=[1,115],de=[1,117],Ee=[1,119],Ne=[22,50,60,61,82,86,87,88,89,90],we=[1,8,9,39,41,44,46],Te=[1,8,9,22],De=[1,150],$e=[1,8,9,61],pe=[1,8,9,22,50,60,61,82,86,87,88,89,90],Je={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,mermaidDoc:4,statements:5,graphConfig:6,CLASS_DIAGRAM:7,NEWLINE:8,EOF:9,statement:10,classLabel:11,SQS:12,STR:13,SQE:14,namespaceName:15,alphaNumToken:16,classLiteralName:17,DOT:18,className:19,GENERICTYPE:20,relationStatement:21,LABEL:22,namespaceStatement:23,classStatement:24,memberStatement:25,annotationStatement:26,clickStatement:27,styleStatement:28,cssClassStatement:29,noteStatement:30,classDefStatement:31,direction:32,acc_title:33,acc_title_value:34,acc_descr:35,acc_descr_value:36,acc_descr_multiline_value:37,namespaceIdentifier:38,STRUCT_START:39,classStatements:40,STRUCT_STOP:41,NAMESPACE:42,classIdentifier:43,STYLE_SEPARATOR:44,members:45,ANNOTATION_START:46,ANNOTATION_END:47,CLASS:48,emptyBody:49,SPACE:50,MEMBER:51,SEPARATOR:52,relation:53,NOTE_FOR:54,noteText:55,NOTE:56,CLASSDEF:57,classList:58,stylesOpt:59,ALPHA:60,COMMA:61,direction_tb:62,direction_bt:63,direction_rl:64,direction_lr:65,relationType:66,lineType:67,AGGREGATION:68,EXTENSION:69,COMPOSITION:70,DEPENDENCY:71,LOLLIPOP:72,LINE:73,DOTTED_LINE:74,CALLBACK:75,LINK:76,LINK_TARGET:77,CLICK:78,CALLBACK_NAME:79,CALLBACK_ARGS:80,HREF:81,STYLE:82,CSSCLASS:83,style:84,styleComponent:85,NUM:86,COLON:87,UNIT:88,BRKT:89,PCT:90,commentToken:91,textToken:92,graphCodeTokens:93,textNoTagsToken:94,TAGSTART:95,TAGEND:96,"==":97,"--":98,DEFAULT:99,MINUS:100,keywords:101,UNICODE_TEXT:102,BQUOTE_STR:103,$accept:0,$end:1},terminals_:{2:"error",7:"CLASS_DIAGRAM",8:"NEWLINE",9:"EOF",12:"SQS",13:"STR",14:"SQE",18:"DOT",20:"GENERICTYPE",22:"LABEL",33:"acc_title",34:"acc_title_value",35:"acc_descr",36:"acc_descr_value",37:"acc_descr_multiline_value",39:"STRUCT_START",41:"STRUCT_STOP",42:"NAMESPACE",44:"STYLE_SEPARATOR",46:"ANNOTATION_START",47:"ANNOTATION_END",48:"CLASS",50:"SPACE",51:"MEMBER",52:"SEPARATOR",54:"NOTE_FOR",56:"NOTE",57:"CLASSDEF",60:"ALPHA",61:"COMMA",62:"direction_tb",63:"direction_bt",64:"direction_rl",65:"direction_lr",68:"AGGREGATION",69:"EXTENSION",70:"COMPOSITION",71:"DEPENDENCY",72:"LOLLIPOP",73:"LINE",74:"DOTTED_LINE",75:"CALLBACK",76:"LINK",77:"LINK_TARGET",78:"CLICK",79:"CALLBACK_NAME",80:"CALLBACK_ARGS",81:"HREF",82:"STYLE",83:"CSSCLASS",86:"NUM",87:"COLON",88:"UNIT",89:"BRKT",90:"PCT",93:"graphCodeTokens",95:"TAGSTART",96:"TAGEND",97:"==",98:"--",99:"DEFAULT",100:"MINUS",101:"keywords",102:"UNICODE_TEXT",103:"BQUOTE_STR"},productions_:[0,[3,1],[3,1],[4,1],[6,4],[5,1],[5,2],[5,3],[11,3],[15,1],[15,1],[15,3],[15,2],[19,1],[19,3],[19,1],[19,2],[19,2],[19,2],[10,1],[10,2],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,1],[10,2],[10,2],[10,1],[23,4],[23,5],[38,2],[40,1],[40,2],[40,3],[40,1],[40,2],[40,3],[24,1],[24,3],[24,4],[24,3],[24,6],[24,4],[24,7],[24,6],[43,2],[43,3],[49,0],[49,2],[49,2],[26,4],[45,1],[45,2],[25,1],[25,2],[25,1],[25,1],[21,3],[21,4],[21,4],[21,5],[30,3],[30,2],[31,3],[58,1],[58,3],[32,1],[32,1],[32,1],[32,1],[53,3],[53,2],[53,2],[53,1],[66,1],[66,1],[66,1],[66,1],[66,1],[67,1],[67,1],[27,3],[27,4],[27,3],[27,4],[27,4],[27,5],[27,3],[27,4],[27,4],[27,5],[27,4],[27,5],[27,5],[27,6],[28,3],[29,3],[59,1],[59,3],[84,1],[84,2],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[85,1],[91,1],[91,1],[92,1],[92,1],[92,1],[92,1],[92,1],[92,1],[92,1],[94,1],[94,1],[94,1],[94,1],[16,1],[16,1],[16,1],[16,1],[17,1],[55,1]],performAction:o(function(qe,Me,He,K,oe,U,ue){var G=U.length-1;switch(oe){case 8:this.$=U[G-1];break;case 9:case 10:case 13:case 15:this.$=U[G];break;case 11:case 14:this.$=U[G-2]+"."+U[G];break;case 12:case 16:this.$=U[G-1]+U[G];break;case 17:case 18:this.$=U[G-1]+"~"+U[G]+"~";break;case 19:K.addRelation(U[G]);break;case 20:U[G-1].title=K.cleanupLabel(U[G]),K.addRelation(U[G-1]);break;case 31:this.$=U[G].trim(),K.setAccTitle(this.$);break;case 32:case 33:this.$=U[G].trim(),K.setAccDescription(this.$);break;case 34:K.addClassesToNamespace(U[G-3],U[G-1][0],U[G-1][1]);break;case 35:K.addClassesToNamespace(U[G-4],U[G-1][0],U[G-1][1]);break;case 36:this.$=U[G],K.addNamespace(U[G]);break;case 37:this.$=[[U[G]],[]];break;case 38:this.$=[[U[G-1]],[]];break;case 39:U[G][0].unshift(U[G-2]),this.$=U[G];break;case 40:this.$=[[],[U[G]]];break;case 41:this.$=[[],[U[G-1]]];break;case 42:U[G][1].unshift(U[G-2]),this.$=U[G];break;case 44:K.setCssClass(U[G-2],U[G]);break;case 45:K.addMembers(U[G-3],U[G-1]);break;case 47:K.setCssClass(U[G-5],U[G-3]),K.addMembers(U[G-5],U[G-1]);break;case 48:K.addAnnotation(U[G-3],U[G-1]);break;case 49:K.addAnnotation(U[G-6],U[G-4]),K.addMembers(U[G-6],U[G-1]);break;case 50:K.addAnnotation(U[G-5],U[G-3]);break;case 51:this.$=U[G],K.addClass(U[G]);break;case 52:this.$=U[G-1],K.addClass(U[G-1]),K.setClassLabel(U[G-1],U[G]);break;case 56:K.addAnnotation(U[G],U[G-2]);break;case 57:case 70:this.$=[U[G]];break;case 58:U[G].push(U[G-1]),this.$=U[G];break;case 59:break;case 60:K.addMember(U[G-1],K.cleanupLabel(U[G]));break;case 61:break;case 62:break;case 63:this.$={id1:U[G-2],id2:U[G],relation:U[G-1],relationTitle1:"none",relationTitle2:"none"};break;case 64:this.$={id1:U[G-3],id2:U[G],relation:U[G-1],relationTitle1:U[G-2],relationTitle2:"none"};break;case 65:this.$={id1:U[G-3],id2:U[G],relation:U[G-2],relationTitle1:"none",relationTitle2:U[G-1]};break;case 66:this.$={id1:U[G-4],id2:U[G],relation:U[G-2],relationTitle1:U[G-3],relationTitle2:U[G-1]};break;case 67:this.$=K.addNote(U[G],U[G-1]);break;case 68:this.$=K.addNote(U[G]);break;case 69:this.$=U[G-2],K.defineClass(U[G-1],U[G]);break;case 71:this.$=U[G-2].concat([U[G]]);break;case 72:K.setDirection("TB");break;case 73:K.setDirection("BT");break;case 74:K.setDirection("RL");break;case 75:K.setDirection("LR");break;case 76:this.$={type1:U[G-2],type2:U[G],lineType:U[G-1]};break;case 77:this.$={type1:"none",type2:U[G],lineType:U[G-1]};break;case 78:this.$={type1:U[G-1],type2:"none",lineType:U[G]};break;case 79:this.$={type1:"none",type2:"none",lineType:U[G]};break;case 80:this.$=K.relationType.AGGREGATION;break;case 81:this.$=K.relationType.EXTENSION;break;case 82:this.$=K.relationType.COMPOSITION;break;case 83:this.$=K.relationType.DEPENDENCY;break;case 84:this.$=K.relationType.LOLLIPOP;break;case 85:this.$=K.lineType.LINE;break;case 86:this.$=K.lineType.DOTTED_LINE;break;case 87:case 93:this.$=U[G-2],K.setClickEvent(U[G-1],U[G]);break;case 88:case 94:this.$=U[G-3],K.setClickEvent(U[G-2],U[G-1]),K.setTooltip(U[G-2],U[G]);break;case 89:this.$=U[G-2],K.setLink(U[G-1],U[G]);break;case 90:this.$=U[G-3],K.setLink(U[G-2],U[G-1],U[G]);break;case 91:this.$=U[G-3],K.setLink(U[G-2],U[G-1]),K.setTooltip(U[G-2],U[G]);break;case 92:this.$=U[G-4],K.setLink(U[G-3],U[G-2],U[G]),K.setTooltip(U[G-3],U[G-1]);break;case 95:this.$=U[G-3],K.setClickEvent(U[G-2],U[G-1],U[G]);break;case 96:this.$=U[G-4],K.setClickEvent(U[G-3],U[G-2],U[G-1]),K.setTooltip(U[G-3],U[G]);break;case 97:this.$=U[G-3],K.setLink(U[G-2],U[G]);break;case 98:this.$=U[G-4],K.setLink(U[G-3],U[G-1],U[G]);break;case 99:this.$=U[G-4],K.setLink(U[G-3],U[G-1]),K.setTooltip(U[G-3],U[G]);break;case 100:this.$=U[G-5],K.setLink(U[G-4],U[G-2],U[G]),K.setTooltip(U[G-4],U[G-1]);break;case 101:this.$=U[G-2],K.setCssStyle(U[G-1],U[G]);break;case 102:K.setCssClass(U[G-1],U[G]);break;case 103:this.$=[U[G]];break;case 104:U[G-2].push(U[G]),this.$=U[G-2];break;case 106:this.$=U[G-1]+U[G];break}},"anonymous"),table:[{3:1,4:2,5:3,6:4,7:[1,6],10:5,16:39,17:40,19:21,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,33:e,35:r,37:i,38:22,42:n,43:23,46:a,48:s,51:l,52:u,54:h,56:f,57:d,60:p,62:m,63:g,64:y,65:v,75:x,76:b,78:T,82:w,83:k,86:C,100:E,102:S,103:L},{1:[3]},{1:[2,1]},{1:[2,2]},{1:[2,3]},t(M,[2,5],{8:[1,48]}),{8:[1,49]},t(I,[2,19],{22:[1,50]}),t(I,[2,21]),t(I,[2,22]),t(I,[2,23]),t(I,[2,24]),t(I,[2,25]),t(I,[2,26]),t(I,[2,27]),t(I,[2,28]),t(I,[2,29]),t(I,[2,30]),{34:[1,51]},{36:[1,52]},t(I,[2,33]),t(I,[2,59],{53:53,66:56,67:57,13:[1,54],22:[1,55],68:A,69:_,70:D,71:N,72:R,73:B,74:O}),{39:[1,65]},t($,[2,43],{39:[1,67],44:[1,66],46:[1,68]}),t(I,[2,61]),t(I,[2,62]),{16:69,60:p,86:C,100:E,102:S},{16:39,17:40,19:70,60:p,86:C,100:E,102:S,103:L},{16:39,17:40,19:71,60:p,86:C,100:E,102:S,103:L},{16:39,17:40,19:72,60:p,86:C,100:E,102:S,103:L},{60:[1,73]},{13:[1,74]},{16:39,17:40,19:75,60:p,86:C,100:E,102:S,103:L},{13:z,55:76},{58:78,60:[1,79]},t(I,[2,72]),t(I,[2,73]),t(I,[2,74]),t(I,[2,75]),t(F,[2,13],{16:39,17:40,19:81,18:[1,80],20:[1,82],60:p,86:C,100:E,102:S,103:L}),t(F,[2,15],{20:[1,83]}),{15:84,16:85,17:86,60:p,86:C,100:E,102:S,103:L},{16:39,17:40,19:87,60:p,86:C,100:E,102:S,103:L},t(V,[2,129]),t(V,[2,130]),t(V,[2,131]),t(V,[2,132]),t([1,8,9,12,13,20,22,39,41,44,46,68,69,70,71,72,73,74,79,81],[2,133]),t(M,[2,6],{10:5,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,19:21,38:22,43:23,16:39,17:40,5:88,33:e,35:r,37:i,42:n,46:a,48:s,51:l,52:u,54:h,56:f,57:d,60:p,62:m,63:g,64:y,65:v,75:x,76:b,78:T,82:w,83:k,86:C,100:E,102:S,103:L}),{5:89,10:5,16:39,17:40,19:21,21:7,23:8,24:9,25:10,26:11,27:12,28:13,29:14,30:15,31:16,32:17,33:e,35:r,37:i,38:22,42:n,43:23,46:a,48:s,51:l,52:u,54:h,56:f,57:d,60:p,62:m,63:g,64:y,65:v,75:x,76:b,78:T,82:w,83:k,86:C,100:E,102:S,103:L},t(I,[2,20]),t(I,[2,31]),t(I,[2,32]),{13:[1,91],16:39,17:40,19:90,60:p,86:C,100:E,102:S,103:L},{53:92,66:56,67:57,68:A,69:_,70:D,71:N,72:R,73:B,74:O},t(I,[2,60]),{67:93,73:B,74:O},t(H,[2,79],{66:94,68:A,69:_,70:D,71:N,72:R}),t(X,[2,80]),t(X,[2,81]),t(X,[2,82]),t(X,[2,83]),t(X,[2,84]),t(W,[2,85]),t(W,[2,86]),{8:[1,96],24:97,30:98,40:95,43:23,48:s,54:h,56:f},{16:99,60:p,86:C,100:E,102:S},{41:[1,101],45:100,51:Z},{16:103,60:p,86:C,100:E,102:S},{47:[1,104]},{13:[1,105]},{13:[1,106]},{79:[1,107],81:[1,108]},{22:Y,50:ae,59:109,60:J,82:ee,84:110,85:111,86:re,87:te,88:be,89:de,90:Ee},{60:[1,121]},{13:z,55:122},t($,[2,68]),t($,[2,134]),{22:Y,50:ae,59:123,60:J,61:[1,124],82:ee,84:110,85:111,86:re,87:te,88:be,89:de,90:Ee},t(Ne,[2,70]),{16:39,17:40,19:125,60:p,86:C,100:E,102:S,103:L},t(F,[2,16]),t(F,[2,17]),t(F,[2,18]),{39:[2,36]},{15:127,16:85,17:86,18:[1,126],39:[2,9],60:p,86:C,100:E,102:S,103:L},{39:[2,10]},t(we,[2,51],{11:128,12:[1,129]}),t(M,[2,7]),{9:[1,130]},t(Te,[2,63]),{16:39,17:40,19:131,60:p,86:C,100:E,102:S,103:L},{13:[1,133],16:39,17:40,19:132,60:p,86:C,100:E,102:S,103:L},t(H,[2,78],{66:134,68:A,69:_,70:D,71:N,72:R}),t(H,[2,77]),{41:[1,135]},{24:97,30:98,40:136,43:23,48:s,54:h,56:f},{8:[1,137],41:[2,37]},{8:[1,138],41:[2,40]},t($,[2,44],{39:[1,139]}),{41:[1,140]},t($,[2,46]),{41:[2,57],45:141,51:Z},{47:[1,142]},{16:39,17:40,19:143,60:p,86:C,100:E,102:S,103:L},t(I,[2,87],{13:[1,144]}),t(I,[2,89],{13:[1,146],77:[1,145]}),t(I,[2,93],{13:[1,147],80:[1,148]}),{13:[1,149]},t(I,[2,101],{61:De}),t($e,[2,103],{85:151,22:Y,50:ae,60:J,82:ee,86:re,87:te,88:be,89:de,90:Ee}),t(pe,[2,105]),t(pe,[2,107]),t(pe,[2,108]),t(pe,[2,109]),t(pe,[2,110]),t(pe,[2,111]),t(pe,[2,112]),t(pe,[2,113]),t(pe,[2,114]),t(pe,[2,115]),t(I,[2,102]),t($,[2,67]),t(I,[2,69],{61:De}),{60:[1,152]},t(F,[2,14]),{15:153,16:85,17:86,60:p,86:C,100:E,102:S,103:L},{39:[2,12]},t(we,[2,52]),{13:[1,154]},{1:[2,4]},t(Te,[2,65]),t(Te,[2,64]),{16:39,17:40,19:155,60:p,86:C,100:E,102:S,103:L},t(H,[2,76]),t(I,[2,34]),{41:[1,156]},{24:97,30:98,40:157,41:[2,38],43:23,48:s,54:h,56:f},{24:97,30:98,40:158,41:[2,41],43:23,48:s,54:h,56:f},{45:159,51:Z},t($,[2,45]),{41:[2,58]},t($,[2,48],{39:[1,160]}),t(I,[2,56]),t(I,[2,88]),t(I,[2,90]),t(I,[2,91],{77:[1,161]}),t(I,[2,94]),t(I,[2,95],{13:[1,162]}),t(I,[2,97],{13:[1,164],77:[1,163]}),{22:Y,50:ae,60:J,82:ee,84:165,85:111,86:re,87:te,88:be,89:de,90:Ee},t(pe,[2,106]),t(Ne,[2,71]),{39:[2,11]},{14:[1,166]},t(Te,[2,66]),t(I,[2,35]),{41:[2,39]},{41:[2,42]},{41:[1,167]},{41:[1,169],45:168,51:Z},t(I,[2,92]),t(I,[2,96]),t(I,[2,98]),t(I,[2,99],{77:[1,170]}),t($e,[2,104],{85:151,22:Y,50:ae,60:J,82:ee,86:re,87:te,88:be,89:de,90:Ee}),t(we,[2,8]),t($,[2,47]),{41:[1,171]},t($,[2,50]),t(I,[2,100]),t($,[2,49])],defaultActions:{2:[2,1],3:[2,2],4:[2,3],84:[2,36],86:[2,10],127:[2,12],130:[2,4],141:[2,58],153:[2,11],157:[2,39],158:[2,42]},parseError:o(function(qe,Me){if(Me.recoverable)this.trace(qe);else{var He=new Error(qe);throw He.hash=Me,He}},"parseError"),parse:o(function(qe){var Me=this,He=[0],K=[],oe=[null],U=[],ue=this.table,G="",se=0,le=0,ke=0,me=2,ye=1,Re=U.slice.call(arguments,1),ve=Object.create(this.lexer),Oe={yy:{}};for(var We in this.yy)Object.prototype.hasOwnProperty.call(this.yy,We)&&(Oe.yy[We]=this.yy[We]);ve.setInput(qe,Oe.yy),Oe.yy.lexer=ve,Oe.yy.parser=this,typeof ve.yylloc>"u"&&(ve.yylloc={});var Be=ve.yylloc;U.push(Be);var Qe=ve.options&&ve.options.ranges;typeof Oe.yy.parseError=="function"?this.parseError=Oe.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function ce(hr){He.length=He.length-2*hr,oe.length=oe.length-hr,U.length=U.length-hr}o(ce,"popStack");function it(){var hr;return hr=K.pop()||ve.lex()||ye,typeof hr!="number"&&(hr instanceof Array&&(K=hr,hr=K.pop()),hr=Me.symbols_[hr]||hr),hr}o(it,"lex");for(var fe,ut,Nt,Pt,St,It,ot={},ct,Dt,kt,yt;;){if(Nt=He[He.length-1],this.defaultActions[Nt]?Pt=this.defaultActions[Nt]:((fe===null||typeof fe>"u")&&(fe=it()),Pt=ue[Nt]&&ue[Nt][fe]),typeof Pt>"u"||!Pt.length||!Pt[0]){var jt="";yt=[];for(ct in ue[Nt])this.terminals_[ct]&&ct>me&&yt.push("'"+this.terminals_[ct]+"'");ve.showPosition?jt="Parse error on line "+(se+1)+`: +`+ve.showPosition()+` +Expecting `+yt.join(", ")+", got '"+(this.terminals_[fe]||fe)+"'":jt="Parse error on line "+(se+1)+": Unexpected "+(fe==ye?"end of input":"'"+(this.terminals_[fe]||fe)+"'"),this.parseError(jt,{text:ve.match,token:this.terminals_[fe]||fe,line:ve.yylineno,loc:Be,expected:yt})}if(Pt[0]instanceof Array&&Pt.length>1)throw new Error("Parse Error: multiple actions possible at state: "+Nt+", token: "+fe);switch(Pt[0]){case 1:He.push(fe),oe.push(ve.yytext),U.push(ve.yylloc),He.push(Pt[1]),fe=null,ut?(fe=ut,ut=null):(le=ve.yyleng,G=ve.yytext,se=ve.yylineno,Be=ve.yylloc,ke>0&&ke--);break;case 2:if(Dt=this.productions_[Pt[1]][1],ot.$=oe[oe.length-Dt],ot._$={first_line:U[U.length-(Dt||1)].first_line,last_line:U[U.length-1].last_line,first_column:U[U.length-(Dt||1)].first_column,last_column:U[U.length-1].last_column},Qe&&(ot._$.range=[U[U.length-(Dt||1)].range[0],U[U.length-1].range[1]]),It=this.performAction.apply(ot,[G,le,se,Oe.yy,Pt[1],oe,U].concat(Re)),typeof It<"u")return It;Dt&&(He=He.slice(0,-1*Dt*2),oe=oe.slice(0,-1*Dt),U=U.slice(0,-1*Dt)),He.push(this.productions_[Pt[1]][0]),oe.push(ot.$),U.push(ot._$),kt=ue[He[He.length-2]][He[He.length-1]],He.push(kt);break;case 3:return!0}}return!0},"parse")},Ce=(function(){var Ue={EOF:1,parseError:o(function(Me,He){if(this.yy.parser)this.yy.parser.parseError(Me,He);else throw new Error(Me)},"parseError"),setInput:o(function(qe,Me){return this.yy=Me||this.yy||{},this._input=qe,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var qe=this._input[0];this.yytext+=qe,this.yyleng++,this.offset++,this.match+=qe,this.matched+=qe;var Me=qe.match(/(?:\r\n?|\n).*/g);return Me?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),qe},"input"),unput:o(function(qe){var Me=qe.length,He=qe.split(/(?:\r\n?|\n)/g);this._input=qe+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-Me),this.offset-=Me;var K=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),He.length-1&&(this.yylineno-=He.length-1);var oe=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:He?(He.length===K.length?this.yylloc.first_column:0)+K[K.length-He.length].length-He[0].length:this.yylloc.first_column-Me},this.options.ranges&&(this.yylloc.range=[oe[0],oe[0]+this.yyleng-Me]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(qe){this.unput(this.match.slice(qe))},"less"),pastInput:o(function(){var qe=this.matched.substr(0,this.matched.length-this.match.length);return(qe.length>20?"...":"")+qe.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var qe=this.match;return qe.length<20&&(qe+=this._input.substr(0,20-qe.length)),(qe.substr(0,20)+(qe.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var qe=this.pastInput(),Me=new Array(qe.length+1).join("-");return qe+this.upcomingInput()+` +`+Me+"^"},"showPosition"),test_match:o(function(qe,Me){var He,K,oe;if(this.options.backtrack_lexer&&(oe={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(oe.yylloc.range=this.yylloc.range.slice(0))),K=qe[0].match(/(?:\r\n?|\n).*/g),K&&(this.yylineno+=K.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:K?K[K.length-1].length-K[K.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+qe[0].length},this.yytext+=qe[0],this.match+=qe[0],this.matches=qe,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(qe[0].length),this.matched+=qe[0],He=this.performAction.call(this,this.yy,this,Me,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),He)return He;if(this._backtrack){for(var U in oe)this[U]=oe[U];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var qe,Me,He,K;this._more||(this.yytext="",this.match="");for(var oe=this._currentRules(),U=0;UMe[0].length)){if(Me=He,K=U,this.options.backtrack_lexer){if(qe=this.test_match(He,oe[U]),qe!==!1)return qe;if(this._backtrack){Me=!1;continue}else return!1}else if(!this.options.flex)break}return Me?(qe=this.test_match(Me,oe[K]),qe!==!1?qe:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var Me=this.next();return Me||this.lex()},"lex"),begin:o(function(Me){this.conditionStack.push(Me)},"begin"),popState:o(function(){var Me=this.conditionStack.length-1;return Me>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(Me){return Me=this.conditionStack.length-1-Math.abs(Me||0),Me>=0?this.conditionStack[Me]:"INITIAL"},"topState"),pushState:o(function(Me){this.begin(Me)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{},performAction:o(function(Me,He,K,oe){var U=oe;switch(K){case 0:return 62;case 1:return 63;case 2:return 64;case 3:return 65;case 4:break;case 5:break;case 6:return this.begin("acc_title"),33;break;case 7:return this.popState(),"acc_title_value";break;case 8:return this.begin("acc_descr"),35;break;case 9:return this.popState(),"acc_descr_value";break;case 10:this.begin("acc_descr_multiline");break;case 11:this.popState();break;case 12:return"acc_descr_multiline_value";case 13:return 8;case 14:break;case 15:return 7;case 16:return 7;case 17:return"EDGE_STATE";case 18:this.begin("callback_name");break;case 19:this.popState();break;case 20:this.popState(),this.begin("callback_args");break;case 21:return 79;case 22:this.popState();break;case 23:return 80;case 24:this.popState();break;case 25:return"STR";case 26:this.begin("string");break;case 27:return 82;case 28:return 57;case 29:return this.begin("namespace"),42;break;case 30:return this.popState(),8;break;case 31:break;case 32:return this.begin("namespace-body"),39;break;case 33:return this.popState(),41;break;case 34:return"EOF_IN_STRUCT";case 35:return 8;case 36:break;case 37:return"EDGE_STATE";case 38:return this.begin("class"),48;break;case 39:return this.popState(),8;break;case 40:break;case 41:return this.popState(),this.popState(),41;break;case 42:return this.begin("class-body"),39;break;case 43:return this.popState(),41;break;case 44:return"EOF_IN_STRUCT";case 45:return"EDGE_STATE";case 46:return"OPEN_IN_STRUCT";case 47:break;case 48:return"MEMBER";case 49:return 83;case 50:return 75;case 51:return 76;case 52:return 78;case 53:return 54;case 54:return 56;case 55:return 46;case 56:return 47;case 57:return 81;case 58:this.popState();break;case 59:return"GENERICTYPE";case 60:this.begin("generic");break;case 61:this.popState();break;case 62:return"BQUOTE_STR";case 63:this.begin("bqstring");break;case 64:return 77;case 65:return 77;case 66:return 77;case 67:return 77;case 68:return 69;case 69:return 69;case 70:return 71;case 71:return 71;case 72:return 70;case 73:return 68;case 74:return 72;case 75:return 73;case 76:return 74;case 77:return 22;case 78:return 44;case 79:return 100;case 80:return 18;case 81:return"PLUS";case 82:return 87;case 83:return 61;case 84:return 89;case 85:return 89;case 86:return 90;case 87:return"EQUALS";case 88:return"EQUALS";case 89:return 60;case 90:return 12;case 91:return 14;case 92:return"PUNCTUATION";case 93:return 86;case 94:return 102;case 95:return 50;case 96:return 50;case 97:return 9}},"anonymous"),rules:[/^(?:.*direction\s+TB[^\n]*)/,/^(?:.*direction\s+BT[^\n]*)/,/^(?:.*direction\s+RL[^\n]*)/,/^(?:.*direction\s+LR[^\n]*)/,/^(?:%%(?!\{)*[^\n]*(\r?\n?)+)/,/^(?:%%[^\n]*(\r?\n)*)/,/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:classDiagram-v2\b)/,/^(?:classDiagram\b)/,/^(?:\[\*\])/,/^(?:call[\s]+)/,/^(?:\([\s]*\))/,/^(?:\()/,/^(?:[^(]*)/,/^(?:\))/,/^(?:[^)]*)/,/^(?:["])/,/^(?:[^"]*)/,/^(?:["])/,/^(?:style\b)/,/^(?:classDef\b)/,/^(?:namespace\b)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:[{])/,/^(?:[}])/,/^(?:$)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:\[\*\])/,/^(?:class\b)/,/^(?:\s*(\r?\n)+)/,/^(?:\s+)/,/^(?:[}])/,/^(?:[{])/,/^(?:[}])/,/^(?:$)/,/^(?:\[\*\])/,/^(?:[{])/,/^(?:[\n])/,/^(?:[^{}\n]*)/,/^(?:cssClass\b)/,/^(?:callback\b)/,/^(?:link\b)/,/^(?:click\b)/,/^(?:note for\b)/,/^(?:note\b)/,/^(?:<<)/,/^(?:>>)/,/^(?:href\b)/,/^(?:[~])/,/^(?:[^~]*)/,/^(?:~)/,/^(?:[`])/,/^(?:[^`]+)/,/^(?:[`])/,/^(?:_self\b)/,/^(?:_blank\b)/,/^(?:_parent\b)/,/^(?:_top\b)/,/^(?:\s*<\|)/,/^(?:\s*\|>)/,/^(?:\s*>)/,/^(?:\s*<)/,/^(?:\s*\*)/,/^(?:\s*o\b)/,/^(?:\s*\(\))/,/^(?:--)/,/^(?:\.\.)/,/^(?::{1}[^:\n;]+)/,/^(?::{3})/,/^(?:-)/,/^(?:\.)/,/^(?:\+)/,/^(?::)/,/^(?:,)/,/^(?:#)/,/^(?:#)/,/^(?:%)/,/^(?:=)/,/^(?:=)/,/^(?:\w+)/,/^(?:\[)/,/^(?:\])/,/^(?:[!"#$%&'*+,-.`?\\/])/,/^(?:[0-9]+)/,/^(?:[\u00AA\u00B5\u00BA\u00C0-\u00D6\u00D8-\u00F6]|[\u00F8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377]|[\u037A-\u037D\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5]|[\u03F7-\u0481\u048A-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA]|[\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE]|[\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA]|[\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0]|[\u08A2-\u08AC\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0977]|[\u0979-\u097F\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2]|[\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A]|[\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39]|[\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8]|[\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C]|[\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C]|[\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99]|[\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0]|[\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C33\u0C35-\u0C39\u0C3D]|[\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3]|[\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10]|[\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1]|[\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81]|[\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3]|[\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6]|[\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A]|[\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081]|[\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D]|[\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0]|[\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310]|[\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C]|[\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u1700-\u170C\u170E-\u1711]|[\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7]|[\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191C]|[\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16]|[\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF]|[\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC]|[\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D]|[\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D]|[\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3]|[\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F]|[\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128]|[\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184]|[\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3]|[\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6]|[\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE]|[\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C]|[\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D]|[\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC]|[\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B]|[\uA640-\uA66E\uA67F-\uA697\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788]|[\uA78B-\uA78E\uA790-\uA793\uA7A0-\uA7AA\uA7F8-\uA801\uA803-\uA805]|[\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB]|[\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uAA00-\uAA28]|[\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA80-\uAAAF\uAAB1\uAAB5]|[\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4]|[\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E]|[\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D]|[\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36]|[\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D]|[\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC]|[\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF]|[\uFFD2-\uFFD7\uFFDA-\uFFDC])/,/^(?:\s)/,/^(?:\s)/,/^(?:$)/],conditions:{"namespace-body":{rules:[26,33,34,35,36,37,38,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},namespace:{rules:[26,29,30,31,32,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},"class-body":{rules:[26,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},class:{rules:[26,39,40,41,42,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},acc_descr_multiline:{rules:[11,12,26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},acc_descr:{rules:[9,26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},acc_title:{rules:[7,26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},callback_args:{rules:[22,23,26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},callback_name:{rules:[19,20,21,26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},href:{rules:[26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},struct:{rules:[26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},generic:{rules:[26,49,50,51,52,53,54,55,56,57,58,59,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},bqstring:{rules:[26,49,50,51,52,53,54,55,56,57,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},string:{rules:[24,25,26,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,86,87,88,89,90,91,92,93,94,95,97],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,8,10,13,14,15,16,17,18,26,27,28,29,38,49,50,51,52,53,54,55,56,57,60,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97],inclusive:!0}}};return Ue})();Je.lexer=Ce;function Fe(){this.yy={}}return o(Fe,"Parser"),Fe.prototype=Je,Je.Parser=Fe,new Fe})();uU.parser=uU;E_=uU});var z3e,OC,G3e=P(()=>{"use strict";Ut();Vr();z3e=["#","+","~","-",""],OC=class{static{o(this,"ClassMember")}constructor(e,r){this.memberType=r,this.visibility="",this.classifier="",this.text="";let i=Tr(e,ge());this.parseMember(i)}getDisplayDetails(){let e=this.visibility+ou(this.id);this.memberType==="method"&&(e+=`(${ou(this.parameters.trim())})`,this.returnType&&(e+=" : "+ou(this.returnType))),e=e.trim();let r=this.parseClassifier();return{displayText:e,cssStyle:r}}parseMember(e){let r="";if(this.memberType==="method"){let a=/([#+~-])?(.+)\((.*)\)([\s$*])?(.*)([$*])?/.exec(e);if(a){let s=a[1]?a[1].trim():"";if(z3e.includes(s)&&(this.visibility=s),this.id=a[2],this.parameters=a[3]?a[3].trim():"",r=a[4]?a[4].trim():"",this.returnType=a[5]?a[5].trim():"",r===""){let l=this.returnType.substring(this.returnType.length-1);/[$*]/.exec(l)&&(r=l,this.returnType=this.returnType.substring(0,this.returnType.length-1))}}}else{let n=e.length,a=e.substring(0,1),s=e.substring(n-1);z3e.includes(a)&&(this.visibility=a),/[$*]/.exec(s)&&(r=s),this.id=e.substring(this.visibility===""?0:1,r===""?n:n-1)}this.classifier=r,this.id=this.id.startsWith(" ")?" "+this.id.trim():this.id.trim();let i=`${this.visibility?"\\"+this.visibility:""}${ou(this.id)}${this.memberType==="method"?`(${ou(this.parameters)})${this.returnType?" : "+ou(this.returnType):""}`:""}`;this.text=i.replaceAll("<","<").replaceAll(">",">"),this.text.startsWith("\\<")&&(this.text=this.text.replace("\\<","~"))}parseClassifier(){switch(this.classifier){case"*":return"font-style:italic;";case"$":return"text-decoration:underline;";default:return""}}}});var S_,V3e,hg,tx,fU=P(()=>{"use strict";Pr();bt();Ut();Vr();er();Ki();y0();G3e();zx();S_="classId-",V3e=0,hg=o(t=>lt.sanitizeText(t,ge()),"sanitizeText"),tx=class{constructor(){this.relations=[];this.classes=new Map;this.styleClasses=new Map;this.notes=new Map;this.interfaces=[];this.namespaces=new Map;this.namespaceCounter=0;this.diagramId="";this.functions=[];this.lineType={LINE:0,DOTTED_LINE:1};this.relationType={AGGREGATION:0,EXTENSION:1,COMPOSITION:2,DEPENDENCY:3,LOLLIPOP:4};this.setupToolTips=o(e=>{let r=E3();Ze(e).select("svg").selectAll("g").filter(function(){return Ze(this).attr("title")!==null}).on("mouseover",a=>{let s=Ze(a.currentTarget),l=s.attr("title");if(!l)return;let u=a.currentTarget.getBoundingClientRect();r.transition().duration(200).style("opacity",".9"),r.html(Tl.sanitize(l)).style("left",`${window.scrollX+u.left+u.width/2}px`).style("top",`${window.scrollY+u.bottom+4}px`),s.classed("hover",!0)}).on("mouseout",a=>{r.transition().duration(500).style("opacity",0),Ze(a.currentTarget).classed("hover",!1)})},"setupToolTips");this.direction="TB";this.setAccTitle=Ar;this.getAccTitle=Dr;this.setAccDescription=Lr;this.getAccDescription=Rr;this.setDiagramTitle=Mr;this.getDiagramTitle=Nr;this.getConfig=o(()=>ge().class,"getConfig");this.functions.push(this.setupToolTips.bind(this)),this.clear(),this.addRelation=this.addRelation.bind(this),this.addClassesToNamespace=this.addClassesToNamespace.bind(this),this.addNamespace=this.addNamespace.bind(this),this.setCssClass=this.setCssClass.bind(this),this.addMembers=this.addMembers.bind(this),this.addClass=this.addClass.bind(this),this.setClassLabel=this.setClassLabel.bind(this),this.addAnnotation=this.addAnnotation.bind(this),this.addMember=this.addMember.bind(this),this.cleanupLabel=this.cleanupLabel.bind(this),this.addNote=this.addNote.bind(this),this.defineClass=this.defineClass.bind(this),this.setDirection=this.setDirection.bind(this),this.setLink=this.setLink.bind(this),this.bindFunctions=this.bindFunctions.bind(this),this.clear=this.clear.bind(this),this.setTooltip=this.setTooltip.bind(this),this.setClickEvent=this.setClickEvent.bind(this),this.setCssStyle=this.setCssStyle.bind(this)}static{o(this,"ClassDB")}splitClassNameAndType(e){let r=lt.sanitizeText(e,ge()),i="",n=r;if(r.indexOf("~")>0){let a=r.split("~");n=hg(a[0]),i=hg(a[1])}return{className:n,type:i}}setClassLabel(e,r){let i=lt.sanitizeText(e,ge());r&&(r=hg(r));let{className:n}=this.splitClassNameAndType(i);this.classes.get(n).label=r,this.classes.get(n).text=`${r}${this.classes.get(n).type?`<${this.classes.get(n).type}>`:""}`}addClass(e){let r=lt.sanitizeText(e,ge()),{className:i,type:n}=this.splitClassNameAndType(r);if(this.classes.has(i))return;let a=lt.sanitizeText(i,ge());this.classes.set(a,{id:a,type:n,label:a,text:`${a}${n?`<${n}>`:""}`,shape:"classBox",cssClasses:"default",methods:[],members:[],annotations:[],styles:[],domId:S_+a+"-"+V3e}),V3e++}addInterface(e,r){let i={id:`interface${this.interfaces.length}`,label:e,classId:r};this.interfaces.push(i)}setDiagramId(e){this.diagramId=e}lookUpDomId(e){let r=lt.sanitizeText(e,ge());if(this.classes.has(r)){let i=this.classes.get(r).domId;return this.diagramId?`${this.diagramId}-${i}`:i}throw new Error("Class not found: "+r)}clear(){this.relations=[],this.classes=new Map,this.notes=new Map,this.interfaces=[],this.functions=[],this.functions.push(this.setupToolTips.bind(this)),this.namespaces=new Map,this.namespaceCounter=0,this.diagramId="",this.direction="TB",wr()}getClass(e){return this.classes.get(e)}getClasses(){return this.classes}getRelations(){return this.relations}getNote(e){let r=typeof e=="number"?`note${e}`:e;return this.notes.get(r)}getNotes(){return this.notes}addRelation(e){Q.debug("Adding relation: "+JSON.stringify(e));let r=[this.relationType.LOLLIPOP,this.relationType.AGGREGATION,this.relationType.COMPOSITION,this.relationType.DEPENDENCY,this.relationType.EXTENSION];e.relation.type1===this.relationType.LOLLIPOP&&!r.includes(e.relation.type2)?(this.addClass(e.id2),this.addInterface(e.id1,e.id2),e.id1=`interface${this.interfaces.length-1}`):e.relation.type2===this.relationType.LOLLIPOP&&!r.includes(e.relation.type1)?(this.addClass(e.id1),this.addInterface(e.id2,e.id1),e.id2=`interface${this.interfaces.length-1}`):(this.addClass(e.id1),this.addClass(e.id2)),e.id1=this.splitClassNameAndType(e.id1).className,e.id2=this.splitClassNameAndType(e.id2).className,e.relationTitle1=lt.sanitizeText(e.relationTitle1.trim(),ge()),e.relationTitle2=lt.sanitizeText(e.relationTitle2.trim(),ge()),this.relations.push(e)}addAnnotation(e,r){let i=this.splitClassNameAndType(e).className;this.classes.get(i).annotations.push(r)}addMember(e,r){this.addClass(e);let i=this.splitClassNameAndType(e).className,n=this.classes.get(i);if(typeof r=="string"){let a=r.trim();a.startsWith("<<")&&a.endsWith(">>")?n.annotations.push(hg(a.substring(2,a.length-2))):a.indexOf(")")>0?n.methods.push(new OC(a,"method")):a&&n.members.push(new OC(a,"attribute"))}}addMembers(e,r){Array.isArray(r)&&(r.reverse(),r.forEach(i=>this.addMember(e,i)))}addNote(e,r){let i=this.notes.size,n={id:`note${i}`,class:r,text:e,index:i};return this.notes.set(n.id,n),n.id}cleanupLabel(e){return e.startsWith(":")&&(e=e.substring(1)),hg(e.trim())}setCssClass(e,r){e.split(",").forEach(i=>{let n=i;/\d/.exec(i[0])&&(n=S_+n);let a=this.classes.get(n);a&&(a.cssClasses+=" "+r)})}defineClass(e,r){for(let i of e){let n=this.styleClasses.get(i);n===void 0&&(n={id:i,styles:[],textStyles:[]},this.styleClasses.set(i,n)),r&&r.forEach(a=>{if(/color/.exec(a)){let s=a.replace("fill","bgFill");n.textStyles.push(s)}n.styles.push(a)}),this.classes.forEach(a=>{a.cssClasses.includes(i)&&a.styles.push(...r.flatMap(s=>s.split(",")))})}}setTooltip(e,r){e.split(",").forEach(i=>{r!==void 0&&(this.classes.get(i).tooltip=hg(r))})}getTooltip(e,r){return r&&this.namespaces.has(r)?this.namespaces.get(r).classes.get(e).tooltip:this.classes.get(e).tooltip}setLink(e,r,i){let n=ge();e.split(",").forEach(a=>{let s=a;/\d/.exec(a[0])&&(s=S_+s);let l=this.classes.get(s);l&&(l.link=Kt.formatUrl(r,n),n.securityLevel==="sandbox"?l.linkTarget="_top":typeof i=="string"?l.linkTarget=hg(i):l.linkTarget="_blank")}),this.setCssClass(e,"clickable")}setClickEvent(e,r,i){e.split(",").forEach(n=>{this.setClickFunc(n,r,i),this.classes.get(n).haveCallback=!0}),this.setCssClass(e,"clickable")}setClickFunc(e,r,i){let n=lt.sanitizeText(e,ge());if(ge().securityLevel!=="loose"||r===void 0)return;let s=n;if(this.classes.has(s)){let l=[];if(typeof i=="string"){l=i.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);for(let u=0;u{let u=this.lookUpDomId(s),h=document.querySelector(`[id="${u}"]`);h!==null&&h.addEventListener("click",()=>{Kt.runFunc(r,...l)},!1)})}}bindFunctions(e){this.functions.forEach(r=>{r(e)})}escapeHtml(e){return e.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")}getDirection(){return this.direction}setDirection(e){this.direction=e}addNamespace(e){this.namespaces.has(e)||(this.namespaces.set(e,{id:e,classes:new Map,notes:new Map,children:new Map,domId:S_+e+"-"+this.namespaceCounter}),this.namespaceCounter++)}getNamespace(e){return this.namespaces.get(e)}getNamespaces(){return this.namespaces}addClassesToNamespace(e,r,i){if(this.namespaces.has(e)){for(let n of r){let{className:a}=this.splitClassNameAndType(n),s=this.getClass(a);s.parent=e,this.namespaces.get(e).classes.set(a,s)}for(let n of i){let a=this.getNote(n);a.parent=e,this.namespaces.get(e).notes.set(n,a)}}}setCssStyle(e,r){let i=this.classes.get(e);if(!(!r||!i))for(let n of r)n.includes(",")?i.styles.push(...n.split(",")):i.styles.push(n)}getArrowMarker(e){let r;switch(e){case 0:r="aggregation";break;case 1:r="extension";break;case 2:r="composition";break;case 3:r="dependency";break;case 4:r="lollipop";break;default:r="none"}return r}getData(){let e=[],r=[],i=ge();for(let a of this.namespaces.values()){let s={id:a.id,label:a.id,isGroup:!0,padding:i.class.padding??16,shape:"rect",cssStyles:[],look:i.look};e.push(s)}for(let a of this.classes.values()){let s={...a,type:void 0,isGroup:!1,parentId:a.parent,look:i.look};e.push(s)}for(let a of this.notes.values()){let s={id:a.id,label:a.text,isGroup:!1,shape:"note",padding:i.class.padding??6,cssStyles:["text-align: left","white-space: nowrap",`fill: ${i.themeVariables.noteBkgColor}`,`stroke: ${i.themeVariables.noteBorderColor}`],look:i.look,parentId:a.parent,labelType:"markdown"};e.push(s);let l=this.classes.get(a.class)?.id;if(l){let u={id:`edgeNote${a.index}`,start:a.id,end:l,type:"normal",thickness:"normal",classes:"relation",arrowTypeStart:"none",arrowTypeEnd:"none",arrowheadStyle:"",labelStyle:[""],style:["fill: none"],pattern:"dotted",look:i.look};r.push(u)}}for(let a of this.interfaces){let s={id:a.id,label:a.label,isGroup:!1,shape:"rect",cssStyles:["opacity: 0;"],look:i.look};e.push(s)}let n=0;for(let a of this.relations){n++;let s={id:Cu(a.id1,a.id2,{prefix:"id",counter:n}),start:a.id1,end:a.id2,type:"normal",label:a.title,labelpos:"c",thickness:"normal",classes:"relation",arrowTypeStart:this.getArrowMarker(a.relation.type1),arrowTypeEnd:this.getArrowMarker(a.relation.type2),startLabelRight:a.relationTitle1==="none"?"":a.relationTitle1,endLabelLeft:a.relationTitle2==="none"?"":a.relationTitle2,arrowheadStyle:"",labelStyle:["display: inline-block"],style:a.style||"",pattern:a.relation.lineType==1?"dashed":"solid",look:i.look,labelType:"markdown"};r.push(s)}return{nodes:e,edges:r,other:{},config:i,direction:this.getDirection()}}}});var _ft,A_,dU=P(()=>{"use strict";wy();_ft=o(t=>`g.classGroup text { + fill: ${t.nodeBorder||t.classText}; + stroke: none; + font-family: ${t.fontFamily}; + font-size: 10px; + + .title { + font-weight: bolder; + } + +} + + .cluster-label text { + fill: ${t.titleColor}; + } + .cluster-label span { + color: ${t.titleColor}; + } + .cluster-label span p { + background-color: transparent; + } + + .cluster rect { + fill: ${t.clusterBkg}; + stroke: ${t.clusterBorder}; + stroke-width: 1px; + } + + .cluster text { + fill: ${t.titleColor}; + } + + .cluster span { + color: ${t.titleColor}; + } + +.nodeLabel, .edgeLabel { + color: ${t.classText}; +} + +.noteLabel .nodeLabel, .noteLabel .edgeLabel { + color: ${t.noteTextColor}; +} +.edgeLabel .label rect { + fill: ${t.mainBkg}; +} +.label text { + fill: ${t.classText}; +} + +.labelBkg { + background: ${t.mainBkg}; +} +.edgeLabel .label span { + background: ${t.mainBkg}; +} + +.classTitle { + font-weight: bolder; +} +.node rect, + .node circle, + .node ellipse, + .node polygon, + .node path { + fill: ${t.mainBkg}; + stroke: ${t.nodeBorder}; + stroke-width: ${t.strokeWidth}; + } + + +.divider { + stroke: ${t.nodeBorder}; + stroke-width: 1; +} + +g.clickable { + cursor: pointer; +} + +g.classGroup rect { + fill: ${t.mainBkg}; + stroke: ${t.nodeBorder}; +} + +g.classGroup line { + stroke: ${t.nodeBorder}; + stroke-width: 1; +} + +.classLabel .box { + stroke: none; + stroke-width: 0; + fill: ${t.mainBkg}; + opacity: 0.5; +} + +.classLabel .label { + fill: ${t.nodeBorder}; + font-size: 10px; +} + +.relation { + stroke: ${t.lineColor}; + stroke-width: ${t.strokeWidth}; + fill: none; +} + +.dashed-line{ + stroke-dasharray: 3; +} + +.dotted-line{ + stroke-dasharray: 1 2; +} + +[id$="-compositionStart"], .composition { + fill: ${t.lineColor} !important; + stroke: ${t.lineColor} !important; + stroke-width: 1; +} + +[id$="-compositionEnd"], .composition { + fill: ${t.lineColor} !important; + stroke: ${t.lineColor} !important; + stroke-width: 1; +} + +[id$="-dependencyStart"], .dependency { + fill: ${t.lineColor} !important; + stroke: ${t.lineColor} !important; + stroke-width: 1; +} + +[id$="-dependencyEnd"], .dependency { + fill: ${t.lineColor} !important; + stroke: ${t.lineColor} !important; + stroke-width: 1; +} + +[id$="-extensionStart"], .extension { + fill: transparent !important; + stroke: ${t.lineColor} !important; + stroke-width: 1; +} + +[id$="-extensionEnd"], .extension { + fill: transparent !important; + stroke: ${t.lineColor} !important; + stroke-width: 1; +} + +[id$="-aggregationStart"], .aggregation { + fill: transparent !important; + stroke: ${t.lineColor} !important; + stroke-width: 1; +} + +[id$="-aggregationEnd"], .aggregation { + fill: transparent !important; + stroke: ${t.lineColor} !important; + stroke-width: 1; +} + +[id$="-lollipopStart"], .lollipop { + fill: ${t.mainBkg} !important; + stroke: ${t.lineColor} !important; + stroke-width: 1; +} + +[id$="-lollipopEnd"], .lollipop { + fill: ${t.mainBkg} !important; + stroke: ${t.lineColor} !important; + stroke-width: 1; +} + +.edgeTerminals { + font-size: 11px; + line-height: initial; +} + +.classTitleText { + text-anchor: middle; + font-size: 18px; + fill: ${t.textColor}; +} + +.edgeLabel[data-look="neo"] { + background-color: ${t.edgeLabelBackground}; + p { + background-color: ${t.edgeLabelBackground}; + } + rect { + opacity: 0.5; + background-color: ${t.edgeLabelBackground}; + fill: ${t.edgeLabelBackground}; + } + text-align: center; +} + ${qu()} +`,"getStyles"),A_=_ft});var Dft,Lft,Rft,__,pU=P(()=>{"use strict";Ut();bt();I0();Wd();Ud();er();Dft=o((t,e="TB")=>{if(!t.doc)return e;let r=e;for(let i of t.doc)i.stmt==="dir"&&(r=i.value);return r},"getDir"),Lft=o(function(t,e){return e.db.getClasses()},"getClasses"),Rft=o(async function(t,e,r,i){Q.info("REF0:"),Q.info("Drawing class diagram (v3)",e);let{securityLevel:n,state:a,layout:s}=ge();i.db.setDiagramId(e);let l=i.db.getData(),u=Ol(e,n);l.type=i.type,l.layoutAlgorithm=Vu(s),l.nodeSpacing=a?.nodeSpacing||50,l.rankSpacing=a?.rankSpacing||50,l.markers=["aggregation","extension","composition","dependency","lollipop"],l.diagramId=e,await Ul(l,u);let h=8;Kt.insertTitle(u,"classDiagramTitleText",a?.titleTopMargin??25,i.db.getDiagramTitle()),Ro(u,h,"classDiagram",a?.useMaxWidth??!0)},"draw"),__={getClasses:Lft,draw:Rft,getDir:Dft}});var q3e={};ur(q3e,{diagram:()=>Nft});var Nft,W3e=P(()=>{"use strict";hU();fU();dU();pU();Nft={parser:E_,get db(){return new tx},renderer:__,styles:A_,init:o(t=>{t.class||(t.class={}),t.class.arrowMarkerAbsolute=t.arrowMarkerAbsolute},"init")}});var Y3e={};ur(Y3e,{diagram:()=>Pft});var Pft,j3e=P(()=>{"use strict";hU();fU();dU();pU();Pft={parser:E_,get db(){return new tx},renderer:__,styles:A_,init:o(t=>{t.class||(t.class={}),t.class.arrowMarkerAbsolute=t.arrowMarkerAbsolute},"init")}});var mU,D_,gU=P(()=>{"use strict";mU=(function(){var t=o(function($,z,F,V){for(F=F||{},V=$.length;V--;F[$[V]]=z);return F},"o"),e=[1,2],r=[1,3],i=[1,4],n=[2,4],a=[1,9],s=[1,11],l=[1,16],u=[1,17],h=[1,18],f=[1,19],d=[1,33],p=[1,20],m=[1,21],g=[1,22],y=[1,23],v=[1,24],x=[1,26],b=[1,27],T=[1,28],w=[1,29],k=[1,30],C=[1,31],E=[1,32],S=[1,35],L=[1,36],M=[1,37],I=[1,38],A=[1,34],_=[1,4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],D=[1,4,5,14,15,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,39,40,41,45,48,51,52,53,54,57],N=[4,5,16,17,19,21,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],R={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,SPACE:4,NL:5,SD:6,document:7,line:8,statement:9,classDefStatement:10,styleStatement:11,cssClassStatement:12,idStatement:13,DESCR:14,"-->":15,HIDE_EMPTY:16,scale:17,WIDTH:18,COMPOSIT_STATE:19,STRUCT_START:20,STRUCT_STOP:21,STATE_DESCR:22,AS:23,ID:24,FORK:25,JOIN:26,CHOICE:27,CONCURRENT:28,note:29,notePosition:30,NOTE_TEXT:31,direction:32,acc_title:33,acc_title_value:34,acc_descr:35,acc_descr_value:36,acc_descr_multiline_value:37,CLICK:38,STRING:39,HREF:40,classDef:41,CLASSDEF_ID:42,CLASSDEF_STYLEOPTS:43,DEFAULT:44,style:45,STYLE_IDS:46,STYLEDEF_STYLEOPTS:47,class:48,CLASSENTITY_IDS:49,STYLECLASS:50,direction_tb:51,direction_bt:52,direction_rl:53,direction_lr:54,eol:55,";":56,EDGE_STATE:57,STYLE_SEPARATOR:58,left_of:59,right_of:60,$accept:0,$end:1},terminals_:{2:"error",4:"SPACE",5:"NL",6:"SD",14:"DESCR",15:"-->",16:"HIDE_EMPTY",17:"scale",18:"WIDTH",19:"COMPOSIT_STATE",20:"STRUCT_START",21:"STRUCT_STOP",22:"STATE_DESCR",23:"AS",24:"ID",25:"FORK",26:"JOIN",27:"CHOICE",28:"CONCURRENT",29:"note",31:"NOTE_TEXT",33:"acc_title",34:"acc_title_value",35:"acc_descr",36:"acc_descr_value",37:"acc_descr_multiline_value",38:"CLICK",39:"STRING",40:"HREF",41:"classDef",42:"CLASSDEF_ID",43:"CLASSDEF_STYLEOPTS",44:"DEFAULT",45:"style",46:"STYLE_IDS",47:"STYLEDEF_STYLEOPTS",48:"class",49:"CLASSENTITY_IDS",50:"STYLECLASS",51:"direction_tb",52:"direction_bt",53:"direction_rl",54:"direction_lr",56:";",57:"EDGE_STATE",58:"STYLE_SEPARATOR",59:"left_of",60:"right_of"},productions_:[0,[3,2],[3,2],[3,2],[7,0],[7,2],[8,2],[8,1],[8,1],[9,1],[9,1],[9,1],[9,1],[9,2],[9,3],[9,4],[9,1],[9,2],[9,1],[9,4],[9,3],[9,6],[9,1],[9,1],[9,1],[9,1],[9,4],[9,4],[9,1],[9,2],[9,2],[9,1],[9,5],[9,5],[10,3],[10,3],[11,3],[12,3],[32,1],[32,1],[32,1],[32,1],[55,1],[55,1],[13,1],[13,1],[13,3],[13,3],[30,1],[30,1]],performAction:o(function(z,F,V,H,X,W,Z){var Y=W.length-1;switch(X){case 3:return H.setRootDoc(W[Y]),W[Y];break;case 4:this.$=[];break;case 5:W[Y]!="nl"&&(W[Y-1].push(W[Y]),this.$=W[Y-1]);break;case 6:case 7:this.$=W[Y];break;case 8:this.$="nl";break;case 12:this.$=W[Y];break;case 13:let re=W[Y-1];re.description=H.trimColon(W[Y]),this.$=re;break;case 14:this.$={stmt:"relation",state1:W[Y-2],state2:W[Y]};break;case 15:let te=H.trimColon(W[Y]);this.$={stmt:"relation",state1:W[Y-3],state2:W[Y-1],description:te};break;case 19:this.$={stmt:"state",id:W[Y-3],type:"default",description:"",doc:W[Y-1]};break;case 20:var ae=W[Y],J=W[Y-2].trim();if(W[Y].match(":")){var ee=W[Y].split(":");ae=ee[0],J=[J,ee[1]]}this.$={stmt:"state",id:ae,type:"default",description:J};break;case 21:this.$={stmt:"state",id:W[Y-3],type:"default",description:W[Y-5],doc:W[Y-1]};break;case 22:this.$={stmt:"state",id:W[Y],type:"fork"};break;case 23:this.$={stmt:"state",id:W[Y],type:"join"};break;case 24:this.$={stmt:"state",id:W[Y],type:"choice"};break;case 25:this.$={stmt:"state",id:H.getDividerId(),type:"divider"};break;case 26:this.$={stmt:"state",id:W[Y-1].trim(),note:{position:W[Y-2].trim(),text:W[Y].trim()}};break;case 29:this.$=W[Y].trim(),H.setAccTitle(this.$);break;case 30:case 31:this.$=W[Y].trim(),H.setAccDescription(this.$);break;case 32:this.$={stmt:"click",id:W[Y-3],url:W[Y-2],tooltip:W[Y-1]};break;case 33:this.$={stmt:"click",id:W[Y-3],url:W[Y-1],tooltip:""};break;case 34:case 35:this.$={stmt:"classDef",id:W[Y-1].trim(),classes:W[Y].trim()};break;case 36:this.$={stmt:"style",id:W[Y-1].trim(),styleClass:W[Y].trim()};break;case 37:this.$={stmt:"applyClass",id:W[Y-1].trim(),styleClass:W[Y].trim()};break;case 38:H.setDirection("TB"),this.$={stmt:"dir",value:"TB"};break;case 39:H.setDirection("BT"),this.$={stmt:"dir",value:"BT"};break;case 40:H.setDirection("RL"),this.$={stmt:"dir",value:"RL"};break;case 41:H.setDirection("LR"),this.$={stmt:"dir",value:"LR"};break;case 44:case 45:this.$={stmt:"state",id:W[Y].trim(),type:"default",description:""};break;case 46:this.$={stmt:"state",id:W[Y-2].trim(),classes:[W[Y].trim()],type:"default",description:""};break;case 47:this.$={stmt:"state",id:W[Y-2].trim(),classes:[W[Y].trim()],type:"default",description:""};break}},"anonymous"),table:[{3:1,4:e,5:r,6:i},{1:[3]},{3:5,4:e,5:r,6:i},{3:6,4:e,5:r,6:i},t([1,4,5,16,17,19,22,24,25,26,27,28,29,33,35,37,38,41,45,48,51,52,53,54,57],n,{7:7}),{1:[2,1]},{1:[2,2]},{1:[2,3],4:a,5:s,8:8,9:10,10:12,11:13,12:14,13:15,16:l,17:u,19:h,22:f,24:d,25:p,26:m,27:g,28:y,29:v,32:25,33:x,35:b,37:T,38:w,41:k,45:C,48:E,51:S,52:L,53:M,54:I,57:A},t(_,[2,5]),{9:39,10:12,11:13,12:14,13:15,16:l,17:u,19:h,22:f,24:d,25:p,26:m,27:g,28:y,29:v,32:25,33:x,35:b,37:T,38:w,41:k,45:C,48:E,51:S,52:L,53:M,54:I,57:A},t(_,[2,7]),t(_,[2,8]),t(_,[2,9]),t(_,[2,10]),t(_,[2,11]),t(_,[2,12],{14:[1,40],15:[1,41]}),t(_,[2,16]),{18:[1,42]},t(_,[2,18],{20:[1,43]}),{23:[1,44]},t(_,[2,22]),t(_,[2,23]),t(_,[2,24]),t(_,[2,25]),{30:45,31:[1,46],59:[1,47],60:[1,48]},t(_,[2,28]),{34:[1,49]},{36:[1,50]},t(_,[2,31]),{13:51,24:d,57:A},{42:[1,52],44:[1,53]},{46:[1,54]},{49:[1,55]},t(D,[2,44],{58:[1,56]}),t(D,[2,45],{58:[1,57]}),t(_,[2,38]),t(_,[2,39]),t(_,[2,40]),t(_,[2,41]),t(_,[2,6]),t(_,[2,13]),{13:58,24:d,57:A},t(_,[2,17]),t(N,n,{7:59}),{24:[1,60]},{24:[1,61]},{23:[1,62]},{24:[2,48]},{24:[2,49]},t(_,[2,29]),t(_,[2,30]),{39:[1,63],40:[1,64]},{43:[1,65]},{43:[1,66]},{47:[1,67]},{50:[1,68]},{24:[1,69]},{24:[1,70]},t(_,[2,14],{14:[1,71]}),{4:a,5:s,8:8,9:10,10:12,11:13,12:14,13:15,16:l,17:u,19:h,21:[1,72],22:f,24:d,25:p,26:m,27:g,28:y,29:v,32:25,33:x,35:b,37:T,38:w,41:k,45:C,48:E,51:S,52:L,53:M,54:I,57:A},t(_,[2,20],{20:[1,73]}),{31:[1,74]},{24:[1,75]},{39:[1,76]},{39:[1,77]},t(_,[2,34]),t(_,[2,35]),t(_,[2,36]),t(_,[2,37]),t(D,[2,46]),t(D,[2,47]),t(_,[2,15]),t(_,[2,19]),t(N,n,{7:78}),t(_,[2,26]),t(_,[2,27]),{5:[1,79]},{5:[1,80]},{4:a,5:s,8:8,9:10,10:12,11:13,12:14,13:15,16:l,17:u,19:h,21:[1,81],22:f,24:d,25:p,26:m,27:g,28:y,29:v,32:25,33:x,35:b,37:T,38:w,41:k,45:C,48:E,51:S,52:L,53:M,54:I,57:A},t(_,[2,32]),t(_,[2,33]),t(_,[2,21])],defaultActions:{5:[2,1],6:[2,2],47:[2,48],48:[2,49]},parseError:o(function(z,F){if(F.recoverable)this.trace(z);else{var V=new Error(z);throw V.hash=F,V}},"parseError"),parse:o(function(z){var F=this,V=[0],H=[],X=[null],W=[],Z=this.table,Y="",ae=0,J=0,ee=0,re=2,te=1,be=W.slice.call(arguments,1),de=Object.create(this.lexer),Ee={yy:{}};for(var Ne in this.yy)Object.prototype.hasOwnProperty.call(this.yy,Ne)&&(Ee.yy[Ne]=this.yy[Ne]);de.setInput(z,Ee.yy),Ee.yy.lexer=de,Ee.yy.parser=this,typeof de.yylloc>"u"&&(de.yylloc={});var we=de.yylloc;W.push(we);var Te=de.options&&de.options.ranges;typeof Ee.yy.parseError=="function"?this.parseError=Ee.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function De(G){V.length=V.length-2*G,X.length=X.length-G,W.length=W.length-G}o(De,"popStack");function $e(){var G;return G=H.pop()||de.lex()||te,typeof G!="number"&&(G instanceof Array&&(H=G,G=H.pop()),G=F.symbols_[G]||G),G}o($e,"lex");for(var pe,Je,Ce,Fe,Ue,qe,Me={},He,K,oe,U;;){if(Ce=V[V.length-1],this.defaultActions[Ce]?Fe=this.defaultActions[Ce]:((pe===null||typeof pe>"u")&&(pe=$e()),Fe=Z[Ce]&&Z[Ce][pe]),typeof Fe>"u"||!Fe.length||!Fe[0]){var ue="";U=[];for(He in Z[Ce])this.terminals_[He]&&He>re&&U.push("'"+this.terminals_[He]+"'");de.showPosition?ue="Parse error on line "+(ae+1)+`: +`+de.showPosition()+` +Expecting `+U.join(", ")+", got '"+(this.terminals_[pe]||pe)+"'":ue="Parse error on line "+(ae+1)+": Unexpected "+(pe==te?"end of input":"'"+(this.terminals_[pe]||pe)+"'"),this.parseError(ue,{text:de.match,token:this.terminals_[pe]||pe,line:de.yylineno,loc:we,expected:U})}if(Fe[0]instanceof Array&&Fe.length>1)throw new Error("Parse Error: multiple actions possible at state: "+Ce+", token: "+pe);switch(Fe[0]){case 1:V.push(pe),X.push(de.yytext),W.push(de.yylloc),V.push(Fe[1]),pe=null,Je?(pe=Je,Je=null):(J=de.yyleng,Y=de.yytext,ae=de.yylineno,we=de.yylloc,ee>0&&ee--);break;case 2:if(K=this.productions_[Fe[1]][1],Me.$=X[X.length-K],Me._$={first_line:W[W.length-(K||1)].first_line,last_line:W[W.length-1].last_line,first_column:W[W.length-(K||1)].first_column,last_column:W[W.length-1].last_column},Te&&(Me._$.range=[W[W.length-(K||1)].range[0],W[W.length-1].range[1]]),qe=this.performAction.apply(Me,[Y,J,ae,Ee.yy,Fe[1],X,W].concat(be)),typeof qe<"u")return qe;K&&(V=V.slice(0,-1*K*2),X=X.slice(0,-1*K),W=W.slice(0,-1*K)),V.push(this.productions_[Fe[1]][0]),X.push(Me.$),W.push(Me._$),oe=Z[V[V.length-2]][V[V.length-1]],V.push(oe);break;case 3:return!0}}return!0},"parse")},B=(function(){var $={EOF:1,parseError:o(function(F,V){if(this.yy.parser)this.yy.parser.parseError(F,V);else throw new Error(F)},"parseError"),setInput:o(function(z,F){return this.yy=F||this.yy||{},this._input=z,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var z=this._input[0];this.yytext+=z,this.yyleng++,this.offset++,this.match+=z,this.matched+=z;var F=z.match(/(?:\r\n?|\n).*/g);return F?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),z},"input"),unput:o(function(z){var F=z.length,V=z.split(/(?:\r\n?|\n)/g);this._input=z+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-F),this.offset-=F;var H=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),V.length-1&&(this.yylineno-=V.length-1);var X=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:V?(V.length===H.length?this.yylloc.first_column:0)+H[H.length-V.length].length-V[0].length:this.yylloc.first_column-F},this.options.ranges&&(this.yylloc.range=[X[0],X[0]+this.yyleng-F]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(z){this.unput(this.match.slice(z))},"less"),pastInput:o(function(){var z=this.matched.substr(0,this.matched.length-this.match.length);return(z.length>20?"...":"")+z.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var z=this.match;return z.length<20&&(z+=this._input.substr(0,20-z.length)),(z.substr(0,20)+(z.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var z=this.pastInput(),F=new Array(z.length+1).join("-");return z+this.upcomingInput()+` +`+F+"^"},"showPosition"),test_match:o(function(z,F){var V,H,X;if(this.options.backtrack_lexer&&(X={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(X.yylloc.range=this.yylloc.range.slice(0))),H=z[0].match(/(?:\r\n?|\n).*/g),H&&(this.yylineno+=H.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:H?H[H.length-1].length-H[H.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+z[0].length},this.yytext+=z[0],this.match+=z[0],this.matches=z,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(z[0].length),this.matched+=z[0],V=this.performAction.call(this,this.yy,this,F,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),V)return V;if(this._backtrack){for(var W in X)this[W]=X[W];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var z,F,V,H;this._more||(this.yytext="",this.match="");for(var X=this._currentRules(),W=0;WF[0].length)){if(F=V,H=W,this.options.backtrack_lexer){if(z=this.test_match(V,X[W]),z!==!1)return z;if(this._backtrack){F=!1;continue}else return!1}else if(!this.options.flex)break}return F?(z=this.test_match(F,X[H]),z!==!1?z:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var F=this.next();return F||this.lex()},"lex"),begin:o(function(F){this.conditionStack.push(F)},"begin"),popState:o(function(){var F=this.conditionStack.length-1;return F>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(F){return F=this.conditionStack.length-1-Math.abs(F||0),F>=0?this.conditionStack[F]:"INITIAL"},"topState"),pushState:o(function(F){this.begin(F)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:o(function(F,V,H,X){var W=X;switch(H){case 0:return 38;case 1:return 40;case 2:return 39;case 3:return 44;case 4:return 51;case 5:return 52;case 6:return 53;case 7:return 54;case 8:break;case 9:break;case 10:return 5;case 11:break;case 12:break;case 13:break;case 14:break;case 15:return this.pushState("SCALE"),17;break;case 16:return 18;case 17:this.popState();break;case 18:return this.begin("acc_title"),33;break;case 19:return this.popState(),"acc_title_value";break;case 20:return this.begin("acc_descr"),35;break;case 21:return this.popState(),"acc_descr_value";break;case 22:this.begin("acc_descr_multiline");break;case 23:this.popState();break;case 24:return"acc_descr_multiline_value";case 25:return this.pushState("CLASSDEF"),41;break;case 26:return this.popState(),this.pushState("CLASSDEFID"),"DEFAULT_CLASSDEF_ID";break;case 27:return this.popState(),this.pushState("CLASSDEFID"),42;break;case 28:return this.popState(),43;break;case 29:return this.pushState("CLASS"),48;break;case 30:return this.popState(),this.pushState("CLASS_STYLE"),49;break;case 31:return this.popState(),50;break;case 32:return this.pushState("STYLE"),45;break;case 33:return this.popState(),this.pushState("STYLEDEF_STYLES"),46;break;case 34:return this.popState(),47;break;case 35:return this.pushState("SCALE"),17;break;case 36:return 18;case 37:this.popState();break;case 38:this.pushState("STATE");break;case 39:return this.popState(),V.yytext=V.yytext.slice(0,-8).trim(),25;break;case 40:return this.popState(),V.yytext=V.yytext.slice(0,-8).trim(),26;break;case 41:return this.popState(),V.yytext=V.yytext.slice(0,-10).trim(),27;break;case 42:return this.popState(),V.yytext=V.yytext.slice(0,-8).trim(),25;break;case 43:return this.popState(),V.yytext=V.yytext.slice(0,-8).trim(),26;break;case 44:return this.popState(),V.yytext=V.yytext.slice(0,-10).trim(),27;break;case 45:return 51;case 46:return 52;case 47:return 53;case 48:return 54;case 49:this.pushState("STATE_STRING");break;case 50:return this.pushState("STATE_ID"),"AS";break;case 51:return this.popState(),"ID";break;case 52:this.popState();break;case 53:return"STATE_DESCR";case 54:return 19;case 55:this.popState();break;case 56:return this.popState(),this.pushState("struct"),20;break;case 57:break;case 58:return this.popState(),21;break;case 59:break;case 60:return this.begin("NOTE"),29;break;case 61:return this.popState(),this.pushState("NOTE_ID"),59;break;case 62:return this.popState(),this.pushState("NOTE_ID"),60;break;case 63:this.popState(),this.pushState("FLOATING_NOTE");break;case 64:return this.popState(),this.pushState("FLOATING_NOTE_ID"),"AS";break;case 65:break;case 66:return"NOTE_TEXT";case 67:return this.popState(),"ID";break;case 68:return this.popState(),this.pushState("NOTE_TEXT"),24;break;case 69:return this.popState(),V.yytext=V.yytext.substr(2).trim(),31;break;case 70:return this.popState(),V.yytext=V.yytext.slice(0,-8).trim(),31;break;case 71:return 6;case 72:return 6;case 73:return 16;case 74:return 57;case 75:return 24;case 76:return V.yytext=V.yytext.trim(),14;break;case 77:return 15;case 78:return 28;case 79:return 58;case 80:return 5;case 81:return"INVALID"}},"anonymous"),rules:[/^(?:click\b)/i,/^(?:href\b)/i,/^(?:"[^"]*")/i,/^(?:default\b)/i,/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:%%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n]+)/i,/^(?:[\s]+)/i,/^(?:((?!\n)\s)+)/i,/^(?:#[^\n]*)/i,/^(?:%[^\n]*)/i,/^(?:scale\s+)/i,/^(?:\d+)/i,/^(?:\s+width\b)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:classDef\s+)/i,/^(?:DEFAULT\s+)/i,/^(?:\w+\s+)/i,/^(?:[^\n]*)/i,/^(?:class\s+)/i,/^(?:(\w+)+((,\s*\w+)*))/i,/^(?:[^\n]*)/i,/^(?:style\s+)/i,/^(?:[\w,]+\s+)/i,/^(?:[^\n]*)/i,/^(?:scale\s+)/i,/^(?:\d+)/i,/^(?:\s+width\b)/i,/^(?:state\s+)/i,/^(?:.*<>)/i,/^(?:.*<>)/i,/^(?:.*<>)/i,/^(?:.*\[\[fork\]\])/i,/^(?:.*\[\[join\]\])/i,/^(?:.*\[\[choice\]\])/i,/^(?:.*direction\s+TB[^\n]*)/i,/^(?:.*direction\s+BT[^\n]*)/i,/^(?:.*direction\s+RL[^\n]*)/i,/^(?:.*direction\s+LR[^\n]*)/i,/^(?:["])/i,/^(?:\s*as\s+)/i,/^(?:[^\n\{]*)/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[^\n\s\{]+)/i,/^(?:\n)/i,/^(?:\{)/i,/^(?:%%(?!\{)[^\n]*)/i,/^(?:\})/i,/^(?:[\n])/i,/^(?:note\s+)/i,/^(?:left of\b)/i,/^(?:right of\b)/i,/^(?:")/i,/^(?:\s*as\s*)/i,/^(?:["])/i,/^(?:[^"]*)/i,/^(?:[^\n]*)/i,/^(?:\s*[^:\n\s\-]+)/i,/^(?:\s*:[^:\n;]+)/i,/^(?:[\s\S]*?end note\b)/i,/^(?:stateDiagram\s+)/i,/^(?:stateDiagram-v2\s+)/i,/^(?:hide empty description\b)/i,/^(?:\[\*\])/i,/^(?:[^:\n\s\-\{]+)/i,/^(?:\s*:(?:[^:\n;]|:[^:\n;])+)/i,/^(?:-->)/i,/^(?:--)/i,/^(?::::)/i,/^(?:$)/i,/^(?:.)/i],conditions:{LINE:{rules:[12,13],inclusive:!1},struct:{rules:[12,13,25,29,32,38,45,46,47,48,57,58,59,60,74,75,76,77,78,79],inclusive:!1},FLOATING_NOTE_ID:{rules:[67],inclusive:!1},FLOATING_NOTE:{rules:[64,65,66],inclusive:!1},NOTE_TEXT:{rules:[69,70],inclusive:!1},NOTE_ID:{rules:[68],inclusive:!1},NOTE:{rules:[61,62,63],inclusive:!1},STYLEDEF_STYLEOPTS:{rules:[],inclusive:!1},STYLEDEF_STYLES:{rules:[34],inclusive:!1},STYLE_IDS:{rules:[],inclusive:!1},STYLE:{rules:[33],inclusive:!1},CLASS_STYLE:{rules:[31],inclusive:!1},CLASS:{rules:[30],inclusive:!1},CLASSDEFID:{rules:[28],inclusive:!1},CLASSDEF:{rules:[26,27],inclusive:!1},acc_descr_multiline:{rules:[23,24],inclusive:!1},acc_descr:{rules:[21],inclusive:!1},acc_title:{rules:[19],inclusive:!1},SCALE:{rules:[16,17,36,37],inclusive:!1},ALIAS:{rules:[],inclusive:!1},STATE_ID:{rules:[51],inclusive:!1},STATE_STRING:{rules:[52,53],inclusive:!1},FORK_STATE:{rules:[],inclusive:!1},STATE:{rules:[12,13,39,40,41,42,43,44,49,50,54,55,56],inclusive:!1},ID:{rules:[12,13],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,13,14,15,18,20,22,25,29,32,35,38,56,60,71,72,73,74,75,76,77,79,80,81],inclusive:!0}}};return $})();R.lexer=B;function O(){this.yy={}}return o(O,"Parser"),O.prototype=R,R.Parser=O,new O})();mU.parser=mU;D_=mU});var Dp,fg,PC,Q3e,Z3e,J3e,dg,L_,yU,vU,xU,bU,R_,N_,e5e,t5e,TU,kU,r5e,i5e,rx,zft,n5e,CU,Gft,Vft,a5e,s5e,qft,o5e,Wft,l5e,wU,EU,c5e,I_,u5e,SU,M_=P(()=>{"use strict";Dp="state",fg="root",PC="relation",Q3e="classDef",Z3e="style",J3e="applyClass",dg="default",L_="divider",yU="fill:none",vU="fill: #333",xU="markdown",bU="normal",R_="rect",N_="rectWithTitle",e5e="stateStart",t5e="stateEnd",TU="divider",kU="roundedWithTitle",r5e="note",i5e="noteGroup",rx="statediagram",zft="state",n5e=`${rx}-${zft}`,CU="transition",Gft="note",Vft="note-edge",a5e=`${CU} ${Vft}`,s5e=`${rx}-${Gft}`,qft="cluster",o5e=`${rx}-${qft}`,Wft="cluster-alt",l5e=`${rx}-${Wft}`,wU="parent",EU="note",c5e="state",I_="----",u5e=`${I_}${EU}`,SU=`${I_}${wU}`});function AU(t="",e=0,r="",i=I_){let n=r!==null&&r.length>0?`${i}${r}`:"";return`${c5e}-${t}${n}-${e}`}function O_(t,e,r){if(!e.id||e.id===""||e.id==="")return;e.cssClasses&&(Array.isArray(e.cssCompiledStyles)||(e.cssCompiledStyles=[]),e.cssClasses.split(" ").forEach(n=>{let a=r.get(n);a&&(e.cssCompiledStyles=[...e.cssCompiledStyles??[],...a.styles])}));let i=t.find(n=>n.id===e.id);i?Object.assign(i,e):t.push(e)}function Hft(t){return t?.classes?.join(" ")??""}function Yft(t){return t?.styles??[]}var P_,Lp,Uft,h5e,ix,d5e,p5e=P(()=>{"use strict";Ut();bt();Vr();M_();P_=new Map,Lp=0;o(AU,"stateDomId");Uft=o((t,e,r,i,n,a,s,l)=>{Q.trace("items",e),e.forEach(u=>{switch(u.stmt){case Dp:ix(t,u,r,i,n,a,s,l);break;case dg:ix(t,u,r,i,n,a,s,l);break;case PC:{ix(t,u.state1,r,i,n,a,s,l),ix(t,u.state2,r,i,n,a,s,l);let h=s==="neo",f={id:"edge"+Lp,start:u.state1.id,end:u.state2.id,arrowhead:"normal",arrowTypeEnd:h?"arrow_barb_neo":"arrow_barb",style:yU,labelStyle:"",label:lt.sanitizeText(u.description??"",ge()),arrowheadStyle:vU,labelpos:"c",labelType:xU,thickness:bU,classes:CU,look:s};n.push(f),Lp++}break}})},"setupDoc"),h5e=o((t,e="TB")=>{let r=e;if(t.doc)for(let i of t.doc)i.stmt==="dir"&&(r=i.value);return r},"getDir");o(O_,"insertOrUpdateNode");o(Hft,"getClassesFromDbInfo");o(Yft,"getStylesFromDbInfo");ix=o((t,e,r,i,n,a,s,l)=>{let u=e.id,h=r.get(u),f=Hft(h),d=Yft(h),p=ge();if(Q.info("dataFetcher parsedItem",e,h,d),u!=="root"){let m=R_;e.start===!0?m=e5e:e.start===!1&&(m=t5e),e.type!==dg&&(m=e.type),P_.get(u)||P_.set(u,{id:u,shape:m,description:lt.sanitizeText(u,p),cssClasses:`${f} ${n5e}`,cssStyles:d});let g=P_.get(u);e.description&&(Array.isArray(g.description)?(g.shape=N_,g.description.push(e.description)):g.description?.length&&g.description.length>0?(g.shape=N_,g.description===u?g.description=[e.description]:g.description=[g.description,e.description]):(g.shape=R_,g.description=e.description),g.description=lt.sanitizeTextOrArray(g.description,p)),g.description?.length===1&&g.shape===N_&&(g.type==="group"?g.shape=kU:g.shape=R_),!g.type&&e.doc&&(Q.info("Setting cluster for XCX",u,h5e(e)),g.type="group",g.isGroup=!0,g.dir=h5e(e),g.shape=e.type===L_?TU:kU,g.cssClasses=`${g.cssClasses} ${o5e} ${a?l5e:""}`);let y={labelStyle:"",shape:g.shape,label:g.description,cssClasses:g.cssClasses,cssCompiledStyles:[],cssStyles:g.cssStyles,id:u,dir:g.dir,domId:AU(u,Lp),type:g.type,isGroup:g.type==="group",padding:8,rx:10,ry:10,look:s,labelType:"markdown"};if(y.shape===TU&&(y.label=""),t&&t.id!=="root"&&(Q.trace("Setting node ",u," to be child of its parent ",t.id),y.parentId=t.id),y.centerLabel=!0,e.note){let v={labelStyle:"",shape:r5e,label:e.note.text,labelType:"markdown",cssClasses:s5e,cssStyles:[],cssCompiledStyles:[],id:u+u5e+"-"+Lp,domId:AU(u,Lp,EU),type:g.type,isGroup:g.type==="group",padding:p.flowchart?.padding,look:s,position:e.note.position},x=u+SU,b={labelStyle:"",shape:i5e,label:e.note.text,cssClasses:g.cssClasses,cssStyles:[],id:u+SU,domId:AU(u,Lp,wU),type:"group",isGroup:!0,padding:16,look:s,position:e.note.position};Lp++,b.id=x,v.parentId=x,O_(i,b,l),O_(i,v,l),O_(i,y,l);let T=u,w=v.id;e.note.position==="left of"&&(T=v.id,w=u),n.push({id:T+"-"+w,start:T,end:w,arrowhead:"none",arrowTypeEnd:"",style:yU,labelStyle:"",classes:a5e,arrowheadStyle:vU,labelpos:"c",labelType:xU,thickness:bU,look:s})}else O_(i,y,l)}e.doc&&(Q.trace("Adding nodes children "),Uft(e,e.doc,r,i,n,!a,s,l))},"dataFetcher"),d5e=o(()=>{P_.clear(),Lp=0},"reset")});var DU,jft,Xft,m5e,LU=P(()=>{"use strict";Ut();bt();I0();Wd();Ud();er();M_();DU=o((t,e="TB")=>{if(!t.doc)return e;let r=e;for(let i of t.doc)i.stmt==="dir"&&(r=i.value);return r},"getDir"),jft=o(function(t,e){return e.db.getClasses()},"getClasses"),Xft=o(async function(t,e,r,i){Q.info("REF0:"),Q.info("Drawing state diagram (v2)",e);let{securityLevel:n,state:a,layout:s}=ge();i.db.extract(i.db.getRootDocV2());let l=i.db.getData(),u=Ol(e,n);l.type=i.type,l.layoutAlgorithm=s,l.nodeSpacing=a?.nodeSpacing||50,l.rankSpacing=a?.rankSpacing||50,ge().look==="neo"?l.markers=["barbNeo"]:l.markers=["barb"],l.diagramId=e,await Ul(l,u);let f=8;try{(typeof i.db.getLinks=="function"?i.db.getLinks():new Map).forEach((p,m)=>{let g=typeof m=="string"?m:typeof m?.id=="string"?m.id:"";if(!g){Q.warn("\u26A0\uFE0F Invalid or missing stateId from key:",JSON.stringify(m));return}let y=u.node()?.querySelectorAll("g"),v;if(y?.forEach(w=>{w.textContent?.trim()===g&&(v=w)}),!v){Q.warn("\u26A0\uFE0F Could not find node matching text:",g);return}let x=v.parentNode;if(!x){Q.warn("\u26A0\uFE0F Node has no parent, cannot wrap:",g);return}let b=document.createElementNS("http://www.w3.org/2000/svg","a"),T=p.url.replace(/^"+|"+$/g,"");if(b.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",T),b.setAttribute("target","_blank"),p.tooltip){let w=p.tooltip.replace(/^"+|"+$/g,"");b.setAttribute("title",w)}x.replaceChild(b,v),b.appendChild(v),Q.info("\u{1F517} Wrapped node in
    tag for:",g,p.url)})}catch(d){Q.error("\u274C Error injecting clickable links:",d)}Kt.insertTitle(u,"statediagramTitleText",a?.titleTopMargin??25,i.db.getDiagramTitle()),Ro(u,f,rx,a?.useMaxWidth??!0)},"draw"),m5e={getClasses:jft,draw:Xft,getDir:DU}});var no,y5e,v5e,B_,rc,F_=P(()=>{"use strict";Ut();bt();er();Vr();Ki();p5e();LU();M_();no={START_NODE:"[*]",START_TYPE:"start",END_NODE:"[*]",END_TYPE:"end",COLOR_KEYWORD:"color",FILL_KEYWORD:"fill",BG_FILL:"bgFill",STYLECLASS_SEP:","},y5e=o(()=>new Map,"newClassesList"),v5e=o(()=>({relations:[],states:new Map,documents:{}}),"newDoc"),B_=o(t=>JSON.parse(JSON.stringify(t)),"clone"),rc=class{constructor(e){this.version=e;this.nodes=[];this.edges=[];this.rootDoc=[];this.classes=y5e();this.documents={root:v5e()};this.currentDocument=this.documents.root;this.startEndCount=0;this.dividerCnt=0;this.links=new Map;this.getAccTitle=Dr;this.setAccTitle=Ar;this.getAccDescription=Rr;this.setAccDescription=Lr;this.setDiagramTitle=Mr;this.getDiagramTitle=Nr;this.clear(),this.setRootDoc=this.setRootDoc.bind(this),this.getDividerId=this.getDividerId.bind(this),this.setDirection=this.setDirection.bind(this),this.trimColon=this.trimColon.bind(this)}static{o(this,"StateDB")}static{this.relationType={AGGREGATION:0,EXTENSION:1,COMPOSITION:2,DEPENDENCY:3}}extract(e){this.clear(!0);for(let n of Array.isArray(e)?e:e.doc)switch(n.stmt){case Dp:this.addState(n.id.trim(),n.type,n.doc,n.description,n.note);break;case PC:this.addRelation(n.state1,n.state2,n.description);break;case Q3e:this.addStyleClass(n.id.trim(),n.classes);break;case Z3e:this.handleStyleDef(n);break;case J3e:this.setCssClass(n.id.trim(),n.styleClass);break;case"click":this.addLink(n.id,n.url,n.tooltip);break}let r=this.getStates(),i=ge();d5e(),ix(void 0,this.getRootDocV2(),r,this.nodes,this.edges,!0,i.look,this.classes);for(let n of this.nodes)if(Array.isArray(n.label)){if(n.description=n.label.slice(1),n.isGroup&&n.description.length>0)throw new Error(`Group nodes can only have label. Remove the additional description for node [${n.id}]`);n.label=n.label[0]}}handleStyleDef(e){let r=e.id.trim().split(","),i=e.styleClass.split(",");for(let n of r){let a=this.getState(n);if(!a){let s=n.trim();this.addState(s),a=this.getState(s)}a&&(a.styles=i.map(s=>s.replace(/;/g,"")?.trim()))}}setRootDoc(e){Q.info("Setting root doc",e),this.rootDoc=e,this.version===1?this.extract(e):this.extract(this.getRootDocV2())}docTranslator(e,r,i){if(r.stmt===PC){this.docTranslator(e,r.state1,!0),this.docTranslator(e,r.state2,!1);return}if(r.stmt===Dp&&(r.id===no.START_NODE?(r.id=e.id+(i?"_start":"_end"),r.start=i):r.id=r.id.trim()),r.stmt!==fg&&r.stmt!==Dp||!r.doc)return;let n=[],a=[];for(let s of r.doc)if(s.type===L_){let l=B_(s);l.doc=B_(a),n.push(l),a=[]}else a.push(s);if(n.length>0&&a.length>0){let s={stmt:Dp,id:bI(),type:"divider",doc:B_(a)};n.push(B_(s)),r.doc=n}r.doc.forEach(s=>this.docTranslator(r,s,!0))}getRootDocV2(){return this.docTranslator({id:fg,stmt:fg},{id:fg,stmt:fg,doc:this.rootDoc},!0),{id:fg,doc:this.rootDoc}}addState(e,r=dg,i=void 0,n=void 0,a=void 0,s=void 0,l=void 0,u=void 0){let h=e?.trim();if(!this.currentDocument.states.has(h))Q.info("Adding state ",h,n),this.currentDocument.states.set(h,{stmt:Dp,id:h,descriptions:[],type:r,doc:i,note:a,classes:[],styles:[],textStyles:[]});else{let f=this.currentDocument.states.get(h);if(!f)throw new Error(`State not found: ${h}`);f.doc||(f.doc=i),f.type||(f.type=r)}if(n&&(Q.info("Setting state description",h,n),(Array.isArray(n)?n:[n]).forEach(d=>this.addDescription(h,d.trim()))),a){let f=this.currentDocument.states.get(h);if(!f)throw new Error(`State not found: ${h}`);f.note=a,f.note.text=lt.sanitizeText(f.note.text,ge())}s&&(Q.info("Setting state classes",h,s),(Array.isArray(s)?s:[s]).forEach(d=>this.setCssClass(h,d.trim()))),l&&(Q.info("Setting state styles",h,l),(Array.isArray(l)?l:[l]).forEach(d=>this.setStyle(h,d.trim()))),u&&(Q.info("Setting state styles",h,l),(Array.isArray(u)?u:[u]).forEach(d=>this.setTextStyle(h,d.trim())))}clear(e){this.nodes=[],this.edges=[],this.documents={root:v5e()},this.currentDocument=this.documents.root,this.startEndCount=0,this.classes=y5e(),e||(this.links=new Map,wr())}getState(e){return this.currentDocument.states.get(e)}getStates(){return this.currentDocument.states}logDocuments(){Q.info("Documents = ",this.documents)}getRelations(){return this.currentDocument.relations}addLink(e,r,i){this.links.set(e,{url:r,tooltip:i}),Q.warn("Adding link",e,r,i)}getLinks(){return this.links}startIdIfNeeded(e=""){return e===no.START_NODE?(this.startEndCount++,`${no.START_TYPE}${this.startEndCount}`):e}startTypeIfNeeded(e="",r=dg){return e===no.START_NODE?no.START_TYPE:r}endIdIfNeeded(e=""){return e===no.END_NODE?(this.startEndCount++,`${no.END_TYPE}${this.startEndCount}`):e}endTypeIfNeeded(e="",r=dg){return e===no.END_NODE?no.END_TYPE:r}addRelationObjs(e,r,i=""){let n=this.startIdIfNeeded(e.id.trim()),a=this.startTypeIfNeeded(e.id.trim(),e.type),s=this.startIdIfNeeded(r.id.trim()),l=this.startTypeIfNeeded(r.id.trim(),r.type);this.addState(n,a,e.doc,e.description,e.note,e.classes,e.styles,e.textStyles),this.addState(s,l,r.doc,r.description,r.note,r.classes,r.styles,r.textStyles),this.currentDocument.relations.push({id1:n,id2:s,relationTitle:lt.sanitizeText(i,ge())})}addRelation(e,r,i){if(typeof e=="object"&&typeof r=="object")this.addRelationObjs(e,r,i);else if(typeof e=="string"&&typeof r=="string"){let n=this.startIdIfNeeded(e.trim()),a=this.startTypeIfNeeded(e),s=this.endIdIfNeeded(r.trim()),l=this.endTypeIfNeeded(r);this.addState(n,a),this.addState(s,l),this.currentDocument.relations.push({id1:n,id2:s,relationTitle:i?lt.sanitizeText(i,ge()):void 0})}}addDescription(e,r){let i=this.currentDocument.states.get(e),n=r.startsWith(":")?r.replace(":","").trim():r;i?.descriptions?.push(lt.sanitizeText(n,ge()))}cleanupLabel(e){return e.startsWith(":")?e.slice(2).trim():e.trim()}getDividerId(){return this.dividerCnt++,`divider-id-${this.dividerCnt}`}addStyleClass(e,r=""){this.classes.has(e)||this.classes.set(e,{id:e,styles:[],textStyles:[]});let i=this.classes.get(e);r&&i&&r.split(no.STYLECLASS_SEP).forEach(n=>{let a=n.replace(/([^;]*);/,"$1").trim();if(RegExp(no.COLOR_KEYWORD).exec(n)){let l=a.replace(no.FILL_KEYWORD,no.BG_FILL).replace(no.COLOR_KEYWORD,no.FILL_KEYWORD);i.textStyles.push(l)}i.styles.push(a)})}getClasses(){return this.classes}setCssClass(e,r){e.split(",").forEach(i=>{let n=this.getState(i);if(!n){let a=i.trim();this.addState(a),n=this.getState(a)}n?.classes?.push(r)})}setStyle(e,r){this.getState(e)?.styles?.push(r)}setTextStyle(e,r){this.getState(e)?.textStyles?.push(r)}getDirectionStatement(){return this.rootDoc.find(e=>e.stmt==="dir")}getDirection(){return this.getDirectionStatement()?.value??"TB"}setDirection(e){let r=this.getDirectionStatement();r?r.value=e:this.rootDoc.unshift({stmt:"dir",value:e})}trimColon(e){return e.startsWith(":")?e.slice(1).trim():e.trim()}getData(){let e=ge();return{nodes:this.nodes,edges:this.edges,other:{},config:e,direction:DU(this.getRootDocV2())}}getConfig(){return ge().state}}});var Qft,$_,RU=P(()=>{"use strict";Qft=o(t=>` +defs [id$="-barbEnd"] { + fill: ${t.transitionColor}; + stroke: ${t.transitionColor}; + } +g.stateGroup text { + fill: ${t.nodeBorder}; + stroke: none; + font-size: 10px; +} +g.stateGroup text { + fill: ${t.textColor}; + stroke: none; + font-size: 10px; + +} +g.stateGroup .state-title { + font-weight: bolder; + fill: ${t.stateLabelColor}; +} + +g.stateGroup rect { + fill: ${t.mainBkg}; + stroke: ${t.nodeBorder}; +} + +g.stateGroup line { + stroke: ${t.lineColor}; + stroke-width: ${t.strokeWidth||1}; +} + +.transition { + stroke: ${t.transitionColor}; + stroke-width: ${t.strokeWidth||1}; + fill: none; +} + +.stateGroup .composit { + fill: ${t.background}; + border-bottom: 1px +} + +.stateGroup .alt-composit { + fill: #e0e0e0; + border-bottom: 1px +} + +.state-note { + stroke: ${t.noteBorderColor}; + fill: ${t.noteBkgColor}; + + text { + fill: ${t.noteTextColor}; + stroke: none; + font-size: 10px; + } +} + +.stateLabel .box { + stroke: none; + stroke-width: 0; + fill: ${t.mainBkg}; + opacity: 0.5; +} + +.edgeLabel .label rect { + fill: ${t.labelBackgroundColor}; + opacity: 0.5; +} +.edgeLabel { + background-color: ${t.edgeLabelBackground}; + p { + background-color: ${t.edgeLabelBackground}; + } + rect { + opacity: 0.5; + background-color: ${t.edgeLabelBackground}; + fill: ${t.edgeLabelBackground}; + } + text-align: center; +} +.edgeLabel .label text { + fill: ${t.transitionLabelColor||t.tertiaryTextColor}; +} +.label div .edgeLabel { + color: ${t.transitionLabelColor||t.tertiaryTextColor}; +} + +.stateLabel text { + fill: ${t.stateLabelColor}; + font-size: 10px; + font-weight: bold; +} + +.node circle.state-start { + fill: ${t.specialStateColor}; + stroke: ${t.specialStateColor}; +} + +.node .fork-join { + fill: ${t.specialStateColor}; + stroke: ${t.specialStateColor}; +} + +.node circle.state-end { + fill: ${t.innerEndBackground}; + stroke: ${t.background}; + stroke-width: 1.5 +} +.end-state-inner { + fill: ${t.compositeBackground||t.background}; + // stroke: ${t.background}; + stroke-width: 1.5 +} + +.node rect { + fill: ${t.stateBkg||t.mainBkg}; + stroke: ${t.stateBorder||t.nodeBorder}; + stroke-width: ${t.strokeWidth||1}px; +} +.node polygon { + fill: ${t.mainBkg}; + stroke: ${t.stateBorder||t.nodeBorder};; + stroke-width: ${t.strokeWidth||1}px; +} +[id$="-barbEnd"] { + fill: ${t.lineColor}; +} + +.statediagram-cluster rect { + fill: ${t.compositeTitleBackground}; + stroke: ${t.stateBorder||t.nodeBorder}; + stroke-width: ${t.strokeWidth||1}px; +} + +.cluster-label, .nodeLabel { + color: ${t.stateLabelColor}; + // line-height: 1; +} + +.statediagram-cluster rect.outer { + rx: 5px; + ry: 5px; +} +.statediagram-state .divider { + stroke: ${t.stateBorder||t.nodeBorder}; +} + +.statediagram-state .title-state { + rx: 5px; + ry: 5px; +} +.statediagram-cluster.statediagram-cluster .inner { + fill: ${t.compositeBackground||t.background}; +} +.statediagram-cluster.statediagram-cluster-alt .inner { + fill: ${t.altBackground?t.altBackground:"#efefef"}; +} + +.statediagram-cluster .inner { + rx:0; + ry:0; +} + +.statediagram-state rect.basic { + rx: 5px; + ry: 5px; +} +.statediagram-state rect.divider { + stroke-dasharray: 10,10; + fill: ${t.altBackground?t.altBackground:"#efefef"}; +} + +.note-edge { + stroke-dasharray: 5; +} + +.statediagram-note rect { + fill: ${t.noteBkgColor}; + stroke: ${t.noteBorderColor}; + stroke-width: 1px; + rx: 0; + ry: 0; +} +.statediagram-note rect { + fill: ${t.noteBkgColor}; + stroke: ${t.noteBorderColor}; + stroke-width: 1px; + rx: 0; + ry: 0; +} + +.statediagram-note text { + fill: ${t.noteTextColor}; +} + +.statediagram-note .nodeLabel { + color: ${t.noteTextColor}; +} +.statediagram .edgeLabel { + color: red; // ${t.noteTextColor}; +} + +[id$="-dependencyStart"], [id$="-dependencyEnd"] { + fill: ${t.lineColor}; + stroke: ${t.lineColor}; + stroke-width: ${t.strokeWidth||1}; +} + +.statediagramTitleText { + text-anchor: middle; + font-size: 18px; + fill: ${t.textColor}; +} + +[data-look="neo"].statediagram-cluster rect { + fill: ${t.mainBkg}; + stroke: ${t.useGradient?"url("+t.svgId+"-gradient)":t.stateBorder||t.nodeBorder}; + stroke-width: ${t.strokeWidth??1}; +} +[data-look="neo"].statediagram-cluster rect.outer { + rx: ${t.radius}px; + ry: ${t.radius}px; + filter: ${t.dropShadow?t.dropShadow.replace("url(#drop-shadow)",`url(${t.svgId}-drop-shadow)`):"none"} +} +`,"getStyles"),$_=Qft});var Zft,Jft,edt,tdt,b5e,rdt,idt,ndt,adt,NU,x5e,T5e,k5e=P(()=>{"use strict";Pr();F_();er();Vr();Ut();bt();Zft=o(t=>t.append("circle").attr("class","start-state").attr("r",ge().state.sizeUnit).attr("cx",ge().state.padding+ge().state.sizeUnit).attr("cy",ge().state.padding+ge().state.sizeUnit),"drawStartState"),Jft=o(t=>t.append("line").style("stroke","grey").style("stroke-dasharray","3").attr("x1",ge().state.textHeight).attr("class","divider").attr("x2",ge().state.textHeight*2).attr("y1",0).attr("y2",0),"drawDivider"),edt=o((t,e)=>{let r=t.append("text").attr("x",2*ge().state.padding).attr("y",ge().state.textHeight+2*ge().state.padding).attr("font-size",ge().state.fontSize).attr("class","state-title").text(e.id),i=r.node().getBBox();return t.insert("rect",":first-child").attr("x",ge().state.padding).attr("y",ge().state.padding).attr("width",i.width+2*ge().state.padding).attr("height",i.height+2*ge().state.padding).attr("rx",ge().state.radius),r},"drawSimpleState"),tdt=o((t,e)=>{let r=o(function(p,m,g){let y=p.append("tspan").attr("x",2*ge().state.padding).text(m);g||y.attr("dy",ge().state.textHeight)},"addTspan"),n=t.append("text").attr("x",2*ge().state.padding).attr("y",ge().state.textHeight+1.3*ge().state.padding).attr("font-size",ge().state.fontSize).attr("class","state-title").text(e.descriptions[0]).node().getBBox(),a=n.height,s=t.append("text").attr("x",ge().state.padding).attr("y",a+ge().state.padding*.4+ge().state.dividerMargin+ge().state.textHeight).attr("class","state-description"),l=!0,u=!0;e.descriptions.forEach(function(p){l||(r(s,p,u),u=!1),l=!1});let h=t.append("line").attr("x1",ge().state.padding).attr("y1",ge().state.padding+a+ge().state.dividerMargin/2).attr("y2",ge().state.padding+a+ge().state.dividerMargin/2).attr("class","descr-divider"),f=s.node().getBBox(),d=Math.max(f.width,n.width);return h.attr("x2",d+3*ge().state.padding),t.insert("rect",":first-child").attr("x",ge().state.padding).attr("y",ge().state.padding).attr("width",d+2*ge().state.padding).attr("height",f.height+a+2*ge().state.padding).attr("rx",ge().state.radius),t},"drawDescrState"),b5e=o((t,e,r)=>{let i=ge().state.padding,n=2*ge().state.padding,a=t.node().getBBox(),s=a.width,l=a.x,u=t.append("text").attr("x",0).attr("y",ge().state.titleShift).attr("font-size",ge().state.fontSize).attr("class","state-title").text(e.id),f=u.node().getBBox().width+n,d=Math.max(f,s);d===s&&(d=d+n);let p,m=t.node().getBBox();e.doc,p=l-i,f>s&&(p=(s-d)/2+i),Math.abs(l-m.x)s&&(p=l-(f-s)/2);let g=1-ge().state.textHeight;return t.insert("rect",":first-child").attr("x",p).attr("y",g).attr("class",r?"alt-composit":"composit").attr("width",d).attr("height",m.height+ge().state.textHeight+ge().state.titleShift+1).attr("rx","0"),u.attr("x",p+i),f<=s&&u.attr("x",l+(d-n)/2-f/2+i),t.insert("rect",":first-child").attr("x",p).attr("y",ge().state.titleShift-ge().state.textHeight-ge().state.padding).attr("width",d).attr("height",ge().state.textHeight*3).attr("rx",ge().state.radius),t.insert("rect",":first-child").attr("x",p).attr("y",ge().state.titleShift-ge().state.textHeight-ge().state.padding).attr("width",d).attr("height",m.height+3+2*ge().state.textHeight).attr("rx",ge().state.radius),t},"addTitleAndBox"),rdt=o(t=>(t.append("circle").attr("class","end-state-outer").attr("r",ge().state.sizeUnit+ge().state.miniPadding).attr("cx",ge().state.padding+ge().state.sizeUnit+ge().state.miniPadding).attr("cy",ge().state.padding+ge().state.sizeUnit+ge().state.miniPadding),t.append("circle").attr("class","end-state-inner").attr("r",ge().state.sizeUnit).attr("cx",ge().state.padding+ge().state.sizeUnit+2).attr("cy",ge().state.padding+ge().state.sizeUnit+2)),"drawEndState"),idt=o((t,e)=>{let r=ge().state.forkWidth,i=ge().state.forkHeight;if(e.parentId){let n=r;r=i,i=n}return t.append("rect").style("stroke","black").style("fill","black").attr("width",r).attr("height",i).attr("x",ge().state.padding).attr("y",ge().state.padding)},"drawForkJoinState"),ndt=o((t,e,r,i)=>{let n=0,a=i.append("text");a.style("text-anchor","start"),a.attr("class","noteText");let s=t.replace(/\r\n/g,"
    ");s=s.replace(/\n/g,"
    ");let l=s.split(lt.lineBreakRegex),u=1.25*ge().state.noteMargin;for(let h of l){let f=h.trim();if(f.length>0){let d=a.append("tspan");if(d.text(f),u===0){let p=d.node().getBBox();u+=p.height}n+=u,d.attr("x",e+ge().state.noteMargin),d.attr("y",r+n+1.25*ge().state.noteMargin)}}return{textWidth:a.node().getBBox().width,textHeight:n}},"_drawLongText"),adt=o((t,e)=>{e.attr("class","state-note");let r=e.append("rect").attr("x",0).attr("y",ge().state.padding),i=e.append("g"),{textWidth:n,textHeight:a}=ndt(t,0,0,i);return r.attr("height",a+2*ge().state.noteMargin),r.attr("width",n+ge().state.noteMargin*2),r},"drawNote"),NU=o(function(t,e){let r=e.id,i={id:r,label:e.id,width:0,height:0},n=t.append("g").attr("id",r).attr("class","stateGroup");e.type==="start"&&Zft(n),e.type==="end"&&rdt(n),(e.type==="fork"||e.type==="join")&&idt(n,e),e.type==="note"&&adt(e.note.text,n),e.type==="divider"&&Jft(n),e.type==="default"&&e.descriptions.length===0&&edt(n,e),e.type==="default"&&e.descriptions.length>0&&tdt(n,e);let a=n.node().getBBox();return i.width=a.width+2*ge().state.padding,i.height=a.height+2*ge().state.padding,i},"drawState"),x5e=0,T5e=o(function(t,e,r){let i=o(function(u){switch(u){case rc.relationType.AGGREGATION:return"aggregation";case rc.relationType.EXTENSION:return"extension";case rc.relationType.COMPOSITION:return"composition";case rc.relationType.DEPENDENCY:return"dependency"}},"getRelationType");e.points=e.points.filter(u=>!Number.isNaN(u.y));let n=e.points,a=Cc().x(function(u){return u.x}).y(function(u){return u.y}).curve(wc),s=t.append("path").attr("d",a(n)).attr("id","edge"+x5e).attr("class","transition"),l="";if(ge().state.arrowMarkerAbsolute&&(l=Yp(!0)),s.attr("marker-end","url("+l+"#"+i(rc.relationType.DEPENDENCY)+"End)"),r.title!==void 0){let u=t.append("g").attr("class","stateLabel"),{x:h,y:f}=Kt.calcLabelPosition(e.points),d=lt.getRows(r.title),p=0,m=[],g=0,y=0;for(let b=0;b<=d.length;b++){let T=u.append("text").attr("text-anchor","middle").text(d[b]).attr("x",h).attr("y",f+p),w=T.node().getBBox();g=Math.max(g,w.width),y=Math.min(y,w.x),Q.info(w.x,h,f+p),p===0&&(p=T.node().getBBox().height,Q.info("Title height",p,f)),m.push(T)}let v=p*d.length;if(d.length>1){let b=(d.length-1)*p*.5;m.forEach((T,w)=>T.attr("y",f+w*p-b)),v=p*d.length}let x=u.node().getBBox();u.insert("rect",":first-child").attr("class","box").attr("x",h-g/2-ge().state.padding/2).attr("y",f-v/2-ge().state.padding/2-3.5).attr("width",g+ge().state.padding).attr("height",v+ge().state.padding),Q.info(x)}x5e++},"drawEdge")});var dl,IU,sdt,odt,ldt,cdt,C5e,w5e,E5e=P(()=>{"use strict";Pr();YO();$l();bt();Vr();k5e();Ut();Xi();IU={},sdt=o(function(){},"setConf"),odt=o(function(t){t.append("defs").append("marker").attr("id","dependencyEnd").attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 19,7 L9,13 L14,7 L9,1 Z")},"insertMarkers"),ldt=o(function(t,e,r,i){dl=ge().state;let n=ge().securityLevel,a;n==="sandbox"&&(a=Ze("#i"+e));let s=n==="sandbox"?Ze(a.nodes()[0].contentDocument.body):Ze("body"),l=n==="sandbox"?a.nodes()[0].contentDocument:document;Q.debug("Rendering diagram "+t);let u=s.select(`[id='${e}']`);odt(u);let h=i.db.getRootDoc(),f=u.append("g").attr("id",e+"-root");C5e(h,f,void 0,!1,s,l,i);let d=dl.padding,p=u.node().getBBox(),m=p.width+d*2,g=p.height+d*2,y=m*1.75;Hr(u,g,y,dl.useMaxWidth),u.attr("viewBox",`${p.x-dl.padding} ${p.y-dl.padding} `+m+" "+g)},"draw"),cdt=o(t=>t?t.length*dl.fontSizeFactor:1,"getLabelWidth"),C5e=o((t,e,r,i,n,a,s)=>{let l=new Ai({compound:!0,multigraph:!0}),u,h=!0;for(u=0;u{let k=w.parentElement,C=0,E=0;k&&(k.parentElement&&(C=k.parentElement.getBBox().width),E=parseInt(k.getAttribute("data-x-shift"),10),Number.isNaN(E)&&(E=0)),w.setAttribute("x1",0-E+8),w.setAttribute("x2",C-E-8)})):Q.debug("No Node "+b+": "+JSON.stringify(l.node(b)))});let v=y.getBBox();l.edges().forEach(function(b){b!==void 0&&l.edge(b)!==void 0&&(Q.debug("Edge "+b.v+" -> "+b.w+": "+JSON.stringify(l.edge(b))),T5e(e,l.edge(b),l.edge(b).relation))}),v=y.getBBox();let x={id:r||"root",label:r||"root",width:0,height:0};return x.width=v.width+2*dl.padding,x.height=v.height+2*dl.padding,Q.debug("Doc rendered",x,l),x},"renderDoc"),w5e={setConf:sdt,draw:ldt}});var S5e={};ur(S5e,{diagram:()=>udt});var udt,A5e=P(()=>{"use strict";gU();F_();RU();E5e();udt={parser:D_,get db(){return new rc(1)},renderer:w5e,styles:$_,init:o(t=>{t.state||(t.state={}),t.state.arrowMarkerAbsolute=t.arrowMarkerAbsolute},"init")}});var L5e={};ur(L5e,{diagram:()=>pdt});var pdt,R5e=P(()=>{"use strict";gU();F_();RU();LU();pdt={parser:D_,get db(){return new rc(2)},renderer:m5e,styles:$_,init:o(t=>{t.state||(t.state={}),t.state.arrowMarkerAbsolute=t.arrowMarkerAbsolute},"init")}});var MU,M5e,O5e=P(()=>{"use strict";MU=(function(){var t=o(function(d,p,m,g){for(m=m||{},g=d.length;g--;m[d[g]]=p);return m},"o"),e=[6,8,10,11,12,14,16,17,18],r=[1,9],i=[1,10],n=[1,11],a=[1,12],s=[1,13],l=[1,14],u={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,journey:4,document:5,EOF:6,line:7,SPACE:8,statement:9,NEWLINE:10,title:11,acc_title:12,acc_title_value:13,acc_descr:14,acc_descr_value:15,acc_descr_multiline_value:16,section:17,taskName:18,taskData:19,$accept:0,$end:1},terminals_:{2:"error",4:"journey",6:"EOF",8:"SPACE",10:"NEWLINE",11:"title",12:"acc_title",13:"acc_title_value",14:"acc_descr",15:"acc_descr_value",16:"acc_descr_multiline_value",17:"section",18:"taskName",19:"taskData"},productions_:[0,[3,3],[5,0],[5,2],[7,2],[7,1],[7,1],[7,1],[9,1],[9,2],[9,2],[9,1],[9,1],[9,2]],performAction:o(function(p,m,g,y,v,x,b){var T=x.length-1;switch(v){case 1:return x[T-1];case 2:this.$=[];break;case 3:x[T-1].push(x[T]),this.$=x[T-1];break;case 4:case 5:this.$=x[T];break;case 6:case 7:this.$=[];break;case 8:y.setDiagramTitle(x[T].substr(6)),this.$=x[T].substr(6);break;case 9:this.$=x[T].trim(),y.setAccTitle(this.$);break;case 10:case 11:this.$=x[T].trim(),y.setAccDescription(this.$);break;case 12:y.addSection(x[T].substr(8)),this.$=x[T].substr(8);break;case 13:y.addTask(x[T-1],x[T]),this.$="task";break}},"anonymous"),table:[{3:1,4:[1,2]},{1:[3]},t(e,[2,2],{5:3}),{6:[1,4],7:5,8:[1,6],9:7,10:[1,8],11:r,12:i,14:n,16:a,17:s,18:l},t(e,[2,7],{1:[2,1]}),t(e,[2,3]),{9:15,11:r,12:i,14:n,16:a,17:s,18:l},t(e,[2,5]),t(e,[2,6]),t(e,[2,8]),{13:[1,16]},{15:[1,17]},t(e,[2,11]),t(e,[2,12]),{19:[1,18]},t(e,[2,4]),t(e,[2,9]),t(e,[2,10]),t(e,[2,13])],defaultActions:{},parseError:o(function(p,m){if(m.recoverable)this.trace(p);else{var g=new Error(p);throw g.hash=m,g}},"parseError"),parse:o(function(p){var m=this,g=[0],y=[],v=[null],x=[],b=this.table,T="",w=0,k=0,C=0,E=2,S=1,L=x.slice.call(arguments,1),M=Object.create(this.lexer),I={yy:{}};for(var A in this.yy)Object.prototype.hasOwnProperty.call(this.yy,A)&&(I.yy[A]=this.yy[A]);M.setInput(p,I.yy),I.yy.lexer=M,I.yy.parser=this,typeof M.yylloc>"u"&&(M.yylloc={});var _=M.yylloc;x.push(_);var D=M.options&&M.options.ranges;typeof I.yy.parseError=="function"?this.parseError=I.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function N(J){g.length=g.length-2*J,v.length=v.length-J,x.length=x.length-J}o(N,"popStack");function R(){var J;return J=y.pop()||M.lex()||S,typeof J!="number"&&(J instanceof Array&&(y=J,J=y.pop()),J=m.symbols_[J]||J),J}o(R,"lex");for(var B,O,$,z,F,V,H={},X,W,Z,Y;;){if($=g[g.length-1],this.defaultActions[$]?z=this.defaultActions[$]:((B===null||typeof B>"u")&&(B=R()),z=b[$]&&b[$][B]),typeof z>"u"||!z.length||!z[0]){var ae="";Y=[];for(X in b[$])this.terminals_[X]&&X>E&&Y.push("'"+this.terminals_[X]+"'");M.showPosition?ae="Parse error on line "+(w+1)+`: +`+M.showPosition()+` +Expecting `+Y.join(", ")+", got '"+(this.terminals_[B]||B)+"'":ae="Parse error on line "+(w+1)+": Unexpected "+(B==S?"end of input":"'"+(this.terminals_[B]||B)+"'"),this.parseError(ae,{text:M.match,token:this.terminals_[B]||B,line:M.yylineno,loc:_,expected:Y})}if(z[0]instanceof Array&&z.length>1)throw new Error("Parse Error: multiple actions possible at state: "+$+", token: "+B);switch(z[0]){case 1:g.push(B),v.push(M.yytext),x.push(M.yylloc),g.push(z[1]),B=null,O?(B=O,O=null):(k=M.yyleng,T=M.yytext,w=M.yylineno,_=M.yylloc,C>0&&C--);break;case 2:if(W=this.productions_[z[1]][1],H.$=v[v.length-W],H._$={first_line:x[x.length-(W||1)].first_line,last_line:x[x.length-1].last_line,first_column:x[x.length-(W||1)].first_column,last_column:x[x.length-1].last_column},D&&(H._$.range=[x[x.length-(W||1)].range[0],x[x.length-1].range[1]]),V=this.performAction.apply(H,[T,k,w,I.yy,z[1],v,x].concat(L)),typeof V<"u")return V;W&&(g=g.slice(0,-1*W*2),v=v.slice(0,-1*W),x=x.slice(0,-1*W)),g.push(this.productions_[z[1]][0]),v.push(H.$),x.push(H._$),Z=b[g[g.length-2]][g[g.length-1]],g.push(Z);break;case 3:return!0}}return!0},"parse")},h=(function(){var d={EOF:1,parseError:o(function(m,g){if(this.yy.parser)this.yy.parser.parseError(m,g);else throw new Error(m)},"parseError"),setInput:o(function(p,m){return this.yy=m||this.yy||{},this._input=p,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var p=this._input[0];this.yytext+=p,this.yyleng++,this.offset++,this.match+=p,this.matched+=p;var m=p.match(/(?:\r\n?|\n).*/g);return m?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),p},"input"),unput:o(function(p){var m=p.length,g=p.split(/(?:\r\n?|\n)/g);this._input=p+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-m),this.offset-=m;var y=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),g.length-1&&(this.yylineno-=g.length-1);var v=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:g?(g.length===y.length?this.yylloc.first_column:0)+y[y.length-g.length].length-g[0].length:this.yylloc.first_column-m},this.options.ranges&&(this.yylloc.range=[v[0],v[0]+this.yyleng-m]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(p){this.unput(this.match.slice(p))},"less"),pastInput:o(function(){var p=this.matched.substr(0,this.matched.length-this.match.length);return(p.length>20?"...":"")+p.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var p=this.match;return p.length<20&&(p+=this._input.substr(0,20-p.length)),(p.substr(0,20)+(p.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var p=this.pastInput(),m=new Array(p.length+1).join("-");return p+this.upcomingInput()+` +`+m+"^"},"showPosition"),test_match:o(function(p,m){var g,y,v;if(this.options.backtrack_lexer&&(v={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(v.yylloc.range=this.yylloc.range.slice(0))),y=p[0].match(/(?:\r\n?|\n).*/g),y&&(this.yylineno+=y.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:y?y[y.length-1].length-y[y.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+p[0].length},this.yytext+=p[0],this.match+=p[0],this.matches=p,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(p[0].length),this.matched+=p[0],g=this.performAction.call(this,this.yy,this,m,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),g)return g;if(this._backtrack){for(var x in v)this[x]=v[x];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var p,m,g,y;this._more||(this.yytext="",this.match="");for(var v=this._currentRules(),x=0;xm[0].length)){if(m=g,y=x,this.options.backtrack_lexer){if(p=this.test_match(g,v[x]),p!==!1)return p;if(this._backtrack){m=!1;continue}else return!1}else if(!this.options.flex)break}return m?(p=this.test_match(m,v[y]),p!==!1?p:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var m=this.next();return m||this.lex()},"lex"),begin:o(function(m){this.conditionStack.push(m)},"begin"),popState:o(function(){var m=this.conditionStack.length-1;return m>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(m){return m=this.conditionStack.length-1-Math.abs(m||0),m>=0?this.conditionStack[m]:"INITIAL"},"topState"),pushState:o(function(m){this.begin(m)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:o(function(m,g,y,v){var x=v;switch(y){case 0:break;case 1:break;case 2:return 10;case 3:break;case 4:break;case 5:return 4;case 6:return 11;case 7:return this.begin("acc_title"),12;break;case 8:return this.popState(),"acc_title_value";break;case 9:return this.begin("acc_descr"),14;break;case 10:return this.popState(),"acc_descr_value";break;case 11:this.begin("acc_descr_multiline");break;case 12:this.popState();break;case 13:return"acc_descr_multiline_value";case 14:return 17;case 15:return 18;case 16:return 19;case 17:return":";case 18:return 6;case 19:return"INVALID"}},"anonymous"),rules:[/^(?:%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:#[^\n]*)/i,/^(?:journey\b)/i,/^(?:title\s[^#\n;]+)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:section\s[^#:\n;]+)/i,/^(?:[^#:\n;]+)/i,/^(?::[^#\n;]+)/i,/^(?::)/i,/^(?:$)/i,/^(?:.)/i],conditions:{acc_descr_multiline:{rules:[12,13],inclusive:!1},acc_descr:{rules:[10],inclusive:!1},acc_title:{rules:[8],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,7,9,11,14,15,16,17,18,19],inclusive:!0}}};return d})();u.lexer=h;function f(){this.yy={}}return o(f,"Parser"),f.prototype=u,u.Parser=f,new f})();MU.parser=MU;M5e=MU});var nx,OU,BC,FC,vdt,xdt,bdt,Tdt,kdt,Cdt,wdt,P5e,Edt,PU,B5e=P(()=>{"use strict";Ut();Ki();nx="",OU=[],BC=[],FC=[],vdt=o(function(){OU.length=0,BC.length=0,nx="",FC.length=0,wr()},"clear"),xdt=o(function(t){nx=t,OU.push(t)},"addSection"),bdt=o(function(){return OU},"getSections"),Tdt=o(function(){let t=P5e(),e=100,r=0;for(;!t&&r{r.people&&t.push(...r.people)}),[...new Set(t)].sort()},"updateActors"),Cdt=o(function(t,e){let r=e.substr(1).split(":"),i=0,n=[];r.length===1?(i=Number(r[0]),n=[]):(i=Number(r[0]),n=r[1].split(","));let a=n.map(l=>l.trim()),s={section:nx,type:nx,people:a,task:t,score:i};FC.push(s)},"addTask"),wdt=o(function(t){let e={section:nx,type:nx,description:t,task:t,classes:[]};BC.push(e)},"addTaskOrg"),P5e=o(function(){let t=o(function(r){return FC[r].processed},"compileTask"),e=!0;for(let[r,i]of FC.entries())t(r),e=e&&i.processed;return e},"compileTasks"),Edt=o(function(){return kdt()},"getActors"),PU={getConfig:o(()=>ge().journey,"getConfig"),clear:vdt,setDiagramTitle:Mr,getDiagramTitle:Nr,setAccTitle:Ar,getAccTitle:Dr,setAccDescription:Lr,getAccDescription:Rr,addSection:xdt,getSections:bdt,getTasks:Tdt,addTask:Cdt,addTaskOrg:wdt,getActors:Edt}});var Sdt,F5e,$5e=P(()=>{"use strict";wy();Sdt=o(t=>`.label { + font-family: ${t.fontFamily}; + color: ${t.textColor}; + } + .mouth { + stroke: #666; + } + + line { + stroke: ${t.textColor} + } + + .legend { + fill: ${t.textColor}; + font-family: ${t.fontFamily}; + } + + .label text { + fill: #333; + } + .label { + color: ${t.textColor} + } + + .face { + ${t.faceColor?`fill: ${t.faceColor}`:"fill: #FFF8DC"}; + stroke: #999; + } + + .node rect, + .node circle, + .node ellipse, + .node polygon, + .node path { + fill: ${t.mainBkg}; + stroke: ${t.nodeBorder}; + stroke-width: 1px; + } + + .node .label { + text-align: center; + } + .node.clickable { + cursor: pointer; + } + + .arrowheadPath { + fill: ${t.arrowheadColor}; + } + + .edgePath .path { + stroke: ${t.lineColor}; + stroke-width: 1.5px; + } + + .flowchart-link { + stroke: ${t.lineColor}; + fill: none; + } + + .edgeLabel { + background-color: ${t.edgeLabelBackground}; + rect { + opacity: 0.5; + } + text-align: center; + } + + .cluster rect { + } + + .cluster text { + fill: ${t.titleColor}; + } + + div.mermaidTooltip { + position: absolute; + text-align: center; + max-width: 200px; + padding: 2px; + font-family: ${t.fontFamily}; + font-size: 12px; + background: ${t.tertiaryColor}; + border: 1px solid ${t.border2}; + border-radius: 2px; + pointer-events: none; + z-index: 100; + } + + .task-type-0, .section-type-0 { + ${t.fillType0?`fill: ${t.fillType0}`:""}; + } + .task-type-1, .section-type-1 { + ${t.fillType0?`fill: ${t.fillType1}`:""}; + } + .task-type-2, .section-type-2 { + ${t.fillType0?`fill: ${t.fillType2}`:""}; + } + .task-type-3, .section-type-3 { + ${t.fillType0?`fill: ${t.fillType3}`:""}; + } + .task-type-4, .section-type-4 { + ${t.fillType0?`fill: ${t.fillType4}`:""}; + } + .task-type-5, .section-type-5 { + ${t.fillType0?`fill: ${t.fillType5}`:""}; + } + .task-type-6, .section-type-6 { + ${t.fillType0?`fill: ${t.fillType6}`:""}; + } + .task-type-7, .section-type-7 { + ${t.fillType0?`fill: ${t.fillType7}`:""}; + } + + .actor-0 { + ${t.actor0?`fill: ${t.actor0}`:""}; + } + .actor-1 { + ${t.actor1?`fill: ${t.actor1}`:""}; + } + .actor-2 { + ${t.actor2?`fill: ${t.actor2}`:""}; + } + .actor-3 { + ${t.actor3?`fill: ${t.actor3}`:""}; + } + .actor-4 { + ${t.actor4?`fill: ${t.actor4}`:""}; + } + .actor-5 { + ${t.actor5?`fill: ${t.actor5}`:""}; + } + ${qu()} +`,"getStyles"),F5e=Sdt});var FU,Adt,z5e,G5e,_dt,Ddt,BU,Ldt,Rdt,V5e,Ndt,ax,q5e=P(()=>{"use strict";Pr();y0();FU=o(function(t,e){return g0(t,e)},"drawRect"),Adt=o(function(t,e){let i=t.append("circle").attr("cx",e.cx).attr("cy",e.cy).attr("class","face").attr("r",15).attr("stroke-width",2).attr("overflow","visible"),n=t.append("g");n.append("circle").attr("cx",e.cx-15/3).attr("cy",e.cy-15/3).attr("r",1.5).attr("stroke-width",2).attr("fill","#666").attr("stroke","#666"),n.append("circle").attr("cx",e.cx+15/3).attr("cy",e.cy-15/3).attr("r",1.5).attr("stroke-width",2).attr("fill","#666").attr("stroke","#666");function a(u){let h=kc().startAngle(Math.PI/2).endAngle(3*(Math.PI/2)).innerRadius(7.5).outerRadius(6.8181818181818175);u.append("path").attr("class","mouth").attr("d",h).attr("transform","translate("+e.cx+","+(e.cy+2)+")")}o(a,"smile");function s(u){let h=kc().startAngle(3*Math.PI/2).endAngle(5*(Math.PI/2)).innerRadius(7.5).outerRadius(6.8181818181818175);u.append("path").attr("class","mouth").attr("d",h).attr("transform","translate("+e.cx+","+(e.cy+7)+")")}o(s,"sad");function l(u){u.append("line").attr("class","mouth").attr("stroke",2).attr("x1",e.cx-5).attr("y1",e.cy+7).attr("x2",e.cx+5).attr("y2",e.cy+7).attr("class","mouth").attr("stroke-width","1px").attr("stroke","#666")}return o(l,"ambivalent"),e.score>3?a(n):e.score<3?s(n):l(n),i},"drawFace"),z5e=o(function(t,e){let r=t.append("circle");return r.attr("cx",e.cx),r.attr("cy",e.cy),r.attr("class","actor-"+e.pos),r.attr("fill",e.fill),r.attr("stroke",e.stroke),r.attr("r",e.r),r.class!==void 0&&r.attr("class",r.class),e.title!==void 0&&r.append("title").text(e.title),r},"drawCircle"),G5e=o(function(t,e){return ure(t,e)},"drawText"),_dt=o(function(t,e){function r(n,a,s,l,u){return n+","+a+" "+(n+s)+","+a+" "+(n+s)+","+(a+l-u)+" "+(n+s-u*1.2)+","+(a+l)+" "+n+","+(a+l)}o(r,"genPoints");let i=t.append("polygon");i.attr("points",r(e.x,e.y,50,20,7)),i.attr("class","labelBox"),e.y=e.y+e.labelMargin,e.x=e.x+.5*e.labelMargin,G5e(t,e)},"drawLabel"),Ddt=o(function(t,e,r){let i=t.append("g"),n=ja();n.x=e.x,n.y=e.y,n.fill=e.fill,n.width=r.width*e.taskCount+r.diagramMarginX*(e.taskCount-1),n.height=r.height,n.class="journey-section section-type-"+e.num,n.rx=3,n.ry=3,FU(i,n),V5e(r)(e.text,i,n.x,n.y,n.width,n.height,{class:"journey-section section-type-"+e.num},r,e.colour)},"drawSection"),BU=-1,Ldt=o(function(t,e,r,i){let n=e.x+r.width/2,a=t.append("g");BU++,a.append("line").attr("id",i+"-task"+BU).attr("x1",n).attr("y1",e.y).attr("x2",n).attr("y2",450).attr("class","task-line").attr("stroke-width","1px").attr("stroke-dasharray","4 2").attr("stroke","#666"),Adt(a,{cx:n,cy:300+(5-e.score)*30,score:e.score});let l=ja();l.x=e.x,l.y=e.y,l.fill=e.fill,l.width=r.width,l.height=r.height,l.class="task task-type-"+e.num,l.rx=3,l.ry=3,FU(a,l);let u=e.x+14;e.people.forEach(h=>{let f=e.actors[h].color,d={cx:u,cy:e.y,r:7,fill:f,stroke:"#000",title:h,pos:e.actors[h].position};z5e(a,d),u+=10}),V5e(r)(e.task,a,l.x,l.y,l.width,l.height,{class:"task"},r,e.colour)},"drawTask"),Rdt=o(function(t,e){k3(t,e)},"drawBackgroundRect"),V5e=(function(){function t(n,a,s,l,u,h,f,d){let p=a.append("text").attr("x",s+u/2).attr("y",l+h/2+5).style("font-color",d).style("text-anchor","middle").text(n);i(p,f)}o(t,"byText");function e(n,a,s,l,u,h,f,d,p){let{taskFontSize:m,taskFontFamily:g}=d,y=n.split(//gi);for(let v=0;v{let a=Ef[n].color,s={cx:20,cy:i,r:7,fill:a,stroke:"#000",pos:Ef[n].position};ax.drawCircle(t,s);let l=t.append("text").attr("visibility","hidden").text(n),u=l.node().getBoundingClientRect().width;l.remove();let h=[];if(u<=r)h=[n];else{let f=n.split(" "),d="";l=t.append("text").attr("visibility","hidden"),f.forEach(p=>{let m=d?`${d} ${p}`:p;if(l.text(m),l.node().getBoundingClientRect().width>r){if(d&&h.push(d),d=p,l.text(p),l.node().getBoundingClientRect().width>r){let y="";for(let v of p)y+=v,l.text(y+"-"),l.node().getBoundingClientRect().width>r&&(h.push(y.slice(0,-1)+"-"),y=v);d=y}}else d=m}),d&&h.push(d),l.remove()}h.forEach((f,d)=>{let p={x:40,y:i+7+d*20,fill:"#666",text:f,textMargin:e.boxTextMargin??5},g=ax.drawText(t,p).node().getBoundingClientRect().width;g>z_&&g>e.leftMargin-g&&(z_=g)}),i+=Math.max(20,h.length*20)})}var Idt,Ef,z_,jc,Rp,Odt,ic,$U,W5e,Pdt,zU,U5e=P(()=>{"use strict";Pr();q5e();Ut();Xi();Idt=o(function(t){Object.keys(t).forEach(function(r){jc[r]=t[r]})},"setConf"),Ef={},z_=0;o(Mdt,"drawActorLegend");jc=ge().journey,Rp=0,Odt=o(function(t,e,r,i){let n=ge(),a=n.journey.titleColor,s=n.journey.titleFontSize,l=n.journey.titleFontFamily,u=n.securityLevel,h;u==="sandbox"&&(h=Ze("#i"+e));let f=u==="sandbox"?Ze(h.nodes()[0].contentDocument.body):Ze("body");ic.init();let d=f.select("#"+e);ax.initGraphics(d,e);let p=i.db.getTasks(),m=i.db.getDiagramTitle(),g=i.db.getActors();for(let w in Ef)delete Ef[w];let y=0;g.forEach(w=>{Ef[w]={color:jc.actorColours[y%jc.actorColours.length],position:y},y++}),Mdt(d),Rp=jc.leftMargin+z_,ic.insert(0,0,Rp,Object.keys(Ef).length*50),Pdt(d,p,0,e);let v=ic.getBounds();m&&d.append("text").text(m).attr("x",Rp).attr("font-size",s).attr("font-weight","bold").attr("y",25).attr("fill",a).attr("font-family",l);let x=v.stopy-v.starty+2*jc.diagramMarginY,b=Rp+v.stopx+2*jc.diagramMarginX;Hr(d,x,b,jc.useMaxWidth),d.append("line").attr("x1",Rp).attr("y1",jc.height*4).attr("x2",b-Rp-4).attr("y2",jc.height*4).attr("stroke-width",4).attr("stroke","black").attr("marker-end","url(#"+e+"-arrowhead)");let T=m?70:0;d.attr("viewBox",`${v.startx} -25 ${b} ${x+T}`),d.attr("preserveAspectRatio","xMinYMin meet"),d.attr("height",x+T+25)},"draw"),ic={data:{startx:void 0,stopx:void 0,starty:void 0,stopy:void 0},verticalPos:0,sequenceItems:[],init:o(function(){this.sequenceItems=[],this.data={startx:void 0,stopx:void 0,starty:void 0,stopy:void 0},this.verticalPos=0},"init"),updateVal:o(function(t,e,r,i){t[e]===void 0?t[e]=r:t[e]=i(r,t[e])},"updateVal"),updateBounds:o(function(t,e,r,i){let n=ge().journey,a=this,s=0;function l(u){return o(function(f){s++;let d=a.sequenceItems.length-s+1;a.updateVal(f,"starty",e-d*n.boxMargin,Math.min),a.updateVal(f,"stopy",i+d*n.boxMargin,Math.max),a.updateVal(ic.data,"startx",t-d*n.boxMargin,Math.min),a.updateVal(ic.data,"stopx",r+d*n.boxMargin,Math.max),u!=="activation"&&(a.updateVal(f,"startx",t-d*n.boxMargin,Math.min),a.updateVal(f,"stopx",r+d*n.boxMargin,Math.max),a.updateVal(ic.data,"starty",e-d*n.boxMargin,Math.min),a.updateVal(ic.data,"stopy",i+d*n.boxMargin,Math.max))},"updateItemBounds")}o(l,"updateFn"),this.sequenceItems.forEach(l())},"updateBounds"),insert:o(function(t,e,r,i){let n=Math.min(t,r),a=Math.max(t,r),s=Math.min(e,i),l=Math.max(e,i);this.updateVal(ic.data,"startx",n,Math.min),this.updateVal(ic.data,"starty",s,Math.min),this.updateVal(ic.data,"stopx",a,Math.max),this.updateVal(ic.data,"stopy",l,Math.max),this.updateBounds(n,s,a,l)},"insert"),bumpVerticalPos:o(function(t){this.verticalPos=this.verticalPos+t,this.data.stopy=this.verticalPos},"bumpVerticalPos"),getVerticalPos:o(function(){return this.verticalPos},"getVerticalPos"),getBounds:o(function(){return this.data},"getBounds")},$U=jc.sectionFills,W5e=jc.sectionColours,Pdt=o(function(t,e,r,i){let n=ge().journey,a="",s=n.height*2+n.diagramMarginY,l=r+s,u=0,h="#CCC",f="black",d=0;for(let[p,m]of e.entries()){if(a!==m.section){h=$U[u%$U.length],d=u%$U.length,f=W5e[u%W5e.length];let y=0,v=m.section;for(let b=p;b(Ef[v]&&(y[v]=Ef[v]),y),{});m.x=p*n.taskMargin+p*n.width+Rp,m.y=l,m.width=n.diagramMarginX,m.height=n.diagramMarginY,m.colour=f,m.fill=h,m.num=d,m.actors=g,ax.drawTask(t,m,n,i),ic.insert(m.x,m.y,m.x+m.width+n.taskMargin,450)}},"drawTasks"),zU={setConf:Idt,draw:Odt}});var H5e={};ur(H5e,{diagram:()=>Bdt});var Bdt,Y5e=P(()=>{"use strict";O5e();B5e();$5e();U5e();Bdt={parser:M5e,db:PU,renderer:zU,styles:F5e,init:o(t=>{zU.setConf(t.journey),PU.clear()},"init")}});var VU,eEe,tEe=P(()=>{"use strict";VU=(function(){var t=o(function(p,m,g,y){for(g=g||{},y=p.length;y--;g[p[y]]=m);return g},"o"),e=[6,11,13,14,15,17,19,20,23,24],r=[1,12],i=[1,13],n=[1,14],a=[1,15],s=[1,16],l=[1,19],u=[1,20],h={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,timeline_header:4,document:5,EOF:6,timeline:7,timeline_lr:8,timeline_td:9,line:10,SPACE:11,statement:12,NEWLINE:13,title:14,acc_title:15,acc_title_value:16,acc_descr:17,acc_descr_value:18,acc_descr_multiline_value:19,section:20,period_statement:21,event_statement:22,period:23,event:24,$accept:0,$end:1},terminals_:{2:"error",6:"EOF",7:"timeline",8:"timeline_lr",9:"timeline_td",11:"SPACE",13:"NEWLINE",14:"title",15:"acc_title",16:"acc_title_value",17:"acc_descr",18:"acc_descr_value",19:"acc_descr_multiline_value",20:"section",23:"period",24:"event"},productions_:[0,[3,3],[4,1],[4,1],[4,1],[5,0],[5,2],[10,2],[10,1],[10,1],[10,1],[12,1],[12,2],[12,2],[12,1],[12,1],[12,1],[12,1],[21,1],[22,1]],performAction:o(function(m,g,y,v,x,b,T){var w=b.length-1;switch(x){case 1:return b[w-1];case 3:v.setDirection("LR");break;case 4:v.setDirection("TD");break;case 5:this.$=[];break;case 6:b[w-1].push(b[w]),this.$=b[w-1];break;case 7:case 8:this.$=b[w];break;case 9:case 10:this.$=[];break;case 11:v.getCommonDb().setDiagramTitle(b[w].substr(6)),this.$=b[w].substr(6);break;case 12:this.$=b[w].trim(),v.getCommonDb().setAccTitle(this.$);break;case 13:case 14:this.$=b[w].trim(),v.getCommonDb().setAccDescription(this.$);break;case 15:v.addSection(b[w].substr(8)),this.$=b[w].substr(8);break;case 18:v.addTask(b[w],0,""),this.$=b[w];break;case 19:v.addEvent(b[w].substr(2)),this.$=b[w];break}},"anonymous"),table:[{3:1,4:2,7:[1,3],8:[1,4],9:[1,5]},{1:[3]},t(e,[2,5],{5:6}),t(e,[2,2]),t(e,[2,3]),t(e,[2,4]),{6:[1,7],10:8,11:[1,9],12:10,13:[1,11],14:r,15:i,17:n,19:a,20:s,21:17,22:18,23:l,24:u},t(e,[2,10],{1:[2,1]}),t(e,[2,6]),{12:21,14:r,15:i,17:n,19:a,20:s,21:17,22:18,23:l,24:u},t(e,[2,8]),t(e,[2,9]),t(e,[2,11]),{16:[1,22]},{18:[1,23]},t(e,[2,14]),t(e,[2,15]),t(e,[2,16]),t(e,[2,17]),t(e,[2,18]),t(e,[2,19]),t(e,[2,7]),t(e,[2,12]),t(e,[2,13])],defaultActions:{},parseError:o(function(m,g){if(g.recoverable)this.trace(m);else{var y=new Error(m);throw y.hash=g,y}},"parseError"),parse:o(function(m){var g=this,y=[0],v=[],x=[null],b=[],T=this.table,w="",k=0,C=0,E=0,S=2,L=1,M=b.slice.call(arguments,1),I=Object.create(this.lexer),A={yy:{}};for(var _ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,_)&&(A.yy[_]=this.yy[_]);I.setInput(m,A.yy),A.yy.lexer=I,A.yy.parser=this,typeof I.yylloc>"u"&&(I.yylloc={});var D=I.yylloc;b.push(D);var N=I.options&&I.options.ranges;typeof A.yy.parseError=="function"?this.parseError=A.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function R(ee){y.length=y.length-2*ee,x.length=x.length-ee,b.length=b.length-ee}o(R,"popStack");function B(){var ee;return ee=v.pop()||I.lex()||L,typeof ee!="number"&&(ee instanceof Array&&(v=ee,ee=v.pop()),ee=g.symbols_[ee]||ee),ee}o(B,"lex");for(var O,$,z,F,V,H,X={},W,Z,Y,ae;;){if(z=y[y.length-1],this.defaultActions[z]?F=this.defaultActions[z]:((O===null||typeof O>"u")&&(O=B()),F=T[z]&&T[z][O]),typeof F>"u"||!F.length||!F[0]){var J="";ae=[];for(W in T[z])this.terminals_[W]&&W>S&&ae.push("'"+this.terminals_[W]+"'");I.showPosition?J="Parse error on line "+(k+1)+`: +`+I.showPosition()+` +Expecting `+ae.join(", ")+", got '"+(this.terminals_[O]||O)+"'":J="Parse error on line "+(k+1)+": Unexpected "+(O==L?"end of input":"'"+(this.terminals_[O]||O)+"'"),this.parseError(J,{text:I.match,token:this.terminals_[O]||O,line:I.yylineno,loc:D,expected:ae})}if(F[0]instanceof Array&&F.length>1)throw new Error("Parse Error: multiple actions possible at state: "+z+", token: "+O);switch(F[0]){case 1:y.push(O),x.push(I.yytext),b.push(I.yylloc),y.push(F[1]),O=null,$?(O=$,$=null):(C=I.yyleng,w=I.yytext,k=I.yylineno,D=I.yylloc,E>0&&E--);break;case 2:if(Z=this.productions_[F[1]][1],X.$=x[x.length-Z],X._$={first_line:b[b.length-(Z||1)].first_line,last_line:b[b.length-1].last_line,first_column:b[b.length-(Z||1)].first_column,last_column:b[b.length-1].last_column},N&&(X._$.range=[b[b.length-(Z||1)].range[0],b[b.length-1].range[1]]),H=this.performAction.apply(X,[w,C,k,A.yy,F[1],x,b].concat(M)),typeof H<"u")return H;Z&&(y=y.slice(0,-1*Z*2),x=x.slice(0,-1*Z),b=b.slice(0,-1*Z)),y.push(this.productions_[F[1]][0]),x.push(X.$),b.push(X._$),Y=T[y[y.length-2]][y[y.length-1]],y.push(Y);break;case 3:return!0}}return!0},"parse")},f=(function(){var p={EOF:1,parseError:o(function(g,y){if(this.yy.parser)this.yy.parser.parseError(g,y);else throw new Error(g)},"parseError"),setInput:o(function(m,g){return this.yy=g||this.yy||{},this._input=m,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var m=this._input[0];this.yytext+=m,this.yyleng++,this.offset++,this.match+=m,this.matched+=m;var g=m.match(/(?:\r\n?|\n).*/g);return g?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),m},"input"),unput:o(function(m){var g=m.length,y=m.split(/(?:\r\n?|\n)/g);this._input=m+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-g),this.offset-=g;var v=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),y.length-1&&(this.yylineno-=y.length-1);var x=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:y?(y.length===v.length?this.yylloc.first_column:0)+v[v.length-y.length].length-y[0].length:this.yylloc.first_column-g},this.options.ranges&&(this.yylloc.range=[x[0],x[0]+this.yyleng-g]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(m){this.unput(this.match.slice(m))},"less"),pastInput:o(function(){var m=this.matched.substr(0,this.matched.length-this.match.length);return(m.length>20?"...":"")+m.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var m=this.match;return m.length<20&&(m+=this._input.substr(0,20-m.length)),(m.substr(0,20)+(m.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var m=this.pastInput(),g=new Array(m.length+1).join("-");return m+this.upcomingInput()+` +`+g+"^"},"showPosition"),test_match:o(function(m,g){var y,v,x;if(this.options.backtrack_lexer&&(x={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(x.yylloc.range=this.yylloc.range.slice(0))),v=m[0].match(/(?:\r\n?|\n).*/g),v&&(this.yylineno+=v.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:v?v[v.length-1].length-v[v.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+m[0].length},this.yytext+=m[0],this.match+=m[0],this.matches=m,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(m[0].length),this.matched+=m[0],y=this.performAction.call(this,this.yy,this,g,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),y)return y;if(this._backtrack){for(var b in x)this[b]=x[b];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var m,g,y,v;this._more||(this.yytext="",this.match="");for(var x=this._currentRules(),b=0;bg[0].length)){if(g=y,v=b,this.options.backtrack_lexer){if(m=this.test_match(y,x[b]),m!==!1)return m;if(this._backtrack){g=!1;continue}else return!1}else if(!this.options.flex)break}return g?(m=this.test_match(g,x[v]),m!==!1?m:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var g=this.next();return g||this.lex()},"lex"),begin:o(function(g){this.conditionStack.push(g)},"begin"),popState:o(function(){var g=this.conditionStack.length-1;return g>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(g){return g=this.conditionStack.length-1-Math.abs(g||0),g>=0?this.conditionStack[g]:"INITIAL"},"topState"),pushState:o(function(g){this.begin(g)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:o(function(g,y,v,x){var b=x;switch(v){case 0:break;case 1:break;case 2:return 13;case 3:break;case 4:break;case 5:return 8;case 6:return 9;case 7:return 7;case 8:return 14;case 9:return this.begin("acc_title"),15;break;case 10:return this.popState(),"acc_title_value";break;case 11:return this.begin("acc_descr"),17;break;case 12:return this.popState(),"acc_descr_value";break;case 13:this.begin("acc_descr_multiline");break;case 14:this.popState();break;case 15:return"acc_descr_multiline_value";case 16:return 20;case 17:return 24;case 18:return 23;case 19:return 6;case 20:return"INVALID"}},"anonymous"),rules:[/^(?:%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[\n]+)/i,/^(?:\s+)/i,/^(?:#[^\n]*)/i,/^(?:timeline[ \t]+LR\b)/i,/^(?:timeline[ \t]+TD\b)/i,/^(?:timeline\b)/i,/^(?:title\s[^\n]+)/i,/^(?:accTitle\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*:\s*)/i,/^(?:(?!\n||)*[^\n]*)/i,/^(?:accDescr\s*\{\s*)/i,/^(?:[\}])/i,/^(?:[^\}]*)/i,/^(?:section\s[^:\n]+)/i,/^(?::\s(?:[^:\n]|:(?!\s))+)/i,/^(?:[^#:\n]+)/i,/^(?:$)/i,/^(?:.)/i],conditions:{acc_descr_multiline:{rules:[14,15],inclusive:!1},acc_descr:{rules:[12],inclusive:!1},acc_title:{rules:[10],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,7,8,9,11,13,16,17,18,19,20],inclusive:!0}}};return p})();h.lexer=f;function d(){this.yy={}}return o(d,"Parser"),d.prototype=h,h.Parser=d,new d})();VU.parser=VU;eEe=VU});var UU={};ur(UU,{addEvent:()=>fEe,addSection:()=>lEe,addTask:()=>hEe,addTaskOrg:()=>dEe,clear:()=>aEe,default:()=>Hdt,getCommonDb:()=>nEe,getDirection:()=>oEe,getSections:()=>cEe,getTasks:()=>uEe,setDirection:()=>sEe});var sx,iEe,qU,WU,G_,ox,nEe,aEe,sEe,oEe,lEe,cEe,uEe,hEe,fEe,dEe,rEe,Hdt,pEe=P(()=>{"use strict";Ki();sx="",iEe=0,qU="LR",WU=[],G_=[],ox=[],nEe=o(()=>e2,"getCommonDb"),aEe=o(function(){WU.length=0,G_.length=0,sx="",ox.length=0,qU="LR",wr()},"clear"),sEe=o(function(t){qU=t},"setDirection"),oEe=o(function(){return qU},"getDirection"),lEe=o(function(t){sx=t,WU.push(t)},"addSection"),cEe=o(function(){return WU},"getSections"),uEe=o(function(){let t=rEe(),e=100,r=0;for(;!t&&rr.id===iEe-1).events.push(t)},"addEvent"),dEe=o(function(t){let e={section:sx,type:sx,description:t,task:t,classes:[]};G_.push(e)},"addTaskOrg"),rEe=o(function(){let t=o(function(r){return ox[r].processed},"compileTask"),e=!0;for(let[r,i]of ox.entries())t(r),e=e&&i.processed;return e},"compileTasks"),Hdt={clear:aEe,getCommonDb:nEe,getDirection:oEe,setDirection:sEe,addSection:lEe,getSections:cEe,getTasks:uEe,addTask:hEe,addTaskOrg:dEe,addEvent:fEe}});function vEe(t,e){t.each(function(){var r=Ze(this),i=r.text().split(/(\s+|
    )/).reverse(),n,a=[],s=1.1,l=r.attr("y"),u=parseFloat(r.attr("dy")),h=r.text(null).append("tspan").attr("x",0).attr("y",l).attr("dy",u+"em");for(let f=0;fe||n==="
    ")&&(a.pop(),h.text(a.join(" ").trim()),n==="
    "?a=[""]:a=[n],h=r.append("tspan").attr("x",0).attr("y",l).attr("dy",s+"em").text(n))})}var mEe,V_,Ydt,jdt,gEe,Xdt,Kdt,HU,Qdt,Zdt,Jdt,YU,yEe,ept,tpt,rpt,ipt,As,jU=P(()=>{"use strict";Pr();mEe=0,V_=o(function(t,e){let r=t.append("rect");return r.attr("x",e.x),r.attr("y",e.y),r.attr("fill",e.fill),r.attr("stroke",e.stroke),r.attr("width",e.width),r.attr("height",e.height),r.attr("rx",e.rx),r.attr("ry",e.ry),e.class!==void 0&&r.attr("class",e.class),r},"drawRect"),Ydt=o(function(t,e){let i=t.append("circle").attr("cx",e.cx).attr("cy",e.cy).attr("class","face").attr("r",15).attr("stroke-width",2).attr("overflow","visible"),n=t.append("g");n.append("circle").attr("cx",e.cx-15/3).attr("cy",e.cy-15/3).attr("r",1.5).attr("stroke-width",2).attr("fill","#666").attr("stroke","#666"),n.append("circle").attr("cx",e.cx+15/3).attr("cy",e.cy-15/3).attr("r",1.5).attr("stroke-width",2).attr("fill","#666").attr("stroke","#666");function a(u){let h=kc().startAngle(Math.PI/2).endAngle(3*(Math.PI/2)).innerRadius(7.5).outerRadius(6.8181818181818175);u.append("path").attr("class","mouth").attr("d",h).attr("transform","translate("+e.cx+","+(e.cy+2)+")")}o(a,"smile");function s(u){let h=kc().startAngle(3*Math.PI/2).endAngle(5*(Math.PI/2)).innerRadius(7.5).outerRadius(6.8181818181818175);u.append("path").attr("class","mouth").attr("d",h).attr("transform","translate("+e.cx+","+(e.cy+7)+")")}o(s,"sad");function l(u){u.append("line").attr("class","mouth").attr("stroke",2).attr("x1",e.cx-5).attr("y1",e.cy+7).attr("x2",e.cx+5).attr("y2",e.cy+7).attr("class","mouth").attr("stroke-width","1px").attr("stroke","#666")}return o(l,"ambivalent"),e.score>3?a(n):e.score<3?s(n):l(n),i},"drawFace"),jdt=o(function(t,e){let r=t.append("circle");return r.attr("cx",e.cx),r.attr("cy",e.cy),r.attr("class","actor-"+e.pos),r.attr("fill",e.fill),r.attr("stroke",e.stroke),r.attr("r",e.r),r.class!==void 0&&r.attr("class",r.class),e.title!==void 0&&r.append("title").text(e.title),r},"drawCircle"),gEe=o(function(t,e){let r=e.text.replace(//gi," "),i=t.append("text");i.attr("x",e.x),i.attr("y",e.y),i.attr("class","legend"),i.style("text-anchor",e.anchor),e.class!==void 0&&i.attr("class",e.class);let n=i.append("tspan");return n.attr("x",e.x+e.textMargin*2),n.text(r),i},"drawText"),Xdt=o(function(t,e){function r(n,a,s,l,u){return n+","+a+" "+(n+s)+","+a+" "+(n+s)+","+(a+l-u)+" "+(n+s-u*1.2)+","+(a+l)+" "+n+","+(a+l)}o(r,"genPoints");let i=t.append("polygon");i.attr("points",r(e.x,e.y,50,20,7)),i.attr("class","labelBox"),e.y=e.y+e.labelMargin,e.x=e.x+.5*e.labelMargin,gEe(t,e)},"drawLabel"),Kdt=o(function(t,e,r){let i=t.append("g"),n=YU();n.x=e.x,n.y=e.y,n.fill=e.fill,n.width=r.width,n.height=r.height,n.class="journey-section section-type-"+e.num,n.rx=3,n.ry=3,V_(i,n),yEe(r)(e.text,i,n.x,n.y,n.width,n.height,{class:"journey-section section-type-"+e.num},r,e.colour)},"drawSection"),HU=-1,Qdt=o(function(t,e,r,i){let n=e.x+r.width/2,a=t.append("g");HU++,a.append("line").attr("id",i+"-task"+HU).attr("x1",n).attr("y1",e.y).attr("x2",n).attr("y2",450).attr("class","task-line").attr("stroke-width","1px").attr("stroke-dasharray","4 2").attr("stroke","#666"),Ydt(a,{cx:n,cy:300+(5-e.score)*30,score:e.score});let l=YU();l.x=e.x,l.y=e.y,l.fill=e.fill,l.width=r.width,l.height=r.height,l.class="task task-type-"+e.num,l.rx=3,l.ry=3,V_(a,l),yEe(r)(e.task,a,l.x,l.y,l.width,l.height,{class:"task"},r,e.colour)},"drawTask"),Zdt=o(function(t,e){V_(t,{x:e.startx,y:e.starty,width:e.stopx-e.startx,height:e.stopy-e.starty,fill:e.fill,class:"rect"}).lower()},"drawBackgroundRect"),Jdt=o(function(){return{x:0,y:0,fill:void 0,"text-anchor":"start",width:100,height:100,textMargin:0,rx:0,ry:0}},"getTextObj"),YU=o(function(){return{x:0,y:0,width:100,anchor:"start",height:100,rx:0,ry:0}},"getNoteRect"),yEe=(function(){function t(n,a,s,l,u,h,f,d){let p=a.append("text").attr("x",s+u/2).attr("y",l+h/2+5).style("font-color",d).style("text-anchor","middle").text(n);i(p,f)}o(t,"byText");function e(n,a,s,l,u,h,f,d,p){let{taskFontSize:m,taskFontFamily:g}=d,y=n.split(//gi);for(let v=0;v0?`M0 ${e.height-l} v${-e.height+2*l} q0,-${s},${s},-${s} h${e.width-2*l} q${s},0,${s},${s} v${e.height-l} H0 Z`:`M0 ${e.height-l} v${-(e.height-l)} h${e.width} v${e.height} H0 Z`;t.append("path").attr("id",i+"-node-"+mEe++).attr("class","node-bkg node-"+e.type).attr("d",u),a?.includes("redux")||t.append("line").attr("class","node-line-"+r).attr("x1",0).attr("y1",e.height).attr("x2",e.width).attr("y2",e.height)},"defaultBkg"),As={drawRect:V_,drawCircle:jdt,drawSection:Kdt,drawText:gEe,drawLabel:Xdt,drawTask:Qdt,drawBackgroundRect:Zdt,getTextObj:Jdt,getNoteRect:YU,initGraphics:ept,drawNode:tpt,getVirtualNodeHeight:rpt}});var npt,xEe,apt,bEe,TEe=P(()=>{"use strict";Pr();jU();bt();Ut();Xi();npt=o(function(t,e,r,i){let n=ge(),{look:a,theme:s,themeVariables:l}=n,{useGradient:u,gradientStart:h,gradientStop:f}=l,d=n.timeline?.leftMargin??50;Q.debug("timeline",i.db);let p=n.securityLevel,m;p==="sandbox"&&(m=Ze("#i"+e));let y=(p==="sandbox"?Ze(m.nodes()[0].contentDocument.body):Ze("body")).select("#"+e);y.append("g");let v=i.db.getTasks(),x=i.db.getCommonDb().getDiagramTitle();Q.debug("task",v),As.initGraphics(y,e);let b=i.db.getSections();Q.debug("sections",b);let T=0,w=0,k=0,C=0,E=50+d,S=50;C=50;let L=0,M=!0;b.forEach(function(N){let R={number:L,descr:N,section:L,width:150,padding:20,maxHeight:T},B=As.getVirtualNodeHeight(y,R,n);Q.debug("sectionHeight before draw",B),T=Math.max(T,B+20)});let I=0,A=0;Q.debug("tasks.length",v.length);for(let[N,R]of v.entries()){let B={number:N,descr:R,section:R.section,width:150,padding:20,maxHeight:w},O=As.getVirtualNodeHeight(y,B,n);Q.debug("taskHeight before draw",O),w=Math.max(w,O+20),I=Math.max(I,R.events.length);let $=0;for(let z of R.events){let F={descr:z,section:R.section,number:R.section,width:150,padding:20,maxHeight:50};$+=As.getVirtualNodeHeight(y,F,n)}R.events.length>0&&($+=(R.events.length-1)*10),A=Math.max(A,$)}Q.debug("maxSectionHeight before draw",T),Q.debug("maxTaskHeight before draw",w),b&&b.length>0?b.forEach(N=>{let R=v.filter(z=>z.section===N),B={number:L,descr:N,section:L,width:200*Math.max(R.length,1)-50,padding:20,maxHeight:T};Q.debug("sectionNode",B);let O=y.append("g"),$=As.drawNode(O,B,L,n,e);Q.debug("sectionNode output",$),O.attr("transform",`translate(${E}, ${C})`),S+=T+50,R.length>0&&xEe(y,R,L,E,S,w,n,I,A,T,!1,e),E+=200*Math.max(R.length,1),S=C,L++}):(M=!1,xEe(y,v,L,E,S,w,n,I,A,T,!0,e));let _=y.node().getBBox();if(Q.debug("bounds",_),x&&y.append("text").text(x).attr("x",a==="neo"?_.x*2+d:_.width/2-d).attr("font-size","4ex").attr("font-weight","bold").attr("y",20),k=M?T+w+150:w+100,y.append("g").attr("class","lineWrapper").append("line").attr("x1",d).attr("y1",k).attr("x2",_.width+3*d).attr("y2",k).attr("stroke-width",4).attr("stroke","black").attr("marker-end",`url(#${e}-arrowhead)`),a==="neo"&&u&&s!=="neutral"){let N=y.select("defs"),B=(N.empty()?y.append("defs"):N).append("linearGradient").attr("id",y.attr("id")+"-gradient").attr("gradientUnits","objectBoundingBox").attr("x1","0%").attr("y1","0%").attr("x2","100%").attr("y2","0%");B.append("stop").attr("offset","0%").attr("stop-color",h).attr("stop-opacity",1),B.append("stop").attr("offset","100%").attr("stop-color",f).attr("stop-opacity",1)}El(void 0,y,n.timeline?.padding??50,n.timeline?.useMaxWidth??!1)},"draw"),xEe=o(function(t,e,r,i,n,a,s,l,u,h,f,d){for(let p of e){let m={descr:p.task,section:r,number:r,width:150,padding:20,maxHeight:a};Q.debug("taskNode",m);let g=t.append("g").attr("class","taskWrapper"),v=As.drawNode(g,m,r,s,d).height;if(Q.debug("taskHeight after draw",v),g.attr("transform",`translate(${i}, ${n})`),a=Math.max(a,v),p.events){let x=t.append("g").attr("class","lineWrapper"),b=a;n+=100,b=b+apt(t,p.events,r,i,n,s,d),n-=100,x.append("line").attr("x1",i+190/2).attr("y1",n+a).attr("x2",i+190/2).attr("y2",n+a+100+u+100).attr("stroke-width",2).attr("stroke","black").attr("marker-end",`url(#${d}-arrowhead)`).attr("stroke-dasharray","5,5")}i=i+200,f&&!s.timeline?.disableMulticolor&&r++}n=n-10},"drawTasks"),apt=o(function(t,e,r,i,n,a,s){let l=0,u=n;n=n+100;for(let h of e){let f={descr:h,section:r,number:r,width:150,padding:20,maxHeight:50};Q.debug("eventNode",f);let d=t.append("g").attr("class","eventWrapper"),m=As.drawNode(d,f,r,a,s,!0).height;l=l+m,d.attr("transform",`translate(${i}, ${n})`),n=n+10+m}return n=u,l},"drawEvents"),bEe={setConf:o(()=>{},"setConf"),draw:npt}});var q_,Sf,spt,XU,opt,EEe,lpt,kEe,SEe,CEe,AEe,cpt,wEe,upt,_Ee,DEe=P(()=>{"use strict";jU();bt();Ut();Xi();ro();er();q_=200,Sf=5,spt=q_+Sf*2,XU=q_+100,opt=XU+Sf*2,EEe=10,lpt=0,kEe=20,SEe=20,CEe=30,AEe=50,cpt=o(function(t,e,r,i){let n=ge(),a=n.timeline?.leftMargin??50;Q.debug("timeline",i.db);let s=Fi(e);s.append("g");let l=i.db.getTasks(),u=i.db.getCommonDb().getDiagramTitle();Q.debug("task",l),As.initGraphics(s);let h=i.db.getSections();Q.debug("sections",h);let f=0,d=0,p=50+a,m=50,g=m,y=p,v=spt+SEe,x=opt+AEe,b=y+v,T=0,w=h&&h.length>0,k=w?b:p+v,C=Math.max(50,v+x-Sf*2);h.forEach(function(N){let R={number:T,descr:N,section:T,width:C,padding:Sf,maxHeight:f},B=As.getVirtualNodeHeight(s,R,n);Q.debug("sectionHeight before draw",B),f=Math.max(f,B)});let E=0;Q.debug("tasks.length",l.length);for(let[N,R]of l.entries()){let B={number:N,descr:R,section:R.section,width:q_,padding:Sf,maxHeight:d},O=As.getVirtualNodeHeight(s,B,n);Q.debug("taskHeight before draw",O),d=Math.max(d,O);let $=0;for(let z of R.events){let F={descr:z,section:R.section,number:R.section,width:XU,padding:Sf,maxHeight:50};$+=As.getVirtualNodeHeight(s,F,n)}R.events.length>0&&($+=(R.events.length-1)*EEe),E=Math.max(E,$)+lpt}Q.debug("maxSectionHeight before draw",f),Q.debug("maxTaskHeight before draw",d);let L=Math.max(d,E)+CEe;w?h.forEach(N=>{let R=l.filter(X=>X.section===N),B={number:T,descr:N,section:T,width:C,padding:Sf,maxHeight:f};Q.debug("sectionNode",B);let O=s.append("g"),$=As.drawNode(O,B,T,n);Q.debug("sectionNode output",$);let z=k-v;O.attr("transform",`translate(${z}, ${m})`);let F=m+$.height+kEe;R.length>0&&wEe(s,R,T,k,F,d,n,L,!1);let V=R.length,H=$.height+kEe+L*Math.max(V,1)-(V>0?CEe*2:0);m+=H,T++}):wEe(s,l,T,k,m,d,n,L,!0);let M=s.node()?.getBBox();if(!M)throw new Error("bbox not found");if(Q.debug("bounds",M),u){if(s.append("text").text(u).attr("x",M.width/2-a).attr("font-size","4ex").attr("font-weight","bold").attr("y",20),M=s.node()?.getBBox(),!M)throw new Error("bbox not found");Q.debug("bounds after title",M)}let[I]=$s(n.fontSize),A=(I??16)*2,_=(I??16)*.5+20,D=s.append("g").attr("class","lineWrapper");D.append("line").attr("x1",k).attr("y1",g-A).attr("x2",k).attr("y2",M.y+M.height+_).attr("stroke-width",4).attr("stroke","black").attr("marker-end","url(#arrowhead)"),D.lower(),El(void 0,s,n.timeline?.padding??50,n.timeline?.useMaxWidth??!1)},"draw"),wEe=o(function(t,e,r,i,n,a,s,l,u){for(let h of e){let f={descr:h.task,section:r,number:r,width:q_,padding:Sf,maxHeight:a};Q.debug("taskNode",f);let d=t.append("g").attr("class","taskWrapper"),p=As.drawNode(d,f,r,s),m=p.height;Q.debug("taskHeight after draw",m);let g=i-SEe-p.width;if(d.attr("transform",`translate(${g}, ${n})`),a=Math.max(a,m),h.events&&h.events.length>0){let y=n,v=i+AEe;upt(t,h.events,r,i,v,y,s)}n=n+l,u&&!s.timeline?.disableMulticolor&&r++}},"drawTasks"),upt=o(function(t,e,r,i,n,a,s){let l=a;for(let u of e){let h={descr:u,section:r,number:r,width:XU,padding:Sf,maxHeight:0};Q.debug("eventNode",h);let f=t.append("g").attr("class","eventWrapper"),p=As.drawNode(f,h,r,s).height;f.attr("transform",`translate(${n}, ${l})`);let m=t.append("g").attr("class","lineWrapper"),g=l+p/2;m.append("line").attr("x1",i).attr("y1",g).attr("x2",n).attr("y2",g).attr("stroke-width",2).attr("stroke","black").attr("marker-end","url(#arrowhead)").attr("stroke-dasharray","5,5"),l=l+p+EEe}return l-a},"drawEvents"),_Ee={setConf:o(()=>{},"setConf"),draw:cpt}});var hpt,fpt,dpt,LEe,REe=P(()=>{"use strict";Yn();Sr();hpt=o(t=>{let{theme:e}=Lt(),r=e?.includes("dark"),i=e?.includes("color"),n=t.svgId?.replace(/^#/,"")??"",a=n?`url(#${n}-drop-shadow)`:t.dropShadow??"none",s="";for(let l=0;l{let e="";for(let r=0;r{let{theme:e}=Lt(),r=e?.includes("redux"),i=e==="neutral",n=t.svgId?.replace(/^#/,"")??"",a="";if(t.useGradient&&n&&t.THEME_COLOR_LIMIT&&!i)for(let s=0;smpt});var ppt,mpt,IEe=P(()=>{"use strict";tEe();pEe();TEe();DEe();REe();ppt={setConf:o(()=>{},"setConf"),draw:o((t,e,r,i)=>(i?.db?.getDirection?.()??"LR")==="TD"?_Ee.draw(t,e,r,i):bEe.draw(t,e,r,i),"draw")},mpt={db:UU,renderer:ppt,parser:eEe,styles:LEe}});var KU,PEe,BEe=P(()=>{"use strict";KU=(function(){var t=o(function(w,k,C,E){for(C=C||{},E=w.length;E--;C[w[E]]=k);return C},"o"),e=[1,4],r=[1,13],i=[1,12],n=[1,15],a=[1,16],s=[1,20],l=[1,19],u=[6,7,8],h=[1,26],f=[1,24],d=[1,25],p=[6,7,11],m=[1,6,13,15,16,19,22],g=[1,33],y=[1,34],v=[1,6,7,11,13,15,16,19,22],x={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,mindMap:4,spaceLines:5,SPACELINE:6,NL:7,MINDMAP:8,document:9,stop:10,EOF:11,statement:12,SPACELIST:13,node:14,ICON:15,CLASS:16,nodeWithId:17,nodeWithoutId:18,NODE_DSTART:19,NODE_DESCR:20,NODE_DEND:21,NODE_ID:22,$accept:0,$end:1},terminals_:{2:"error",6:"SPACELINE",7:"NL",8:"MINDMAP",11:"EOF",13:"SPACELIST",15:"ICON",16:"CLASS",19:"NODE_DSTART",20:"NODE_DESCR",21:"NODE_DEND",22:"NODE_ID"},productions_:[0,[3,1],[3,2],[5,1],[5,2],[5,2],[4,2],[4,3],[10,1],[10,1],[10,1],[10,2],[10,2],[9,3],[9,2],[12,2],[12,2],[12,2],[12,1],[12,1],[12,1],[12,1],[12,1],[14,1],[14,1],[18,3],[17,1],[17,4]],performAction:o(function(k,C,E,S,L,M,I){var A=M.length-1;switch(L){case 6:case 7:return S;case 8:S.getLogger().trace("Stop NL ");break;case 9:S.getLogger().trace("Stop EOF ");break;case 11:S.getLogger().trace("Stop NL2 ");break;case 12:S.getLogger().trace("Stop EOF2 ");break;case 15:S.getLogger().info("Node: ",M[A].id),S.addNode(M[A-1].length,M[A].id,M[A].descr,M[A].type);break;case 16:S.getLogger().trace("Icon: ",M[A]),S.decorateNode({icon:M[A]});break;case 17:case 21:S.decorateNode({class:M[A]});break;case 18:S.getLogger().trace("SPACELIST");break;case 19:S.getLogger().trace("Node: ",M[A].id),S.addNode(0,M[A].id,M[A].descr,M[A].type);break;case 20:S.decorateNode({icon:M[A]});break;case 25:S.getLogger().trace("node found ..",M[A-2]),this.$={id:M[A-1],descr:M[A-1],type:S.getType(M[A-2],M[A])};break;case 26:this.$={id:M[A],descr:M[A],type:S.nodeType.DEFAULT};break;case 27:S.getLogger().trace("node found ..",M[A-3]),this.$={id:M[A-3],descr:M[A-1],type:S.getType(M[A-2],M[A])};break}},"anonymous"),table:[{3:1,4:2,5:3,6:[1,5],8:e},{1:[3]},{1:[2,1]},{4:6,6:[1,7],7:[1,8],8:e},{6:r,7:[1,10],9:9,12:11,13:i,14:14,15:n,16:a,17:17,18:18,19:s,22:l},t(u,[2,3]),{1:[2,2]},t(u,[2,4]),t(u,[2,5]),{1:[2,6],6:r,12:21,13:i,14:14,15:n,16:a,17:17,18:18,19:s,22:l},{6:r,9:22,12:11,13:i,14:14,15:n,16:a,17:17,18:18,19:s,22:l},{6:h,7:f,10:23,11:d},t(p,[2,22],{17:17,18:18,14:27,15:[1,28],16:[1,29],19:s,22:l}),t(p,[2,18]),t(p,[2,19]),t(p,[2,20]),t(p,[2,21]),t(p,[2,23]),t(p,[2,24]),t(p,[2,26],{19:[1,30]}),{20:[1,31]},{6:h,7:f,10:32,11:d},{1:[2,7],6:r,12:21,13:i,14:14,15:n,16:a,17:17,18:18,19:s,22:l},t(m,[2,14],{7:g,11:y}),t(v,[2,8]),t(v,[2,9]),t(v,[2,10]),t(p,[2,15]),t(p,[2,16]),t(p,[2,17]),{20:[1,35]},{21:[1,36]},t(m,[2,13],{7:g,11:y}),t(v,[2,11]),t(v,[2,12]),{21:[1,37]},t(p,[2,25]),t(p,[2,27])],defaultActions:{2:[2,1],6:[2,2]},parseError:o(function(k,C){if(C.recoverable)this.trace(k);else{var E=new Error(k);throw E.hash=C,E}},"parseError"),parse:o(function(k){var C=this,E=[0],S=[],L=[null],M=[],I=this.table,A="",_=0,D=0,N=0,R=2,B=1,O=M.slice.call(arguments,1),$=Object.create(this.lexer),z={yy:{}};for(var F in this.yy)Object.prototype.hasOwnProperty.call(this.yy,F)&&(z.yy[F]=this.yy[F]);$.setInput(k,z.yy),z.yy.lexer=$,z.yy.parser=this,typeof $.yylloc>"u"&&($.yylloc={});var V=$.yylloc;M.push(V);var H=$.options&&$.options.ranges;typeof z.yy.parseError=="function"?this.parseError=z.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function X(Te){E.length=E.length-2*Te,L.length=L.length-Te,M.length=M.length-Te}o(X,"popStack");function W(){var Te;return Te=S.pop()||$.lex()||B,typeof Te!="number"&&(Te instanceof Array&&(S=Te,Te=S.pop()),Te=C.symbols_[Te]||Te),Te}o(W,"lex");for(var Z,Y,ae,J,ee,re,te={},be,de,Ee,Ne;;){if(ae=E[E.length-1],this.defaultActions[ae]?J=this.defaultActions[ae]:((Z===null||typeof Z>"u")&&(Z=W()),J=I[ae]&&I[ae][Z]),typeof J>"u"||!J.length||!J[0]){var we="";Ne=[];for(be in I[ae])this.terminals_[be]&&be>R&&Ne.push("'"+this.terminals_[be]+"'");$.showPosition?we="Parse error on line "+(_+1)+`: +`+$.showPosition()+` +Expecting `+Ne.join(", ")+", got '"+(this.terminals_[Z]||Z)+"'":we="Parse error on line "+(_+1)+": Unexpected "+(Z==B?"end of input":"'"+(this.terminals_[Z]||Z)+"'"),this.parseError(we,{text:$.match,token:this.terminals_[Z]||Z,line:$.yylineno,loc:V,expected:Ne})}if(J[0]instanceof Array&&J.length>1)throw new Error("Parse Error: multiple actions possible at state: "+ae+", token: "+Z);switch(J[0]){case 1:E.push(Z),L.push($.yytext),M.push($.yylloc),E.push(J[1]),Z=null,Y?(Z=Y,Y=null):(D=$.yyleng,A=$.yytext,_=$.yylineno,V=$.yylloc,N>0&&N--);break;case 2:if(de=this.productions_[J[1]][1],te.$=L[L.length-de],te._$={first_line:M[M.length-(de||1)].first_line,last_line:M[M.length-1].last_line,first_column:M[M.length-(de||1)].first_column,last_column:M[M.length-1].last_column},H&&(te._$.range=[M[M.length-(de||1)].range[0],M[M.length-1].range[1]]),re=this.performAction.apply(te,[A,D,_,z.yy,J[1],L,M].concat(O)),typeof re<"u")return re;de&&(E=E.slice(0,-1*de*2),L=L.slice(0,-1*de),M=M.slice(0,-1*de)),E.push(this.productions_[J[1]][0]),L.push(te.$),M.push(te._$),Ee=I[E[E.length-2]][E[E.length-1]],E.push(Ee);break;case 3:return!0}}return!0},"parse")},b=(function(){var w={EOF:1,parseError:o(function(C,E){if(this.yy.parser)this.yy.parser.parseError(C,E);else throw new Error(C)},"parseError"),setInput:o(function(k,C){return this.yy=C||this.yy||{},this._input=k,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var k=this._input[0];this.yytext+=k,this.yyleng++,this.offset++,this.match+=k,this.matched+=k;var C=k.match(/(?:\r\n?|\n).*/g);return C?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),k},"input"),unput:o(function(k){var C=k.length,E=k.split(/(?:\r\n?|\n)/g);this._input=k+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-C),this.offset-=C;var S=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),E.length-1&&(this.yylineno-=E.length-1);var L=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:E?(E.length===S.length?this.yylloc.first_column:0)+S[S.length-E.length].length-E[0].length:this.yylloc.first_column-C},this.options.ranges&&(this.yylloc.range=[L[0],L[0]+this.yyleng-C]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(k){this.unput(this.match.slice(k))},"less"),pastInput:o(function(){var k=this.matched.substr(0,this.matched.length-this.match.length);return(k.length>20?"...":"")+k.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var k=this.match;return k.length<20&&(k+=this._input.substr(0,20-k.length)),(k.substr(0,20)+(k.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var k=this.pastInput(),C=new Array(k.length+1).join("-");return k+this.upcomingInput()+` +`+C+"^"},"showPosition"),test_match:o(function(k,C){var E,S,L;if(this.options.backtrack_lexer&&(L={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(L.yylloc.range=this.yylloc.range.slice(0))),S=k[0].match(/(?:\r\n?|\n).*/g),S&&(this.yylineno+=S.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:S?S[S.length-1].length-S[S.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+k[0].length},this.yytext+=k[0],this.match+=k[0],this.matches=k,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(k[0].length),this.matched+=k[0],E=this.performAction.call(this,this.yy,this,C,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),E)return E;if(this._backtrack){for(var M in L)this[M]=L[M];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var k,C,E,S;this._more||(this.yytext="",this.match="");for(var L=this._currentRules(),M=0;MC[0].length)){if(C=E,S=M,this.options.backtrack_lexer){if(k=this.test_match(E,L[M]),k!==!1)return k;if(this._backtrack){C=!1;continue}else return!1}else if(!this.options.flex)break}return C?(k=this.test_match(C,L[S]),k!==!1?k:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var C=this.next();return C||this.lex()},"lex"),begin:o(function(C){this.conditionStack.push(C)},"begin"),popState:o(function(){var C=this.conditionStack.length-1;return C>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(C){return C=this.conditionStack.length-1-Math.abs(C||0),C>=0?this.conditionStack[C]:"INITIAL"},"topState"),pushState:o(function(C){this.begin(C)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:o(function(C,E,S,L){var M=L;switch(S){case 0:return C.getLogger().trace("Found comment",E.yytext),6;break;case 1:return 8;case 2:this.begin("CLASS");break;case 3:return this.popState(),16;break;case 4:this.popState();break;case 5:C.getLogger().trace("Begin icon"),this.begin("ICON");break;case 6:return C.getLogger().trace("SPACELINE"),6;break;case 7:return 7;case 8:return 15;case 9:C.getLogger().trace("end icon"),this.popState();break;case 10:return C.getLogger().trace("Exploding node"),this.begin("NODE"),19;break;case 11:return C.getLogger().trace("Cloud"),this.begin("NODE"),19;break;case 12:return C.getLogger().trace("Explosion Bang"),this.begin("NODE"),19;break;case 13:return C.getLogger().trace("Cloud Bang"),this.begin("NODE"),19;break;case 14:return this.begin("NODE"),19;break;case 15:return this.begin("NODE"),19;break;case 16:return this.begin("NODE"),19;break;case 17:return this.begin("NODE"),19;break;case 18:return 13;case 19:return 22;case 20:return 11;case 21:this.begin("NSTR2");break;case 22:return"NODE_DESCR";case 23:this.popState();break;case 24:C.getLogger().trace("Starting NSTR"),this.begin("NSTR");break;case 25:return C.getLogger().trace("description:",E.yytext),"NODE_DESCR";break;case 26:this.popState();break;case 27:return this.popState(),C.getLogger().trace("node end ))"),"NODE_DEND";break;case 28:return this.popState(),C.getLogger().trace("node end )"),"NODE_DEND";break;case 29:return this.popState(),C.getLogger().trace("node end ...",E.yytext),"NODE_DEND";break;case 30:return this.popState(),C.getLogger().trace("node end (("),"NODE_DEND";break;case 31:return this.popState(),C.getLogger().trace("node end (-"),"NODE_DEND";break;case 32:return this.popState(),C.getLogger().trace("node end (-"),"NODE_DEND";break;case 33:return this.popState(),C.getLogger().trace("node end (("),"NODE_DEND";break;case 34:return this.popState(),C.getLogger().trace("node end (("),"NODE_DEND";break;case 35:return C.getLogger().trace("Long description:",E.yytext),20;break;case 36:return C.getLogger().trace("Long description:",E.yytext),20;break}},"anonymous"),rules:[/^(?:\s*%%.*)/i,/^(?:mindmap\b)/i,/^(?::::)/i,/^(?:.+)/i,/^(?:\n)/i,/^(?:::icon\()/i,/^(?:[\s]+[\n])/i,/^(?:[\n]+)/i,/^(?:[^\)]+)/i,/^(?:\))/i,/^(?:-\))/i,/^(?:\(-)/i,/^(?:\)\))/i,/^(?:\))/i,/^(?:\(\()/i,/^(?:\{\{)/i,/^(?:\()/i,/^(?:\[)/i,/^(?:[\s]+)/i,/^(?:[^\(\[\n\)\{\}]+)/i,/^(?:$)/i,/^(?:["][`])/i,/^(?:[^`"]+)/i,/^(?:[`]["])/i,/^(?:["])/i,/^(?:[^"]+)/i,/^(?:["])/i,/^(?:[\)]\))/i,/^(?:[\)])/i,/^(?:[\]])/i,/^(?:\}\})/i,/^(?:\(-)/i,/^(?:-\))/i,/^(?:\(\()/i,/^(?:\()/i,/^(?:[^\)\]\(\}]+)/i,/^(?:.+(?!\(\())/i],conditions:{CLASS:{rules:[3,4],inclusive:!1},ICON:{rules:[8,9],inclusive:!1},NSTR2:{rules:[22,23],inclusive:!1},NSTR:{rules:[25,26],inclusive:!1},NODE:{rules:[21,24,27,28,29,30,31,32,33,34,35,36],inclusive:!1},INITIAL:{rules:[0,1,2,5,6,7,10,11,12,13,14,15,16,17,18,19,20],inclusive:!0}}};return w})();x.lexer=b;function T(){this.yy={}}return o(T,"Parser"),T.prototype=x,x.Parser=T,new T})();KU.parser=KU;PEe=KU});function FEe(t,e=0){return(os[t[e+0]]+os[t[e+1]]+os[t[e+2]]+os[t[e+3]]+"-"+os[t[e+4]]+os[t[e+5]]+"-"+os[t[e+6]]+os[t[e+7]]+"-"+os[t[e+8]]+os[t[e+9]]+"-"+os[t[e+10]]+os[t[e+11]]+os[t[e+12]]+os[t[e+13]]+os[t[e+14]]+os[t[e+15]]).toLowerCase()}var os,$Ee=P(()=>{"use strict";os=[];for(let t=0;t<256;++t)os.push((t+256).toString(16).slice(1));o(FEe,"unsafeStringify")});function ZU(){if(!QU){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");QU=crypto.getRandomValues.bind(crypto)}return QU(xpt)}var QU,xpt,zEe=P(()=>{"use strict";xpt=new Uint8Array(16);o(ZU,"rng")});var bpt,JU,GEe=P(()=>{"use strict";bpt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),JU={randomUUID:bpt}});function Tpt(t,e,r){if(JU.randomUUID&&!e&&!t)return JU.randomUUID();t=t||{};let i=t.random??t.rng?.()??ZU();if(i.length<16)throw new Error("Random bytes length must be >= 16");if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let n=0;n<16;++n)e[r+n]=i[n];return e}return FEe(i)}var eH,VEe=P(()=>{"use strict";GEe();zEe();$Ee();o(Tpt,"v4");eH=Tpt});var qEe=P(()=>{"use strict";VEe()});var WEe,UEe=P(()=>{"use strict";To();er();WEe=12});var Af,W_,HEe=P(()=>{"use strict";Ut();qEe();Vr();bt();wa();Sr();UEe();Af={DEFAULT:0,NO_BORDER:0,ROUNDED_RECT:1,RECT:2,CIRCLE:3,CLOUD:4,BANG:5,HEXAGON:6},W_=class{constructor(){this.nodes=[];this.count=0;this.elements={};this.getLogger=this.getLogger.bind(this),this.nodeType=Af,this.clear(),this.getType=this.getType.bind(this),this.getElementById=this.getElementById.bind(this),this.getParent=this.getParent.bind(this),this.getMindmap=this.getMindmap.bind(this),this.addNode=this.addNode.bind(this),this.decorateNode=this.decorateNode.bind(this)}static{o(this,"MindmapDB")}clear(){this.nodes=[],this.count=0,this.elements={},this.baseLevel=void 0}getParent(e){for(let r=this.nodes.length-1;r>=0;r--)if(this.nodes[r].level0?this.nodes[0]:null}addNode(e,r,i,n){Q.info("addNode",e,r,i,n);let a=!1;this.nodes.length===0?(this.baseLevel=e,e=0,a=!0):this.baseLevel!==void 0&&(e=e-this.baseLevel,a=!1);let s=ge(),l=s.mindmap?.padding??fr.mindmap.padding;switch(n){case this.nodeType.ROUNDED_RECT:case this.nodeType.RECT:case this.nodeType.HEXAGON:l*=2;break}let u={id:this.count++,nodeId:Tr(r,s),level:e,descr:Tr(i,s),type:n,children:[],width:s.mindmap?.maxNodeWidth??fr.mindmap.maxNodeWidth,padding:l,isRoot:a},h=this.getParent(e);if(h)h.children.push(u),this.nodes.push(u);else if(a)this.nodes.push(u);else throw new Error(`There can be only one root. No parent could be found for ("${u.descr}")`)}getType(e,r){switch(Q.debug("In get type",e,r),e){case"[":return this.nodeType.RECT;case"(":return r===")"?this.nodeType.ROUNDED_RECT:this.nodeType.CLOUD;case"((":return this.nodeType.CIRCLE;case")":return this.nodeType.CLOUD;case"))":return this.nodeType.BANG;case"{{":return this.nodeType.HEXAGON;default:return this.nodeType.DEFAULT}}setElementForId(e,r){this.elements[e]=r}getElementById(e){return this.elements[e]}decorateNode(e){if(!e)return;let r=ge(),i=this.nodes[this.nodes.length-1];e.icon&&(i.icon=Tr(e.icon,r)),e.class&&(i.class=Tr(e.class,r))}type2Str(e){switch(e){case this.nodeType.DEFAULT:return"no-border";case this.nodeType.RECT:return"rect";case this.nodeType.ROUNDED_RECT:return"rounded-rect";case this.nodeType.CIRCLE:return"circle";case this.nodeType.CLOUD:return"cloud";case this.nodeType.BANG:return"bang";case this.nodeType.HEXAGON:return"hexgon";default:return"no-border"}}assignSections(e,r){if(e.level===0?e.section=void 0:e.section=r,e.children)for(let[i,n]of e.children.entries()){let a=e.level===0?i%(WEe-1):r;this.assignSections(n,a)}}flattenNodes(e,r){let i=ge(),n=["mindmap-node"];e.isRoot===!0?n.push("section-root","section--1"):e.section!==void 0&&n.push(`section-${e.section}`),e.class&&n.push(e.class);let a=n.join(" "),s=o(u=>{let f=(i.theme?.toLowerCase()??"").includes("redux");switch(u){case Af.CIRCLE:return"mindmapCircle";case Af.RECT:return"rect";case Af.ROUNDED_RECT:return"rounded";case Af.CLOUD:return"cloud";case Af.BANG:return"bang";case Af.HEXAGON:return"hexagon";case Af.DEFAULT:return f?"rounded":"defaultMindmapNode";case Af.NO_BORDER:default:return"rect"}},"getShapeFromType"),l={id:e.id.toString(),domId:"node_"+e.id.toString(),label:e.descr,labelType:"markdown",isGroup:!1,shape:s(e.type),width:e.width,height:e.height??0,padding:e.padding,cssClasses:a,cssStyles:[],look:i.look,icon:e.icon,x:e.x,y:e.y,level:e.level,nodeId:e.nodeId,type:e.type,section:e.section};if(r.push(l),e.children)for(let u of e.children)this.flattenNodes(u,r)}generateEdges(e,r){if(!e.children)return;let i=ge();for(let n of e.children){let a="edge";n.section!==void 0&&(a+=` section-edge-${n.section}`);let s=e.level+1;a+=` edge-depth-${s}`;let l={id:`edge_${e.id}_${n.id}`,start:e.id.toString(),end:n.id.toString(),type:"normal",curve:"basis",thickness:"normal",look:i.look,classes:a,depth:e.level,section:n.section};r.push(l),this.generateEdges(n,r)}}getData(){let e=this.getMindmap(),r=ge(),n=Hj().layout!==void 0,a=r;if(n||(a.layout="cose-bilkent"),!e)return{nodes:[],edges:[],config:a};Q.debug("getData: mindmapRoot",e,r),this.assignSections(e);let s=[],l=[];this.flattenNodes(e,s),this.generateEdges(e,l),Q.debug(`getData: processed ${s.length} nodes and ${l.length} edges`);let u=new Map;for(let h of s)u.set(h.id,{shape:h.shape,width:h.width,height:h.height,padding:h.padding});return{nodes:s,edges:l,config:a,rootNode:e,markers:["point"],direction:"TB",nodeSpacing:50,rankSpacing:50,shapes:Object.fromEntries(u),type:"mindmap",diagramId:"mindmap-"+eH()}}getLogger(){return Q}}});var kpt,YEe,jEe=P(()=>{"use strict";bt();I0();Wd();Ud();wa();Sr();kpt=o(async(t,e,r,i)=>{Q.debug(`Rendering mindmap diagram +`+t);let n=i.db,a=n.getData(),s=Ol(e,a.config.securityLevel);if(a.type=i.type,a.layoutAlgorithm=Vu(a.config.layout,{fallback:"cose-bilkent"}),a.diagramId=e,!n.getMindmap())return;a.nodes.forEach(p=>{p.shape==="rounded"?(p.radius=15,p.taper=15,p.stroke="none",p.width=0,p.padding=15):p.shape==="circle"?p.padding=10:p.shape==="rect"?(p.width=0,p.padding=10):p.shape==="hexagon"&&(p.width=0,p.height=0)}),await Ul(a,s);let{themeVariables:u}=Lt(),{useGradient:h,gradientStart:f,gradientStop:d}=u;if(h&&f&&d){let p=s.attr("id"),m=s.append("defs").append("linearGradient").attr("id",`${p}-gradient`).attr("gradientUnits","objectBoundingBox").attr("x1","0%").attr("y1","0%").attr("x2","100%").attr("y2","0%");m.append("stop").attr("offset","0%").attr("stop-color",f).attr("stop-opacity",1),m.append("stop").attr("offset","100%").attr("stop-color",d).attr("stop-opacity",1)}Ro(s,a.config.mindmap?.padding??fr.mindmap.padding,"mindmapDiagram",a.config.mindmap?.useMaxWidth??fr.mindmap.useMaxWidth)},"draw"),YEe={draw:kpt}});var Cpt,wpt,Ept,XEe,KEe=P(()=>{"use strict";Yn();Cpt=o(t=>{let{theme:e,look:r}=t,i="";for(let n=0;n{let i="";for(let n=0;n{let{theme:e}=t,r=t.svgId,i=t.dropShadow?t.dropShadow.replace("url(#drop-shadow)",`url(${r}-drop-shadow)`):"none";return` + .edge { + stroke-width: 3; + } + ${Cpt(t)} + .section-root rect, .section-root path, .section-root circle, .section-root polygon { + fill: ${t.git0}; + } + .section-root text { + fill: ${t.gitBranchLabel0}; + } + .section-root span { + color: ${e?.includes("redux")?t.nodeBorder:t.gitBranchLabel0}; + } + .icon-container { + height:100%; + display: flex; + justify-content: center; + align-items: center; + } + .edge { + fill: none; + } + .mindmap-node-label { + dy: 1em; + alignment-baseline: middle; + text-anchor: middle; + dominant-baseline: middle; + text-align: center; + } + [data-look="neo"].mindmap-node { + filter: ${i}; + } + [data-look="neo"].mindmap-node.section-root rect, [data-look="neo"].mindmap-node.section-root path, [data-look="neo"].mindmap-node.section-root circle, [data-look="neo"].mindmap-node.section-root polygon { + fill: ${e?.includes("redux")?t.mainBkg:t.git0}; + } + [data-look="neo"].mindmap-node.section-root .text-inner-tspan { + fill: ${e?.includes("redux")?t.nodeBorder:t["cScaleLabel"+(e==="neutral"?1:0)]}; + } + ${t.useGradient&&r&&t.mainBkg?wpt(t.THEME_COLOR_LIMIT,r,t.mainBkg):""} +`},"getStyles"),XEe=Ept});var QEe={};ur(QEe,{diagram:()=>Spt});var Spt,ZEe=P(()=>{"use strict";BEe();HEe();jEe();KEe();Spt={get db(){return new W_},renderer:YEe,parser:PEe,styles:XEe}});var tH,tSe,rSe=P(()=>{"use strict";tH=(function(){var t=o(function(E,S,L,M){for(L=L||{},M=E.length;M--;L[E[M]]=S);return L},"o"),e=[1,4],r=[1,13],i=[1,12],n=[1,15],a=[1,16],s=[1,20],l=[1,19],u=[6,7,8],h=[1,26],f=[1,24],d=[1,25],p=[6,7,11],m=[1,31],g=[6,7,11,24],y=[1,6,13,16,17,20,23],v=[1,35],x=[1,36],b=[1,6,7,11,13,16,17,20,23],T=[1,38],w={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,mindMap:4,spaceLines:5,SPACELINE:6,NL:7,KANBAN:8,document:9,stop:10,EOF:11,statement:12,SPACELIST:13,node:14,shapeData:15,ICON:16,CLASS:17,nodeWithId:18,nodeWithoutId:19,NODE_DSTART:20,NODE_DESCR:21,NODE_DEND:22,NODE_ID:23,SHAPE_DATA:24,$accept:0,$end:1},terminals_:{2:"error",6:"SPACELINE",7:"NL",8:"KANBAN",11:"EOF",13:"SPACELIST",16:"ICON",17:"CLASS",20:"NODE_DSTART",21:"NODE_DESCR",22:"NODE_DEND",23:"NODE_ID",24:"SHAPE_DATA"},productions_:[0,[3,1],[3,2],[5,1],[5,2],[5,2],[4,2],[4,3],[10,1],[10,1],[10,1],[10,2],[10,2],[9,3],[9,2],[12,3],[12,2],[12,2],[12,2],[12,1],[12,2],[12,1],[12,1],[12,1],[12,1],[14,1],[14,1],[19,3],[18,1],[18,4],[15,2],[15,1]],performAction:o(function(S,L,M,I,A,_,D){var N=_.length-1;switch(A){case 6:case 7:return I;case 8:I.getLogger().trace("Stop NL ");break;case 9:I.getLogger().trace("Stop EOF ");break;case 11:I.getLogger().trace("Stop NL2 ");break;case 12:I.getLogger().trace("Stop EOF2 ");break;case 15:I.getLogger().info("Node: ",_[N-1].id),I.addNode(_[N-2].length,_[N-1].id,_[N-1].descr,_[N-1].type,_[N]);break;case 16:I.getLogger().info("Node: ",_[N].id),I.addNode(_[N-1].length,_[N].id,_[N].descr,_[N].type);break;case 17:I.getLogger().trace("Icon: ",_[N]),I.decorateNode({icon:_[N]});break;case 18:case 23:I.decorateNode({class:_[N]});break;case 19:I.getLogger().trace("SPACELIST");break;case 20:I.getLogger().trace("Node: ",_[N-1].id),I.addNode(0,_[N-1].id,_[N-1].descr,_[N-1].type,_[N]);break;case 21:I.getLogger().trace("Node: ",_[N].id),I.addNode(0,_[N].id,_[N].descr,_[N].type);break;case 22:I.decorateNode({icon:_[N]});break;case 27:I.getLogger().trace("node found ..",_[N-2]),this.$={id:_[N-1],descr:_[N-1],type:I.getType(_[N-2],_[N])};break;case 28:this.$={id:_[N],descr:_[N],type:0};break;case 29:I.getLogger().trace("node found ..",_[N-3]),this.$={id:_[N-3],descr:_[N-1],type:I.getType(_[N-2],_[N])};break;case 30:this.$=_[N-1]+_[N];break;case 31:this.$=_[N];break}},"anonymous"),table:[{3:1,4:2,5:3,6:[1,5],8:e},{1:[3]},{1:[2,1]},{4:6,6:[1,7],7:[1,8],8:e},{6:r,7:[1,10],9:9,12:11,13:i,14:14,16:n,17:a,18:17,19:18,20:s,23:l},t(u,[2,3]),{1:[2,2]},t(u,[2,4]),t(u,[2,5]),{1:[2,6],6:r,12:21,13:i,14:14,16:n,17:a,18:17,19:18,20:s,23:l},{6:r,9:22,12:11,13:i,14:14,16:n,17:a,18:17,19:18,20:s,23:l},{6:h,7:f,10:23,11:d},t(p,[2,24],{18:17,19:18,14:27,16:[1,28],17:[1,29],20:s,23:l}),t(p,[2,19]),t(p,[2,21],{15:30,24:m}),t(p,[2,22]),t(p,[2,23]),t(g,[2,25]),t(g,[2,26]),t(g,[2,28],{20:[1,32]}),{21:[1,33]},{6:h,7:f,10:34,11:d},{1:[2,7],6:r,12:21,13:i,14:14,16:n,17:a,18:17,19:18,20:s,23:l},t(y,[2,14],{7:v,11:x}),t(b,[2,8]),t(b,[2,9]),t(b,[2,10]),t(p,[2,16],{15:37,24:m}),t(p,[2,17]),t(p,[2,18]),t(p,[2,20],{24:T}),t(g,[2,31]),{21:[1,39]},{22:[1,40]},t(y,[2,13],{7:v,11:x}),t(b,[2,11]),t(b,[2,12]),t(p,[2,15],{24:T}),t(g,[2,30]),{22:[1,41]},t(g,[2,27]),t(g,[2,29])],defaultActions:{2:[2,1],6:[2,2]},parseError:o(function(S,L){if(L.recoverable)this.trace(S);else{var M=new Error(S);throw M.hash=L,M}},"parseError"),parse:o(function(S){var L=this,M=[0],I=[],A=[null],_=[],D=this.table,N="",R=0,B=0,O=0,$=2,z=1,F=_.slice.call(arguments,1),V=Object.create(this.lexer),H={yy:{}};for(var X in this.yy)Object.prototype.hasOwnProperty.call(this.yy,X)&&(H.yy[X]=this.yy[X]);V.setInput(S,H.yy),H.yy.lexer=V,H.yy.parser=this,typeof V.yylloc>"u"&&(V.yylloc={});var W=V.yylloc;_.push(W);var Z=V.options&&V.options.ranges;typeof H.yy.parseError=="function"?this.parseError=H.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function Y(pe){M.length=M.length-2*pe,A.length=A.length-pe,_.length=_.length-pe}o(Y,"popStack");function ae(){var pe;return pe=I.pop()||V.lex()||z,typeof pe!="number"&&(pe instanceof Array&&(I=pe,pe=I.pop()),pe=L.symbols_[pe]||pe),pe}o(ae,"lex");for(var J,ee,re,te,be,de,Ee={},Ne,we,Te,De;;){if(re=M[M.length-1],this.defaultActions[re]?te=this.defaultActions[re]:((J===null||typeof J>"u")&&(J=ae()),te=D[re]&&D[re][J]),typeof te>"u"||!te.length||!te[0]){var $e="";De=[];for(Ne in D[re])this.terminals_[Ne]&&Ne>$&&De.push("'"+this.terminals_[Ne]+"'");V.showPosition?$e="Parse error on line "+(R+1)+`: +`+V.showPosition()+` +Expecting `+De.join(", ")+", got '"+(this.terminals_[J]||J)+"'":$e="Parse error on line "+(R+1)+": Unexpected "+(J==z?"end of input":"'"+(this.terminals_[J]||J)+"'"),this.parseError($e,{text:V.match,token:this.terminals_[J]||J,line:V.yylineno,loc:W,expected:De})}if(te[0]instanceof Array&&te.length>1)throw new Error("Parse Error: multiple actions possible at state: "+re+", token: "+J);switch(te[0]){case 1:M.push(J),A.push(V.yytext),_.push(V.yylloc),M.push(te[1]),J=null,ee?(J=ee,ee=null):(B=V.yyleng,N=V.yytext,R=V.yylineno,W=V.yylloc,O>0&&O--);break;case 2:if(we=this.productions_[te[1]][1],Ee.$=A[A.length-we],Ee._$={first_line:_[_.length-(we||1)].first_line,last_line:_[_.length-1].last_line,first_column:_[_.length-(we||1)].first_column,last_column:_[_.length-1].last_column},Z&&(Ee._$.range=[_[_.length-(we||1)].range[0],_[_.length-1].range[1]]),de=this.performAction.apply(Ee,[N,B,R,H.yy,te[1],A,_].concat(F)),typeof de<"u")return de;we&&(M=M.slice(0,-1*we*2),A=A.slice(0,-1*we),_=_.slice(0,-1*we)),M.push(this.productions_[te[1]][0]),A.push(Ee.$),_.push(Ee._$),Te=D[M[M.length-2]][M[M.length-1]],M.push(Te);break;case 3:return!0}}return!0},"parse")},k=(function(){var E={EOF:1,parseError:o(function(L,M){if(this.yy.parser)this.yy.parser.parseError(L,M);else throw new Error(L)},"parseError"),setInput:o(function(S,L){return this.yy=L||this.yy||{},this._input=S,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var S=this._input[0];this.yytext+=S,this.yyleng++,this.offset++,this.match+=S,this.matched+=S;var L=S.match(/(?:\r\n?|\n).*/g);return L?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),S},"input"),unput:o(function(S){var L=S.length,M=S.split(/(?:\r\n?|\n)/g);this._input=S+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-L),this.offset-=L;var I=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),M.length-1&&(this.yylineno-=M.length-1);var A=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:M?(M.length===I.length?this.yylloc.first_column:0)+I[I.length-M.length].length-M[0].length:this.yylloc.first_column-L},this.options.ranges&&(this.yylloc.range=[A[0],A[0]+this.yyleng-L]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(S){this.unput(this.match.slice(S))},"less"),pastInput:o(function(){var S=this.matched.substr(0,this.matched.length-this.match.length);return(S.length>20?"...":"")+S.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var S=this.match;return S.length<20&&(S+=this._input.substr(0,20-S.length)),(S.substr(0,20)+(S.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var S=this.pastInput(),L=new Array(S.length+1).join("-");return S+this.upcomingInput()+` +`+L+"^"},"showPosition"),test_match:o(function(S,L){var M,I,A;if(this.options.backtrack_lexer&&(A={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(A.yylloc.range=this.yylloc.range.slice(0))),I=S[0].match(/(?:\r\n?|\n).*/g),I&&(this.yylineno+=I.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:I?I[I.length-1].length-I[I.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+S[0].length},this.yytext+=S[0],this.match+=S[0],this.matches=S,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(S[0].length),this.matched+=S[0],M=this.performAction.call(this,this.yy,this,L,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),M)return M;if(this._backtrack){for(var _ in A)this[_]=A[_];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var S,L,M,I;this._more||(this.yytext="",this.match="");for(var A=this._currentRules(),_=0;_L[0].length)){if(L=M,I=_,this.options.backtrack_lexer){if(S=this.test_match(M,A[_]),S!==!1)return S;if(this._backtrack){L=!1;continue}else return!1}else if(!this.options.flex)break}return L?(S=this.test_match(L,A[I]),S!==!1?S:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var L=this.next();return L||this.lex()},"lex"),begin:o(function(L){this.conditionStack.push(L)},"begin"),popState:o(function(){var L=this.conditionStack.length-1;return L>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(L){return L=this.conditionStack.length-1-Math.abs(L||0),L>=0?this.conditionStack[L]:"INITIAL"},"topState"),pushState:o(function(L){this.begin(L)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:o(function(L,M,I,A){var _=A;switch(I){case 0:return this.pushState("shapeData"),M.yytext="",24;break;case 1:return this.pushState("shapeDataStr"),24;break;case 2:return this.popState(),24;break;case 3:let D=/\n\s*/g;return M.yytext=M.yytext.replace(D,"
    "),24;break;case 4:return 24;case 5:this.popState();break;case 6:return L.getLogger().trace("Found comment",M.yytext),6;break;case 7:return 8;case 8:this.begin("CLASS");break;case 9:return this.popState(),17;break;case 10:this.popState();break;case 11:L.getLogger().trace("Begin icon"),this.begin("ICON");break;case 12:return L.getLogger().trace("SPACELINE"),6;break;case 13:return 7;case 14:return 16;case 15:L.getLogger().trace("end icon"),this.popState();break;case 16:return L.getLogger().trace("Exploding node"),this.begin("NODE"),20;break;case 17:return L.getLogger().trace("Cloud"),this.begin("NODE"),20;break;case 18:return L.getLogger().trace("Explosion Bang"),this.begin("NODE"),20;break;case 19:return L.getLogger().trace("Cloud Bang"),this.begin("NODE"),20;break;case 20:return this.begin("NODE"),20;break;case 21:return this.begin("NODE"),20;break;case 22:return this.begin("NODE"),20;break;case 23:return this.begin("NODE"),20;break;case 24:return 13;case 25:return 23;case 26:return 11;case 27:this.begin("NSTR2");break;case 28:return"NODE_DESCR";case 29:this.popState();break;case 30:L.getLogger().trace("Starting NSTR"),this.begin("NSTR");break;case 31:return L.getLogger().trace("description:",M.yytext),"NODE_DESCR";break;case 32:this.popState();break;case 33:return this.popState(),L.getLogger().trace("node end ))"),"NODE_DEND";break;case 34:return this.popState(),L.getLogger().trace("node end )"),"NODE_DEND";break;case 35:return this.popState(),L.getLogger().trace("node end ...",M.yytext),"NODE_DEND";break;case 36:return this.popState(),L.getLogger().trace("node end (("),"NODE_DEND";break;case 37:return this.popState(),L.getLogger().trace("node end (-"),"NODE_DEND";break;case 38:return this.popState(),L.getLogger().trace("node end (-"),"NODE_DEND";break;case 39:return this.popState(),L.getLogger().trace("node end (("),"NODE_DEND";break;case 40:return this.popState(),L.getLogger().trace("node end (("),"NODE_DEND";break;case 41:return L.getLogger().trace("Long description:",M.yytext),21;break;case 42:return L.getLogger().trace("Long description:",M.yytext),21;break}},"anonymous"),rules:[/^(?:@\{)/i,/^(?:["])/i,/^(?:["])/i,/^(?:[^\"]+)/i,/^(?:[^}^"]+)/i,/^(?:\})/i,/^(?:\s*%%.*)/i,/^(?:kanban\b)/i,/^(?::::)/i,/^(?:.+)/i,/^(?:\n)/i,/^(?:::icon\()/i,/^(?:[\s]+[\n])/i,/^(?:[\n]+)/i,/^(?:[^\)]+)/i,/^(?:\))/i,/^(?:-\))/i,/^(?:\(-)/i,/^(?:\)\))/i,/^(?:\))/i,/^(?:\(\()/i,/^(?:\{\{)/i,/^(?:\()/i,/^(?:\[)/i,/^(?:[\s]+)/i,/^(?:[^\(\[\n\)\{\}@]+)/i,/^(?:$)/i,/^(?:["][`])/i,/^(?:[^`"]+)/i,/^(?:[`]["])/i,/^(?:["])/i,/^(?:[^"]+)/i,/^(?:["])/i,/^(?:[\)]\))/i,/^(?:[\)])/i,/^(?:[\]])/i,/^(?:\}\})/i,/^(?:\(-)/i,/^(?:-\))/i,/^(?:\(\()/i,/^(?:\()/i,/^(?:[^\)\]\(\}]+)/i,/^(?:.+(?!\(\())/i],conditions:{shapeDataEndBracket:{rules:[],inclusive:!1},shapeDataStr:{rules:[2,3],inclusive:!1},shapeData:{rules:[1,4,5],inclusive:!1},CLASS:{rules:[9,10],inclusive:!1},ICON:{rules:[14,15],inclusive:!1},NSTR2:{rules:[28,29],inclusive:!1},NSTR:{rules:[31,32],inclusive:!1},NODE:{rules:[27,30,33,34,35,36,37,38,39,40,41,42],inclusive:!1},INITIAL:{rules:[0,6,7,8,11,12,13,16,17,18,19,20,21,22,23,24,25,26],inclusive:!0}}};return E})();w.lexer=k;function C(){this.yy={}}return o(C,"Parser"),C.prototype=w,w.Parser=C,new C})();tH.parser=tH;tSe=tH});var nc,iH,rH,nH,Lpt,Rpt,iSe,Npt,Ipt,ka,Mpt,Opt,Ppt,Bpt,Fpt,$pt,zpt,nSe,aSe=P(()=>{"use strict";Ut();Vr();bt();wa();xb();nc=[],iH=[],rH=0,nH={},Lpt=o(()=>{nc=[],iH=[],rH=0,nH={}},"clear"),Rpt=o(t=>{if(nc.length===0)return null;let e=nc[0].level,r=null;for(let i=nc.length-1;i>=0;i--)if(nc[i].level===e&&!r&&(r=nc[i]),nc[i].levell.parentId===n.id);for(let l of s){let u={id:l.id,parentId:n.id,label:Tr(l.label??"",i),labelType:"markdown",isGroup:!1,ticket:l?.ticket,priority:l?.priority,assigned:l?.assigned,icon:l?.icon,shape:"kanbanItem",level:l.level,rx:5,ry:5,cssStyles:["text-align: left"]};e.push(u)}}return{nodes:e,edges:t,other:{},config:ge()}},"getData"),Ipt=o((t,e,r,i,n)=>{let a=ge(),s=a.mindmap?.padding??fr.mindmap.padding;switch(i){case ka.ROUNDED_RECT:case ka.RECT:case ka.HEXAGON:s*=2}let l={id:Tr(e,a)||"kbn"+rH++,level:t,label:Tr(r,a),width:a.mindmap?.maxNodeWidth??fr.mindmap.maxNodeWidth,padding:s,isGroup:!1};if(n!==void 0){let h;n.includes(` +`)?h=n+` +`:h=`{ +`+n+` +}`;let f=ud(h,{schema:cd});if(f.shape&&(f.shape!==f.shape.toLowerCase()||f.shape.includes("_")))throw new Error(`No such shape: ${f.shape}. Shape names should be lowercase.`);f?.shape&&f.shape==="kanbanItem"&&(l.shape=f?.shape),f?.label&&(l.label=f?.label),f?.icon&&(l.icon=f?.icon.toString()),f?.assigned&&(l.assigned=f?.assigned.toString()),f?.ticket&&(l.ticket=f?.ticket.toString()),f?.priority&&(l.priority=f?.priority)}let u=Rpt(t);u?l.parentId=u.id||"kbn"+rH++:iH.push(l),nc.push(l)},"addNode"),ka={DEFAULT:0,NO_BORDER:0,ROUNDED_RECT:1,RECT:2,CIRCLE:3,CLOUD:4,BANG:5,HEXAGON:6},Mpt=o((t,e)=>{switch(Q.debug("In get type",t,e),t){case"[":return ka.RECT;case"(":return e===")"?ka.ROUNDED_RECT:ka.CLOUD;case"((":return ka.CIRCLE;case")":return ka.CLOUD;case"))":return ka.BANG;case"{{":return ka.HEXAGON;default:return ka.DEFAULT}},"getType"),Opt=o((t,e)=>{nH[t]=e},"setElementForId"),Ppt=o(t=>{if(!t)return;let e=ge(),r=nc[nc.length-1];t.icon&&(r.icon=Tr(t.icon,e)),t.class&&(r.cssClasses=Tr(t.class,e))},"decorateNode"),Bpt=o(t=>{switch(t){case ka.DEFAULT:return"no-border";case ka.RECT:return"rect";case ka.ROUNDED_RECT:return"rounded-rect";case ka.CIRCLE:return"circle";case ka.CLOUD:return"cloud";case ka.BANG:return"bang";case ka.HEXAGON:return"hexgon";default:return"no-border"}},"type2Str"),Fpt=o(()=>Q,"getLogger"),$pt=o(t=>nH[t],"getElementById"),zpt={clear:Lpt,addNode:Ipt,getSections:iSe,getData:Npt,nodeType:ka,getType:Mpt,setElementForId:Opt,decorateNode:Ppt,type2Str:Bpt,getLogger:Fpt,getElementById:$pt},nSe=zpt});var Gpt,sSe,oSe=P(()=>{"use strict";Ut();bt();ro();Xi();wa();A5();B5();Gpt=o(async(t,e,r,i)=>{Q.debug(`Rendering kanban diagram +`+t);let a=i.db.getData(),s=ge();s.htmlLabels=!1;let l=Fi(e);for(let v of a.nodes)v.domId=`${e}-${v.id}`;let u=l.append("g");u.attr("class","sections");let h=l.append("g");h.attr("class","items");let f=a.nodes.filter(v=>v.isGroup),d=0,p=10,m=[],g=25;for(let v of f){let x=s?.kanban?.sectionWidth||200;d=d+1,v.x=x*d+(d-1)*p/2,v.width=x,v.y=0,v.height=x*3,v.rx=5,v.ry=5,v.cssClasses=v.cssClasses+" section-"+d;let b=await N1(u,v);g=Math.max(g,b?.labelBBox?.height),m.push(b)}let y=0;for(let v of f){let x=m[y];y=y+1;let b=s?.kanban?.sectionWidth||200,T=-b*3/2+g,w=T,k=a.nodes.filter(S=>S.parentId===v.id);for(let S of k){if(S.isGroup)throw new Error("Groups within groups are not allowed in Kanban diagrams");S.x=v.x,S.width=b-1.5*p;let M=(await I1(h,S,{config:s})).node().getBBox();S.y=w+M.height/2,await Mb(S),w=S.y+M.height/2+p/2}let C=x.cluster.select("rect"),E=Math.max(w-T+3*p,50)+(g-25);C.attr("height",E)}El(void 0,l,s.mindmap?.padding??fr.kanban.padding,s.mindmap?.useMaxWidth??fr.kanban.useMaxWidth)},"draw"),sSe={draw:Gpt}});var Vpt,qpt,lSe,cSe=P(()=>{"use strict";Yn();wy();Vpt=o(t=>{let e="";for(let i=0;it.darkMode?Ye(i,n):Ke(i,n),"adjuster");for(let i=0;i` + .edge { + stroke-width: 3; + } + ${Vpt(t)} + .section-root rect, .section-root path, .section-root circle, .section-root polygon { + fill: ${t.git0}; + } + .section-root text { + fill: ${t.gitBranchLabel0}; + } + .icon-container { + height:100%; + display: flex; + justify-content: center; + align-items: center; + } + .edge { + fill: none; + } + .cluster-label, .label { + color: ${t.textColor}; + fill: ${t.textColor}; + } + .kanban-label { + dy: 1em; + alignment-baseline: middle; + text-anchor: middle; + dominant-baseline: middle; + text-align: center; + } + ${qu()} +`,"getStyles"),lSe=qpt});var uSe={};ur(uSe,{diagram:()=>Wpt});var Wpt,hSe=P(()=>{"use strict";rSe();aSe();oSe();cSe();Wpt={db:nSe,renderer:sSe,parser:tSe,styles:lSe}});var aH,$C,pSe=P(()=>{"use strict";aH=(function(){var t=o(function(l,u,h,f){for(h=h||{},f=l.length;f--;h[l[f]]=u);return h},"o"),e=[1,9],r=[1,10],i=[1,5,10,12],n={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,SANKEY:4,NEWLINE:5,csv:6,opt_eof:7,record:8,csv_tail:9,EOF:10,"field[source]":11,COMMA:12,"field[target]":13,"field[value]":14,field:15,escaped:16,non_escaped:17,DQUOTE:18,ESCAPED_TEXT:19,NON_ESCAPED_TEXT:20,$accept:0,$end:1},terminals_:{2:"error",4:"SANKEY",5:"NEWLINE",10:"EOF",11:"field[source]",12:"COMMA",13:"field[target]",14:"field[value]",18:"DQUOTE",19:"ESCAPED_TEXT",20:"NON_ESCAPED_TEXT"},productions_:[0,[3,4],[6,2],[9,2],[9,0],[7,1],[7,0],[8,5],[15,1],[15,1],[16,3],[17,1]],performAction:o(function(u,h,f,d,p,m,g){var y=m.length-1;switch(p){case 7:let v=d.findOrCreateNode(m[y-4].trim().replaceAll('""','"')),x=d.findOrCreateNode(m[y-2].trim().replaceAll('""','"')),b=parseFloat(m[y].trim());d.addLink(v,x,b);break;case 8:case 9:case 11:this.$=m[y];break;case 10:this.$=m[y-1];break}},"anonymous"),table:[{3:1,4:[1,2]},{1:[3]},{5:[1,3]},{6:4,8:5,15:6,16:7,17:8,18:e,20:r},{1:[2,6],7:11,10:[1,12]},t(r,[2,4],{9:13,5:[1,14]}),{12:[1,15]},t(i,[2,8]),t(i,[2,9]),{19:[1,16]},t(i,[2,11]),{1:[2,1]},{1:[2,5]},t(r,[2,2]),{6:17,8:5,15:6,16:7,17:8,18:e,20:r},{15:18,16:7,17:8,18:e,20:r},{18:[1,19]},t(r,[2,3]),{12:[1,20]},t(i,[2,10]),{15:21,16:7,17:8,18:e,20:r},t([1,5,10],[2,7])],defaultActions:{11:[2,1],12:[2,5]},parseError:o(function(u,h){if(h.recoverable)this.trace(u);else{var f=new Error(u);throw f.hash=h,f}},"parseError"),parse:o(function(u){var h=this,f=[0],d=[],p=[null],m=[],g=this.table,y="",v=0,x=0,b=0,T=2,w=1,k=m.slice.call(arguments,1),C=Object.create(this.lexer),E={yy:{}};for(var S in this.yy)Object.prototype.hasOwnProperty.call(this.yy,S)&&(E.yy[S]=this.yy[S]);C.setInput(u,E.yy),E.yy.lexer=C,E.yy.parser=this,typeof C.yylloc>"u"&&(C.yylloc={});var L=C.yylloc;m.push(L);var M=C.options&&C.options.ranges;typeof E.yy.parseError=="function"?this.parseError=E.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function I(W){f.length=f.length-2*W,p.length=p.length-W,m.length=m.length-W}o(I,"popStack");function A(){var W;return W=d.pop()||C.lex()||w,typeof W!="number"&&(W instanceof Array&&(d=W,W=d.pop()),W=h.symbols_[W]||W),W}o(A,"lex");for(var _,D,N,R,B,O,$={},z,F,V,H;;){if(N=f[f.length-1],this.defaultActions[N]?R=this.defaultActions[N]:((_===null||typeof _>"u")&&(_=A()),R=g[N]&&g[N][_]),typeof R>"u"||!R.length||!R[0]){var X="";H=[];for(z in g[N])this.terminals_[z]&&z>T&&H.push("'"+this.terminals_[z]+"'");C.showPosition?X="Parse error on line "+(v+1)+`: +`+C.showPosition()+` +Expecting `+H.join(", ")+", got '"+(this.terminals_[_]||_)+"'":X="Parse error on line "+(v+1)+": Unexpected "+(_==w?"end of input":"'"+(this.terminals_[_]||_)+"'"),this.parseError(X,{text:C.match,token:this.terminals_[_]||_,line:C.yylineno,loc:L,expected:H})}if(R[0]instanceof Array&&R.length>1)throw new Error("Parse Error: multiple actions possible at state: "+N+", token: "+_);switch(R[0]){case 1:f.push(_),p.push(C.yytext),m.push(C.yylloc),f.push(R[1]),_=null,D?(_=D,D=null):(x=C.yyleng,y=C.yytext,v=C.yylineno,L=C.yylloc,b>0&&b--);break;case 2:if(F=this.productions_[R[1]][1],$.$=p[p.length-F],$._$={first_line:m[m.length-(F||1)].first_line,last_line:m[m.length-1].last_line,first_column:m[m.length-(F||1)].first_column,last_column:m[m.length-1].last_column},M&&($._$.range=[m[m.length-(F||1)].range[0],m[m.length-1].range[1]]),O=this.performAction.apply($,[y,x,v,E.yy,R[1],p,m].concat(k)),typeof O<"u")return O;F&&(f=f.slice(0,-1*F*2),p=p.slice(0,-1*F),m=m.slice(0,-1*F)),f.push(this.productions_[R[1]][0]),p.push($.$),m.push($._$),V=g[f[f.length-2]][f[f.length-1]],f.push(V);break;case 3:return!0}}return!0},"parse")},a=(function(){var l={EOF:1,parseError:o(function(h,f){if(this.yy.parser)this.yy.parser.parseError(h,f);else throw new Error(h)},"parseError"),setInput:o(function(u,h){return this.yy=h||this.yy||{},this._input=u,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var u=this._input[0];this.yytext+=u,this.yyleng++,this.offset++,this.match+=u,this.matched+=u;var h=u.match(/(?:\r\n?|\n).*/g);return h?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),u},"input"),unput:o(function(u){var h=u.length,f=u.split(/(?:\r\n?|\n)/g);this._input=u+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-h),this.offset-=h;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),f.length-1&&(this.yylineno-=f.length-1);var p=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:f?(f.length===d.length?this.yylloc.first_column:0)+d[d.length-f.length].length-f[0].length:this.yylloc.first_column-h},this.options.ranges&&(this.yylloc.range=[p[0],p[0]+this.yyleng-h]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(u){this.unput(this.match.slice(u))},"less"),pastInput:o(function(){var u=this.matched.substr(0,this.matched.length-this.match.length);return(u.length>20?"...":"")+u.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var u=this.match;return u.length<20&&(u+=this._input.substr(0,20-u.length)),(u.substr(0,20)+(u.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var u=this.pastInput(),h=new Array(u.length+1).join("-");return u+this.upcomingInput()+` +`+h+"^"},"showPosition"),test_match:o(function(u,h){var f,d,p;if(this.options.backtrack_lexer&&(p={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(p.yylloc.range=this.yylloc.range.slice(0))),d=u[0].match(/(?:\r\n?|\n).*/g),d&&(this.yylineno+=d.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:d?d[d.length-1].length-d[d.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+u[0].length},this.yytext+=u[0],this.match+=u[0],this.matches=u,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(u[0].length),this.matched+=u[0],f=this.performAction.call(this,this.yy,this,h,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),f)return f;if(this._backtrack){for(var m in p)this[m]=p[m];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var u,h,f,d;this._more||(this.yytext="",this.match="");for(var p=this._currentRules(),m=0;mh[0].length)){if(h=f,d=m,this.options.backtrack_lexer){if(u=this.test_match(f,p[m]),u!==!1)return u;if(this._backtrack){h=!1;continue}else return!1}else if(!this.options.flex)break}return h?(u=this.test_match(h,p[d]),u!==!1?u:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var h=this.next();return h||this.lex()},"lex"),begin:o(function(h){this.conditionStack.push(h)},"begin"),popState:o(function(){var h=this.conditionStack.length-1;return h>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(h){return h=this.conditionStack.length-1-Math.abs(h||0),h>=0?this.conditionStack[h]:"INITIAL"},"topState"),pushState:o(function(h){this.begin(h)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:o(function(h,f,d,p){var m=p;switch(d){case 0:return this.pushState("csv"),4;break;case 1:return this.pushState("csv"),4;break;case 2:return 10;case 3:return 5;case 4:return 12;case 5:return this.pushState("escaped_text"),18;break;case 6:return 20;case 7:return this.popState("escaped_text"),18;break;case 8:return 19}},"anonymous"),rules:[/^(?:sankey-beta\b)/i,/^(?:sankey\b)/i,/^(?:$)/i,/^(?:((\u000D\u000A)|(\u000A)))/i,/^(?:(\u002C))/i,/^(?:(\u0022))/i,/^(?:([\u0020-\u0021\u0023-\u002B\u002D-\u007E])*)/i,/^(?:(\u0022)(?!(\u0022)))/i,/^(?:(([\u0020-\u0021\u0023-\u002B\u002D-\u007E])|(\u002C)|(\u000D)|(\u000A)|(\u0022)(\u0022))*)/i],conditions:{csv:{rules:[2,3,4,5,6,7,8],inclusive:!1},escaped_text:{rules:[7,8],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,7,8],inclusive:!0}}};return l})();n.lexer=a;function s(){this.yy={}}return o(s,"Parser"),s.prototype=n,n.Parser=s,new s})();aH.parser=aH;$C=aH});var H_,Y_,U_,jpt,sH,Xpt,oH,Kpt,Qpt,Zpt,Jpt,mSe,gSe=P(()=>{"use strict";Ut();Vr();Ki();H_=[],Y_=[],U_=new Map,jpt=o(()=>{H_=[],Y_=[],U_=new Map,wr()},"clear"),sH=class{constructor(e,r,i=0){this.source=e;this.target=r;this.value=i}static{o(this,"SankeyLink")}},Xpt=o((t,e,r)=>{H_.push(new sH(t,e,r))},"addLink"),oH=class{constructor(e){this.ID=e}static{o(this,"SankeyNode")}},Kpt=o(t=>{t=lt.sanitizeText(t,ge());let e=U_.get(t);return e===void 0&&(e=new oH(t),U_.set(t,e),Y_.push(e)),e},"findOrCreateNode"),Qpt=o(()=>Y_,"getNodes"),Zpt=o(()=>H_,"getLinks"),Jpt=o(()=>({nodes:Y_.map(t=>({id:t.ID})),links:H_.map(t=>({source:t.source.ID,target:t.target.ID,value:t.value}))}),"getGraph"),mSe={nodesMap:U_,getConfig:o(()=>ge().sankey,"getConfig"),getNodes:Qpt,getLinks:Zpt,getGraph:Jpt,addLink:Xpt,findOrCreateNode:Kpt,getAccTitle:Dr,setAccTitle:Ar,getAccDescription:Rr,setAccDescription:Lr,getDiagramTitle:Nr,setDiagramTitle:Mr,clear:jpt}});function zC(t,e){let r;if(e===void 0)for(let i of t)i!=null&&(r=i)&&(r=i);else{let i=-1;for(let n of t)(n=e(n,++i,t))!=null&&(r=n)&&(r=n)}return r}var ySe=P(()=>{"use strict";o(zC,"max")});function lx(t,e){let r;if(e===void 0)for(let i of t)i!=null&&(r>i||r===void 0&&i>=i)&&(r=i);else{let i=-1;for(let n of t)(n=e(n,++i,t))!=null&&(r>n||r===void 0&&n>=n)&&(r=n)}return r}var vSe=P(()=>{"use strict";o(lx,"min")});function cx(t,e){let r=0;if(e===void 0)for(let i of t)(i=+i)&&(r+=i);else{let i=-1;for(let n of t)(n=+e(n,++i,t))&&(r+=n)}return r}var xSe=P(()=>{"use strict";o(cx,"sum")});var lH=P(()=>{"use strict";ySe();vSe();xSe()});function e0t(t){return t.target.depth}function cH(t){return t.depth}function uH(t,e){return e-1-t.height}function GC(t,e){return t.sourceLinks.length?t.depth:e-1}function hH(t){return t.targetLinks.length?t.depth:t.sourceLinks.length?lx(t.sourceLinks,e0t)-1:0}var fH=P(()=>{"use strict";lH();o(e0t,"targetDepth");o(cH,"left");o(uH,"right");o(GC,"justify");o(hH,"center")});function ux(t){return function(){return t}}var bSe=P(()=>{"use strict";o(ux,"constant")});function TSe(t,e){return j_(t.source,e.source)||t.index-e.index}function kSe(t,e){return j_(t.target,e.target)||t.index-e.index}function j_(t,e){return t.y0-e.y0}function dH(t){return t.value}function t0t(t){return t.index}function r0t(t){return t.nodes}function i0t(t){return t.links}function CSe(t,e){let r=t.get(e);if(!r)throw new Error("missing: "+e);return r}function wSe({nodes:t}){for(let e of t){let r=e.y0,i=r;for(let n of e.sourceLinks)n.y0=r+n.width/2,r+=n.width;for(let n of e.targetLinks)n.y1=i+n.width/2,i+=n.width}}function X_(){let t=0,e=0,r=1,i=1,n=24,a=8,s,l=t0t,u=GC,h,f,d=r0t,p=i0t,m=6;function g(){let N={nodes:d.apply(null,arguments),links:p.apply(null,arguments)};return y(N),v(N),x(N),b(N),k(N),wSe(N),N}o(g,"sankey"),g.update=function(N){return wSe(N),N},g.nodeId=function(N){return arguments.length?(l=typeof N=="function"?N:ux(N),g):l},g.nodeAlign=function(N){return arguments.length?(u=typeof N=="function"?N:ux(N),g):u},g.nodeSort=function(N){return arguments.length?(h=N,g):h},g.nodeWidth=function(N){return arguments.length?(n=+N,g):n},g.nodePadding=function(N){return arguments.length?(a=s=+N,g):a},g.nodes=function(N){return arguments.length?(d=typeof N=="function"?N:ux(N),g):d},g.links=function(N){return arguments.length?(p=typeof N=="function"?N:ux(N),g):p},g.linkSort=function(N){return arguments.length?(f=N,g):f},g.size=function(N){return arguments.length?(t=e=0,r=+N[0],i=+N[1],g):[r-t,i-e]},g.extent=function(N){return arguments.length?(t=+N[0][0],r=+N[1][0],e=+N[0][1],i=+N[1][1],g):[[t,e],[r,i]]},g.iterations=function(N){return arguments.length?(m=+N,g):m};function y({nodes:N,links:R}){for(let[O,$]of N.entries())$.index=O,$.sourceLinks=[],$.targetLinks=[];let B=new Map(N.map((O,$)=>[l(O,$,N),O]));for(let[O,$]of R.entries()){$.index=O;let{source:z,target:F}=$;typeof z!="object"&&(z=$.source=CSe(B,z)),typeof F!="object"&&(F=$.target=CSe(B,F)),z.sourceLinks.push($),F.targetLinks.push($)}if(f!=null)for(let{sourceLinks:O,targetLinks:$}of N)O.sort(f),$.sort(f)}o(y,"computeNodeLinks");function v({nodes:N}){for(let R of N)R.value=R.fixedValue===void 0?Math.max(cx(R.sourceLinks,dH),cx(R.targetLinks,dH)):R.fixedValue}o(v,"computeNodeValues");function x({nodes:N}){let R=N.length,B=new Set(N),O=new Set,$=0;for(;B.size;){for(let z of B){z.depth=$;for(let{target:F}of z.sourceLinks)O.add(F)}if(++$>R)throw new Error("circular link");B=O,O=new Set}}o(x,"computeNodeDepths");function b({nodes:N}){let R=N.length,B=new Set(N),O=new Set,$=0;for(;B.size;){for(let z of B){z.height=$;for(let{source:F}of z.targetLinks)O.add(F)}if(++$>R)throw new Error("circular link");B=O,O=new Set}}o(b,"computeNodeHeights");function T({nodes:N}){let R=zC(N,$=>$.depth)+1,B=(r-t-n)/(R-1),O=new Array(R);for(let $ of N){let z=Math.max(0,Math.min(R-1,Math.floor(u.call(null,$,R))));$.layer=z,$.x0=t+z*B,$.x1=$.x0+n,O[z]?O[z].push($):O[z]=[$]}if(h)for(let $ of O)$.sort(h);return O}o(T,"computeNodeLayers");function w(N){let R=lx(N,B=>(i-e-(B.length-1)*s)/cx(B,dH));for(let B of N){let O=e;for(let $ of B){$.y0=O,$.y1=O+$.value*R,O=$.y1+s;for(let z of $.sourceLinks)z.width=z.value*R}O=(i-O+s)/(B.length+1);for(let $=0;$B.length)-1)),w(R);for(let B=0;B0))continue;let X=(V/H-F.y0)*R;F.y0+=X,F.y1+=X,I(F)}h===void 0&&z.sort(j_),S(z,B)}}o(C,"relaxLeftToRight");function E(N,R,B){for(let O=N.length,$=O-2;$>=0;--$){let z=N[$];for(let F of z){let V=0,H=0;for(let{target:W,value:Z}of F.sourceLinks){let Y=Z*(W.layer-F.layer);V+=D(F,W)*Y,H+=Y}if(!(H>0))continue;let X=(V/H-F.y0)*R;F.y0+=X,F.y1+=X,I(F)}h===void 0&&z.sort(j_),S(z,B)}}o(E,"relaxRightToLeft");function S(N,R){let B=N.length>>1,O=N[B];M(N,O.y0-s,B-1,R),L(N,O.y1+s,B+1,R),M(N,i,N.length-1,R),L(N,e,0,R)}o(S,"resolveCollisions");function L(N,R,B,O){for(;B1e-6&&($.y0+=z,$.y1+=z),R=$.y1+s}}o(L,"resolveCollisionsTopToBottom");function M(N,R,B,O){for(;B>=0;--B){let $=N[B],z=($.y1-R)*O;z>1e-6&&($.y0-=z,$.y1-=z),R=$.y0-s}}o(M,"resolveCollisionsBottomToTop");function I({sourceLinks:N,targetLinks:R}){if(f===void 0){for(let{source:{sourceLinks:B}}of R)B.sort(kSe);for(let{target:{targetLinks:B}}of N)B.sort(TSe)}}o(I,"reorderNodeLinks");function A(N){if(f===void 0)for(let{sourceLinks:R,targetLinks:B}of N)R.sort(kSe),B.sort(TSe)}o(A,"reorderLinks");function _(N,R){let B=N.y0-(N.sourceLinks.length-1)*s/2;for(let{target:O,width:$}of N.sourceLinks){if(O===R)break;B+=$+s}for(let{source:O,width:$}of R.targetLinks){if(O===N)break;B-=$}return B}o(_,"targetTop");function D(N,R){let B=R.y0-(R.targetLinks.length-1)*s/2;for(let{source:O,width:$}of R.targetLinks){if(O===N)break;B+=$+s}for(let{target:O,width:$}of N.sourceLinks){if(O===R)break;B-=$}return B}return o(D,"sourceTop"),g}var ESe=P(()=>{"use strict";lH();fH();bSe();o(TSe,"ascendingSourceBreadth");o(kSe,"ascendingTargetBreadth");o(j_,"ascendingBreadth");o(dH,"value");o(t0t,"defaultId");o(r0t,"defaultNodes");o(i0t,"defaultLinks");o(CSe,"find");o(wSe,"computeLinkBreadths");o(X_,"Sankey")});function gH(){this._x0=this._y0=this._x1=this._y1=null,this._=""}function SSe(){return new gH}var pH,mH,pg,n0t,yH,ASe=P(()=>{"use strict";pH=Math.PI,mH=2*pH,pg=1e-6,n0t=mH-pg;o(gH,"Path");o(SSe,"path");gH.prototype=SSe.prototype={constructor:gH,moveTo:o(function(t,e){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)},"moveTo"),closePath:o(function(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")},"closePath"),lineTo:o(function(t,e){this._+="L"+(this._x1=+t)+","+(this._y1=+e)},"lineTo"),quadraticCurveTo:o(function(t,e,r,i){this._+="Q"+ +t+","+ +e+","+(this._x1=+r)+","+(this._y1=+i)},"quadraticCurveTo"),bezierCurveTo:o(function(t,e,r,i,n,a){this._+="C"+ +t+","+ +e+","+ +r+","+ +i+","+(this._x1=+n)+","+(this._y1=+a)},"bezierCurveTo"),arcTo:o(function(t,e,r,i,n){t=+t,e=+e,r=+r,i=+i,n=+n;var a=this._x1,s=this._y1,l=r-t,u=i-e,h=a-t,f=s-e,d=h*h+f*f;if(n<0)throw new Error("negative radius: "+n);if(this._x1===null)this._+="M"+(this._x1=t)+","+(this._y1=e);else if(d>pg)if(!(Math.abs(f*l-u*h)>pg)||!n)this._+="L"+(this._x1=t)+","+(this._y1=e);else{var p=r-a,m=i-s,g=l*l+u*u,y=p*p+m*m,v=Math.sqrt(g),x=Math.sqrt(d),b=n*Math.tan((pH-Math.acos((g+d-y)/(2*v*x)))/2),T=b/x,w=b/v;Math.abs(T-1)>pg&&(this._+="L"+(t+T*h)+","+(e+T*f)),this._+="A"+n+","+n+",0,0,"+ +(f*p>h*m)+","+(this._x1=t+w*l)+","+(this._y1=e+w*u)}},"arcTo"),arc:o(function(t,e,r,i,n,a){t=+t,e=+e,r=+r,a=!!a;var s=r*Math.cos(i),l=r*Math.sin(i),u=t+s,h=e+l,f=1^a,d=a?i-n:n-i;if(r<0)throw new Error("negative radius: "+r);this._x1===null?this._+="M"+u+","+h:(Math.abs(this._x1-u)>pg||Math.abs(this._y1-h)>pg)&&(this._+="L"+u+","+h),r&&(d<0&&(d=d%mH+mH),d>n0t?this._+="A"+r+","+r+",0,1,"+f+","+(t-s)+","+(e-l)+"A"+r+","+r+",0,1,"+f+","+(this._x1=u)+","+(this._y1=h):d>pg&&(this._+="A"+r+","+r+",0,"+ +(d>=pH)+","+f+","+(this._x1=t+r*Math.cos(n))+","+(this._y1=e+r*Math.sin(n))))},"arc"),rect:o(function(t,e,r,i){this._+="M"+(this._x0=this._x1=+t)+","+(this._y0=this._y1=+e)+"h"+ +r+"v"+ +i+"h"+-r+"Z"},"rect"),toString:o(function(){return this._},"toString")};yH=SSe});var _Se=P(()=>{"use strict";ASe()});function K_(t){return o(function(){return t},"constant")}var DSe=P(()=>{"use strict";o(K_,"default")});function LSe(t){return t[0]}function RSe(t){return t[1]}var NSe=P(()=>{"use strict";o(LSe,"x");o(RSe,"y")});var ISe,MSe=P(()=>{"use strict";ISe=Array.prototype.slice});function a0t(t){return t.source}function s0t(t){return t.target}function o0t(t){var e=a0t,r=s0t,i=LSe,n=RSe,a=null;function s(){var l,u=ISe.call(arguments),h=e.apply(this,u),f=r.apply(this,u);if(a||(a=l=yH()),t(a,+i.apply(this,(u[0]=h,u)),+n.apply(this,u),+i.apply(this,(u[0]=f,u)),+n.apply(this,u)),l)return a=null,l+""||null}return o(s,"link"),s.source=function(l){return arguments.length?(e=l,s):e},s.target=function(l){return arguments.length?(r=l,s):r},s.x=function(l){return arguments.length?(i=typeof l=="function"?l:K_(+l),s):i},s.y=function(l){return arguments.length?(n=typeof l=="function"?l:K_(+l),s):n},s.context=function(l){return arguments.length?(a=l??null,s):a},s}function l0t(t,e,r,i,n){t.moveTo(e,r),t.bezierCurveTo(e=(e+i)/2,r,e,n,i,n)}function vH(){return o0t(l0t)}var OSe=P(()=>{"use strict";_Se();MSe();DSe();NSe();o(a0t,"linkSource");o(s0t,"linkTarget");o(o0t,"link");o(l0t,"curveHorizontal");o(vH,"linkHorizontal")});var PSe=P(()=>{"use strict";OSe()});function c0t(t){return[t.source.x1,t.y0]}function u0t(t){return[t.target.x0,t.y1]}function Q_(){return vH().source(c0t).target(u0t)}var BSe=P(()=>{"use strict";PSe();o(c0t,"horizontalSource");o(u0t,"horizontalTarget");o(Q_,"default")});var FSe=P(()=>{"use strict";ESe();fH();BSe()});var VC,$Se=P(()=>{"use strict";VC=class t{static{o(this,"Uid")}static{this.count=0}static next(e){return new t(e+ ++t.count)}constructor(e){this.id=e,this.href=`#${e}`}toString(){return"url("+this.href+")"}}});var h0t,f0t,zSe,GSe=P(()=>{"use strict";Ut();Pr();FSe();Xi();$Se();h0t={left:cH,right:uH,center:hH,justify:GC},f0t=o(function(t,e,r,i){let{securityLevel:n,sankey:a}=ge(),s=iw.sankey,l;n==="sandbox"&&(l=Ze("#i"+e));let u=n==="sandbox"?Ze(l.nodes()[0].contentDocument.body):Ze("body"),h=n==="sandbox"?u.select(`[id="${e}"]`):Ze(`[id="${e}"]`),f=a?.width??s.width,d=a?.height??s.width,p=a?.useMaxWidth??s.useMaxWidth,m=a?.nodeAlignment??s.nodeAlignment,g=a?.prefix??s.prefix,y=a?.suffix??s.suffix,v=a?.showValues??s.showValues,x=i.db.getGraph(),b=h0t[m];X_().nodeId(M=>M.id).nodeWidth(10).nodePadding(10+(v?15:0)).nodeAlign(b).extent([[0,0],[f,d]])(x);let k=jo(SN);h.append("g").attr("class","nodes").selectAll(".node").data(x.nodes).join("g").attr("class","node").attr("id",M=>(M.uid=VC.next("node-")).id).attr("transform",function(M){return"translate("+M.x0+","+M.y0+")"}).attr("x",M=>M.x0).attr("y",M=>M.y0).append("rect").attr("height",M=>M.y1-M.y0).attr("width",M=>M.x1-M.x0).attr("fill",M=>k(M.id));let C=o(({id:M,value:I})=>v?`${M} +${g}${Math.round(I*100)/100}${y}`:M,"getText");h.append("g").attr("class","node-labels").attr("font-size",14).selectAll("text").data(x.nodes).join("text").attr("x",M=>M.x0(M.y1+M.y0)/2).attr("dy",`${v?"0":"0.35"}em`).attr("text-anchor",M=>M.x0(I.uid=VC.next("linearGradient-")).id).attr("gradientUnits","userSpaceOnUse").attr("x1",I=>I.source.x1).attr("x2",I=>I.target.x0);M.append("stop").attr("offset","0%").attr("stop-color",I=>k(I.source.id)),M.append("stop").attr("offset","100%").attr("stop-color",I=>k(I.target.id))}let L;switch(S){case"gradient":L=o(M=>M.uid,"coloring");break;case"source":L=o(M=>k(M.source.id),"coloring");break;case"target":L=o(M=>k(M.target.id),"coloring");break;default:L=S}E.append("path").attr("d",Q_()).attr("stroke",L).attr("stroke-width",M=>Math.max(1,M.width)),El(void 0,h,0,p)},"draw"),zSe={draw:f0t}});var VSe,qSe=P(()=>{"use strict";VSe=o(t=>t.replaceAll(/^[^\S\n\r]+|[^\S\n\r]+$/g,"").replaceAll(/([\n\r])+/g,` +`).trim(),"prepareTextForParsing")});var d0t,WSe,USe=P(()=>{"use strict";d0t=o(t=>`.label { + font-family: ${t.fontFamily}; + }`,"getStyles"),WSe=d0t});var HSe={};ur(HSe,{diagram:()=>m0t});var p0t,m0t,YSe=P(()=>{"use strict";pSe();gSe();GSe();qSe();USe();p0t=$C.parse.bind($C);$C.parse=t=>p0t(VSe(t));m0t={styles:WSe,parser:$C,db:mSe,renderer:zSe}});var x0t,hx,xH=P(()=>{"use strict";Sr();wa();er();Ki();x0t=fr.packet,hx=class{constructor(){this.packet=[];this.setAccTitle=Ar;this.getAccTitle=Dr;this.setDiagramTitle=Mr;this.getDiagramTitle=Nr;this.getAccDescription=Rr;this.setAccDescription=Lr}static{o(this,"PacketDB")}getConfig(){let e=fi({...x0t,...Lt().packet});return e.showBits&&(e.paddingY+=10),e}getPacket(){return this.packet}pushWord(e){e.length>0&&this.packet.push(e)}clear(){wr(),this.packet=[]}}});var b0t,T0t,k0t,bH,KSe=P(()=>{"use strict";sh();bt();vf();xH();b0t=1e4,T0t=o((t,e)=>{Ss(t,e);let r=-1,i=[],n=1,{bitsPerRow:a}=e.getConfig();for(let{start:s,end:l,bits:u,label:h}of t.blocks){if(s!==void 0&&l!==void 0&&l{if(t.start===void 0)throw new Error("start should have been set during first phase");if(t.end===void 0)throw new Error("end should have been set during first phase");if(t.start>t.end)throw new Error(`Block start ${t.start} is greater than block end ${t.end}.`);if(t.end+1<=e*r)return[t,void 0];let i=e*r-1,n=e*r;return[{start:t.start,end:i,label:t.label,bits:i-t.start},{start:n,end:t.end,label:t.label,bits:t.end-n}]},"getNextFittingBlock"),bH={parser:{yy:void 0},parse:o(async t=>{let e=await ba("packet",t),r=bH.parser?.yy;if(!(r instanceof hx))throw new Error("parser.parser?.yy was not a PacketDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.");Q.debug(e),T0t(e,r)},"parse")}});var C0t,w0t,QSe,ZSe=P(()=>{"use strict";ro();Xi();C0t=o((t,e,r,i)=>{let n=i.db,a=n.getConfig(),{rowHeight:s,paddingY:l,bitWidth:u,bitsPerRow:h}=a,f=n.getPacket(),d=n.getDiagramTitle(),p=s+l,m=p*(f.length+1)-(d?0:s),g=u*h+2,y=Fi(e);y.attr("viewBox",`0 0 ${g} ${m}`),Hr(y,m,g,a.useMaxWidth);for(let[v,x]of f.entries())w0t(y,x,v,a);y.append("text").text(d).attr("x",g/2).attr("y",m-p/2).attr("dominant-baseline","middle").attr("text-anchor","middle").attr("class","packetTitle")},"draw"),w0t=o((t,e,r,{rowHeight:i,paddingX:n,paddingY:a,bitWidth:s,bitsPerRow:l,showBits:u})=>{let h=t.append("g"),f=r*(i+a)+a;for(let d of e){let p=d.start%l*s+1,m=(d.end-d.start+1)*s-n;if(h.append("rect").attr("x",p).attr("y",f).attr("width",m).attr("height",i).attr("class","packetBlock"),h.append("text").attr("x",p+m/2).attr("y",f+i/2).attr("class","packetLabel").attr("dominant-baseline","middle").attr("text-anchor","middle").text(d.label),!u)continue;let g=d.end===d.start,y=f-2;h.append("text").attr("x",p+(g?m/2:0)).attr("y",y).attr("class","packetByte start").attr("dominant-baseline","auto").attr("text-anchor",g?"middle":"start").text(d.start),g||h.append("text").attr("x",p+m).attr("y",y).attr("class","packetByte end").attr("dominant-baseline","auto").attr("text-anchor","end").text(d.end)}},"drawWord"),QSe={draw:C0t}});var E0t,JSe,e6e=P(()=>{"use strict";er();E0t={byteFontSize:"10px",startByteColor:"black",endByteColor:"black",labelColor:"black",labelFontSize:"12px",titleColor:"black",titleFontSize:"14px",blockStrokeColor:"black",blockStrokeWidth:"1",blockFillColor:"#efefef"},JSe=o(({packet:t}={})=>{let e=fi(E0t,t);return` + .packetByte { + font-size: ${e.byteFontSize}; + } + .packetByte.start { + fill: ${e.startByteColor}; + } + .packetByte.end { + fill: ${e.endByteColor}; + } + .packetLabel { + fill: ${e.labelColor}; + font-size: ${e.labelFontSize}; + } + .packetTitle { + fill: ${e.titleColor}; + font-size: ${e.titleFontSize}; + } + .packetBlock { + stroke: ${e.blockStrokeColor}; + stroke-width: ${e.blockStrokeWidth}; + fill: ${e.blockFillColor}; + } + `},"styles")});var t6e={};ur(t6e,{diagram:()=>S0t});var S0t,r6e=P(()=>{"use strict";xH();KSe();ZSe();e6e();S0t={parser:bH,get db(){return new hx},renderer:QSe,styles:JSe}});var fx,a6e,mg,D0t,L0t,s6e,R0t,N0t,I0t,M0t,O0t,P0t,B0t,gg,TH=P(()=>{"use strict";Sr();wa();er();Ki();fx={showLegend:!0,ticks:5,max:null,min:0,graticule:"circle"},a6e={axes:[],curves:[],options:fx},mg=structuredClone(a6e),D0t=fr.radar,L0t=o(()=>fi({...D0t,...Lt().radar}),"getConfig"),s6e=o(()=>mg.axes,"getAxes"),R0t=o(()=>mg.curves,"getCurves"),N0t=o(()=>mg.options,"getOptions"),I0t=o(t=>{mg.axes=t.map(e=>({name:e.name,label:e.label??e.name}))},"setAxes"),M0t=o(t=>{mg.curves=t.map(e=>({name:e.name,label:e.label??e.name,entries:O0t(e.entries)}))},"setCurves"),O0t=o(t=>{if(t[0].axis==null)return t.map(r=>r.value);let e=s6e();if(e.length===0)throw new Error("Axes must be populated before curves for reference entries");return e.map(r=>{let i=t.find(n=>n.axis?.$refText===r.name);if(i===void 0)throw new Error("Missing entry for axis "+r.label);return i.value})},"computeCurveEntries"),P0t=o(t=>{let e=t.reduce((r,i)=>(r[i.name]=i,r),{});mg.options={showLegend:e.showLegend?.value??fx.showLegend,ticks:e.ticks?.value??fx.ticks,max:e.max?.value??fx.max,min:e.min?.value??fx.min,graticule:e.graticule?.value??fx.graticule}},"setOptions"),B0t=o(()=>{wr(),mg=structuredClone(a6e)},"clear"),gg={getAxes:s6e,getCurves:R0t,getOptions:N0t,setAxes:I0t,setCurves:M0t,setOptions:P0t,getConfig:L0t,clear:B0t,setAccTitle:Ar,getAccTitle:Dr,setDiagramTitle:Mr,getDiagramTitle:Nr,getAccDescription:Rr,setAccDescription:Lr}});var F0t,o6e,l6e=P(()=>{"use strict";sh();bt();vf();TH();F0t=o(t=>{Ss(t,gg);let{axes:e,curves:r,options:i}=t;gg.setAxes(e),gg.setCurves(r),gg.setOptions(i)},"populate"),o6e={parse:o(async t=>{let e=await ba("radar",t);Q.debug(e),F0t(e)},"parse")}});function q0t(t,e,r,i,n,a,s){let l=e.length,u=Math.min(s.width,s.height)/2;r.forEach((h,f)=>{if(h.entries.length!==l)return;let d=h.entries.map((p,m)=>{let g=2*Math.PI*m/l-Math.PI/2,y=W0t(p,i,n,u),v=y*Math.cos(g),x=y*Math.sin(g);return{x:v,y:x}});a==="circle"?t.append("path").attr("d",U0t(d,s.curveTension)).attr("class",`radarCurve-${f}`):a==="polygon"&&t.append("polygon").attr("points",d.map(p=>`${p.x},${p.y}`).join(" ")).attr("class",`radarCurve-${f}`)})}function W0t(t,e,r,i){let n=Math.min(Math.max(t,e),r);return i*(n-e)/(r-e)}function U0t(t,e){let r=t.length,i=`M${t[0].x},${t[0].y}`;for(let n=0;n{let h=t.append("g").attr("transform",`translate(${n}, ${a+u*s})`);h.append("rect").attr("width",12).attr("height",12).attr("class",`radarLegendBox-${u}`),h.append("text").attr("x",16).attr("y",0).attr("class","radarLegendText").text(l.label)})}var $0t,z0t,G0t,V0t,c6e,u6e=P(()=>{"use strict";ro();Xi();$0t=o((t,e,r,i)=>{let n=i.db,a=n.getAxes(),s=n.getCurves(),l=n.getOptions(),u=n.getConfig(),h=n.getDiagramTitle(),f=Fi(e),d=z0t(f,u),p=l.max??Math.max(...s.map(y=>Math.max(...y.entries))),m=l.min,g=Math.min(u.width,u.height)/2;G0t(d,a,g,l.ticks,l.graticule),V0t(d,a,g,u),q0t(d,a,s,m,p,l.graticule,u),H0t(d,s,l.showLegend,u),d.append("text").attr("class","radarTitle").text(h).attr("x",0).attr("y",-u.height/2-u.marginTop)},"draw"),z0t=o((t,e)=>{let r=e.width+e.marginLeft+e.marginRight,i=e.height+e.marginTop+e.marginBottom,n={x:e.marginLeft+e.width/2,y:e.marginTop+e.height/2};return Hr(t,i,r,e.useMaxWidth??!0),t.attr("viewBox",`0 0 ${r} ${i}`),t.append("g").attr("transform",`translate(${n.x}, ${n.y})`)},"drawFrame"),G0t=o((t,e,r,i,n)=>{if(n==="circle")for(let a=0;a{let d=2*f*Math.PI/a-Math.PI/2,p=l*Math.cos(d),m=l*Math.sin(d);return`${p},${m}`}).join(" ");t.append("polygon").attr("points",u).attr("class","radarGraticule")}}},"drawGraticule"),V0t=o((t,e,r,i)=>{let n=e.length;for(let a=0;a{"use strict";er();wg();Sr();Y0t=o((t,e)=>{let r="";for(let i=0;i{let e=Zc(),r=Lt(),i=fi(e,r.themeVariables),n=fi(i.radar,t);return{themeVariables:i,radarOptions:n}},"buildRadarStyleOptions"),h6e=o(({radar:t}={})=>{let{themeVariables:e,radarOptions:r}=j0t(t);return` + .radarTitle { + font-size: ${e.fontSize}; + color: ${e.titleColor}; + dominant-baseline: hanging; + text-anchor: middle; + } + .radarAxisLine { + stroke: ${r.axisColor}; + stroke-width: ${r.axisStrokeWidth}; + } + .radarAxisLabel { + dominant-baseline: middle; + text-anchor: middle; + font-size: ${r.axisLabelFontSize}px; + color: ${r.axisColor}; + } + .radarGraticule { + fill: ${r.graticuleColor}; + fill-opacity: ${r.graticuleOpacity}; + stroke: ${r.graticuleColor}; + stroke-width: ${r.graticuleStrokeWidth}; + } + .radarLegendText { + text-anchor: start; + font-size: ${r.legendFontSize}px; + dominant-baseline: hanging; + } + ${Y0t(e,r)} + `},"styles")});var d6e={};ur(d6e,{diagram:()=>X0t});var X0t,p6e=P(()=>{"use strict";TH();l6e();u6e();f6e();X0t={parser:o6e,db:gg,renderer:c6e,styles:h6e}});var kH,y6e,v6e=P(()=>{"use strict";kH=(function(){var t=o(function(T,w,k,C){for(k=k||{},C=T.length;C--;k[T[C]]=w);return k},"o"),e=[1,15],r=[1,7],i=[1,13],n=[1,14],a=[1,19],s=[1,16],l=[1,17],u=[1,18],h=[8,30],f=[8,10,21,28,29,30,31,39,43,46],d=[1,23],p=[1,24],m=[8,10,15,16,21,28,29,30,31,39,43,46],g=[8,10,15,16,21,27,28,29,30,31,39,43,46],y=[1,49],v={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,spaceLines:3,SPACELINE:4,NL:5,separator:6,SPACE:7,EOF:8,start:9,BLOCK_DIAGRAM_KEY:10,document:11,stop:12,statement:13,link:14,LINK:15,START_LINK:16,LINK_LABEL:17,STR:18,nodeStatement:19,columnsStatement:20,SPACE_BLOCK:21,blockStatement:22,classDefStatement:23,cssClassStatement:24,styleStatement:25,node:26,SIZE:27,COLUMNS:28,"id-block":29,end:30,NODE_ID:31,nodeShapeNLabel:32,dirList:33,DIR:34,NODE_DSTART:35,NODE_DEND:36,BLOCK_ARROW_START:37,BLOCK_ARROW_END:38,classDef:39,CLASSDEF_ID:40,CLASSDEF_STYLEOPTS:41,DEFAULT:42,class:43,CLASSENTITY_IDS:44,STYLECLASS:45,style:46,STYLE_ENTITY_IDS:47,STYLE_DEFINITION_DATA:48,$accept:0,$end:1},terminals_:{2:"error",4:"SPACELINE",5:"NL",7:"SPACE",8:"EOF",10:"BLOCK_DIAGRAM_KEY",15:"LINK",16:"START_LINK",17:"LINK_LABEL",18:"STR",21:"SPACE_BLOCK",27:"SIZE",28:"COLUMNS",29:"id-block",30:"end",31:"NODE_ID",34:"DIR",35:"NODE_DSTART",36:"NODE_DEND",37:"BLOCK_ARROW_START",38:"BLOCK_ARROW_END",39:"classDef",40:"CLASSDEF_ID",41:"CLASSDEF_STYLEOPTS",42:"DEFAULT",43:"class",44:"CLASSENTITY_IDS",45:"STYLECLASS",46:"style",47:"STYLE_ENTITY_IDS",48:"STYLE_DEFINITION_DATA"},productions_:[0,[3,1],[3,2],[3,2],[6,1],[6,1],[6,1],[9,3],[12,1],[12,1],[12,2],[12,2],[11,1],[11,2],[14,1],[14,4],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[13,1],[19,3],[19,2],[19,1],[20,1],[22,4],[22,3],[26,1],[26,2],[33,1],[33,2],[32,3],[32,4],[23,3],[23,3],[24,3],[25,3]],performAction:o(function(w,k,C,E,S,L,M){var I=L.length-1;switch(S){case 4:E.getLogger().debug("Rule: separator (NL) ");break;case 5:E.getLogger().debug("Rule: separator (Space) ");break;case 6:E.getLogger().debug("Rule: separator (EOF) ");break;case 7:E.getLogger().debug("Rule: hierarchy: ",L[I-1]),E.setHierarchy(L[I-1]);break;case 8:E.getLogger().debug("Stop NL ");break;case 9:E.getLogger().debug("Stop EOF ");break;case 10:E.getLogger().debug("Stop NL2 ");break;case 11:E.getLogger().debug("Stop EOF2 ");break;case 12:E.getLogger().debug("Rule: statement: ",L[I]),typeof L[I].length=="number"?this.$=L[I]:this.$=[L[I]];break;case 13:E.getLogger().debug("Rule: statement #2: ",L[I-1]),this.$=[L[I-1]].concat(L[I]);break;case 14:E.getLogger().debug("Rule: link: ",L[I],w),this.$={edgeTypeStr:L[I],label:""};break;case 15:E.getLogger().debug("Rule: LABEL link: ",L[I-3],L[I-1],L[I]),this.$={edgeTypeStr:L[I],label:L[I-1]};break;case 18:let A=parseInt(L[I]),_=E.generateId();this.$={id:_,type:"space",label:"",width:A,children:[]};break;case 23:E.getLogger().debug("Rule: (nodeStatement link node) ",L[I-2],L[I-1],L[I]," typestr: ",L[I-1].edgeTypeStr);let D=E.edgeStrToEdgeData(L[I-1].edgeTypeStr);this.$=[{id:L[I-2].id,label:L[I-2].label,type:L[I-2].type,directions:L[I-2].directions},{id:L[I-2].id+"-"+L[I].id,start:L[I-2].id,end:L[I].id,label:L[I-1].label,type:"edge",directions:L[I].directions,arrowTypeEnd:D,arrowTypeStart:"arrow_open"},{id:L[I].id,label:L[I].label,type:E.typeStr2Type(L[I].typeStr),directions:L[I].directions}];break;case 24:E.getLogger().debug("Rule: nodeStatement (abc88 node size) ",L[I-1],L[I]),this.$={id:L[I-1].id,label:L[I-1].label,type:E.typeStr2Type(L[I-1].typeStr),directions:L[I-1].directions,widthInColumns:parseInt(L[I],10)};break;case 25:E.getLogger().debug("Rule: nodeStatement (node) ",L[I]),this.$={id:L[I].id,label:L[I].label,type:E.typeStr2Type(L[I].typeStr),directions:L[I].directions,widthInColumns:1};break;case 26:E.getLogger().debug("APA123",this?this:"na"),E.getLogger().debug("COLUMNS: ",L[I]),this.$={type:"column-setting",columns:L[I]==="auto"?-1:parseInt(L[I])};break;case 27:E.getLogger().debug("Rule: id-block statement : ",L[I-2],L[I-1]);let N=E.generateId();this.$={...L[I-2],type:"composite",children:L[I-1]};break;case 28:E.getLogger().debug("Rule: blockStatement : ",L[I-2],L[I-1],L[I]);let R=E.generateId();this.$={id:R,type:"composite",label:"",children:L[I-1]};break;case 29:E.getLogger().debug("Rule: node (NODE_ID separator): ",L[I]),this.$={id:L[I]};break;case 30:E.getLogger().debug("Rule: node (NODE_ID nodeShapeNLabel separator): ",L[I-1],L[I]),this.$={id:L[I-1],label:L[I].label,typeStr:L[I].typeStr,directions:L[I].directions};break;case 31:E.getLogger().debug("Rule: dirList: ",L[I]),this.$=[L[I]];break;case 32:E.getLogger().debug("Rule: dirList: ",L[I-1],L[I]),this.$=[L[I-1]].concat(L[I]);break;case 33:E.getLogger().debug("Rule: nodeShapeNLabel: ",L[I-2],L[I-1],L[I]),this.$={typeStr:L[I-2]+L[I],label:L[I-1]};break;case 34:E.getLogger().debug("Rule: BLOCK_ARROW nodeShapeNLabel: ",L[I-3],L[I-2]," #3:",L[I-1],L[I]),this.$={typeStr:L[I-3]+L[I],label:L[I-2],directions:L[I-1]};break;case 35:case 36:this.$={type:"classDef",id:L[I-1].trim(),css:L[I].trim()};break;case 37:this.$={type:"applyClass",id:L[I-1].trim(),styleClass:L[I].trim()};break;case 38:this.$={type:"applyStyles",id:L[I-1].trim(),stylesStr:L[I].trim()};break}},"anonymous"),table:[{9:1,10:[1,2]},{1:[3]},{10:e,11:3,13:4,19:5,20:6,21:r,22:8,23:9,24:10,25:11,26:12,28:i,29:n,31:a,39:s,43:l,46:u},{8:[1,20]},t(h,[2,12],{13:4,19:5,20:6,22:8,23:9,24:10,25:11,26:12,11:21,10:e,21:r,28:i,29:n,31:a,39:s,43:l,46:u}),t(f,[2,16],{14:22,15:d,16:p}),t(f,[2,17]),t(f,[2,18]),t(f,[2,19]),t(f,[2,20]),t(f,[2,21]),t(f,[2,22]),t(m,[2,25],{27:[1,25]}),t(f,[2,26]),{19:26,26:12,31:a},{10:e,11:27,13:4,19:5,20:6,21:r,22:8,23:9,24:10,25:11,26:12,28:i,29:n,31:a,39:s,43:l,46:u},{40:[1,28],42:[1,29]},{44:[1,30]},{47:[1,31]},t(g,[2,29],{32:32,35:[1,33],37:[1,34]}),{1:[2,7]},t(h,[2,13]),{26:35,31:a},{31:[2,14]},{17:[1,36]},t(m,[2,24]),{10:e,11:37,13:4,14:22,15:d,16:p,19:5,20:6,21:r,22:8,23:9,24:10,25:11,26:12,28:i,29:n,31:a,39:s,43:l,46:u},{30:[1,38]},{41:[1,39]},{41:[1,40]},{45:[1,41]},{48:[1,42]},t(g,[2,30]),{18:[1,43]},{18:[1,44]},t(m,[2,23]),{18:[1,45]},{30:[1,46]},t(f,[2,28]),t(f,[2,35]),t(f,[2,36]),t(f,[2,37]),t(f,[2,38]),{36:[1,47]},{33:48,34:y},{15:[1,50]},t(f,[2,27]),t(g,[2,33]),{38:[1,51]},{33:52,34:y,38:[2,31]},{31:[2,15]},t(g,[2,34]),{38:[2,32]}],defaultActions:{20:[2,7],23:[2,14],50:[2,15],52:[2,32]},parseError:o(function(w,k){if(k.recoverable)this.trace(w);else{var C=new Error(w);throw C.hash=k,C}},"parseError"),parse:o(function(w){var k=this,C=[0],E=[],S=[null],L=[],M=this.table,I="",A=0,_=0,D=0,N=2,R=1,B=L.slice.call(arguments,1),O=Object.create(this.lexer),$={yy:{}};for(var z in this.yy)Object.prototype.hasOwnProperty.call(this.yy,z)&&($.yy[z]=this.yy[z]);O.setInput(w,$.yy),$.yy.lexer=O,$.yy.parser=this,typeof O.yylloc>"u"&&(O.yylloc={});var F=O.yylloc;L.push(F);var V=O.options&&O.options.ranges;typeof $.yy.parseError=="function"?this.parseError=$.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function H(we){C.length=C.length-2*we,S.length=S.length-we,L.length=L.length-we}o(H,"popStack");function X(){var we;return we=E.pop()||O.lex()||R,typeof we!="number"&&(we instanceof Array&&(E=we,we=E.pop()),we=k.symbols_[we]||we),we}o(X,"lex");for(var W,Z,Y,ae,J,ee,re={},te,be,de,Ee;;){if(Y=C[C.length-1],this.defaultActions[Y]?ae=this.defaultActions[Y]:((W===null||typeof W>"u")&&(W=X()),ae=M[Y]&&M[Y][W]),typeof ae>"u"||!ae.length||!ae[0]){var Ne="";Ee=[];for(te in M[Y])this.terminals_[te]&&te>N&&Ee.push("'"+this.terminals_[te]+"'");O.showPosition?Ne="Parse error on line "+(A+1)+`: +`+O.showPosition()+` +Expecting `+Ee.join(", ")+", got '"+(this.terminals_[W]||W)+"'":Ne="Parse error on line "+(A+1)+": Unexpected "+(W==R?"end of input":"'"+(this.terminals_[W]||W)+"'"),this.parseError(Ne,{text:O.match,token:this.terminals_[W]||W,line:O.yylineno,loc:F,expected:Ee})}if(ae[0]instanceof Array&&ae.length>1)throw new Error("Parse Error: multiple actions possible at state: "+Y+", token: "+W);switch(ae[0]){case 1:C.push(W),S.push(O.yytext),L.push(O.yylloc),C.push(ae[1]),W=null,Z?(W=Z,Z=null):(_=O.yyleng,I=O.yytext,A=O.yylineno,F=O.yylloc,D>0&&D--);break;case 2:if(be=this.productions_[ae[1]][1],re.$=S[S.length-be],re._$={first_line:L[L.length-(be||1)].first_line,last_line:L[L.length-1].last_line,first_column:L[L.length-(be||1)].first_column,last_column:L[L.length-1].last_column},V&&(re._$.range=[L[L.length-(be||1)].range[0],L[L.length-1].range[1]]),ee=this.performAction.apply(re,[I,_,A,$.yy,ae[1],S,L].concat(B)),typeof ee<"u")return ee;be&&(C=C.slice(0,-1*be*2),S=S.slice(0,-1*be),L=L.slice(0,-1*be)),C.push(this.productions_[ae[1]][0]),S.push(re.$),L.push(re._$),de=M[C[C.length-2]][C[C.length-1]],C.push(de);break;case 3:return!0}}return!0},"parse")},x=(function(){var T={EOF:1,parseError:o(function(k,C){if(this.yy.parser)this.yy.parser.parseError(k,C);else throw new Error(k)},"parseError"),setInput:o(function(w,k){return this.yy=k||this.yy||{},this._input=w,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var w=this._input[0];this.yytext+=w,this.yyleng++,this.offset++,this.match+=w,this.matched+=w;var k=w.match(/(?:\r\n?|\n).*/g);return k?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),w},"input"),unput:o(function(w){var k=w.length,C=w.split(/(?:\r\n?|\n)/g);this._input=w+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-k),this.offset-=k;var E=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),C.length-1&&(this.yylineno-=C.length-1);var S=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:C?(C.length===E.length?this.yylloc.first_column:0)+E[E.length-C.length].length-C[0].length:this.yylloc.first_column-k},this.options.ranges&&(this.yylloc.range=[S[0],S[0]+this.yyleng-k]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(w){this.unput(this.match.slice(w))},"less"),pastInput:o(function(){var w=this.matched.substr(0,this.matched.length-this.match.length);return(w.length>20?"...":"")+w.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var w=this.match;return w.length<20&&(w+=this._input.substr(0,20-w.length)),(w.substr(0,20)+(w.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var w=this.pastInput(),k=new Array(w.length+1).join("-");return w+this.upcomingInput()+` +`+k+"^"},"showPosition"),test_match:o(function(w,k){var C,E,S;if(this.options.backtrack_lexer&&(S={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(S.yylloc.range=this.yylloc.range.slice(0))),E=w[0].match(/(?:\r\n?|\n).*/g),E&&(this.yylineno+=E.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:E?E[E.length-1].length-E[E.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+w[0].length},this.yytext+=w[0],this.match+=w[0],this.matches=w,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(w[0].length),this.matched+=w[0],C=this.performAction.call(this,this.yy,this,k,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),C)return C;if(this._backtrack){for(var L in S)this[L]=S[L];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var w,k,C,E;this._more||(this.yytext="",this.match="");for(var S=this._currentRules(),L=0;Lk[0].length)){if(k=C,E=L,this.options.backtrack_lexer){if(w=this.test_match(C,S[L]),w!==!1)return w;if(this._backtrack){k=!1;continue}else return!1}else if(!this.options.flex)break}return k?(w=this.test_match(k,S[E]),w!==!1?w:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var k=this.next();return k||this.lex()},"lex"),begin:o(function(k){this.conditionStack.push(k)},"begin"),popState:o(function(){var k=this.conditionStack.length-1;return k>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(k){return k=this.conditionStack.length-1-Math.abs(k||0),k>=0?this.conditionStack[k]:"INITIAL"},"topState"),pushState:o(function(k){this.begin(k)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{},performAction:o(function(k,C,E,S){var L=S;switch(E){case 0:return k.getLogger().debug("Found block-beta"),10;break;case 1:return k.getLogger().debug("Found id-block"),29;break;case 2:return k.getLogger().debug("Found block"),10;break;case 3:k.getLogger().debug(".",C.yytext);break;case 4:k.getLogger().debug("_",C.yytext);break;case 5:return 5;case 6:return C.yytext=-1,28;break;case 7:return C.yytext=C.yytext.replace(/columns\s+/,""),k.getLogger().debug("COLUMNS (LEX)",C.yytext),28;break;case 8:this.pushState("md_string");break;case 9:return"MD_STR";case 10:this.popState();break;case 11:this.pushState("string");break;case 12:k.getLogger().debug("LEX: POPPING STR:",C.yytext),this.popState();break;case 13:return k.getLogger().debug("LEX: STR end:",C.yytext),"STR";break;case 14:return C.yytext=C.yytext.replace(/space\:/,""),k.getLogger().debug("SPACE NUM (LEX)",C.yytext),21;break;case 15:return C.yytext="1",k.getLogger().debug("COLUMNS (LEX)",C.yytext),21;break;case 16:return 42;case 17:return"LINKSTYLE";case 18:return"INTERPOLATE";case 19:return this.pushState("CLASSDEF"),39;break;case 20:return this.popState(),this.pushState("CLASSDEFID"),"DEFAULT_CLASSDEF_ID";break;case 21:return this.popState(),this.pushState("CLASSDEFID"),40;break;case 22:return this.popState(),41;break;case 23:return this.pushState("CLASS"),43;break;case 24:return this.popState(),this.pushState("CLASS_STYLE"),44;break;case 25:return this.popState(),45;break;case 26:return this.pushState("STYLE_STMNT"),46;break;case 27:return this.popState(),this.pushState("STYLE_DEFINITION"),47;break;case 28:return this.popState(),48;break;case 29:return this.pushState("acc_title"),"acc_title";break;case 30:return this.popState(),"acc_title_value";break;case 31:return this.pushState("acc_descr"),"acc_descr";break;case 32:return this.popState(),"acc_descr_value";break;case 33:this.pushState("acc_descr_multiline");break;case 34:this.popState();break;case 35:return"acc_descr_multiline_value";case 36:return 30;case 37:return this.popState(),k.getLogger().debug("Lex: (("),"NODE_DEND";break;case 38:return this.popState(),k.getLogger().debug("Lex: (("),"NODE_DEND";break;case 39:return this.popState(),k.getLogger().debug("Lex: ))"),"NODE_DEND";break;case 40:return this.popState(),k.getLogger().debug("Lex: (("),"NODE_DEND";break;case 41:return this.popState(),k.getLogger().debug("Lex: (("),"NODE_DEND";break;case 42:return this.popState(),k.getLogger().debug("Lex: (-"),"NODE_DEND";break;case 43:return this.popState(),k.getLogger().debug("Lex: -)"),"NODE_DEND";break;case 44:return this.popState(),k.getLogger().debug("Lex: (("),"NODE_DEND";break;case 45:return this.popState(),k.getLogger().debug("Lex: ]]"),"NODE_DEND";break;case 46:return this.popState(),k.getLogger().debug("Lex: ("),"NODE_DEND";break;case 47:return this.popState(),k.getLogger().debug("Lex: ])"),"NODE_DEND";break;case 48:return this.popState(),k.getLogger().debug("Lex: /]"),"NODE_DEND";break;case 49:return this.popState(),k.getLogger().debug("Lex: /]"),"NODE_DEND";break;case 50:return this.popState(),k.getLogger().debug("Lex: )]"),"NODE_DEND";break;case 51:return this.popState(),k.getLogger().debug("Lex: )"),"NODE_DEND";break;case 52:return this.popState(),k.getLogger().debug("Lex: ]>"),"NODE_DEND";break;case 53:return this.popState(),k.getLogger().debug("Lex: ]"),"NODE_DEND";break;case 54:return k.getLogger().debug("Lexa: -)"),this.pushState("NODE"),35;break;case 55:return k.getLogger().debug("Lexa: (-"),this.pushState("NODE"),35;break;case 56:return k.getLogger().debug("Lexa: ))"),this.pushState("NODE"),35;break;case 57:return k.getLogger().debug("Lexa: )"),this.pushState("NODE"),35;break;case 58:return k.getLogger().debug("Lex: ((("),this.pushState("NODE"),35;break;case 59:return k.getLogger().debug("Lexa: )"),this.pushState("NODE"),35;break;case 60:return k.getLogger().debug("Lexa: )"),this.pushState("NODE"),35;break;case 61:return k.getLogger().debug("Lexa: )"),this.pushState("NODE"),35;break;case 62:return k.getLogger().debug("Lexc: >"),this.pushState("NODE"),35;break;case 63:return k.getLogger().debug("Lexa: (["),this.pushState("NODE"),35;break;case 64:return k.getLogger().debug("Lexa: )"),this.pushState("NODE"),35;break;case 65:return this.pushState("NODE"),35;break;case 66:return this.pushState("NODE"),35;break;case 67:return this.pushState("NODE"),35;break;case 68:return this.pushState("NODE"),35;break;case 69:return this.pushState("NODE"),35;break;case 70:return this.pushState("NODE"),35;break;case 71:return this.pushState("NODE"),35;break;case 72:return k.getLogger().debug("Lexa: ["),this.pushState("NODE"),35;break;case 73:return this.pushState("BLOCK_ARROW"),k.getLogger().debug("LEX ARR START"),37;break;case 74:return k.getLogger().debug("Lex: NODE_ID",C.yytext),31;break;case 75:return k.getLogger().debug("Lex: EOF",C.yytext),8;break;case 76:this.pushState("md_string");break;case 77:this.pushState("md_string");break;case 78:return"NODE_DESCR";case 79:this.popState();break;case 80:k.getLogger().debug("Lex: Starting string"),this.pushState("string");break;case 81:k.getLogger().debug("LEX ARR: Starting string"),this.pushState("string");break;case 82:return k.getLogger().debug("LEX: NODE_DESCR:",C.yytext),"NODE_DESCR";break;case 83:k.getLogger().debug("LEX POPPING"),this.popState();break;case 84:k.getLogger().debug("Lex: =>BAE"),this.pushState("ARROW_DIR");break;case 85:return C.yytext=C.yytext.replace(/^,\s*/,""),k.getLogger().debug("Lex (right): dir:",C.yytext),"DIR";break;case 86:return C.yytext=C.yytext.replace(/^,\s*/,""),k.getLogger().debug("Lex (left):",C.yytext),"DIR";break;case 87:return C.yytext=C.yytext.replace(/^,\s*/,""),k.getLogger().debug("Lex (x):",C.yytext),"DIR";break;case 88:return C.yytext=C.yytext.replace(/^,\s*/,""),k.getLogger().debug("Lex (y):",C.yytext),"DIR";break;case 89:return C.yytext=C.yytext.replace(/^,\s*/,""),k.getLogger().debug("Lex (up):",C.yytext),"DIR";break;case 90:return C.yytext=C.yytext.replace(/^,\s*/,""),k.getLogger().debug("Lex (down):",C.yytext),"DIR";break;case 91:return C.yytext="]>",k.getLogger().debug("Lex (ARROW_DIR end):",C.yytext),this.popState(),this.popState(),"BLOCK_ARROW_END";break;case 92:return k.getLogger().debug("Lex: LINK","#"+C.yytext+"#"),15;break;case 93:return k.getLogger().debug("Lex: LINK",C.yytext),15;break;case 94:return k.getLogger().debug("Lex: LINK",C.yytext),15;break;case 95:return k.getLogger().debug("Lex: LINK",C.yytext),15;break;case 96:return k.getLogger().debug("Lex: START_LINK",C.yytext),this.pushState("LLABEL"),16;break;case 97:return k.getLogger().debug("Lex: START_LINK",C.yytext),this.pushState("LLABEL"),16;break;case 98:return k.getLogger().debug("Lex: START_LINK",C.yytext),this.pushState("LLABEL"),16;break;case 99:this.pushState("md_string");break;case 100:return k.getLogger().debug("Lex: Starting string"),this.pushState("string"),"LINK_LABEL";break;case 101:return this.popState(),k.getLogger().debug("Lex: LINK","#"+C.yytext+"#"),15;break;case 102:return this.popState(),k.getLogger().debug("Lex: LINK",C.yytext),15;break;case 103:return this.popState(),k.getLogger().debug("Lex: LINK",C.yytext),15;break;case 104:return k.getLogger().debug("Lex: COLON",C.yytext),C.yytext=C.yytext.slice(1),27;break}},"anonymous"),rules:[/^(?:block-beta\b)/,/^(?:block:)/,/^(?:block\b)/,/^(?:[\s]+)/,/^(?:[\n]+)/,/^(?:((\u000D\u000A)|(\u000A)))/,/^(?:columns\s+auto\b)/,/^(?:columns\s+[\d]+)/,/^(?:["][`])/,/^(?:[^`"]+)/,/^(?:[`]["])/,/^(?:["])/,/^(?:["])/,/^(?:[^"]*)/,/^(?:space[:]\d+)/,/^(?:space\b)/,/^(?:default\b)/,/^(?:linkStyle\b)/,/^(?:interpolate\b)/,/^(?:classDef\s+)/,/^(?:DEFAULT\s+)/,/^(?:\w+\s+)/,/^(?:[^\n]*)/,/^(?:class\s+)/,/^(?:(\w+)+((,\s*\w+)*))/,/^(?:[^\n]*)/,/^(?:style\s+)/,/^(?:(\w+)+((,\s*\w+)*))/,/^(?:[^\n]*)/,/^(?:accTitle\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*:\s*)/,/^(?:(?!\n||)*[^\n]*)/,/^(?:accDescr\s*\{\s*)/,/^(?:[\}])/,/^(?:[^\}]*)/,/^(?:end\b\s*)/,/^(?:\(\(\()/,/^(?:\)\)\))/,/^(?:[\)]\))/,/^(?:\}\})/,/^(?:\})/,/^(?:\(-)/,/^(?:-\))/,/^(?:\(\()/,/^(?:\]\])/,/^(?:\()/,/^(?:\]\))/,/^(?:\\\])/,/^(?:\/\])/,/^(?:\)\])/,/^(?:[\)])/,/^(?:\]>)/,/^(?:[\]])/,/^(?:-\))/,/^(?:\(-)/,/^(?:\)\))/,/^(?:\))/,/^(?:\(\(\()/,/^(?:\(\()/,/^(?:\{\{)/,/^(?:\{)/,/^(?:>)/,/^(?:\(\[)/,/^(?:\()/,/^(?:\[\[)/,/^(?:\[\|)/,/^(?:\[\()/,/^(?:\)\)\))/,/^(?:\[\\)/,/^(?:\[\/)/,/^(?:\[\\)/,/^(?:\[)/,/^(?:<\[)/,/^(?:[^\(\[\n\-\)\{\}\s\<\>:]+)/,/^(?:$)/,/^(?:["][`])/,/^(?:["][`])/,/^(?:[^`"]+)/,/^(?:[`]["])/,/^(?:["])/,/^(?:["])/,/^(?:[^"]+)/,/^(?:["])/,/^(?:\]>\s*\()/,/^(?:,?\s*right\s*)/,/^(?:,?\s*left\s*)/,/^(?:,?\s*x\s*)/,/^(?:,?\s*y\s*)/,/^(?:,?\s*up\s*)/,/^(?:,?\s*down\s*)/,/^(?:\)\s*)/,/^(?:\s*[xo<]?--+[-xo>]\s*)/,/^(?:\s*[xo<]?==+[=xo>]\s*)/,/^(?:\s*[xo<]?-?\.+-[xo>]?\s*)/,/^(?:\s*~~[\~]+\s*)/,/^(?:\s*[xo<]?--\s*)/,/^(?:\s*[xo<]?==\s*)/,/^(?:\s*[xo<]?-\.\s*)/,/^(?:["][`])/,/^(?:["])/,/^(?:\s*[xo<]?--+[-xo>]\s*)/,/^(?:\s*[xo<]?==+[=xo>]\s*)/,/^(?:\s*[xo<]?-?\.+-[xo>]?\s*)/,/^(?::\d+)/],conditions:{STYLE_DEFINITION:{rules:[28],inclusive:!1},STYLE_STMNT:{rules:[27],inclusive:!1},CLASSDEFID:{rules:[22],inclusive:!1},CLASSDEF:{rules:[20,21],inclusive:!1},CLASS_STYLE:{rules:[25],inclusive:!1},CLASS:{rules:[24],inclusive:!1},LLABEL:{rules:[99,100,101,102,103],inclusive:!1},ARROW_DIR:{rules:[85,86,87,88,89,90,91],inclusive:!1},BLOCK_ARROW:{rules:[76,81,84],inclusive:!1},NODE:{rules:[37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,77,80],inclusive:!1},md_string:{rules:[9,10,78,79],inclusive:!1},space:{rules:[],inclusive:!1},string:{rules:[12,13,82,83],inclusive:!1},acc_descr_multiline:{rules:[34,35],inclusive:!1},acc_descr:{rules:[32],inclusive:!1},acc_title:{rules:[30],inclusive:!1},INITIAL:{rules:[0,1,2,3,4,5,6,7,8,11,14,15,16,17,18,19,23,26,29,31,33,36,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,92,93,94,95,96,97,98,104],inclusive:!0}}};return T})();v.lexer=x;function b(){this.yy={}}return o(b,"Parser"),b.prototype=v,v.Parser=b,new b})();kH.parser=kH;y6e=kH});function amt(t){switch(Q.debug("typeStr2Type",t),t){case"[]":return"square";case"()":return Q.debug("we have a round"),"round";case"(())":return"circle";case">]":return"rect_left_inv_arrow";case"{}":return"diamond";case"{{}}":return"hexagon";case"([])":return"stadium";case"[[]]":return"subroutine";case"[()]":return"cylinder";case"((()))":return"doublecircle";case"[//]":return"lean_right";case"[\\\\]":return"lean_left";case"[/\\]":return"trapezoid";case"[\\/]":return"inv_trapezoid";case"<[]>":return"block_arrow";default:return"na"}}function smt(t){switch(Q.debug("typeStr2Type",t),t){case"==":return"thick";default:return"normal"}}function omt(t){switch(t.replace(/^[\s-]+|[\s-]+$/g,"")){case"x":return"arrow_cross";case"o":return"arrow_circle";case">":return"arrow_point";default:return""}}var Xc,wH,CH,x6e,b6e,Z0t,k6e,J0t,Z_,EH,emt,tmt,rmt,imt,C6e,SH,qC,nmt,T6e,lmt,cmt,umt,hmt,fmt,dmt,pmt,mmt,gmt,ymt,vmt,xmt,bmt,w6e,E6e=P(()=>{"use strict";YM();Sr();Ut();bt();Vr();Ki();Xc=new Map,wH=[],CH=new Map,x6e="color",b6e="fill",Z0t="bgFill",k6e=",",J0t=ge(),Z_=new Map,EH="",emt=o(t=>lt.sanitizeText(t,J0t),"sanitizeText"),tmt=o(function(t,e=""){let r=Z_.get(t);r||(r={id:t,styles:[],textStyles:[]},Z_.set(t,r)),e?.split(k6e).forEach(i=>{let n=i.replace(/([^;]*);/,"$1").trim();if(RegExp(x6e).exec(i)){let s=n.replace(b6e,Z0t).replace(x6e,b6e);r.textStyles.push(s)}r.styles.push(n)})},"addStyleClass"),rmt=o(function(t,e=""){let r=Xc.get(t);e!=null&&(r.styles=e.split(k6e))},"addStyle2Node"),imt=o(function(t,e){t.split(",").forEach(function(r){let i=Xc.get(r);if(i===void 0){let n=r.trim();i={id:n,type:"na",children:[]},Xc.set(n,i)}i.classes||(i.classes=[]),i.classes.push(e)})},"setCssClass"),C6e=o((t,e)=>{let r=t.flat(),i=[],a=r.find(s=>s?.type==="column-setting")?.columns??-1;for(let s of r){if(typeof a=="number"&&a>0&&s.type!=="column-setting"&&typeof s.widthInColumns=="number"&&s.widthInColumns>a&&Q.warn(`Block ${s.id} width ${s.widthInColumns} exceeds configured column width ${a}`),s.label&&(s.label=emt(s.label)),s.type==="classDef"){tmt(s.id,s.css);continue}if(s.type==="applyClass"){imt(s.id,s?.styleClass??"");continue}if(s.type==="applyStyles"){s?.stylesStr&&rmt(s.id,s?.stylesStr);continue}if(s.type==="column-setting")e.columns=s.columns??-1;else if(s.type==="edge"){let l=(CH.get(s.id)??0)+1;CH.set(s.id,l),s.id=l+"-"+s.id,wH.push(s)}else{s.label||(s.type==="composite"?s.label="":s.label=s.id);let l=Xc.get(s.id);if(l===void 0?Xc.set(s.id,s):(s.type!=="na"&&(l.type=s.type),s.label!==s.id&&(l.label=s.label)),s.children&&C6e(s.children,s),s.type==="space"){let u=s.width??1;for(let h=0;h{Q.debug("Clear called"),wr(),qC={id:"root",type:"composite",children:[],columns:-1},Xc=new Map([["root",qC]]),SH=[],Z_=new Map,wH=[],CH=new Map,EH=""},"clear");o(amt,"typeStr2Type");o(smt,"edgeTypeStr2Type");o(omt,"edgeStrToEdgeData");T6e=0,lmt=o(()=>(T6e++,"id-"+Math.random().toString(36).substr(2,12)+"-"+T6e),"generateId"),cmt=o(t=>{qC.children=t,C6e(t,qC),SH=qC.children},"setHierarchy"),umt=o(t=>{let e=Xc.get(t);return e?e.columns?e.columns:e.children?e.children.length:-1:-1},"getColumns"),hmt=o(()=>[...Xc.values()],"getBlocksFlat"),fmt=o(()=>SH||[],"getBlocks"),dmt=o(()=>wH,"getEdges"),pmt=o(t=>Xc.get(t),"getBlock"),mmt=o(t=>{Xc.set(t.id,t)},"setBlock"),gmt=o(t=>{EH=t},"setDiagramId"),ymt=o(()=>EH,"getDiagramId"),vmt=o(()=>Q,"getLogger"),xmt=o(function(){return Z_},"getClasses"),bmt={getConfig:o(()=>Lt().block,"getConfig"),typeStr2Type:amt,edgeTypeStr2Type:smt,edgeStrToEdgeData:omt,getLogger:vmt,getBlocksFlat:hmt,getBlocks:fmt,getEdges:dmt,setHierarchy:cmt,getBlock:pmt,setBlock:mmt,getColumns:umt,getClasses:xmt,clear:nmt,generateId:lmt,setDiagramId:gmt,getDiagramId:ymt},w6e=bmt});var AH,Tmt,S6e,A6e=P(()=>{"use strict";Yn();wy();AH=o((t,e)=>{let r=zp,i=r(t,"r"),n=r(t,"g"),a=r(t,"b");return Fn(i,n,a,e)},"fade"),Tmt=o(t=>`.label { + font-family: ${t.fontFamily}; + color: ${t.nodeTextColor||t.textColor}; + } + .cluster-label text { + fill: ${t.titleColor}; + } + .cluster-label span,p { + color: ${t.titleColor}; + } + + + + .label text,span,p { + fill: ${t.nodeTextColor||t.textColor}; + color: ${t.nodeTextColor||t.textColor}; + } + + .node rect, + .node circle, + .node ellipse, + .node polygon, + .node path { + fill: ${t.mainBkg}; + stroke: ${t.nodeBorder}; + stroke-width: 1px; + } + .flowchart-label text { + text-anchor: middle; + } + // .flowchart-label .text-outer-tspan { + // text-anchor: middle; + // } + // .flowchart-label .text-inner-tspan { + // text-anchor: start; + // } + + .node .label { + text-align: center; + } + .node.clickable { + cursor: pointer; + } + + .arrowheadPath { + fill: ${t.arrowheadColor}; + } + + .edgePath .path { + stroke: ${t.lineColor}; + stroke-width: 2.0px; + } + + .flowchart-link { + stroke: ${t.lineColor}; + fill: none; + } + + .edgeLabel { + background-color: ${t.edgeLabelBackground}; + /* + * This is for backward compatibility with existing code that didn't + * add a \`

    \` around edge labels. + * + * TODO: We should probably remove this in a future release. + */ + p { + margin: 0; + padding: 0; + display: inline; + } + rect { + opacity: 0.5; + background-color: ${t.edgeLabelBackground}; + fill: ${t.edgeLabelBackground}; + } + text-align: center; + } + + /* For html labels only */ + .labelBkg { + background-color: ${t.edgeLabelBackground}; + } + + .node .cluster { + // fill: ${AH(t.mainBkg,.5)}; + fill: ${AH(t.clusterBkg,.5)}; + stroke: ${AH(t.clusterBorder,.2)}; + box-shadow: rgba(50, 50, 93, 0.25) 0px 13px 27px -5px, rgba(0, 0, 0, 0.3) 0px 8px 16px -8px; + stroke-width: 1px; + } + + .cluster text { + fill: ${t.titleColor}; + } + + .cluster span,p { + color: ${t.titleColor}; + } + /* .cluster div { + color: ${t.titleColor}; + } */ + + div.mermaidTooltip { + position: absolute; + text-align: center; + max-width: 200px; + padding: 2px; + font-family: ${t.fontFamily}; + font-size: 12px; + background: ${t.tertiaryColor}; + border: 1px solid ${t.border2}; + border-radius: 2px; + pointer-events: none; + z-index: 100; + } + + .flowchartTitleText { + text-anchor: middle; + font-size: 18px; + fill: ${t.textColor}; + } + ${qu()} +`,"getStyles"),S6e=Tmt});var kmt,Cmt,wmt,Emt,Smt,Amt,_mt,Dmt,Lmt,Rmt,Nmt,_6e,D6e=P(()=>{"use strict";bt();kmt=o((t,e,r,i)=>{e.forEach(n=>{Nmt[n](t,r,i)})},"insertMarkers"),Cmt=o((t,e,r)=>{Q.trace("Making markers for ",r),t.append("defs").append("marker").attr("id",r+"_"+e+"-extensionStart").attr("class","marker extension "+e).attr("refX",18).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 1,7 L18,13 V 1 Z"),t.append("defs").append("marker").attr("id",r+"_"+e+"-extensionEnd").attr("class","marker extension "+e).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 1,1 V 13 L18,7 Z")},"extension"),wmt=o((t,e,r)=>{t.append("defs").append("marker").attr("id",r+"_"+e+"-compositionStart").attr("class","marker composition "+e).attr("refX",18).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),t.append("defs").append("marker").attr("id",r+"_"+e+"-compositionEnd").attr("class","marker composition "+e).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z")},"composition"),Emt=o((t,e,r)=>{t.append("defs").append("marker").attr("id",r+"_"+e+"-aggregationStart").attr("class","marker aggregation "+e).attr("refX",18).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z"),t.append("defs").append("marker").attr("id",r+"_"+e+"-aggregationEnd").attr("class","marker aggregation "+e).attr("refX",1).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L1,7 L9,1 Z")},"aggregation"),Smt=o((t,e,r)=>{t.append("defs").append("marker").attr("id",r+"_"+e+"-dependencyStart").attr("class","marker dependency "+e).attr("refX",6).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("path").attr("d","M 5,7 L9,13 L1,7 L9,1 Z"),t.append("defs").append("marker").attr("id",r+"_"+e+"-dependencyEnd").attr("class","marker dependency "+e).attr("refX",13).attr("refY",7).attr("markerWidth",20).attr("markerHeight",28).attr("orient","auto").append("path").attr("d","M 18,7 L9,13 L14,7 L9,1 Z")},"dependency"),Amt=o((t,e,r)=>{t.append("defs").append("marker").attr("id",r+"_"+e+"-lollipopStart").attr("class","marker lollipop "+e).attr("refX",13).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("circle").attr("stroke","black").attr("fill","transparent").attr("cx",7).attr("cy",7).attr("r",6),t.append("defs").append("marker").attr("id",r+"_"+e+"-lollipopEnd").attr("class","marker lollipop "+e).attr("refX",1).attr("refY",7).attr("markerWidth",190).attr("markerHeight",240).attr("orient","auto").append("circle").attr("stroke","black").attr("fill","transparent").attr("cx",7).attr("cy",7).attr("r",6)},"lollipop"),_mt=o((t,e,r)=>{t.append("marker").attr("id",r+"_"+e+"-pointEnd").attr("class","marker "+e).attr("viewBox","0 0 10 10").attr("refX",6).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0"),t.append("marker").attr("id",r+"_"+e+"-pointStart").attr("class","marker "+e).attr("viewBox","0 0 10 10").attr("refX",4.5).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",12).attr("markerHeight",12).attr("orient","auto").append("path").attr("d","M 0 5 L 10 10 L 10 0 z").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0")},"point"),Dmt=o((t,e,r)=>{t.append("marker").attr("id",r+"_"+e+"-circleEnd").attr("class","marker "+e).attr("viewBox","0 0 10 10").attr("refX",11).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("circle").attr("cx","5").attr("cy","5").attr("r","5").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0"),t.append("marker").attr("id",r+"_"+e+"-circleStart").attr("class","marker "+e).attr("viewBox","0 0 10 10").attr("refX",-1).attr("refY",5).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("circle").attr("cx","5").attr("cy","5").attr("r","5").attr("class","arrowMarkerPath").style("stroke-width",1).style("stroke-dasharray","1,0")},"circle"),Lmt=o((t,e,r)=>{t.append("marker").attr("id",r+"_"+e+"-crossEnd").attr("class","marker cross "+e).attr("viewBox","0 0 11 11").attr("refX",12).attr("refY",5.2).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("path").attr("d","M 1,1 l 9,9 M 10,1 l -9,9").attr("class","arrowMarkerPath").style("stroke-width",2).style("stroke-dasharray","1,0"),t.append("marker").attr("id",r+"_"+e+"-crossStart").attr("class","marker cross "+e).attr("viewBox","0 0 11 11").attr("refX",-1).attr("refY",5.2).attr("markerUnits","userSpaceOnUse").attr("markerWidth",11).attr("markerHeight",11).attr("orient","auto").append("path").attr("d","M 1,1 l 9,9 M 10,1 l -9,9").attr("class","arrowMarkerPath").style("stroke-width",2).style("stroke-dasharray","1,0")},"cross"),Rmt=o((t,e,r)=>{t.append("defs").append("marker").attr("id",r+"_"+e+"-barbEnd").attr("refX",19).attr("refY",7).attr("markerWidth",20).attr("markerHeight",14).attr("markerUnits","strokeWidth").attr("orient","auto").append("path").attr("d","M 19,7 L9,13 L14,7 L9,1 Z")},"barb"),Nmt={extension:Cmt,composition:wmt,aggregation:Emt,dependency:Smt,lollipop:Amt,point:_mt,circle:Dmt,cross:Lmt,barb:Rmt},_6e=kmt});function L6e(t,e){if(t===0||!Number.isInteger(t))throw new Error("Columns must be an integer !== 0.");if(e<0||!Number.isInteger(e))throw new Error("Position must be a non-negative integer."+e);if(t<0)return{px:e,py:0};if(t===1)return{px:0,py:e};let r=e%t,i=Math.floor(e/t);return{px:r,py:i}}function _H(t,e,r=0,i=0){Q.debug("setBlockSizes abc95 (start)",t.id,t?.size?.x,"block width =",t?.size,"siblingWidth",r),t?.size?.width||(t.size={width:r,height:i,x:0,y:0});let n=0,a=0;if(t.children?.length>0){for(let m of t.children)_H(m,e);let s=Imt(t);n=s.width,a=s.height,Q.debug("setBlockSizes abc95 maxWidth of",t.id,":s children is ",n,a);for(let m of t.children)m.size&&(Q.debug(`abc95 Setting size of children of ${t.id} id=${m.id} ${n} ${a} ${JSON.stringify(m.size)}`),m.size.width=n*(m.widthInColumns??1)+Hn*((m.widthInColumns??1)-1),m.size.height=a,m.size.x=0,m.size.y=0,Q.debug(`abc95 updating size of ${t.id} children child:${m.id} maxWidth:${n} maxHeight:${a}`));for(let m of t.children)_H(m,e,n,a);let l=t.columns??-1,u=0;for(let m of t.children)u+=m.widthInColumns??1;let h=t.children.length;l>0&&l0?Math.min(t.children.length,l):t.children.length;if(m>0){let g=(d-m*Hn-Hn)/m;Q.debug("abc95 (growing to fit) width",t.id,d,t.size?.width,g);for(let y of t.children)y.size&&(y.size.width=g)}}t.size={width:d,height:p,x:0,y:0}}Q.debug("setBlockSizes abc94 (done)",t.id,t?.size?.x,t?.size?.width,t?.size?.y,t?.size?.height)}function R6e(t,e){Q.debug(`abc85 layout blocks (=>layoutBlocks) ${t.id} x: ${t?.size?.x} y: ${t?.size?.y} width: ${t?.size?.width}`);let r=t.columns??-1;if(Q.debug("layoutBlocks columns abc95",t.id,"=>",r,t),t.children&&t.children.length>0){let i=t?.children[0]?.size?.width??0,n=t.children.length*i+(t.children.length-1)*Hn;Q.debug("widthOfChildren 88",n,"posX");let a=new Map;{let f=0;for(let d of t.children){if(!d.size)continue;let{py:p}=L6e(r,f),m=a.get(p)??0;d.size.height>m&&a.set(p,d.size.height);let g=d?.widthInColumns??1;r>0&&(g=Math.min(g,r-f%r)),f+=g}}let s=new Map;{let f=0,d=[...a.keys()].sort((p,m)=>p-m);for(let p of d)s.set(p,f),f+=(a.get(p)??0)+Hn}let l=0;Q.debug("abc91 block?.size?.x",t.id,t?.size?.x);let u=t?.size?.x?t?.size?.x+(-t?.size?.width/2||0):-Hn,h=0;for(let f of t.children){let d=t;if(!f.size)continue;let{width:p,height:m}=f.size,{px:g,py:y}=L6e(r,l);if(y!=h&&(h=y,u=t?.size?.x?t?.size?.x+(-t?.size?.width/2||0):-Hn,Q.debug("New row in layout for block",t.id," and child ",f.id,h)),Q.debug(`abc89 layout blocks (child) id: ${f.id} Pos: ${l} (px, py) ${g},${y} (${d?.size?.x},${d?.size?.y}) parent: ${d.id} width: ${p}${Hn}`),d.size){let x=p/2;f.size.x=u+Hn+x,Q.debug(`abc91 layout blocks (calc) px, pyid:${f.id} startingPos=X${u} new startingPosX${f.size.x} ${x} padding=${Hn} width=${p} halfWidth=${x} => x:${f.size.x} y:${f.size.y} ${f.widthInColumns} (width * (child?.w || 1)) / 2 ${p*(f?.widthInColumns??1)/2}`),u=f.size.x+x;let b=s.get(y)??0,T=a.get(y)??m;f.size.y=d.size.y-d.size.height/2+b+T/2+Hn,Q.debug(`abc88 layout blocks (calc) px, pyid:${f.id}startingPosX${u}${Hn}${x}=>x:${f.size.x}y:${f.size.y}${f.widthInColumns}(width * (child?.w || 1)) / 2${p*(f?.widthInColumns??1)/2}`)}f.children&&R6e(f,e);let v=f?.widthInColumns??1;r>0&&(v=Math.min(v,r-l%r)),l+=v,Q.debug("abc88 columnsPos",f,l)}}Q.debug(`layout blocks (<==layoutBlocks) ${t.id} x: ${t?.size?.x} y: ${t?.size?.y} width: ${t?.size?.width}`)}function N6e(t,{minX:e,minY:r,maxX:i,maxY:n}={minX:0,minY:0,maxX:0,maxY:0}){if(t.size&&t.id!=="root"){let{x:a,y:s,width:l,height:u}=t.size;a-l/2i&&(i=a+l/2),s+u/2>n&&(n=s+u/2)}if(t.children)for(let a of t.children)({minX:e,minY:r,maxX:i,maxY:n}=N6e(a,{minX:e,minY:r,maxX:i,maxY:n}));return{minX:e,minY:r,maxX:i,maxY:n}}function I6e(t){let e=t.getBlock("root");if(!e)return;_H(e,t,0,0),R6e(e,t),Q.debug("getBlocks",JSON.stringify(e,null,2));let{minX:r,minY:i,maxX:n,maxY:a}=N6e(e),s=a-i,l=n-r;return{x:r,y:i,width:l,height:s}}var Hn,Imt,M6e=P(()=>{"use strict";bt();Ut();Hn=ge()?.block?.padding??8;o(L6e,"calculateBlockPosition");Imt=o(t=>{let e=0,r=0;for(let i of t.children){let{width:n,height:a,x:s,y:l}=i.size??{width:0,height:0,x:0,y:0};Q.debug("getMaxChildSize abc95 child:",i.id,"width:",n,"height:",a,"x:",s,"y:",l,i.type),i.type!=="space"&&(n>e&&(e=n/(i.widthInColumns??1)),a>r&&(r=a))}return{width:e,height:r}},"getMaxChildSize");o(_H,"setBlockSizes");o(R6e,"layoutBlocks");o(N6e,"findBounds");o(I6e,"layout")});var Mmt,Vo,J_=P(()=>{"use strict";Sr();Ut();To();Mmt=o(async(t,e,r,i=!1,n=!1)=>{let a=e||"";typeof a=="object"&&(a=a[0]);let s=ge(),l=Or(s);return await Vi(t,a,{style:r,isTitle:i,useHtmlLabels:l,markdown:!1,isNode:n,width:Number.POSITIVE_INFINITY},s)},"createLabel"),Vo=Mmt});var P6e,Omt,O6e,B6e=P(()=>{"use strict";bt();P6e=o((t,e,r,i,n)=>{e.arrowTypeStart&&O6e(t,"start",e.arrowTypeStart,r,i,n),e.arrowTypeEnd&&O6e(t,"end",e.arrowTypeEnd,r,i,n)},"addEdgeMarkers"),Omt={arrow_cross:"cross",arrow_point:"point",arrow_barb:"barb",arrow_circle:"circle",aggregation:"aggregation",extension:"extension",composition:"composition",dependency:"dependency",lollipop:"lollipop"},O6e=o((t,e,r,i,n,a)=>{let s=Omt[r];if(!s){Q.warn(`Unknown arrow type: ${r}`);return}let l=e==="start"?"Start":"End";t.attr(`marker-${e}`,`url(${i}#${n}_${a}-${s}${l})`)},"addEdgeMarker")});function e8(t,e){Or(ge())&&t&&(t.style.width=e.length*9+"px",t.style.height="12px")}var DH,_s,$6e,z6e,Pmt,Bmt,F6e,G6e,V6e=P(()=>{"use strict";bt();J_();To();_M();Pr();Ut();Sr();er();Vr();LM();Nb();B6e();DH={},_s={},$6e=o(async(t,e)=>{let r=ge(),i=Or(r),n=t.insert("g").attr("class","edgeLabel"),a=n.insert("g").attr("class","label"),s=e.labelType==="markdown",l=await Vi(t,e.label,{style:e.labelStyle,useHtmlLabels:i,addSvgBackground:s,isNode:!1,markdown:s,width:s?void 0:Number.POSITIVE_INFINITY},r);a.node().appendChild(l);let u=l.getBBox(),h=u;if(i){let d=l.children[0],p=Ze(l);u=d.getBoundingClientRect(),h=u,p.attr("width",u.width),p.attr("height",u.height)}else{let d=Ze(l).select("text").node();d&&typeof d.getBBox=="function"&&(h=d.getBBox())}a.attr("transform",Pl(h,i)),DH[e.id]=n,e.width=u.width,e.height=u.height;let f;if(e.startLabelLeft){let d=t.insert("g").attr("class","edgeTerminals"),p=d.insert("g").attr("class","inner"),m=await Vo(p,e.startLabelLeft,e.labelStyle);f=m;let g=m.getBBox();if(i){let y=m.children[0],v=Ze(m);g=y.getBoundingClientRect(),v.attr("width",g.width),v.attr("height",g.height)}p.attr("transform",Pl(g,i)),_s[e.id]||(_s[e.id]={}),_s[e.id].startLeft=d,e8(f,e.startLabelLeft)}if(e.startLabelRight){let d=t.insert("g").attr("class","edgeTerminals"),p=d.insert("g").attr("class","inner"),m=await Vo(d,e.startLabelRight,e.labelStyle);f=m,p.node().appendChild(m);let g=m.getBBox();if(i){let y=m.children[0],v=Ze(m);g=y.getBoundingClientRect(),v.attr("width",g.width),v.attr("height",g.height)}p.attr("transform",Pl(g,i)),_s[e.id]||(_s[e.id]={}),_s[e.id].startRight=d,e8(f,e.startLabelRight)}if(e.endLabelLeft){let d=t.insert("g").attr("class","edgeTerminals"),p=d.insert("g").attr("class","inner"),m=await Vo(p,e.endLabelLeft,e.labelStyle);f=m;let g=m.getBBox();if(i){let y=m.children[0],v=Ze(m);g=y.getBoundingClientRect(),v.attr("width",g.width),v.attr("height",g.height)}p.attr("transform",Pl(g,i)),d.node().appendChild(m),_s[e.id]||(_s[e.id]={}),_s[e.id].endLeft=d,e8(f,e.endLabelLeft)}if(e.endLabelRight){let d=t.insert("g").attr("class","edgeTerminals"),p=d.insert("g").attr("class","inner"),m=await Vo(p,e.endLabelRight,e.labelStyle);f=m;let g=m.getBBox();if(i){let y=m.children[0],v=Ze(m);g=y.getBoundingClientRect(),v.attr("width",g.width),v.attr("height",g.height)}p.attr("transform",Pl(g,i)),d.node().appendChild(m),_s[e.id]||(_s[e.id]={}),_s[e.id].endRight=d,e8(f,e.endLabelRight)}return l},"insertEdgeLabel");o(e8,"setTerminalWidth");z6e=o((t,e)=>{Q.debug("Moving label abc88 ",t.id,t.label,DH[t.id],e);let r=e.updatedPath?e.updatedPath:e.originalPath,i=ge(),{subGraphTitleTotalMargin:n}=Uh(i);if(t.label){let a=DH[t.id],s=t.x,l=t.y;if(r){let u=Kt.calcLabelPosition(r);Q.debug("Moving label "+t.label+" from (",s,",",l,") to (",u.x,",",u.y,") abc88"),e.updatedPath&&(s=u.x,l=u.y)}a.attr("transform",`translate(${s}, ${l+n/2})`)}if(t.startLabelLeft){let a=_s[t.id].startLeft,s=t.x,l=t.y;if(r){let u=Kt.calcTerminalLabelPosition(t.arrowTypeStart?10:0,"start_left",r);s=u.x,l=u.y}a.attr("transform",`translate(${s}, ${l})`)}if(t.startLabelRight){let a=_s[t.id].startRight,s=t.x,l=t.y;if(r){let u=Kt.calcTerminalLabelPosition(t.arrowTypeStart?10:0,"start_right",r);s=u.x,l=u.y}a.attr("transform",`translate(${s}, ${l})`)}if(t.endLabelLeft){let a=_s[t.id].endLeft,s=t.x,l=t.y;if(r){let u=Kt.calcTerminalLabelPosition(t.arrowTypeEnd?10:0,"end_left",r);s=u.x,l=u.y}a.attr("transform",`translate(${s}, ${l})`)}if(t.endLabelRight){let a=_s[t.id].endRight,s=t.x,l=t.y;if(r){let u=Kt.calcTerminalLabelPosition(t.arrowTypeEnd?10:0,"end_right",r);s=u.x,l=u.y}a.attr("transform",`translate(${s}, ${l})`)}},"positionEdgeLabel"),Pmt=o((t,e)=>{let r=t.x,i=t.y,n=Math.abs(e.x-r),a=Math.abs(e.y-i),s=t.width/2,l=t.height/2;return n>=s||a>=l},"outsideNode"),Bmt=o((t,e,r)=>{Q.debug(`intersection calc abc89: + outsidePoint: ${JSON.stringify(e)} + insidePoint : ${JSON.stringify(r)} + node : x:${t.x} y:${t.y} w:${t.width} h:${t.height}`);let i=t.x,n=t.y,a=Math.abs(i-r.x),s=t.width/2,l=r.xMath.abs(i-e.x)*u){let d=r.y{Q.debug("abc88 cutPathAtIntersect",t,e);let r=[],i=t[0],n=!1;return t.forEach(a=>{if(!Pmt(e,a)&&!n){let s=Bmt(e,i,a),l=!1;r.forEach(u=>{l=l||u.x===s.x&&u.y===s.y}),r.some(u=>u.x===s.x&&u.y===s.y)||r.push(s),n=!0}else i=a,n||r.push(a)}),r},"cutPathAtIntersect"),G6e=o(function(t,e,r,i,n,a,s){let l=r.points;Q.debug("abc88 InsertEdge: edge=",r,"e=",e);let u=!1,h=a.node(e.v);var f=a.node(e.w);f?.intersect&&h?.intersect&&(l=l.slice(1,r.points.length-1),l.unshift(h.intersect(l[0])),l.push(f.intersect(l[l.length-1]))),r.toCluster&&(Q.debug("to cluster abc88",i[r.toCluster]),l=F6e(r.points,i[r.toCluster].node),u=!0),r.fromCluster&&(Q.debug("from cluster abc88",i[r.fromCluster]),l=F6e(l.reverse(),i[r.fromCluster].node).reverse(),u=!0);let d=l.filter(w=>!Number.isNaN(w.y)),p=wc;r.curve&&(n==="graph"||n==="flowchart")&&(p=r.curve);let{x:m,y:g}=D5(r),y=Cc().x(m).y(g).curve(p),v;switch(r.thickness){case"normal":v="edge-thickness-normal";break;case"thick":v="edge-thickness-thick";break;case"invisible":v="edge-thickness-thick";break;default:v=""}switch(r.pattern){case"solid":v+=" edge-pattern-solid";break;case"dotted":v+=" edge-pattern-dotted";break;case"dashed":v+=" edge-pattern-dashed";break}let x=t.append("path").attr("d",y(d)).attr("id",r.id).attr("class"," "+v+(r.classes?" "+r.classes:"")).attr("style",r.style),b="";(ge().flowchart.arrowMarkerAbsolute||ge().state.arrowMarkerAbsolute)&&(b=Yp(!0)),P6e(x,r,b,s,n);let T={};return u&&(T.updatedPath=l),T.originalPath=r.points,T},"insertEdge")});var Fmt,q6e,W6e=P(()=>{"use strict";Fmt=o(t=>{let e=new Set;for(let r of t)switch(r){case"x":e.add("right"),e.add("left");break;case"y":e.add("up"),e.add("down");break;default:e.add(r);break}return e},"expandAndDeduplicateDirections"),q6e=o((t,e,r)=>{let i=Fmt(t),n=2,a=e.height+2*r.padding,s=a/n,l=e.width+2*s+r.padding,u=r.padding/2;return i.has("right")&&i.has("left")&&i.has("up")&&i.has("down")?[{x:0,y:0},{x:s,y:0},{x:l/2,y:2*u},{x:l-s,y:0},{x:l,y:0},{x:l,y:-a/3},{x:l+2*u,y:-a/2},{x:l,y:-2*a/3},{x:l,y:-a},{x:l-s,y:-a},{x:l/2,y:-a-2*u},{x:s,y:-a},{x:0,y:-a},{x:0,y:-2*a/3},{x:-2*u,y:-a/2},{x:0,y:-a/3}]:i.has("right")&&i.has("left")&&i.has("up")?[{x:s,y:0},{x:l-s,y:0},{x:l,y:-a/2},{x:l-s,y:-a},{x:s,y:-a},{x:0,y:-a/2}]:i.has("right")&&i.has("left")&&i.has("down")?[{x:0,y:0},{x:s,y:-a},{x:l-s,y:-a},{x:l,y:0}]:i.has("right")&&i.has("up")&&i.has("down")?[{x:0,y:0},{x:l,y:-s},{x:l,y:-a+s},{x:0,y:-a}]:i.has("left")&&i.has("up")&&i.has("down")?[{x:l,y:0},{x:0,y:-s},{x:0,y:-a+s},{x:l,y:-a}]:i.has("right")&&i.has("left")?[{x:s,y:0},{x:s,y:-u},{x:l-s,y:-u},{x:l-s,y:0},{x:l,y:-a/2},{x:l-s,y:-a},{x:l-s,y:-a+u},{x:s,y:-a+u},{x:s,y:-a},{x:0,y:-a/2}]:i.has("up")&&i.has("down")?[{x:l/2,y:0},{x:0,y:-u},{x:s,y:-u},{x:s,y:-a+u},{x:0,y:-a+u},{x:l/2,y:-a},{x:l,y:-a+u},{x:l-s,y:-a+u},{x:l-s,y:-u},{x:l,y:-u}]:i.has("right")&&i.has("up")?[{x:0,y:0},{x:l,y:-s},{x:0,y:-a}]:i.has("right")&&i.has("down")?[{x:0,y:0},{x:l,y:0},{x:0,y:-a}]:i.has("left")&&i.has("up")?[{x:l,y:0},{x:0,y:-s},{x:l,y:-a}]:i.has("left")&&i.has("down")?[{x:l,y:0},{x:0,y:0},{x:l,y:-a}]:i.has("right")?[{x:s,y:-u},{x:s,y:-u},{x:l-s,y:-u},{x:l-s,y:0},{x:l,y:-a/2},{x:l-s,y:-a},{x:l-s,y:-a+u},{x:s,y:-a+u},{x:s,y:-a+u}]:i.has("left")?[{x:s,y:0},{x:s,y:-u},{x:l-s,y:-u},{x:l-s,y:-a+u},{x:s,y:-a+u},{x:s,y:-a},{x:0,y:-a/2}]:i.has("up")?[{x:s,y:-u},{x:s,y:-a+u},{x:0,y:-a+u},{x:l/2,y:-a},{x:l,y:-a+u},{x:l-s,y:-a+u},{x:l-s,y:-u}]:i.has("down")?[{x:l/2,y:0},{x:0,y:-u},{x:s,y:-u},{x:s,y:-a+u},{x:l-s,y:-a+u},{x:l-s,y:-u},{x:l,y:-u}]:[{x:0,y:0}]},"getArrowPoints")});function $mt(t,e){return t.intersect(e)}var U6e,H6e=P(()=>{"use strict";o($mt,"intersectNode");U6e=$mt});function zmt(t,e,r,i){var n=t.x,a=t.y,s=n-i.x,l=a-i.y,u=Math.sqrt(e*e*l*l+r*r*s*s),h=Math.abs(e*r*s/u);i.x{"use strict";o(zmt,"intersectEllipse");t8=zmt});function Gmt(t,e,r){return t8(t,e,e,r)}var Y6e,j6e=P(()=>{"use strict";LH();o(Gmt,"intersectCircle");Y6e=Gmt});function Vmt(t,e,r,i){var n,a,s,l,u,h,f,d,p,m,g,y,v,x,b;if(n=e.y-t.y,s=t.x-e.x,u=e.x*t.y-t.x*e.y,p=n*r.x+s*r.y+u,m=n*i.x+s*i.y+u,!(p!==0&&m!==0&&X6e(p,m))&&(a=i.y-r.y,l=r.x-i.x,h=i.x*r.y-r.x*i.y,f=a*t.x+l*t.y+h,d=a*e.x+l*e.y+h,!(f!==0&&d!==0&&X6e(f,d))&&(g=n*l-a*s,g!==0)))return y=Math.abs(g/2),v=s*h-l*u,x=v<0?(v-y)/g:(v+y)/g,v=a*u-n*h,b=v<0?(v-y)/g:(v+y)/g,{x,y:b}}function X6e(t,e){return t*e>0}var K6e,Q6e=P(()=>{"use strict";o(Vmt,"intersectLine");o(X6e,"sameSign");K6e=Vmt});function qmt(t,e,r){var i=t.x,n=t.y,a=[],s=Number.POSITIVE_INFINITY,l=Number.POSITIVE_INFINITY;typeof e.forEach=="function"?e.forEach(function(g){s=Math.min(s,g.x),l=Math.min(l,g.y)}):(s=Math.min(s,e.x),l=Math.min(l,e.y));for(var u=i-t.width/2-s,h=n-t.height/2-l,f=0;f1&&a.sort(function(g,y){var v=g.x-r.x,x=g.y-r.y,b=Math.sqrt(v*v+x*x),T=y.x-r.x,w=y.y-r.y,k=Math.sqrt(T*T+w*w);return b{"use strict";Q6e();Z6e=qmt;o(qmt,"intersectPolygon")});var Wmt,eAe,tAe=P(()=>{"use strict";Wmt=o((t,e)=>{var r=t.x,i=t.y,n=e.x-r,a=e.y-i,s=t.width/2,l=t.height/2,u,h;return Math.abs(a)*s>Math.abs(n)*l?(a<0&&(l=-l),u=a===0?0:l*n/a,h=l):(n<0&&(s=-s),u=s,h=n===0?0:s*a/n),{x:r+u,y:i+h}},"intersectRect"),eAe=Wmt});var an,RH=P(()=>{"use strict";H6e();j6e();LH();J6e();tAe();an={node:U6e,circle:Y6e,ellipse:t8,polygon:Z6e,rect:eAe}});function Kc(t,e,r,i){return t.insert("polygon",":first-child").attr("points",i.map(function(n){return n.x+","+n.y}).join(" ")).attr("class","label-container").attr("transform","translate("+-e/2+","+r/2+")")}var na,Tn,NH=P(()=>{"use strict";J_();To();Ut();Sr();Pr();Vr();er();rM();na=o(async(t,e,r,i)=>{let n=ge(),a,s=e.useHtmlLabels||Or(n);r?a=r:a="node default";let l=t.insert("g").attr("class",a).attr("id",e.domId||e.id),u=l.insert("g").attr("class","label").attr("style",e.labelStyle),h;e.labelText===void 0?h="":h=typeof e.labelText=="string"?e.labelText:e.labelText[0];let f;e.labelType==="markdown"?f=Vi(u,Tr(zs(h),n),{useHtmlLabels:s,width:e.width||n.flowchart.wrappingWidth,classes:"markdown-node-label"},n):f=await Vo(u,Tr(zs(h),n),e.labelStyle,!1,i);let d=f.getBBox(),p=e.padding/2;if(Or(n)){let m=f.children[0],g=Ze(f);await u5(m,h),d=m.getBoundingClientRect(),g.attr("width",d.width),g.attr("height",d.height)}return s?u.attr("transform","translate("+-d.width/2+", "+-d.height/2+")"):u.attr("transform","translate(0, "+-d.height/2+")"),e.centerLabel&&u.attr("transform","translate("+-d.width/2+", "+-d.height/2+")"),u.insert("rect",":first-child"),{shapeSvg:l,bbox:d,halfPadding:p,label:u}},"labelHelper"),Tn=o((t,e)=>{let r=e.node().getBBox();t.width=r.width,t.height=r.height},"updateNodeBounds");o(Kc,"insertPolygonShape")});var Umt,rAe,iAe=P(()=>{"use strict";NH();bt();Ut();Sr();RH();Umt=o(async(t,e)=>{e.useHtmlLabels||Or(ge())||(e.centerLabel=!0);let{shapeSvg:i,bbox:n,halfPadding:a}=await na(t,e,"node "+e.classes,!0);Q.info("Classes = ",e.classes);let s=i.insert("rect",":first-child");return s.attr("rx",e.rx).attr("ry",e.ry).attr("x",-n.width/2-a).attr("y",-n.height/2-a).attr("width",n.width+e.padding).attr("height",n.height+e.padding),Tn(e,s),e.intersect=function(l){return an.rect(e,l)},i},"note"),rAe=Umt});function IH(t,e,r,i){let n=[],a=o(l=>{n.push(l,0)},"addBorder"),s=o(l=>{n.push(0,l)},"skipBorder");e.includes("t")?(Q.debug("add top border"),a(r)):s(r),e.includes("r")?(Q.debug("add right border"),a(i)):s(i),e.includes("b")?(Q.debug("add bottom border"),a(r)):s(r),e.includes("l")?(Q.debug("add left border"),a(i)):s(i),t.attr("stroke-dasharray",n.join(" "))}var nAe,pl,aAe,Hmt,Ymt,jmt,Xmt,Kmt,Qmt,Zmt,Jmt,egt,tgt,rgt,igt,ngt,agt,sgt,ogt,lgt,cgt,ugt,sAe,hgt,fgt,oAe,r8,MH,lAe,cAe=P(()=>{"use strict";Pr();Ut();Sr();bt();W6e();J_();RH();iAe();NH();nAe=o(t=>t?" "+t:"","formatClass"),pl=o((t,e)=>`${e||"node default"}${nAe(t.classes)} ${nAe(t.class)}`,"getClassesFromNode"),aAe=o(async(t,e)=>{let{shapeSvg:r,bbox:i}=await na(t,e,pl(e,void 0),!0),n=i.width+e.padding,a=i.height+e.padding,s=n+a,l=[{x:s/2,y:0},{x:s,y:-s/2},{x:s/2,y:-s},{x:0,y:-s/2}];Q.info("Question main (Circle)");let u=Kc(r,s,s,l);return u.attr("style",e.style),Tn(e,u),e.intersect=function(h){return Q.warn("Intersect called"),an.polygon(e,l,h)},r},"question"),Hmt=o((t,e)=>{let r=t.insert("g").attr("class","node default").attr("id",e.domId||e.id),i=28,n=[{x:0,y:i/2},{x:i/2,y:0},{x:0,y:-i/2},{x:-i/2,y:0}];return r.insert("polygon",":first-child").attr("points",n.map(function(s){return s.x+","+s.y}).join(" ")).attr("class","state-start").attr("r",7).attr("width",28).attr("height",28),e.width=28,e.height=28,e.intersect=function(s){return an.circle(e,14,s)},r},"choice"),Ymt=o(async(t,e)=>{let{shapeSvg:r,bbox:i}=await na(t,e,pl(e,void 0),!0),n=4,a=i.height+e.padding,s=a/n,l=i.width+2*s+e.padding,u=[{x:s,y:0},{x:l-s,y:0},{x:l,y:-a/2},{x:l-s,y:-a},{x:s,y:-a},{x:0,y:-a/2}],h=Kc(r,l,a,u);return h.attr("style",e.style),Tn(e,h),e.intersect=function(f){return an.polygon(e,u,f)},r},"hexagon"),jmt=o(async(t,e)=>{let{shapeSvg:r,bbox:i}=await na(t,e,void 0,!0),n=2,a=i.height+2*e.padding,s=a/n,l=i.width+2*s+e.padding,u=q6e(e.directions,i,e),h=Kc(r,l,a,u);return h.attr("style",e.style),Tn(e,h),e.intersect=function(f){return an.polygon(e,u,f)},r},"block_arrow"),Xmt=o(async(t,e)=>{let{shapeSvg:r,bbox:i}=await na(t,e,pl(e,void 0),!0),n=i.width+e.padding,a=i.height+e.padding,s=[{x:-a/2,y:0},{x:n,y:0},{x:n,y:-a},{x:-a/2,y:-a},{x:0,y:-a/2}];return Kc(r,n,a,s).attr("style",e.style),e.width=n+a,e.height=a,e.intersect=function(u){return an.polygon(e,s,u)},r},"rect_left_inv_arrow"),Kmt=o(async(t,e)=>{let{shapeSvg:r,bbox:i}=await na(t,e,pl(e),!0),n=i.width+e.padding,a=i.height+e.padding,s=[{x:-2*a/6,y:0},{x:n-a/6,y:0},{x:n+2*a/6,y:-a},{x:a/6,y:-a}],l=Kc(r,n,a,s);return l.attr("style",e.style),Tn(e,l),e.intersect=function(u){return an.polygon(e,s,u)},r},"lean_right"),Qmt=o(async(t,e)=>{let{shapeSvg:r,bbox:i}=await na(t,e,pl(e,void 0),!0),n=i.width+e.padding,a=i.height+e.padding,s=[{x:2*a/6,y:0},{x:n+a/6,y:0},{x:n-2*a/6,y:-a},{x:-a/6,y:-a}],l=Kc(r,n,a,s);return l.attr("style",e.style),Tn(e,l),e.intersect=function(u){return an.polygon(e,s,u)},r},"lean_left"),Zmt=o(async(t,e)=>{let{shapeSvg:r,bbox:i}=await na(t,e,pl(e,void 0),!0),n=i.width+e.padding,a=i.height+e.padding,s=[{x:-2*a/6,y:0},{x:n+2*a/6,y:0},{x:n-a/6,y:-a},{x:a/6,y:-a}],l=Kc(r,n,a,s);return l.attr("style",e.style),Tn(e,l),e.intersect=function(u){return an.polygon(e,s,u)},r},"trapezoid"),Jmt=o(async(t,e)=>{let{shapeSvg:r,bbox:i}=await na(t,e,pl(e,void 0),!0),n=i.width+e.padding,a=i.height+e.padding,s=[{x:a/6,y:0},{x:n-a/6,y:0},{x:n+2*a/6,y:-a},{x:-2*a/6,y:-a}],l=Kc(r,n,a,s);return l.attr("style",e.style),Tn(e,l),e.intersect=function(u){return an.polygon(e,s,u)},r},"inv_trapezoid"),egt=o(async(t,e)=>{let{shapeSvg:r,bbox:i}=await na(t,e,pl(e,void 0),!0),n=i.width+e.padding,a=i.height+e.padding,s=[{x:0,y:0},{x:n+a/2,y:0},{x:n,y:-a/2},{x:n+a/2,y:-a},{x:0,y:-a}],l=Kc(r,n,a,s);return l.attr("style",e.style),Tn(e,l),e.intersect=function(u){return an.polygon(e,s,u)},r},"rect_right_inv_arrow"),tgt=o(async(t,e)=>{let{shapeSvg:r,bbox:i}=await na(t,e,pl(e,void 0),!0),n=i.width+e.padding,a=n/2,s=a/(2.5+n/50),l=i.height+s+e.padding,u="M 0,"+s+" a "+a+","+s+" 0,0,0 "+n+" 0 a "+a+","+s+" 0,0,0 "+-n+" 0 l 0,"+l+" a "+a+","+s+" 0,0,0 "+n+" 0 l 0,"+-l,h=r.attr("label-offset-y",s).insert("path",":first-child").attr("style",e.style).attr("d",u).attr("transform","translate("+-n/2+","+-(l/2+s)+")");return Tn(e,h),e.intersect=function(f){let d=an.rect(e,f),p=d.x-e.x;if(a!=0&&(Math.abs(p)e.height/2-s)){let m=s*s*(1-p*p/(a*a));m!=0&&(m=Math.sqrt(m)),m=s-m,f.y-e.y>0&&(m=-m),d.y+=m}return d},r},"cylinder"),rgt=o(async(t,e)=>{let{shapeSvg:r,bbox:i,halfPadding:n}=await na(t,e,"node "+e.classes+" "+e.class,!0),a=r.insert("rect",":first-child"),s=e.positioned?e.width:i.width+e.padding,l=e.positioned?e.height:i.height+e.padding,u=e.positioned?-s/2:-i.width/2-n,h=e.positioned?-l/2:-i.height/2-n;if(a.attr("class","basic label-container").attr("style",e.style).attr("rx",e.rx).attr("ry",e.ry).attr("x",u).attr("y",h).attr("width",s).attr("height",l),e.props){let f=new Set(Object.keys(e.props));e.props.borders&&(IH(a,e.props.borders,s,l),f.delete("borders")),f.forEach(d=>{Q.warn(`Unknown node property ${d}`)})}return Tn(e,a),e.intersect=function(f){return an.rect(e,f)},r},"rect"),igt=o(async(t,e)=>{let{shapeSvg:r,bbox:i,halfPadding:n}=await na(t,e,"node "+e.classes,!0),a=r.insert("rect",":first-child"),s=e.positioned?e.width:i.width+e.padding,l=e.positioned?e.height:i.height+e.padding,u=e.positioned?-s/2:-i.width/2-n,h=e.positioned?-l/2:-i.height/2-n;if(a.attr("class","basic cluster composite label-container").attr("style",e.style).attr("rx",e.rx).attr("ry",e.ry).attr("x",u).attr("y",h).attr("width",s).attr("height",l),e.props){let f=new Set(Object.keys(e.props));e.props.borders&&(IH(a,e.props.borders,s,l),f.delete("borders")),f.forEach(d=>{Q.warn(`Unknown node property ${d}`)})}return Tn(e,a),e.intersect=function(f){return an.rect(e,f)},r},"composite"),ngt=o(async(t,e)=>{let{shapeSvg:r}=await na(t,e,"label",!0);Q.trace("Classes = ",e.class);let i=r.insert("rect",":first-child"),n=0,a=0;if(i.attr("width",n).attr("height",a),r.attr("class","label edgeLabel"),e.props){let s=new Set(Object.keys(e.props));e.props.borders&&(IH(i,e.props.borders,n,a),s.delete("borders")),s.forEach(l=>{Q.warn(`Unknown node property ${l}`)})}return Tn(e,i),e.intersect=function(s){return an.rect(e,s)},r},"labelRect");o(IH,"applyNodePropertyBorders");agt=o(async(t,e)=>{let r;e.classes?r="node "+e.classes:r="node default";let i=t.insert("g").attr("class",r).attr("id",e.domId||e.id),n=i.insert("rect",":first-child"),a=i.insert("line"),s=i.insert("g").attr("class","label"),l=e.labelText.flat?e.labelText.flat():e.labelText,u="";typeof l=="object"?u=l[0]:u=l,Q.info("Label text abc79",u,l,typeof l=="object");let h=await Vo(s,u,e.labelStyle,!0,!0),f={width:0,height:0};if(Or(ge())){let y=h.children[0],v=Ze(h);f=y.getBoundingClientRect(),v.attr("width",f.width),v.attr("height",f.height)}Q.info("Text 2",l);let d=l.slice(1,l.length),p=h.getBBox(),m=await Vo(s,d.join?d.join("
    "):d,e.labelStyle,!0,!0);if(Or(ge())){let y=m.children[0],v=Ze(m);f=y.getBoundingClientRect(),v.attr("width",f.width),v.attr("height",f.height)}let g=e.padding/2;return Ze(m).attr("transform","translate( "+(f.width>p.width?0:(p.width-f.width)/2)+", "+(p.height+g+5)+")"),Ze(h).attr("transform","translate( "+(f.width{let{shapeSvg:r,bbox:i}=await na(t,e,pl(e,void 0),!0),n=i.height+e.padding,a=i.width+n/4+e.padding,s=r.insert("rect",":first-child").attr("style",e.style).attr("rx",n/2).attr("ry",n/2).attr("x",-a/2).attr("y",-n/2).attr("width",a).attr("height",n);return Tn(e,s),e.intersect=function(l){return an.rect(e,l)},r},"stadium"),ogt=o(async(t,e)=>{let{shapeSvg:r,bbox:i,halfPadding:n}=await na(t,e,pl(e,void 0),!0),a=r.insert("circle",":first-child");return a.attr("style",e.style).attr("rx",e.rx).attr("ry",e.ry).attr("r",i.width/2+n).attr("width",i.width+e.padding).attr("height",i.height+e.padding),Q.info("Circle main"),Tn(e,a),e.intersect=function(s){return Q.info("Circle intersect",e,i.width/2+n,s),an.circle(e,i.width/2+n,s)},r},"circle"),lgt=o(async(t,e)=>{let{shapeSvg:r,bbox:i,halfPadding:n}=await na(t,e,pl(e,void 0),!0),a=5,s=r.insert("g",":first-child"),l=s.insert("circle"),u=s.insert("circle");return s.attr("class",e.class),l.attr("style",e.style).attr("rx",e.rx).attr("ry",e.ry).attr("r",i.width/2+n+a).attr("width",i.width+e.padding+a*2).attr("height",i.height+e.padding+a*2),u.attr("style",e.style).attr("rx",e.rx).attr("ry",e.ry).attr("r",i.width/2+n).attr("width",i.width+e.padding).attr("height",i.height+e.padding),Q.info("DoubleCircle main"),Tn(e,l),e.intersect=function(h){return Q.info("DoubleCircle intersect",e,i.width/2+n+a,h),an.circle(e,i.width/2+n+a,h)},r},"doublecircle"),cgt=o(async(t,e)=>{let{shapeSvg:r,bbox:i}=await na(t,e,pl(e,void 0),!0),n=i.width+e.padding,a=i.height+e.padding,s=[{x:0,y:0},{x:n,y:0},{x:n,y:-a},{x:0,y:-a},{x:0,y:0},{x:-8,y:0},{x:n+8,y:0},{x:n+8,y:-a},{x:-8,y:-a},{x:-8,y:0}],l=Kc(r,n,a,s);return l.attr("style",e.style),Tn(e,l),e.intersect=function(u){return an.polygon(e,s,u)},r},"subroutine"),ugt=o((t,e)=>{let r=t.insert("g").attr("class","node default").attr("id",e.domId||e.id),i=r.insert("circle",":first-child");return i.attr("class","state-start").attr("r",7).attr("width",14).attr("height",14),Tn(e,i),e.intersect=function(n){return an.circle(e,7,n)},r},"start"),sAe=o((t,e,r)=>{let i=t.insert("g").attr("class","node default").attr("id",e.domId||e.id),n=70,a=10;r==="LR"&&(n=10,a=70);let s=i.append("rect").attr("x",-1*n/2).attr("y",-1*a/2).attr("width",n).attr("height",a).attr("class","fork-join");return Tn(e,s),e.height=e.height+e.padding/2,e.width=e.width+e.padding/2,e.intersect=function(l){return an.rect(e,l)},i},"forkJoin"),hgt=o((t,e)=>{let r=t.insert("g").attr("class","node default").attr("id",e.domId||e.id),i=r.insert("circle",":first-child"),n=r.insert("circle",":first-child");return n.attr("class","state-start").attr("r",7).attr("width",14).attr("height",14),i.attr("class","state-end").attr("r",5).attr("width",10).attr("height",10),Tn(e,n),e.intersect=function(a){return an.circle(e,7,a)},r},"end"),fgt=o(async(t,e)=>{let r=e.padding/2,i=4,n=8,a;e.classes?a="node "+e.classes:a="node default";let s=t.insert("g").attr("class",a).attr("id",e.domId||e.id),l=s.insert("rect",":first-child"),u=s.insert("line"),h=s.insert("line"),f=0,d=i,p=s.insert("g").attr("class","label"),m=0,g=e.classData.annotations?.[0],y=e.classData.annotations[0]?"\xAB"+e.classData.annotations[0]+"\xBB":"",v=await Vo(p,y,e.labelStyle,!0,!0),x=v.getBBox();if(Or(ge())){let S=v.children[0],L=Ze(v);x=S.getBoundingClientRect(),L.attr("width",x.width),L.attr("height",x.height)}e.classData.annotations[0]&&(d+=x.height+i,f+=x.width);let b=e.classData.label;e.classData.type!==void 0&&e.classData.type!==""&&(Or(ge())?b+="<"+e.classData.type+">":b+="<"+e.classData.type+">");let T=await Vo(p,b,e.labelStyle,!0,!0);Ze(T).attr("class","classTitle");let w=T.getBBox();if(Or(ge())){let S=T.children[0],L=Ze(T);w=S.getBoundingClientRect(),L.attr("width",w.width),L.attr("height",w.height)}d+=w.height+i,w.width>f&&(f=w.width);let k=[];e.classData.members.forEach(async S=>{let L=S.getDisplayDetails(),M=L.displayText;Or(ge())&&(M=M.replace(//g,">"));let I=await Vo(p,M,L.cssStyle?L.cssStyle:e.labelStyle,!0,!0),A=I.getBBox();if(Or(ge())){let _=I.children[0],D=Ze(I);A=_.getBoundingClientRect(),D.attr("width",A.width),D.attr("height",A.height)}A.width>f&&(f=A.width),d+=A.height+i,k.push(I)}),d+=n;let C=[];if(e.classData.methods.forEach(async S=>{let L=S.getDisplayDetails(),M=L.displayText;Or(ge())&&(M=M.replace(//g,">"));let I=await Vo(p,M,L.cssStyle?L.cssStyle:e.labelStyle,!0,!0),A=I.getBBox();if(Or(ge())){let _=I.children[0],D=Ze(I);A=_.getBoundingClientRect(),D.attr("width",A.width),D.attr("height",A.height)}A.width>f&&(f=A.width),d+=A.height+i,C.push(I)}),d+=n,g){let S=(f-x.width)/2;Ze(v).attr("transform","translate( "+(-1*f/2+S)+", "+-1*d/2+")"),m=x.height+i}let E=(f-w.width)/2;return Ze(T).attr("transform","translate( "+(-1*f/2+E)+", "+(-1*d/2+m)+")"),m+=w.height+i,u.attr("class","divider").attr("x1",-f/2-r).attr("x2",f/2+r).attr("y1",-d/2-r+n+m).attr("y2",-d/2-r+n+m),m+=n,k.forEach(S=>{Ze(S).attr("transform","translate( "+-f/2+", "+(-1*d/2+m+n/2)+")");let L=S?.getBBox();m+=(L?.height??0)+i}),m+=n,h.attr("class","divider").attr("x1",-f/2-r).attr("x2",f/2+r).attr("y1",-d/2-r+n+m).attr("y2",-d/2-r+n+m),m+=n,C.forEach(S=>{Ze(S).attr("transform","translate( "+-f/2+", "+(-1*d/2+m)+")");let L=S?.getBBox();m+=(L?.height??0)+i}),l.attr("style",e.style).attr("class","outer title-state").attr("x",-f/2-r).attr("y",-(d/2)-r).attr("width",f+e.padding).attr("height",d+e.padding),Tn(e,l),e.intersect=function(S){return an.rect(e,S)},s},"class_box"),oAe={rhombus:aAe,composite:igt,question:aAe,rect:rgt,labelRect:ngt,rectWithTitle:agt,choice:Hmt,circle:ogt,doublecircle:lgt,stadium:sgt,hexagon:Ymt,block_arrow:jmt,rect_left_inv_arrow:Xmt,lean_right:Kmt,lean_left:Qmt,trapezoid:Zmt,inv_trapezoid:Jmt,rect_right_inv_arrow:egt,cylinder:tgt,start:ugt,end:hgt,note:rAe,subroutine:cgt,fork:sAe,join:sAe,class_box:fgt},r8={},MH=o(async(t,e,r)=>{let i,n;if(e.link){let a;ge().securityLevel==="sandbox"?a="_top":e.linkTarget&&(a=e.linkTarget||"_blank"),i=t.insert("svg:a").attr("xlink:href",e.link).attr("target",a),n=await oAe[e.shape](i,e,r)}else n=await oAe[e.shape](t,e,r),i=n;return e.tooltip&&n.attr("title",e.tooltip),e.class&&n.attr("class","node default "+e.class),r8[e.id]=i,e.haveCallback&&r8[e.id].attr("class",r8[e.id].attr("class")+" clickable"),i},"insertNode"),lAe=o(t=>{let e=r8[t.id];Q.trace("Transforming node",t.diff,t,"translate("+(t.x-t.width/2-5)+", "+t.width/2+")");let r=8,i=t.diff||0;return t.clusterNode?e.attr("transform","translate("+(t.x+i-t.width/2)+", "+(t.y-t.height/2-r)+")"):e.attr("transform","translate("+t.x+", "+t.y+")"),i},"positionNode")});function uAe(t,e,r=!1){let i=t,n="default";(i?.classes?.length||0)>0&&(n=(i?.classes??[]).join(" ")),n=n+" flowchart-label";let a=0,s="",l;switch(i.type){case"round":a=5,s="rect";break;case"composite":a=0,s="composite",l=0;break;case"square":s="rect";break;case"diamond":s="question";break;case"hexagon":s="hexagon";break;case"block_arrow":s="block_arrow";break;case"odd":s="rect_left_inv_arrow";break;case"lean_right":s="lean_right";break;case"lean_left":s="lean_left";break;case"trapezoid":s="trapezoid";break;case"inv_trapezoid":s="inv_trapezoid";break;case"rect_left_inv_arrow":s="rect_left_inv_arrow";break;case"circle":s="circle";break;case"ellipse":s="ellipse";break;case"stadium":s="stadium";break;case"subroutine":s="subroutine";break;case"cylinder":s="cylinder";break;case"group":s="rect";break;case"doublecircle":s="doublecircle";break;default:s="rect"}let u=xI(i?.styles??[]),h=i.label,f=i.size??{width:0,height:0,x:0,y:0},d=e.getDiagramId();return{labelStyle:u.labelStyle,shape:s,labelText:h,rx:a,ry:a,class:n,style:u.style,id:i.id,domId:d?`${d}-${i.id}`:i.id,directions:i.directions,width:f.width,height:f.height,x:f.x,y:f.y,positioned:r,intersect:void 0,type:i.type,padding:l??Lt()?.block?.padding??0}}async function dgt(t,e,r){let i=uAe(e,r,!1);if(i.type==="group")return;let n=Lt(),a=await MH(t,i,{config:n}),s=a.node().getBBox(),l=r.getBlock(i.id);l.size={width:s.width,height:s.height,x:0,y:0,node:a},r.setBlock(l),a.remove()}async function pgt(t,e,r){let i=uAe(e,r,!0);if(r.getBlock(i.id).type!=="space"){let a=Lt();await MH(t,i,{config:a}),e.intersect=i?.intersect,lAe(i)}}async function OH(t,e,r,i){for(let n of e)await i(t,n,r),n.children&&await OH(t,n.children,r,i)}async function hAe(t,e,r){await OH(t,e,r,dgt)}async function fAe(t,e,r){await OH(t,e,r,pgt)}async function dAe(t,e,r,i,n){let a=new Ai({multigraph:!0,compound:!0});a.setGraph({rankdir:"TB",nodesep:10,ranksep:10,marginx:8,marginy:8});for(let s of r)s.size&&a.setNode(s.id,{width:s.size.width,height:s.size.height,intersect:s.intersect});for(let s of e)if(s.start&&s.end){let l=i.getBlock(s.start),u=i.getBlock(s.end);if(l?.size&&u?.size){let h=l.size,f=u.size,d=[{x:h.x,y:h.y},{x:h.x+(f.x-h.x)/2,y:h.y+(f.y-h.y)/2},{x:f.x,y:f.y}],p=n?`${n}-${s.id}`:s.id;G6e(t,{v:s.start,w:s.end,name:p},{...s,id:p,arrowTypeEnd:s.arrowTypeEnd,arrowTypeStart:s.arrowTypeStart,points:d,classes:"edge-thickness-normal edge-pattern-solid flowchart-link LS-a1 LE-b1"},void 0,"block",a,n),s.label&&(await $6e(t,{...s,label:s.label,labelStyle:"stroke: #333; stroke-width: 1.5px;fill:none;",arrowTypeEnd:s.arrowTypeEnd,arrowTypeStart:s.arrowTypeStart,points:d,classes:"edge-thickness-normal edge-pattern-solid flowchart-link LS-a1 LE-b1"}),z6e({...s,x:d[1].x,y:d[1].y},{originalPath:d}))}}}var pAe=P(()=>{"use strict";$l();Sr();V6e();cAe();er();o(uAe,"getNodeFromBlock");o(dgt,"calculateBlockSize");o(pgt,"insertBlockPositioned");o(OH,"performOperations");o(hAe,"calculateBlockSizes");o(fAe,"insertBlocks");o(dAe,"insertEdges")});var mgt,ggt,mAe,gAe=P(()=>{"use strict";Pr();Sr();D6e();bt();Xi();M6e();pAe();mgt=o(function(t,e){return e.db.getClasses()},"getClasses"),ggt=o(async function(t,e,r,i){let{securityLevel:n,block:a}=Lt(),s=i.db;s.setDiagramId(e);let l;n==="sandbox"&&(l=Ze("#i"+e));let u=n==="sandbox"?Ze(l.nodes()[0].contentDocument.body):Ze("body"),h=n==="sandbox"?u.select(`[id="${e}"]`):Ze(`[id="${e}"]`);_6e(h,["point","circle","cross"],i.type,e);let d=s.getBlocks(),p=s.getBlocksFlat(),m=s.getEdges(),g=h.insert("g").attr("class","block");await hAe(g,d,s);let y=I6e(s);if(await fAe(g,d,s),await dAe(g,m,p,s,e),y){let v=y,x=Math.max(1,Math.round(.125*(v.width/v.height))),b=v.height+x+10,T=v.width+10,{useMaxWidth:w}=a;Hr(h,b,T,!!w),Q.debug("Here Bounds",y,v),h.attr("viewBox",`${v.x-5} ${v.y-5} ${v.width+10} ${v.height+10}`)}},"draw"),mAe={draw:ggt,getClasses:mgt}});var yAe={};ur(yAe,{diagram:()=>ygt});var ygt,vAe=P(()=>{"use strict";v6e();E6e();A6e();gAe();ygt={parser:y6e,db:w6e,renderer:mAe,styles:S6e}});var uh,Tgt,kgt,Cgt,wgt,Egt,Sgt,Agt,WC,PH=P(()=>{"use strict";Sr();wa();Ki();er();J7();uh=new Cp(()=>({cnt:1,stack:[{id:0,level:-1,name:"/",children:[]}]})),Tgt=o(()=>{uh.reset(),wr()},"clear"),kgt=o(()=>uh.records.stack[0],"getRoot"),Cgt=o(()=>uh.records.cnt,"getCount"),wgt=fr.treeView,Egt=o(()=>fi(wgt,Lt().treeView),"getConfig"),Sgt=o((t,e)=>{for(;t<=uh.records.stack[uh.records.stack.length-1].level;)uh.records.stack.pop();let r={id:uh.records.cnt++,level:t,name:e,children:[]};uh.records.stack[uh.records.stack.length-1].children.push(r),uh.records.stack.push(r)},"addNode"),Agt={clear:Tgt,addNode:Sgt,getRoot:kgt,getCount:Cgt,getConfig:Egt,getAccTitle:Dr,getAccDescription:Rr,getDiagramTitle:Nr,setAccDescription:Lr,setAccTitle:Ar,setDiagramTitle:Mr},WC=Agt});var _gt,TAe,kAe=P(()=>{"use strict";bt();vf();PH();sh();_gt=o(t=>{Ss(t,WC),t.nodes.map(e=>WC.addNode(e.indent?parseInt(e.indent):0,e.name))},"populate"),TAe={parse:o(async t=>{let e=await ba("treeView",t);Q.debug(e),_gt(e)},"parse")}});var Dgt,CAe,Lgt,Rgt,Ngt,wAe,EAe=P(()=>{"use strict";bt();ro();Xi();Dgt=o((t,e,r,i,n)=>{let a=i.append("text").text(r.name).attr("dominant-baseline","middle").attr("class","treeView-node-label"),{height:s,width:l}=a.node().getBBox(),u=s+n.paddingY*2,h=l+n.paddingX*2;a.attr("x",t+n.paddingX),a.attr("y",e+u/2),r.BBox={x:t,y:e,width:h,height:u}},"positionLabel"),CAe=o((t,e,r,i,n,a)=>t.append("line").attr("x1",e).attr("y1",r).attr("x2",i).attr("y2",n).attr("stroke-width",a).attr("class","treeView-node-line"),"positionLine"),Lgt=o((t,e,r)=>{let i=0,n=0,a=o((l,u,h,f)=>{let d=f*(h.rowIndent+h.paddingX);Dgt(d,i,u,l,h);let{height:p,width:m}=u.BBox;CAe(l,d-h.rowIndent,i+p/2,d,i+p/2,h.lineThickness),n=Math.max(n,d+m),i+=p},"drawNode"),s=o((l,u=0)=>{a(t,l,r,u),l.children.forEach(p=>{s(p,u+1)});let{x:h,y:f,height:d}=l.BBox;if(l.children.length){let{y:p,height:m}=l.children[l.children.length-1].BBox;CAe(t,h+r.paddingX,f+d,h+r.paddingX,p+m/2+r.lineThickness/2,r.lineThickness)}},"processNode");return s(e),{totalHeight:i,totalWidth:n}},"drawTree"),Rgt=o((t,e,r,i)=>{Q.debug(`Rendering treeView diagram +`+t);let n=i.db,a=n.getRoot(),s=n.getConfig(),l=Fi(e),u=l.append("g");u.attr("class","tree-view");let{totalHeight:h,totalWidth:f}=Lgt(u,a,s);l.attr("viewBox",`-${s.lineThickness/2} 0 ${f} ${h}`),Hr(l,h,f,s.useMaxWidth)},"draw"),Ngt={draw:Rgt},wAe=Ngt});var Igt,Mgt,SAe,AAe=P(()=>{"use strict";er();Igt={labelFontSize:"16px",labelColor:"black",lineColor:"black"},Mgt=o(({treeView:t})=>{let{labelFontSize:e,labelColor:r,lineColor:i}=fi(Igt,t);return` + .treeView-node-label { + font-size: ${e}; + fill: ${r}; + } + .treeView-node-line { + stroke: ${i}; + } + `},"styles"),SAe=Mgt});var _Ae={};ur(_Ae,{diagram:()=>Ogt});var Ogt,DAe=P(()=>{"use strict";kAe();PH();EAe();AAe();Ogt={db:WC,renderer:wAe,parser:TAe,styles:SAe}});var BH,FH,UC,NAe,$H,Ds,hh,HC,IAe,$gt,YC,MAe,OAe,PAe,BAe,FAe,i8,Np,n8=P(()=>{"use strict";BH={L:"left",R:"right",T:"top",B:"bottom"},FH={L:o(t=>`${t},${t/2} 0,${t} 0,0`,"L"),R:o(t=>`0,${t/2} ${t},0 ${t},${t}`,"R"),T:o(t=>`0,0 ${t},0 ${t/2},${t}`,"T"),B:o(t=>`${t/2},0 ${t},${t} 0,${t}`,"B")},UC={L:o((t,e)=>t-e+2,"L"),R:o((t,e)=>t-2,"R"),T:o((t,e)=>t-e+2,"T"),B:o((t,e)=>t-2,"B")},NAe=o(function(t){return Ds(t)?t==="L"?"R":"L":t==="T"?"B":"T"},"getOppositeArchitectureDirection"),$H=o(function(t){let e=t;return e==="L"||e==="R"||e==="T"||e==="B"},"isArchitectureDirection"),Ds=o(function(t){let e=t;return e==="L"||e==="R"},"isArchitectureDirectionX"),hh=o(function(t){let e=t;return e==="T"||e==="B"},"isArchitectureDirectionY"),HC=o(function(t,e){let r=Ds(t)&&hh(e),i=hh(t)&&Ds(e);return r||i},"isArchitectureDirectionXY"),IAe=o(function(t){let e=t[0],r=t[1],i=Ds(e)&&hh(r),n=hh(e)&&Ds(r);return i||n},"isArchitecturePairXY"),$gt=o(function(t){return t!=="LL"&&t!=="RR"&&t!=="TT"&&t!=="BB"},"isValidArchitectureDirectionPair"),YC=o(function(t,e){let r=`${t}${e}`;return $gt(r)?r:void 0},"getArchitectureDirectionPair"),MAe=o(function([t,e],r){let i=r[0],n=r[1];return Ds(i)?hh(n)?[t+(i==="L"?-1:1),e+(n==="T"?1:-1)]:[t+(i==="L"?-1:1),e]:Ds(n)?[t+(n==="L"?1:-1),e+(i==="T"?1:-1)]:[t,e+(i==="T"?1:-1)]},"shiftPositionByArchitectureDirectionPair"),OAe=o(function(t){return t==="LT"||t==="TL"?[1,1]:t==="BL"||t==="LB"?[1,-1]:t==="BR"||t==="RB"?[-1,-1]:[-1,1]},"getArchitectureDirectionXYFactors"),PAe=o(function(t,e){return HC(t,e)?"bend":Ds(t)?"horizontal":"vertical"},"getArchitectureDirectionAlignment"),BAe=o(function(t){return t.type==="service"},"isArchitectureService"),FAe=o(function(t){return t.type==="junction"},"isArchitectureJunction"),i8=o(t=>t.data(),"edgeData"),Np=o(t=>t.data(),"nodeData")});var zgt,dx,zH=P(()=>{"use strict";Sr();wa();er();Ki();n8();zgt=fr.architecture,dx=class{constructor(){this.nodes={};this.groups={};this.edges=[];this.registeredIds={};this.elements={};this.diagramId="";this.setAccTitle=Ar;this.getAccTitle=Dr;this.setDiagramTitle=Mr;this.getDiagramTitle=Nr;this.getAccDescription=Rr;this.setAccDescription=Lr;this.clear()}static{o(this,"ArchitectureDB")}setDiagramId(e){this.diagramId=e}getDiagramId(){return this.diagramId}clear(){this.nodes={},this.groups={},this.edges=[],this.registeredIds={},this.dataStructures=void 0,this.elements={},this.diagramId="",wr()}addService({id:e,icon:r,in:i,title:n,iconText:a}){if(this.registeredIds[e]!==void 0)throw new Error(`The service id [${e}] is already in use by another ${this.registeredIds[e]}`);if(i!==void 0){if(e===i)throw new Error(`The service [${e}] cannot be placed within itself`);if(this.registeredIds[i]===void 0)throw new Error(`The service [${e}]'s parent does not exist. Please make sure the parent is created before this service`);if(this.registeredIds[i]==="node")throw new Error(`The service [${e}]'s parent is not a group`)}this.registeredIds[e]="node",this.nodes[e]={id:e,type:"service",icon:r,iconText:a,title:n,edges:[],in:i}}getServices(){return Object.values(this.nodes).filter(BAe)}addJunction({id:e,in:r}){if(this.registeredIds[e]!==void 0)throw new Error(`The junction id [${e}] is already in use by another ${this.registeredIds[e]}`);if(r!==void 0){if(e===r)throw new Error(`The junction [${e}] cannot be placed within itself`);if(this.registeredIds[r]===void 0)throw new Error(`The junction [${e}]'s parent does not exist. Please make sure the parent is created before this junction`);if(this.registeredIds[r]==="node")throw new Error(`The junction [${e}]'s parent is not a group`)}this.registeredIds[e]="node",this.nodes[e]={id:e,type:"junction",edges:[],in:r}}getJunctions(){return Object.values(this.nodes).filter(FAe)}getNodes(){return Object.values(this.nodes)}getNode(e){return this.nodes[e]??null}addGroup({id:e,icon:r,in:i,title:n}){if(this.registeredIds?.[e]!==void 0)throw new Error(`The group id [${e}] is already in use by another ${this.registeredIds[e]}`);if(i!==void 0){if(e===i)throw new Error(`The group [${e}] cannot be placed within itself`);if(this.registeredIds?.[i]===void 0)throw new Error(`The group [${e}]'s parent does not exist. Please make sure the parent is created before this group`);if(this.registeredIds?.[i]==="node")throw new Error(`The group [${e}]'s parent is not a group`)}this.registeredIds[e]="group",this.groups[e]={id:e,icon:r,title:n,in:i}}getGroups(){return Object.values(this.groups)}addEdge({lhsId:e,rhsId:r,lhsDir:i,rhsDir:n,lhsInto:a,rhsInto:s,lhsGroup:l,rhsGroup:u,title:h}){if(!$H(i))throw new Error(`Invalid direction given for left hand side of edge ${e}--${r}. Expected (L,R,T,B) got ${String(i)}`);if(!$H(n))throw new Error(`Invalid direction given for right hand side of edge ${e}--${r}. Expected (L,R,T,B) got ${String(n)}`);if(this.nodes[e]===void 0&&this.groups[e]===void 0)throw new Error(`The left-hand id [${e}] does not yet exist. Please create the service/group before declaring an edge to it.`);if(this.nodes[r]===void 0&&this.groups[r]===void 0)throw new Error(`The right-hand id [${r}] does not yet exist. Please create the service/group before declaring an edge to it.`);let f=this.nodes[e].in,d=this.nodes[r].in;if(l&&f&&d&&f==d)throw new Error(`The left-hand id [${e}] is modified to traverse the group boundary, but the edge does not pass through two groups.`);if(u&&f&&d&&f==d)throw new Error(`The right-hand id [${r}] is modified to traverse the group boundary, but the edge does not pass through two groups.`);let p={lhsId:e,lhsDir:i,lhsInto:a,lhsGroup:l,rhsId:r,rhsDir:n,rhsInto:s,rhsGroup:u,title:h};this.edges.push(p),this.nodes[e]&&this.nodes[r]&&(this.nodes[e].edges.push(this.edges[this.edges.length-1]),this.nodes[r].edges.push(this.edges[this.edges.length-1]))}getEdges(){return this.edges}getDataStructures(){if(this.dataStructures===void 0){let e={},r=Object.entries(this.nodes).reduce((u,[h,f])=>(u[h]=f.edges.reduce((d,p)=>{let m=this.getNode(p.lhsId)?.in,g=this.getNode(p.rhsId)?.in;if(m&&g&&m!==g){let y=PAe(p.lhsDir,p.rhsDir);y!=="bend"&&(e[m]??={},e[m][g]=y,e[g]??={},e[g][m]=y)}if(p.lhsId===h){let y=YC(p.lhsDir,p.rhsDir);y&&(d[y]=p.rhsId)}else{let y=YC(p.rhsDir,p.lhsDir);y&&(d[y]=p.lhsId)}return d},{}),u),{}),i=Object.keys(r)[0],n={[i]:1},a=Object.keys(r).reduce((u,h)=>h===i?u:{...u,[h]:1},{}),s=o(u=>{let h={[u]:[0,0]},f=[u];for(;f.length>0;){let d=f.shift();if(d){n[d]=1,delete a[d];let p=r[d],[m,g]=h[d];Object.entries(p).forEach(([y,v])=>{n[v]||(h[v]=MAe([m,g],y),f.push(v))})}}return h},"BFS"),l=[s(i)];for(;Object.keys(a).length>0;)l.push(s(Object.keys(a)[0]));this.dataStructures={adjList:r,spatialMaps:l,groupAlignments:e}}return this.dataStructures}setElementForId(e,r){this.elements[e]=r}getElementById(e){return this.elements[e]}getConfig(){return fi({...zgt,...Lt().architecture})}getConfigField(e){return this.getConfig()[e]}}});var Ggt,GH,$Ae=P(()=>{"use strict";sh();bt();vf();zH();Ggt=o((t,e)=>{Ss(t,e),t.groups.map(r=>e.addGroup(r)),t.services.map(r=>e.addService({...r,type:"service"})),t.junctions.map(r=>e.addJunction({...r,type:"junction"})),t.edges.map(r=>e.addEdge(r))},"populateDb"),GH={parser:{yy:void 0},parse:o(async t=>{let e=await ba("architecture",t);Q.debug(e);let r=GH.parser?.yy;if(!(r instanceof dx))throw new Error("parser.parser?.yy was not a ArchitectureDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.");Ggt(e,r)},"parse")}});var Vgt,zAe,GAe=P(()=>{"use strict";Vgt=o(t=>` + .edge { + stroke-width: ${t.archEdgeWidth}; + stroke: ${t.archEdgeColor}; + fill: none; + } + + .arrow { + fill: ${t.archEdgeArrowColor}; + } + + .node-bkg { + fill: none; + stroke: ${t.archGroupBorderColor}; + stroke-width: ${t.archGroupBorderWidth}; + stroke-dasharray: 8; + } + .node-icon-text { + display: flex; + align-items: center; + } + + .node-icon-text > div { + color: #fff; + margin: 1px; + height: fit-content; + text-align: center; + overflow: hidden; + display: -webkit-box; + -webkit-box-orient: vertical; + } +`,"getStyles"),zAe=Vgt});var qH=ar((jC,VH)=>{"use strict";o((function(e,r){typeof jC=="object"&&typeof VH=="object"?VH.exports=r():typeof define=="function"&&define.amd?define([],r):typeof jC=="object"?jC.layoutBase=r():e.layoutBase=r()}),"webpackUniversalModuleDefinition")(jC,function(){return(function(t){var e={};function r(i){if(e[i])return e[i].exports;var n=e[i]={i,l:!1,exports:{}};return t[i].call(n.exports,n,n.exports,r),n.l=!0,n.exports}return o(r,"__webpack_require__"),r.m=t,r.c=e,r.i=function(i){return i},r.d=function(i,n,a){r.o(i,n)||Object.defineProperty(i,n,{configurable:!1,enumerable:!0,get:a})},r.n=function(i){var n=i&&i.__esModule?o(function(){return i.default},"getDefault"):o(function(){return i},"getModuleExports");return r.d(n,"a",n),n},r.o=function(i,n){return Object.prototype.hasOwnProperty.call(i,n)},r.p="",r(r.s=28)})([(function(t,e,r){"use strict";function i(){}o(i,"LayoutConstants"),i.QUALITY=1,i.DEFAULT_CREATE_BENDS_AS_NEEDED=!1,i.DEFAULT_INCREMENTAL=!1,i.DEFAULT_ANIMATION_ON_LAYOUT=!0,i.DEFAULT_ANIMATION_DURING_LAYOUT=!1,i.DEFAULT_ANIMATION_PERIOD=50,i.DEFAULT_UNIFORM_LEAF_NODE_SIZES=!1,i.DEFAULT_GRAPH_MARGIN=15,i.NODE_DIMENSIONS_INCLUDE_LABELS=!1,i.SIMPLE_NODE_SIZE=40,i.SIMPLE_NODE_HALF_SIZE=i.SIMPLE_NODE_SIZE/2,i.EMPTY_COMPOUND_NODE_SIZE=40,i.MIN_EDGE_LENGTH=1,i.WORLD_BOUNDARY=1e6,i.INITIAL_WORLD_BOUNDARY=i.WORLD_BOUNDARY/1e3,i.WORLD_CENTER_X=1200,i.WORLD_CENTER_Y=900,t.exports=i}),(function(t,e,r){"use strict";var i=r(2),n=r(8),a=r(9);function s(u,h,f){i.call(this,f),this.isOverlapingSourceAndTarget=!1,this.vGraphObject=f,this.bendpoints=[],this.source=u,this.target=h}o(s,"LEdge"),s.prototype=Object.create(i.prototype);for(var l in i)s[l]=i[l];s.prototype.getSource=function(){return this.source},s.prototype.getTarget=function(){return this.target},s.prototype.isInterGraph=function(){return this.isInterGraph},s.prototype.getLength=function(){return this.length},s.prototype.isOverlapingSourceAndTarget=function(){return this.isOverlapingSourceAndTarget},s.prototype.getBendpoints=function(){return this.bendpoints},s.prototype.getLca=function(){return this.lca},s.prototype.getSourceInLca=function(){return this.sourceInLca},s.prototype.getTargetInLca=function(){return this.targetInLca},s.prototype.getOtherEnd=function(u){if(this.source===u)return this.target;if(this.target===u)return this.source;throw"Node is not incident with this edge"},s.prototype.getOtherEndInGraph=function(u,h){for(var f=this.getOtherEnd(u),d=h.getGraphManager().getRoot();;){if(f.getOwner()==h)return f;if(f.getOwner()==d)break;f=f.getOwner().getParent()}return null},s.prototype.updateLength=function(){var u=new Array(4);this.isOverlapingSourceAndTarget=n.getIntersection(this.target.getRect(),this.source.getRect(),u),this.isOverlapingSourceAndTarget||(this.lengthX=u[0]-u[2],this.lengthY=u[1]-u[3],Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY))},s.prototype.updateLengthSimple=function(){this.lengthX=this.target.getCenterX()-this.source.getCenterX(),this.lengthY=this.target.getCenterY()-this.source.getCenterY(),Math.abs(this.lengthX)<1&&(this.lengthX=a.sign(this.lengthX)),Math.abs(this.lengthY)<1&&(this.lengthY=a.sign(this.lengthY)),this.length=Math.sqrt(this.lengthX*this.lengthX+this.lengthY*this.lengthY)},t.exports=s}),(function(t,e,r){"use strict";function i(n){this.vGraphObject=n}o(i,"LGraphObject"),t.exports=i}),(function(t,e,r){"use strict";var i=r(2),n=r(10),a=r(13),s=r(0),l=r(16),u=r(5);function h(d,p,m,g){m==null&&g==null&&(g=p),i.call(this,g),d.graphManager!=null&&(d=d.graphManager),this.estimatedSize=n.MIN_VALUE,this.inclusionTreeDepth=n.MAX_VALUE,this.vGraphObject=g,this.edges=[],this.graphManager=d,m!=null&&p!=null?this.rect=new a(p.x,p.y,m.width,m.height):this.rect=new a}o(h,"LNode"),h.prototype=Object.create(i.prototype);for(var f in i)h[f]=i[f];h.prototype.getEdges=function(){return this.edges},h.prototype.getChild=function(){return this.child},h.prototype.getOwner=function(){return this.owner},h.prototype.getWidth=function(){return this.rect.width},h.prototype.setWidth=function(d){this.rect.width=d},h.prototype.getHeight=function(){return this.rect.height},h.prototype.setHeight=function(d){this.rect.height=d},h.prototype.getCenterX=function(){return this.rect.x+this.rect.width/2},h.prototype.getCenterY=function(){return this.rect.y+this.rect.height/2},h.prototype.getCenter=function(){return new u(this.rect.x+this.rect.width/2,this.rect.y+this.rect.height/2)},h.prototype.getLocation=function(){return new u(this.rect.x,this.rect.y)},h.prototype.getRect=function(){return this.rect},h.prototype.getDiagonal=function(){return Math.sqrt(this.rect.width*this.rect.width+this.rect.height*this.rect.height)},h.prototype.getHalfTheDiagonal=function(){return Math.sqrt(this.rect.height*this.rect.height+this.rect.width*this.rect.width)/2},h.prototype.setRect=function(d,p){this.rect.x=d.x,this.rect.y=d.y,this.rect.width=p.width,this.rect.height=p.height},h.prototype.setCenter=function(d,p){this.rect.x=d-this.rect.width/2,this.rect.y=p-this.rect.height/2},h.prototype.setLocation=function(d,p){this.rect.x=d,this.rect.y=p},h.prototype.moveBy=function(d,p){this.rect.x+=d,this.rect.y+=p},h.prototype.getEdgeListToNode=function(d){var p=[],m,g=this;return g.edges.forEach(function(y){if(y.target==d){if(y.source!=g)throw"Incorrect edge source!";p.push(y)}}),p},h.prototype.getEdgesBetween=function(d){var p=[],m,g=this;return g.edges.forEach(function(y){if(!(y.source==g||y.target==g))throw"Incorrect edge source and/or target";(y.target==d||y.source==d)&&p.push(y)}),p},h.prototype.getNeighborsList=function(){var d=new Set,p=this;return p.edges.forEach(function(m){if(m.source==p)d.add(m.target);else{if(m.target!=p)throw"Incorrect incidency!";d.add(m.source)}}),d},h.prototype.withChildren=function(){var d=new Set,p,m;if(d.add(this),this.child!=null)for(var g=this.child.getNodes(),y=0;yp?(this.rect.x-=(this.labelWidth-p)/2,this.setWidth(this.labelWidth)):this.labelPosHorizontal=="right"&&this.setWidth(p+this.labelWidth)),this.labelHeight&&(this.labelPosVertical=="top"?(this.rect.y-=this.labelHeight,this.setHeight(m+this.labelHeight)):this.labelPosVertical=="center"&&this.labelHeight>m?(this.rect.y-=(this.labelHeight-m)/2,this.setHeight(this.labelHeight)):this.labelPosVertical=="bottom"&&this.setHeight(m+this.labelHeight))}}},h.prototype.getInclusionTreeDepth=function(){if(this.inclusionTreeDepth==n.MAX_VALUE)throw"assert failed";return this.inclusionTreeDepth},h.prototype.transform=function(d){var p=this.rect.x;p>s.WORLD_BOUNDARY?p=s.WORLD_BOUNDARY:p<-s.WORLD_BOUNDARY&&(p=-s.WORLD_BOUNDARY);var m=this.rect.y;m>s.WORLD_BOUNDARY?m=s.WORLD_BOUNDARY:m<-s.WORLD_BOUNDARY&&(m=-s.WORLD_BOUNDARY);var g=new u(p,m),y=d.inverseTransformPoint(g);this.setLocation(y.x,y.y)},h.prototype.getLeft=function(){return this.rect.x},h.prototype.getRight=function(){return this.rect.x+this.rect.width},h.prototype.getTop=function(){return this.rect.y},h.prototype.getBottom=function(){return this.rect.y+this.rect.height},h.prototype.getParent=function(){return this.owner==null?null:this.owner.getParent()},t.exports=h}),(function(t,e,r){"use strict";var i=r(0);function n(){}o(n,"FDLayoutConstants");for(var a in i)n[a]=i[a];n.MAX_ITERATIONS=2500,n.DEFAULT_EDGE_LENGTH=50,n.DEFAULT_SPRING_STRENGTH=.45,n.DEFAULT_REPULSION_STRENGTH=4500,n.DEFAULT_GRAVITY_STRENGTH=.4,n.DEFAULT_COMPOUND_GRAVITY_STRENGTH=1,n.DEFAULT_GRAVITY_RANGE_FACTOR=3.8,n.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=1.5,n.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION=!0,n.DEFAULT_USE_SMART_REPULSION_RANGE_CALCULATION=!0,n.DEFAULT_COOLING_FACTOR_INCREMENTAL=.3,n.COOLING_ADAPTATION_FACTOR=.33,n.ADAPTATION_LOWER_NODE_LIMIT=1e3,n.ADAPTATION_UPPER_NODE_LIMIT=5e3,n.MAX_NODE_DISPLACEMENT_INCREMENTAL=100,n.MAX_NODE_DISPLACEMENT=n.MAX_NODE_DISPLACEMENT_INCREMENTAL*3,n.MIN_REPULSION_DIST=n.DEFAULT_EDGE_LENGTH/10,n.CONVERGENCE_CHECK_PERIOD=100,n.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=.1,n.MIN_EDGE_LENGTH=1,n.GRID_CALCULATION_CHECK_PERIOD=10,t.exports=n}),(function(t,e,r){"use strict";function i(n,a){n==null&&a==null?(this.x=0,this.y=0):(this.x=n,this.y=a)}o(i,"PointD"),i.prototype.getX=function(){return this.x},i.prototype.getY=function(){return this.y},i.prototype.setX=function(n){this.x=n},i.prototype.setY=function(n){this.y=n},i.prototype.getDifference=function(n){return new DimensionD(this.x-n.x,this.y-n.y)},i.prototype.getCopy=function(){return new i(this.x,this.y)},i.prototype.translate=function(n){return this.x+=n.width,this.y+=n.height,this},t.exports=i}),(function(t,e,r){"use strict";var i=r(2),n=r(10),a=r(0),s=r(7),l=r(3),u=r(1),h=r(13),f=r(12),d=r(11);function p(g,y,v){i.call(this,v),this.estimatedSize=n.MIN_VALUE,this.margin=a.DEFAULT_GRAPH_MARGIN,this.edges=[],this.nodes=[],this.isConnected=!1,this.parent=g,y!=null&&y instanceof s?this.graphManager=y:y!=null&&y instanceof Layout&&(this.graphManager=y.graphManager)}o(p,"LGraph"),p.prototype=Object.create(i.prototype);for(var m in i)p[m]=i[m];p.prototype.getNodes=function(){return this.nodes},p.prototype.getEdges=function(){return this.edges},p.prototype.getGraphManager=function(){return this.graphManager},p.prototype.getParent=function(){return this.parent},p.prototype.getLeft=function(){return this.left},p.prototype.getRight=function(){return this.right},p.prototype.getTop=function(){return this.top},p.prototype.getBottom=function(){return this.bottom},p.prototype.isConnected=function(){return this.isConnected},p.prototype.add=function(g,y,v){if(y==null&&v==null){var x=g;if(this.graphManager==null)throw"Graph has no graph mgr!";if(this.getNodes().indexOf(x)>-1)throw"Node already in graph!";return x.owner=this,this.getNodes().push(x),x}else{var b=g;if(!(this.getNodes().indexOf(y)>-1&&this.getNodes().indexOf(v)>-1))throw"Source or target not in graph!";if(!(y.owner==v.owner&&y.owner==this))throw"Both owners must be this graph!";return y.owner!=v.owner?null:(b.source=y,b.target=v,b.isInterGraph=!1,this.getEdges().push(b),y.edges.push(b),v!=y&&v.edges.push(b),b)}},p.prototype.remove=function(g){var y=g;if(g instanceof l){if(y==null)throw"Node is null!";if(!(y.owner!=null&&y.owner==this))throw"Owner graph is invalid!";if(this.graphManager==null)throw"Owner graph manager is invalid!";for(var v=y.edges.slice(),x,b=v.length,T=0;T-1&&C>-1))throw"Source and/or target doesn't know this edge!";x.source.edges.splice(k,1),x.target!=x.source&&x.target.edges.splice(C,1);var w=x.source.owner.getEdges().indexOf(x);if(w==-1)throw"Not in owner's edge list!";x.source.owner.getEdges().splice(w,1)}},p.prototype.updateLeftTop=function(){for(var g=n.MAX_VALUE,y=n.MAX_VALUE,v,x,b,T=this.getNodes(),w=T.length,k=0;kv&&(g=v),y>x&&(y=x)}return g==n.MAX_VALUE?null:(T[0].getParent().paddingLeft!=null?b=T[0].getParent().paddingLeft:b=this.margin,this.left=y-b,this.top=g-b,new f(this.left,this.top))},p.prototype.updateBounds=function(g){for(var y=n.MAX_VALUE,v=-n.MAX_VALUE,x=n.MAX_VALUE,b=-n.MAX_VALUE,T,w,k,C,E,S=this.nodes,L=S.length,M=0;MT&&(y=T),vk&&(x=k),bT&&(y=T),vk&&(x=k),b=this.nodes.length){var L=0;v.forEach(function(M){M.owner==g&&L++}),L==this.nodes.length&&(this.isConnected=!0)}},t.exports=p}),(function(t,e,r){"use strict";var i,n=r(1);function a(s){i=r(6),this.layout=s,this.graphs=[],this.edges=[]}o(a,"LGraphManager"),a.prototype.addRoot=function(){var s=this.layout.newGraph(),l=this.layout.newNode(null),u=this.add(s,l);return this.setRootGraph(u),this.rootGraph},a.prototype.add=function(s,l,u,h,f){if(u==null&&h==null&&f==null){if(s==null)throw"Graph is null!";if(l==null)throw"Parent node is null!";if(this.graphs.indexOf(s)>-1)throw"Graph already in this graph mgr!";if(this.graphs.push(s),s.parent!=null)throw"Already has a parent!";if(l.child!=null)throw"Already has a child!";return s.parent=l,l.child=s,s}else{f=u,h=l,u=s;var d=h.getOwner(),p=f.getOwner();if(!(d!=null&&d.getGraphManager()==this))throw"Source not in this graph mgr!";if(!(p!=null&&p.getGraphManager()==this))throw"Target not in this graph mgr!";if(d==p)return u.isInterGraph=!1,d.add(u,h,f);if(u.isInterGraph=!0,u.source=h,u.target=f,this.edges.indexOf(u)>-1)throw"Edge already in inter-graph edge list!";if(this.edges.push(u),!(u.source!=null&&u.target!=null))throw"Edge source and/or target is null!";if(!(u.source.edges.indexOf(u)==-1&&u.target.edges.indexOf(u)==-1))throw"Edge already in source and/or target incidency list!";return u.source.edges.push(u),u.target.edges.push(u),u}},a.prototype.remove=function(s){if(s instanceof i){var l=s;if(l.getGraphManager()!=this)throw"Graph not in this graph mgr";if(!(l==this.rootGraph||l.parent!=null&&l.parent.graphManager==this))throw"Invalid parent node!";var u=[];u=u.concat(l.getEdges());for(var h,f=u.length,d=0;d=s.getRight()?l[0]+=Math.min(s.getX()-a.getX(),a.getRight()-s.getRight()):s.getX()<=a.getX()&&s.getRight()>=a.getRight()&&(l[0]+=Math.min(a.getX()-s.getX(),s.getRight()-a.getRight())),a.getY()<=s.getY()&&a.getBottom()>=s.getBottom()?l[1]+=Math.min(s.getY()-a.getY(),a.getBottom()-s.getBottom()):s.getY()<=a.getY()&&s.getBottom()>=a.getBottom()&&(l[1]+=Math.min(a.getY()-s.getY(),s.getBottom()-a.getBottom()));var f=Math.abs((s.getCenterY()-a.getCenterY())/(s.getCenterX()-a.getCenterX()));s.getCenterY()===a.getCenterY()&&s.getCenterX()===a.getCenterX()&&(f=1);var d=f*l[0],p=l[1]/f;l[0]d)return l[0]=u,l[1]=m,l[2]=f,l[3]=S,!1;if(hf)return l[0]=p,l[1]=h,l[2]=C,l[3]=d,!1;if(uf?(l[0]=y,l[1]=v,A=!0):(l[0]=g,l[1]=m,A=!0):D===R&&(u>f?(l[0]=p,l[1]=m,A=!0):(l[0]=x,l[1]=v,A=!0)),-N===R?f>u?(l[2]=E,l[3]=S,_=!0):(l[2]=C,l[3]=k,_=!0):N===R&&(f>u?(l[2]=w,l[3]=k,_=!0):(l[2]=L,l[3]=S,_=!0)),A&&_)return!1;if(u>f?h>d?(B=this.getCardinalDirection(D,R,4),O=this.getCardinalDirection(N,R,2)):(B=this.getCardinalDirection(-D,R,3),O=this.getCardinalDirection(-N,R,1)):h>d?(B=this.getCardinalDirection(-D,R,1),O=this.getCardinalDirection(-N,R,3)):(B=this.getCardinalDirection(D,R,2),O=this.getCardinalDirection(N,R,4)),!A)switch(B){case 1:z=m,$=u+-T/R,l[0]=$,l[1]=z;break;case 2:$=x,z=h+b*R,l[0]=$,l[1]=z;break;case 3:z=v,$=u+T/R,l[0]=$,l[1]=z;break;case 4:$=y,z=h+-b*R,l[0]=$,l[1]=z;break}if(!_)switch(O){case 1:V=k,F=f+-I/R,l[2]=F,l[3]=V;break;case 2:F=L,V=d+M*R,l[2]=F,l[3]=V;break;case 3:V=S,F=f+I/R,l[2]=F,l[3]=V;break;case 4:F=E,V=d+-M*R,l[2]=F,l[3]=V;break}}return!1},n.getCardinalDirection=function(a,s,l){return a>s?l:1+l%4},n.getIntersection=function(a,s,l,u){if(u==null)return this.getIntersection2(a,s,l);var h=a.x,f=a.y,d=s.x,p=s.y,m=l.x,g=l.y,y=u.x,v=u.y,x=void 0,b=void 0,T=void 0,w=void 0,k=void 0,C=void 0,E=void 0,S=void 0,L=void 0;return T=p-f,k=h-d,E=d*f-h*p,w=v-g,C=m-y,S=y*g-m*v,L=T*C-w*k,L===0?null:(x=(k*S-C*E)/L,b=(w*E-T*S)/L,new i(x,b))},n.angleOfVector=function(a,s,l,u){var h=void 0;return a!==l?(h=Math.atan((u-s)/(l-a)),l=0){var v=(-m+Math.sqrt(m*m-4*p*g))/(2*p),x=(-m-Math.sqrt(m*m-4*p*g))/(2*p),b=null;return v>=0&&v<=1?[v]:x>=0&&x<=1?[x]:b}else return null},n.HALF_PI=.5*Math.PI,n.ONE_AND_HALF_PI=1.5*Math.PI,n.TWO_PI=2*Math.PI,n.THREE_PI=3*Math.PI,t.exports=n}),(function(t,e,r){"use strict";function i(){}o(i,"IMath"),i.sign=function(n){return n>0?1:n<0?-1:0},i.floor=function(n){return n<0?Math.ceil(n):Math.floor(n)},i.ceil=function(n){return n<0?Math.floor(n):Math.ceil(n)},t.exports=i}),(function(t,e,r){"use strict";function i(){}o(i,"Integer"),i.MAX_VALUE=2147483647,i.MIN_VALUE=-2147483648,t.exports=i}),(function(t,e,r){"use strict";var i=(function(){function h(f,d){for(var p=0;p"u"?"undefined":i(a);return a==null||s!="object"&&s!="function"},t.exports=n}),(function(t,e,r){"use strict";function i(m){if(Array.isArray(m)){for(var g=0,y=Array(m.length);g0&&g;){for(T.push(k[0]);T.length>0&&g;){var C=T[0];T.splice(0,1),b.add(C);for(var E=C.getEdges(),x=0;x-1&&k.splice(I,1)}b=new Set,w=new Map}}return m},p.prototype.createDummyNodesForBendpoints=function(m){for(var g=[],y=m.source,v=this.graphManager.calcLowestCommonAncestor(m.source,m.target),x=0;x0){for(var v=this.edgeToDummyNodes.get(y),x=0;x=0&&g.splice(S,1);var L=w.getNeighborsList();L.forEach(function(A){if(y.indexOf(A)<0){var _=v.get(A),D=_-1;D==1&&C.push(A),v.set(A,D)}})}y=y.concat(C),(g.length==1||g.length==2)&&(x=!0,b=g[0])}return b},p.prototype.setGraphManager=function(m){this.graphManager=m},t.exports=p}),(function(t,e,r){"use strict";function i(){}o(i,"RandomSeed"),i.seed=1,i.x=0,i.nextDouble=function(){return i.x=Math.sin(i.seed++)*1e4,i.x-Math.floor(i.x)},t.exports=i}),(function(t,e,r){"use strict";var i=r(5);function n(a,s){this.lworldOrgX=0,this.lworldOrgY=0,this.ldeviceOrgX=0,this.ldeviceOrgY=0,this.lworldExtX=1,this.lworldExtY=1,this.ldeviceExtX=1,this.ldeviceExtY=1}o(n,"Transform"),n.prototype.getWorldOrgX=function(){return this.lworldOrgX},n.prototype.setWorldOrgX=function(a){this.lworldOrgX=a},n.prototype.getWorldOrgY=function(){return this.lworldOrgY},n.prototype.setWorldOrgY=function(a){this.lworldOrgY=a},n.prototype.getWorldExtX=function(){return this.lworldExtX},n.prototype.setWorldExtX=function(a){this.lworldExtX=a},n.prototype.getWorldExtY=function(){return this.lworldExtY},n.prototype.setWorldExtY=function(a){this.lworldExtY=a},n.prototype.getDeviceOrgX=function(){return this.ldeviceOrgX},n.prototype.setDeviceOrgX=function(a){this.ldeviceOrgX=a},n.prototype.getDeviceOrgY=function(){return this.ldeviceOrgY},n.prototype.setDeviceOrgY=function(a){this.ldeviceOrgY=a},n.prototype.getDeviceExtX=function(){return this.ldeviceExtX},n.prototype.setDeviceExtX=function(a){this.ldeviceExtX=a},n.prototype.getDeviceExtY=function(){return this.ldeviceExtY},n.prototype.setDeviceExtY=function(a){this.ldeviceExtY=a},n.prototype.transformX=function(a){var s=0,l=this.lworldExtX;return l!=0&&(s=this.ldeviceOrgX+(a-this.lworldOrgX)*this.ldeviceExtX/l),s},n.prototype.transformY=function(a){var s=0,l=this.lworldExtY;return l!=0&&(s=this.ldeviceOrgY+(a-this.lworldOrgY)*this.ldeviceExtY/l),s},n.prototype.inverseTransformX=function(a){var s=0,l=this.ldeviceExtX;return l!=0&&(s=this.lworldOrgX+(a-this.ldeviceOrgX)*this.lworldExtX/l),s},n.prototype.inverseTransformY=function(a){var s=0,l=this.ldeviceExtY;return l!=0&&(s=this.lworldOrgY+(a-this.ldeviceOrgY)*this.lworldExtY/l),s},n.prototype.inverseTransformPoint=function(a){var s=new i(this.inverseTransformX(a.x),this.inverseTransformY(a.y));return s},t.exports=n}),(function(t,e,r){"use strict";function i(d){if(Array.isArray(d)){for(var p=0,m=Array(d.length);pa.ADAPTATION_LOWER_NODE_LIMIT&&(this.coolingFactor=Math.max(this.coolingFactor*a.COOLING_ADAPTATION_FACTOR,this.coolingFactor-(d-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*this.coolingFactor*(1-a.COOLING_ADAPTATION_FACTOR))),this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT_INCREMENTAL):(d>a.ADAPTATION_LOWER_NODE_LIMIT?this.coolingFactor=Math.max(a.COOLING_ADAPTATION_FACTOR,1-(d-a.ADAPTATION_LOWER_NODE_LIMIT)/(a.ADAPTATION_UPPER_NODE_LIMIT-a.ADAPTATION_LOWER_NODE_LIMIT)*(1-a.COOLING_ADAPTATION_FACTOR)):this.coolingFactor=1,this.initialCoolingFactor=this.coolingFactor,this.maxNodeDisplacement=a.MAX_NODE_DISPLACEMENT),this.maxIterations=Math.max(this.getAllNodes().length*5,this.maxIterations),this.displacementThresholdPerNode=3*a.DEFAULT_EDGE_LENGTH/100,this.totalDisplacementThreshold=this.displacementThresholdPerNode*this.getAllNodes().length,this.repulsionRange=this.calcRepulsionRange()},h.prototype.calcSpringForces=function(){for(var d=this.getAllEdges(),p,m=0;m0&&arguments[0]!==void 0?arguments[0]:!0,p=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!1,m,g,y,v,x=this.getAllNodes(),b;if(this.useFRGridVariant)for(this.totalIterations%a.GRID_CALCULATION_CHECK_PERIOD==1&&d&&this.updateGrid(),b=new Set,m=0;mT||b>T)&&(d.gravitationForceX=-this.gravityConstant*y,d.gravitationForceY=-this.gravityConstant*v)):(T=p.getEstimatedSize()*this.compoundGravityRangeFactor,(x>T||b>T)&&(d.gravitationForceX=-this.gravityConstant*y*this.compoundGravityConstant,d.gravitationForceY=-this.gravityConstant*v*this.compoundGravityConstant))},h.prototype.isConverged=function(){var d,p=!1;return this.totalIterations>this.maxIterations/3&&(p=Math.abs(this.totalDisplacement-this.oldTotalDisplacement)<2),d=this.totalDisplacement=x.length||T>=x[0].length)){for(var w=0;wh},"_defaultCompareFunction")}]),l})();t.exports=s}),(function(t,e,r){"use strict";function i(){}o(i,"SVD"),i.svd=function(n){this.U=null,this.V=null,this.s=null,this.m=0,this.n=0,this.m=n.length,this.n=n[0].length;var a=Math.min(this.m,this.n);this.s=(function(It){for(var ot=[];It-- >0;)ot.push(0);return ot})(Math.min(this.m+1,this.n)),this.U=(function(It){var ot=o(function ct(Dt){if(Dt.length==0)return 0;for(var kt=[],yt=0;yt0;)ot.push(0);return ot})(this.n),l=(function(It){for(var ot=[];It-- >0;)ot.push(0);return ot})(this.m),u=!0,h=!0,f=Math.min(this.m-1,this.n),d=Math.max(0,Math.min(this.n-2,this.m)),p=0;p=0;R--)if(this.s[R]!==0){for(var B=R+1;B=0;X--){if((function(It,ot){return It&&ot})(X0;){var de=void 0,Ee=void 0;for(de=_-2;de>=-1&&de!==-1;de--)if(Math.abs(s[de])<=be+te*(Math.abs(this.s[de])+Math.abs(this.s[de+1]))){s[de]=0;break}if(de===_-2)Ee=4;else{var Ne=void 0;for(Ne=_-1;Ne>=de&&Ne!==de;Ne--){var we=(Ne!==_?Math.abs(s[Ne]):0)+(Ne!==de+1?Math.abs(s[Ne-1]):0);if(Math.abs(this.s[Ne])<=be+te*we){this.s[Ne]=0;break}}Ne===de?Ee=3:Ne===_-1?Ee=1:(Ee=2,de=Ne)}switch(de++,Ee){case 1:{var Te=s[_-2];s[_-2]=0;for(var De=_-2;De>=de;De--){var $e=i.hypot(this.s[De],Te),pe=this.s[De]/$e,Je=Te/$e;if(this.s[De]=$e,De!==de&&(Te=-Je*s[De-1],s[De-1]=pe*s[De-1]),h)for(var Ce=0;Ce=this.s[de+1]);){var ut=this.s[de];if(this.s[de]=this.s[de+1],this.s[de+1]=ut,h&&deMath.abs(a)?(s=a/n,s=Math.abs(n)*Math.sqrt(1+s*s)):a!=0?(s=n/a,s=Math.abs(a)*Math.sqrt(1+s*s)):s=0,s},t.exports=i}),(function(t,e,r){"use strict";var i=(function(){function s(l,u){for(var h=0;h2&&arguments[2]!==void 0?arguments[2]:1,f=arguments.length>3&&arguments[3]!==void 0?arguments[3]:-1,d=arguments.length>4&&arguments[4]!==void 0?arguments[4]:-1;n(this,s),this.sequence1=l,this.sequence2=u,this.match_score=h,this.mismatch_penalty=f,this.gap_penalty=d,this.iMax=l.length+1,this.jMax=u.length+1,this.grid=new Array(this.iMax);for(var p=0;p=0;l--){var u=this.listeners[l];u.event===a&&u.callback===s&&this.listeners.splice(l,1)}},n.emit=function(a,s){for(var l=0;l{"use strict";o((function(e,r){typeof XC=="object"&&typeof WH=="object"?WH.exports=r(qH()):typeof define=="function"&&define.amd?define(["layout-base"],r):typeof XC=="object"?XC.coseBase=r(qH()):e.coseBase=r(e.layoutBase)}),"webpackUniversalModuleDefinition")(XC,function(t){return(()=>{"use strict";var e={45:((a,s,l)=>{var u={};u.layoutBase=l(551),u.CoSEConstants=l(806),u.CoSEEdge=l(767),u.CoSEGraph=l(880),u.CoSEGraphManager=l(578),u.CoSELayout=l(765),u.CoSENode=l(991),u.ConstraintHandler=l(902),a.exports=u}),806:((a,s,l)=>{var u=l(551).FDLayoutConstants;function h(){}o(h,"CoSEConstants");for(var f in u)h[f]=u[f];h.DEFAULT_USE_MULTI_LEVEL_SCALING=!1,h.DEFAULT_RADIAL_SEPARATION=u.DEFAULT_EDGE_LENGTH,h.DEFAULT_COMPONENT_SEPERATION=60,h.TILE=!0,h.TILING_PADDING_VERTICAL=10,h.TILING_PADDING_HORIZONTAL=10,h.TRANSFORM_ON_CONSTRAINT_HANDLING=!0,h.ENFORCE_CONSTRAINTS=!0,h.APPLY_LAYOUT=!0,h.RELAX_MOVEMENT_ON_CONSTRAINTS=!0,h.TREE_REDUCTION_ON_INCREMENTAL=!0,h.PURE_INCREMENTAL=h.DEFAULT_INCREMENTAL,a.exports=h}),767:((a,s,l)=>{var u=l(551).FDLayoutEdge;function h(d,p,m){u.call(this,d,p,m)}o(h,"CoSEEdge"),h.prototype=Object.create(u.prototype);for(var f in u)h[f]=u[f];a.exports=h}),880:((a,s,l)=>{var u=l(551).LGraph;function h(d,p,m){u.call(this,d,p,m)}o(h,"CoSEGraph"),h.prototype=Object.create(u.prototype);for(var f in u)h[f]=u[f];a.exports=h}),578:((a,s,l)=>{var u=l(551).LGraphManager;function h(d){u.call(this,d)}o(h,"CoSEGraphManager"),h.prototype=Object.create(u.prototype);for(var f in u)h[f]=u[f];a.exports=h}),765:((a,s,l)=>{var u=l(551).FDLayout,h=l(578),f=l(880),d=l(991),p=l(767),m=l(806),g=l(902),y=l(551).FDLayoutConstants,v=l(551).LayoutConstants,x=l(551).Point,b=l(551).PointD,T=l(551).DimensionD,w=l(551).Layout,k=l(551).Integer,C=l(551).IGeometry,E=l(551).LGraph,S=l(551).Transform,L=l(551).LinkedList;function M(){u.call(this),this.toBeTiled={},this.constraints={}}o(M,"CoSELayout"),M.prototype=Object.create(u.prototype);for(var I in u)M[I]=u[I];M.prototype.newGraphManager=function(){var A=new h(this);return this.graphManager=A,A},M.prototype.newGraph=function(A){return new f(null,this.graphManager,A)},M.prototype.newNode=function(A){return new d(this.graphManager,A)},M.prototype.newEdge=function(A){return new p(null,null,A)},M.prototype.initParameters=function(){u.prototype.initParameters.call(this,arguments),this.isSubLayout||(m.DEFAULT_EDGE_LENGTH<10?this.idealEdgeLength=10:this.idealEdgeLength=m.DEFAULT_EDGE_LENGTH,this.useSmartIdealEdgeLengthCalculation=m.DEFAULT_USE_SMART_IDEAL_EDGE_LENGTH_CALCULATION,this.gravityConstant=y.DEFAULT_GRAVITY_STRENGTH,this.compoundGravityConstant=y.DEFAULT_COMPOUND_GRAVITY_STRENGTH,this.gravityRangeFactor=y.DEFAULT_GRAVITY_RANGE_FACTOR,this.compoundGravityRangeFactor=y.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR,this.prunedNodesAll=[],this.growTreeIterations=0,this.afterGrowthIterations=0,this.isTreeGrowing=!1,this.isGrowthFinished=!1)},M.prototype.initSpringEmbedder=function(){u.prototype.initSpringEmbedder.call(this),this.coolingCycle=0,this.maxCoolingCycle=this.maxIterations/y.CONVERGENCE_CHECK_PERIOD,this.finalTemperature=.04,this.coolingAdjuster=1},M.prototype.layout=function(){var A=v.DEFAULT_CREATE_BENDS_AS_NEEDED;return A&&(this.createBendpoints(),this.graphManager.resetAllEdges()),this.level=0,this.classicLayout()},M.prototype.classicLayout=function(){if(this.nodesWithGravity=this.calculateNodesToApplyGravitationTo(),this.graphManager.setAllNodesToApplyGravitation(this.nodesWithGravity),this.calcNoOfChildrenForAllNodes(),this.graphManager.calcLowestCommonAncestors(),this.graphManager.calcInclusionTreeDepths(),this.graphManager.getRoot().calcEstimatedSize(),this.calcIdealEdgeLengths(),this.incremental){if(m.TREE_REDUCTION_ON_INCREMENTAL){this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var _=new Set(this.getAllNodes()),D=this.nodesWithGravity.filter(function(B){return _.has(B)});this.graphManager.setAllNodesToApplyGravitation(D)}}else{var A=this.getFlatForest();if(A.length>0)this.positionNodesRadially(A);else{this.reduceTrees(),this.graphManager.resetAllNodesToApplyGravitation();var _=new Set(this.getAllNodes()),D=this.nodesWithGravity.filter(function(N){return _.has(N)});this.graphManager.setAllNodesToApplyGravitation(D),this.positionNodesRandomly()}}return Object.keys(this.constraints).length>0&&(g.handleConstraints(this),this.initConstraintVariables()),this.initSpringEmbedder(),m.APPLY_LAYOUT&&this.runSpringEmbedder(),!0},M.prototype.tick=function(){if(this.totalIterations++,this.totalIterations===this.maxIterations&&!this.isTreeGrowing&&!this.isGrowthFinished)if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;if(this.totalIterations%y.CONVERGENCE_CHECK_PERIOD==0&&!this.isTreeGrowing&&!this.isGrowthFinished){if(this.isConverged())if(this.prunedNodesAll.length>0)this.isTreeGrowing=!0;else return!0;this.coolingCycle++,this.layoutQuality==0?this.coolingAdjuster=this.coolingCycle:this.layoutQuality==1&&(this.coolingAdjuster=this.coolingCycle/3),this.coolingFactor=Math.max(this.initialCoolingFactor-Math.pow(this.coolingCycle,Math.log(100*(this.initialCoolingFactor-this.finalTemperature))/Math.log(this.maxCoolingCycle))/100*this.coolingAdjuster,this.finalTemperature),this.animationPeriod=Math.ceil(this.initialAnimationPeriod*Math.sqrt(this.coolingFactor))}if(this.isTreeGrowing){if(this.growTreeIterations%10==0)if(this.prunedNodesAll.length>0){this.graphManager.updateBounds(),this.updateGrid(),this.growTree(this.prunedNodesAll),this.graphManager.resetAllNodesToApplyGravitation();var A=new Set(this.getAllNodes()),_=this.nodesWithGravity.filter(function(R){return A.has(R)});this.graphManager.setAllNodesToApplyGravitation(_),this.graphManager.updateBounds(),this.updateGrid(),m.PURE_INCREMENTAL?this.coolingFactor=y.DEFAULT_COOLING_FACTOR_INCREMENTAL/2:this.coolingFactor=y.DEFAULT_COOLING_FACTOR_INCREMENTAL}else this.isTreeGrowing=!1,this.isGrowthFinished=!0;this.growTreeIterations++}if(this.isGrowthFinished){if(this.isConverged())return!0;this.afterGrowthIterations%10==0&&(this.graphManager.updateBounds(),this.updateGrid()),m.PURE_INCREMENTAL?this.coolingFactor=y.DEFAULT_COOLING_FACTOR_INCREMENTAL/2*((100-this.afterGrowthIterations)/100):this.coolingFactor=y.DEFAULT_COOLING_FACTOR_INCREMENTAL*((100-this.afterGrowthIterations)/100),this.afterGrowthIterations++}var D=!this.isTreeGrowing&&!this.isGrowthFinished,N=this.growTreeIterations%10==1&&this.isTreeGrowing||this.afterGrowthIterations%10==1&&this.isGrowthFinished;return this.totalDisplacement=0,this.graphManager.updateBounds(),this.calcSpringForces(),this.calcRepulsionForces(D,N),this.calcGravitationalForces(),this.moveNodes(),this.animate(),!1},M.prototype.getPositionsData=function(){for(var A=this.graphManager.getAllNodes(),_={},D=0;D0&&this.updateDisplacements();for(var D=0;D0&&(N.fixedNodeWeight=B)}}if(this.constraints.relativePlacementConstraint){var O=new Map,$=new Map;if(this.dummyToNodeForVerticalAlignment=new Map,this.dummyToNodeForHorizontalAlignment=new Map,this.fixedNodesOnHorizontal=new Set,this.fixedNodesOnVertical=new Set,this.fixedNodeSet.forEach(function(Y){A.fixedNodesOnHorizontal.add(Y),A.fixedNodesOnVertical.add(Y)}),this.constraints.alignmentConstraint){if(this.constraints.alignmentConstraint.vertical)for(var z=this.constraints.alignmentConstraint.vertical,D=0;D=2*Y.length/3;ee--)ae=Math.floor(Math.random()*(ee+1)),J=Y[ee],Y[ee]=Y[ae],Y[ae]=J;return Y},this.nodesInRelativeHorizontal=[],this.nodesInRelativeVertical=[],this.nodeToRelativeConstraintMapHorizontal=new Map,this.nodeToRelativeConstraintMapVertical=new Map,this.nodeToTempPositionMapHorizontal=new Map,this.nodeToTempPositionMapVertical=new Map,this.constraints.relativePlacementConstraint.forEach(function(Y){if(Y.left){var ae=O.has(Y.left)?O.get(Y.left):Y.left,J=O.has(Y.right)?O.get(Y.right):Y.right;A.nodesInRelativeHorizontal.includes(ae)||(A.nodesInRelativeHorizontal.push(ae),A.nodeToRelativeConstraintMapHorizontal.set(ae,[]),A.dummyToNodeForVerticalAlignment.has(ae)?A.nodeToTempPositionMapHorizontal.set(ae,A.idToNodeMap.get(A.dummyToNodeForVerticalAlignment.get(ae)[0]).getCenterX()):A.nodeToTempPositionMapHorizontal.set(ae,A.idToNodeMap.get(ae).getCenterX())),A.nodesInRelativeHorizontal.includes(J)||(A.nodesInRelativeHorizontal.push(J),A.nodeToRelativeConstraintMapHorizontal.set(J,[]),A.dummyToNodeForVerticalAlignment.has(J)?A.nodeToTempPositionMapHorizontal.set(J,A.idToNodeMap.get(A.dummyToNodeForVerticalAlignment.get(J)[0]).getCenterX()):A.nodeToTempPositionMapHorizontal.set(J,A.idToNodeMap.get(J).getCenterX())),A.nodeToRelativeConstraintMapHorizontal.get(ae).push({right:J,gap:Y.gap}),A.nodeToRelativeConstraintMapHorizontal.get(J).push({left:ae,gap:Y.gap})}else{var ee=$.has(Y.top)?$.get(Y.top):Y.top,re=$.has(Y.bottom)?$.get(Y.bottom):Y.bottom;A.nodesInRelativeVertical.includes(ee)||(A.nodesInRelativeVertical.push(ee),A.nodeToRelativeConstraintMapVertical.set(ee,[]),A.dummyToNodeForHorizontalAlignment.has(ee)?A.nodeToTempPositionMapVertical.set(ee,A.idToNodeMap.get(A.dummyToNodeForHorizontalAlignment.get(ee)[0]).getCenterY()):A.nodeToTempPositionMapVertical.set(ee,A.idToNodeMap.get(ee).getCenterY())),A.nodesInRelativeVertical.includes(re)||(A.nodesInRelativeVertical.push(re),A.nodeToRelativeConstraintMapVertical.set(re,[]),A.dummyToNodeForHorizontalAlignment.has(re)?A.nodeToTempPositionMapVertical.set(re,A.idToNodeMap.get(A.dummyToNodeForHorizontalAlignment.get(re)[0]).getCenterY()):A.nodeToTempPositionMapVertical.set(re,A.idToNodeMap.get(re).getCenterY())),A.nodeToRelativeConstraintMapVertical.get(ee).push({bottom:re,gap:Y.gap}),A.nodeToRelativeConstraintMapVertical.get(re).push({top:ee,gap:Y.gap})}});else{var V=new Map,H=new Map;this.constraints.relativePlacementConstraint.forEach(function(Y){if(Y.left){var ae=O.has(Y.left)?O.get(Y.left):Y.left,J=O.has(Y.right)?O.get(Y.right):Y.right;V.has(ae)?V.get(ae).push(J):V.set(ae,[J]),V.has(J)?V.get(J).push(ae):V.set(J,[ae])}else{var ee=$.has(Y.top)?$.get(Y.top):Y.top,re=$.has(Y.bottom)?$.get(Y.bottom):Y.bottom;H.has(ee)?H.get(ee).push(re):H.set(ee,[re]),H.has(re)?H.get(re).push(ee):H.set(re,[ee])}});var X=o(function(ae,J){var ee=[],re=[],te=new L,be=new Set,de=0;return ae.forEach(function(Ee,Ne){if(!be.has(Ne)){ee[de]=[],re[de]=!1;var we=Ne;for(te.push(we),be.add(we),ee[de].push(we);te.length!=0;){we=te.shift(),J.has(we)&&(re[de]=!0);var Te=ae.get(we);Te.forEach(function(De){be.has(De)||(te.push(De),be.add(De),ee[de].push(De))})}de++}}),{components:ee,isFixed:re}},"constructComponents"),W=X(V,A.fixedNodesOnHorizontal);this.componentsOnHorizontal=W.components,this.fixedComponentsOnHorizontal=W.isFixed;var Z=X(H,A.fixedNodesOnVertical);this.componentsOnVertical=Z.components,this.fixedComponentsOnVertical=Z.isFixed}}},M.prototype.updateDisplacements=function(){var A=this;if(this.constraints.fixedNodeConstraint&&this.constraints.fixedNodeConstraint.forEach(function(Z){var Y=A.idToNodeMap.get(Z.nodeId);Y.displacementX=0,Y.displacementY=0}),this.constraints.alignmentConstraint){if(this.constraints.alignmentConstraint.vertical)for(var _=this.constraints.alignmentConstraint.vertical,D=0;D<_.length;D++){for(var N=0,R=0;R<_[D].length;R++){if(this.fixedNodeSet.has(_[D][R])){N=0;break}N+=this.idToNodeMap.get(_[D][R]).displacementX}for(var B=N/_[D].length,R=0;R<_[D].length;R++)this.idToNodeMap.get(_[D][R]).displacementX=B}if(this.constraints.alignmentConstraint.horizontal)for(var O=this.constraints.alignmentConstraint.horizontal,D=0;D1){var $;for($=0;$N&&(N=Math.floor(O.y)),B=Math.floor(O.x+m.DEFAULT_COMPONENT_SEPERATION)}this.transform(new b(v.WORLD_CENTER_X-O.x/2,v.WORLD_CENTER_Y-O.y/2))},M.radialLayout=function(A,_,D){var N=Math.max(this.maxDiagonalInTree(A),m.DEFAULT_RADIAL_SEPARATION);M.branchRadialLayout(_,null,0,359,0,N);var R=E.calculateBounds(A),B=new S;B.setDeviceOrgX(R.getMinX()),B.setDeviceOrgY(R.getMinY()),B.setWorldOrgX(D.x),B.setWorldOrgY(D.y);for(var O=0;O1;){var ee=J[0];J.splice(0,1);var re=X.indexOf(ee);re>=0&&X.splice(re,1),Y--,W--}_!=null?ae=(X.indexOf(J[0])+1)%Y:ae=0;for(var te=Math.abs(N-D)/W,be=ae;Z!=W;be=++be%Y){var de=X[be].getOtherEnd(A);if(de!=_){var Ee=(D+Z*te)%360,Ne=(Ee+te)%360;M.branchRadialLayout(de,A,Ee,Ne,R+B,B),Z++}}},M.maxDiagonalInTree=function(A){for(var _=k.MIN_VALUE,D=0;D_&&(_=R)}return _},M.prototype.calcRepulsionRange=function(){return 2*(this.level+1)*this.idealEdgeLength},M.prototype.groupZeroDegreeMembers=function(){var A=this,_={};this.memberGroups={},this.idToDummyNode={};for(var D=[],N=this.graphManager.getAllNodes(),R=0;R"u"&&(_[$]=[]),_[$]=_[$].concat(B)}Object.keys(_).forEach(function(z){if(_[z].length>1){var F="DummyCompound_"+z;A.memberGroups[F]=_[z];var V=_[z][0].getParent(),H=new d(A.graphManager);H.id=F,H.paddingLeft=V.paddingLeft||0,H.paddingRight=V.paddingRight||0,H.paddingBottom=V.paddingBottom||0,H.paddingTop=V.paddingTop||0,A.idToDummyNode[F]=H;var X=A.getGraphManager().add(A.newGraph(),H),W=V.getChild();W.add(H);for(var Z=0;Z<_[z].length;Z++){var Y=_[z][Z];W.remove(Y),X.add(Y)}}})},M.prototype.clearCompounds=function(){var A={},_={};this.performDFSOnCompounds();for(var D=0;DR?(N.rect.x-=(N.labelWidth-R)/2,N.setWidth(N.labelWidth),N.labelMarginLeft=(N.labelWidth-R)/2):N.labelPosHorizontal=="right"&&N.setWidth(R+N.labelWidth)),N.labelHeight&&(N.labelPosVertical=="top"?(N.rect.y-=N.labelHeight,N.setHeight(B+N.labelHeight),N.labelMarginTop=N.labelHeight):N.labelPosVertical=="center"&&N.labelHeight>B?(N.rect.y-=(N.labelHeight-B)/2,N.setHeight(N.labelHeight),N.labelMarginTop=(N.labelHeight-B)/2):N.labelPosVertical=="bottom"&&N.setHeight(B+N.labelHeight))}})},M.prototype.repopulateCompounds=function(){for(var A=this.compoundOrder.length-1;A>=0;A--){var _=this.compoundOrder[A],D=_.id,N=_.paddingLeft,R=_.paddingTop,B=_.labelMarginLeft,O=_.labelMarginTop;this.adjustLocations(this.tiledMemberPack[D],_.rect.x,_.rect.y,N,R,B,O)}},M.prototype.repopulateZeroDegreeMembers=function(){var A=this,_=this.tiledZeroDegreePack;Object.keys(_).forEach(function(D){var N=A.idToDummyNode[D],R=N.paddingLeft,B=N.paddingTop,O=N.labelMarginLeft,$=N.labelMarginTop;A.adjustLocations(_[D],N.rect.x,N.rect.y,R,B,O,$)})},M.prototype.getToBeTiled=function(A){var _=A.id;if(this.toBeTiled[_]!=null)return this.toBeTiled[_];var D=A.getChild();if(D==null)return this.toBeTiled[_]=!1,!1;for(var N=D.getNodes(),R=0;R0)return this.toBeTiled[_]=!1,!1;if(B.getChild()==null){this.toBeTiled[B.id]=!1;continue}if(!this.getToBeTiled(B))return this.toBeTiled[_]=!1,!1}return this.toBeTiled[_]=!0,!0},M.prototype.getNodeDegree=function(A){for(var _=A.id,D=A.getEdges(),N=0,R=0;RV&&(V=X.rect.height)}D+=V+A.verticalPadding}},M.prototype.tileCompoundMembers=function(A,_){var D=this;this.tiledMemberPack=[],Object.keys(A).forEach(function(N){var R=_[N];if(D.tiledMemberPack[N]=D.tileNodes(A[N],R.paddingLeft+R.paddingRight),R.rect.width=D.tiledMemberPack[N].width,R.rect.height=D.tiledMemberPack[N].height,R.setCenter(D.tiledMemberPack[N].centerX,D.tiledMemberPack[N].centerY),R.labelMarginLeft=0,R.labelMarginTop=0,m.NODE_DIMENSIONS_INCLUDE_LABELS){var B=R.rect.width,O=R.rect.height;R.labelWidth&&(R.labelPosHorizontal=="left"?(R.rect.x-=R.labelWidth,R.setWidth(B+R.labelWidth),R.labelMarginLeft=R.labelWidth):R.labelPosHorizontal=="center"&&R.labelWidth>B?(R.rect.x-=(R.labelWidth-B)/2,R.setWidth(R.labelWidth),R.labelMarginLeft=(R.labelWidth-B)/2):R.labelPosHorizontal=="right"&&R.setWidth(B+R.labelWidth)),R.labelHeight&&(R.labelPosVertical=="top"?(R.rect.y-=R.labelHeight,R.setHeight(O+R.labelHeight),R.labelMarginTop=R.labelHeight):R.labelPosVertical=="center"&&R.labelHeight>O?(R.rect.y-=(R.labelHeight-O)/2,R.setHeight(R.labelHeight),R.labelMarginTop=(R.labelHeight-O)/2):R.labelPosVertical=="bottom"&&R.setHeight(O+R.labelHeight))}})},M.prototype.tileNodes=function(A,_){var D=this.tileNodesByFavoringDim(A,_,!0),N=this.tileNodesByFavoringDim(A,_,!1),R=this.getOrgRatio(D),B=this.getOrgRatio(N),O;return B$&&($=Z.getWidth())});var z=B/R,F=O/R,V=Math.pow(D-N,2)+4*(z+N)*(F+D)*R,H=(N-D+Math.sqrt(V))/(2*(z+N)),X;_?(X=Math.ceil(H),X==H&&X++):X=Math.floor(H);var W=X*(z+N)-N;return $>W&&(W=$),W+=N*2,W},M.prototype.tileNodesByFavoringDim=function(A,_,D){var N=m.TILING_PADDING_VERTICAL,R=m.TILING_PADDING_HORIZONTAL,B=m.TILING_COMPARE_BY,O={rows:[],rowWidth:[],rowHeight:[],width:0,height:_,verticalPadding:N,horizontalPadding:R,centerX:0,centerY:0};B&&(O.idealRowWidth=this.calcIdealRowWidth(A,D));var $=o(function(Y){return Y.rect.width*Y.rect.height},"getNodeArea"),z=o(function(Y,ae){return $(ae)-$(Y)},"areaCompareFcn");A.sort(function(Z,Y){var ae=z;return O.idealRowWidth?(ae=B,ae(Z.id,Y.id)):ae(Z,Y)});for(var F=0,V=0,H=0;H0&&(O+=A.horizontalPadding),A.rowWidth[D]=O,A.width0&&($+=A.verticalPadding);var z=0;$>A.rowHeight[D]&&(z=A.rowHeight[D],A.rowHeight[D]=$,z=A.rowHeight[D]-z),A.height+=z,A.rows[D].push(_)},M.prototype.getShortestRowIndex=function(A){for(var _=-1,D=Number.MAX_VALUE,N=0;ND&&(_=N,D=A.rowWidth[N]);return _},M.prototype.canAddHorizontal=function(A,_,D){if(A.idealRowWidth){var N=A.rows.length-1,R=A.rowWidth[N];return R+_+A.horizontalPadding<=A.idealRowWidth}var B=this.getShortestRowIndex(A);if(B<0)return!0;var O=A.rowWidth[B];if(O+A.horizontalPadding+_<=A.width)return!0;var $=0;A.rowHeight[B]0&&($=D+A.verticalPadding-A.rowHeight[B]);var z;A.width-O>=_+A.horizontalPadding?z=(A.height+$)/(O+_+A.horizontalPadding):z=(A.height+$)/A.width,$=D+A.verticalPadding;var F;return A.width<_?F=(A.height+$)/_:F=(A.height+$)/A.width,F<1&&(F=1/F),z<1&&(z=1/z),zB&&_!=D){N.splice(-1,1),A.rows[D].push(R),A.rowWidth[_]=A.rowWidth[_]-B,A.rowWidth[D]=A.rowWidth[D]+B,A.width=A.rowWidth[instance.getLongestRowIndex(A)];for(var O=Number.MIN_VALUE,$=0;$O&&(O=N[$].height);_>0&&(O+=A.verticalPadding);var z=A.rowHeight[_]+A.rowHeight[D];A.rowHeight[_]=O,A.rowHeight[D]0)for(var W=R;W<=B;W++)X[0]+=this.grid[W][O-1].length+this.grid[W][O].length-1;if(B0)for(var W=O;W<=$;W++)X[3]+=this.grid[R-1][W].length+this.grid[R][W].length-1;for(var Z=k.MAX_VALUE,Y,ae,J=0;J{var u=l(551).FDLayoutNode,h=l(551).IMath;function f(p,m,g,y){u.call(this,p,m,g,y)}o(f,"CoSENode"),f.prototype=Object.create(u.prototype);for(var d in u)f[d]=u[d];f.prototype.calculateDisplacement=function(){var p=this.graphManager.getLayout();this.getChild()!=null&&this.fixedNodeWeight?(this.displacementX+=p.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.fixedNodeWeight,this.displacementY+=p.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.fixedNodeWeight):(this.displacementX+=p.coolingFactor*(this.springForceX+this.repulsionForceX+this.gravitationForceX)/this.noOfChildren,this.displacementY+=p.coolingFactor*(this.springForceY+this.repulsionForceY+this.gravitationForceY)/this.noOfChildren),Math.abs(this.displacementX)>p.coolingFactor*p.maxNodeDisplacement&&(this.displacementX=p.coolingFactor*p.maxNodeDisplacement*h.sign(this.displacementX)),Math.abs(this.displacementY)>p.coolingFactor*p.maxNodeDisplacement&&(this.displacementY=p.coolingFactor*p.maxNodeDisplacement*h.sign(this.displacementY)),this.child&&this.child.getNodes().length>0&&this.propogateDisplacementToChildren(this.displacementX,this.displacementY)},f.prototype.propogateDisplacementToChildren=function(p,m){for(var g=this.getChild().getNodes(),y,v=0;v{function u(g){if(Array.isArray(g)){for(var y=0,v=Array(g.length);y0){var it=0;ce.forEach(function(ut){ue=="horizontal"?(ye.set(ut,x.has(ut)?b[x.get(ut)]:se.get(ut)),it+=ye.get(ut)):(ye.set(ut,x.has(ut)?T[x.get(ut)]:se.get(ut)),it+=ye.get(ut))}),it=it/ce.length,Qe.forEach(function(ut){G.has(ut)||ye.set(ut,it)})}else{var fe=0;Qe.forEach(function(ut){ue=="horizontal"?fe+=x.has(ut)?b[x.get(ut)]:se.get(ut):fe+=x.has(ut)?T[x.get(ut)]:se.get(ut)}),fe=fe/Qe.length,Qe.forEach(function(ut){ye.set(ut,fe)})}});for(var Oe=o(function(){var ce=ve.shift(),it=U.get(ce);it.forEach(function(fe){if(ye.get(fe.id)ut&&(ut=kt),ytNt&&(Nt=yt)}}catch(Ii){St=!0,It=Ii}finally{try{!Pt&&ot.return&&ot.return()}finally{if(St)throw It}}var jt=(it+ut)/2-(fe+Nt)/2,hr=!0,Qt=!1,Er=void 0;try{for(var dr=Qe[Symbol.iterator](),ir;!(hr=(ir=dr.next()).done);hr=!0){var pr=ir.value;ye.set(pr,ye.get(pr)+jt)}}catch(Ii){Qt=!0,Er=Ii}finally{try{!hr&&dr.return&&dr.return()}finally{if(Qt)throw Er}}})}return ye},"findAppropriatePositionForRelativePlacement"),I=o(function(U){var ue=0,G=0,se=0,le=0;if(U.forEach(function(Re){Re.left?b[x.get(Re.left)]-b[x.get(Re.right)]>=0?ue++:G++:T[x.get(Re.top)]-T[x.get(Re.bottom)]>=0?se++:le++}),ue>G&&se>le)for(var ke=0;keG)for(var me=0;mele)for(var ye=0;ye1)y.fixedNodeConstraint.forEach(function(oe,U){N[U]=[oe.position.x,oe.position.y],R[U]=[b[x.get(oe.nodeId)],T[x.get(oe.nodeId)]]}),B=!0;else if(y.alignmentConstraint)(function(){var oe=0;if(y.alignmentConstraint.vertical){for(var U=y.alignmentConstraint.vertical,ue=o(function(ye){var Re=new Set;U[ye].forEach(function(We){Re.add(We)});var ve=new Set([].concat(u(Re)).filter(function(We){return $.has(We)})),Oe=void 0;ve.size>0?Oe=b[x.get(ve.values().next().value)]:Oe=L(Re).x,U[ye].forEach(function(We){N[oe]=[Oe,T[x.get(We)]],R[oe]=[b[x.get(We)],T[x.get(We)]],oe++})},"_loop2"),G=0;G0?Oe=b[x.get(ve.values().next().value)]:Oe=L(Re).y,se[ye].forEach(function(We){N[oe]=[b[x.get(We)],Oe],R[oe]=[b[x.get(We)],T[x.get(We)]],oe++})},"_loop3"),ke=0;keH&&(H=V[W].length,X=W);if(H0){var pe={x:0,y:0};y.fixedNodeConstraint.forEach(function(oe,U){var ue={x:b[x.get(oe.nodeId)],y:T[x.get(oe.nodeId)]},G=oe.position,se=S(G,ue);pe.x+=se.x,pe.y+=se.y}),pe.x/=y.fixedNodeConstraint.length,pe.y/=y.fixedNodeConstraint.length,b.forEach(function(oe,U){b[U]+=pe.x}),T.forEach(function(oe,U){T[U]+=pe.y}),y.fixedNodeConstraint.forEach(function(oe){b[x.get(oe.nodeId)]=oe.position.x,T[x.get(oe.nodeId)]=oe.position.y})}if(y.alignmentConstraint){if(y.alignmentConstraint.vertical)for(var Je=y.alignmentConstraint.vertical,Ce=o(function(U){var ue=new Set;Je[U].forEach(function(le){ue.add(le)});var G=new Set([].concat(u(ue)).filter(function(le){return $.has(le)})),se=void 0;G.size>0?se=b[x.get(G.values().next().value)]:se=L(ue).x,ue.forEach(function(le){$.has(le)||(b[x.get(le)]=se)})},"_loop4"),Fe=0;Fe0?se=T[x.get(G.values().next().value)]:se=L(ue).y,ue.forEach(function(le){$.has(le)||(T[x.get(le)]=se)})},"_loop5"),Me=0;Me{a.exports=t})},r={};function i(a){var s=r[a];if(s!==void 0)return s.exports;var l=r[a]={exports:{}};return e[a](l,l.exports,i),l.exports}o(i,"__webpack_require__");var n=i(45);return n})()})});var VAe=ar((KC,HH)=>{"use strict";o((function(e,r){typeof KC=="object"&&typeof HH=="object"?HH.exports=r(UH()):typeof define=="function"&&define.amd?define(["cose-base"],r):typeof KC=="object"?KC.cytoscapeFcose=r(UH()):e.cytoscapeFcose=r(e.coseBase)}),"webpackUniversalModuleDefinition")(KC,function(t){return(()=>{"use strict";var e={658:(a=>{a.exports=Object.assign!=null?Object.assign.bind(Object):function(s){for(var l=arguments.length,u=Array(l>1?l-1:0),h=1;h{var u=(function(){function d(p,m){var g=[],y=!0,v=!1,x=void 0;try{for(var b=p[Symbol.iterator](),T;!(y=(T=b.next()).done)&&(g.push(T.value),!(m&&g.length===m));y=!0);}catch(w){v=!0,x=w}finally{try{!y&&b.return&&b.return()}finally{if(v)throw x}}return g}return o(d,"sliceIterator"),function(p,m){if(Array.isArray(p))return p;if(Symbol.iterator in Object(p))return d(p,m);throw new TypeError("Invalid attempt to destructure non-iterable instance")}})(),h=l(140).layoutBase.LinkedList,f={};f.getTopMostNodes=function(d){for(var p={},m=0;m0&&B.merge(F)});for(var O=0;O1){T=x[0],w=T.connectedEdges().length,x.forEach(function(R){R.connectedEdges().length0&&g.set("dummy"+(g.size+1),E),S},f.relocateComponent=function(d,p,m){if(!m.fixedNodeConstraint){var g=Number.POSITIVE_INFINITY,y=Number.NEGATIVE_INFINITY,v=Number.POSITIVE_INFINITY,x=Number.NEGATIVE_INFINITY;if(m.quality=="draft"){var b=!0,T=!1,w=void 0;try{for(var k=p.nodeIndexes[Symbol.iterator](),C;!(b=(C=k.next()).done);b=!0){var E=C.value,S=u(E,2),L=S[0],M=S[1],I=m.cy.getElementById(L);if(I){var A=I.boundingBox(),_=p.xCoords[M]-A.w/2,D=p.xCoords[M]+A.w/2,N=p.yCoords[M]-A.h/2,R=p.yCoords[M]+A.h/2;_y&&(y=D),Nx&&(x=R)}}}catch(F){T=!0,w=F}finally{try{!b&&k.return&&k.return()}finally{if(T)throw w}}var B=d.x-(y+g)/2,O=d.y-(x+v)/2;p.xCoords=p.xCoords.map(function(F){return F+B}),p.yCoords=p.yCoords.map(function(F){return F+O})}else{Object.keys(p).forEach(function(F){var V=p[F],H=V.getRect().x,X=V.getRect().x+V.getRect().width,W=V.getRect().y,Z=V.getRect().y+V.getRect().height;Hy&&(y=X),Wx&&(x=Z)});var $=d.x-(y+g)/2,z=d.y-(x+v)/2;Object.keys(p).forEach(function(F){var V=p[F];V.setCenter(V.getCenterX()+$,V.getCenterY()+z)})}}},f.calcBoundingBox=function(d,p,m,g){for(var y=Number.MAX_SAFE_INTEGER,v=Number.MIN_SAFE_INTEGER,x=Number.MAX_SAFE_INTEGER,b=Number.MIN_SAFE_INTEGER,T=void 0,w=void 0,k=void 0,C=void 0,E=d.descendants().not(":parent"),S=E.length,L=0;LT&&(y=T),vk&&(x=k),b{var u=l(548),h=l(140).CoSELayout,f=l(140).CoSENode,d=l(140).layoutBase.PointD,p=l(140).layoutBase.DimensionD,m=l(140).layoutBase.LayoutConstants,g=l(140).layoutBase.FDLayoutConstants,y=l(140).CoSEConstants,v=o(function(b,T){var w=b.cy,k=b.eles,C=k.nodes(),E=k.edges(),S=void 0,L=void 0,M=void 0,I={};b.randomize&&(S=T.nodeIndexes,L=T.xCoords,M=T.yCoords);var A=o(function(F){return typeof F=="function"},"isFn"),_=o(function(F,V){return A(F)?F(V):F},"optFn"),D=u.calcParentsWithoutChildren(w,k),N=o(function z(F,V,H,X){for(var W=V.length,Z=0;Z0){var te=void 0;te=H.getGraphManager().add(H.newGraph(),J),z(te,ae,H,X)}}},"processChildrenList"),R=o(function(F,V,H){for(var X=0,W=0,Z=0;Z0?y.DEFAULT_EDGE_LENGTH=g.DEFAULT_EDGE_LENGTH=X/W:A(b.idealEdgeLength)?y.DEFAULT_EDGE_LENGTH=g.DEFAULT_EDGE_LENGTH=50:y.DEFAULT_EDGE_LENGTH=g.DEFAULT_EDGE_LENGTH=b.idealEdgeLength,y.MIN_REPULSION_DIST=g.MIN_REPULSION_DIST=g.DEFAULT_EDGE_LENGTH/10,y.DEFAULT_RADIAL_SEPARATION=g.DEFAULT_EDGE_LENGTH)},"processEdges"),B=o(function(F,V){V.fixedNodeConstraint&&(F.constraints.fixedNodeConstraint=V.fixedNodeConstraint),V.alignmentConstraint&&(F.constraints.alignmentConstraint=V.alignmentConstraint),V.relativePlacementConstraint&&(F.constraints.relativePlacementConstraint=V.relativePlacementConstraint)},"processConstraints");b.nestingFactor!=null&&(y.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=g.PER_LEVEL_IDEAL_EDGE_LENGTH_FACTOR=b.nestingFactor),b.gravity!=null&&(y.DEFAULT_GRAVITY_STRENGTH=g.DEFAULT_GRAVITY_STRENGTH=b.gravity),b.numIter!=null&&(y.MAX_ITERATIONS=g.MAX_ITERATIONS=b.numIter),b.gravityRange!=null&&(y.DEFAULT_GRAVITY_RANGE_FACTOR=g.DEFAULT_GRAVITY_RANGE_FACTOR=b.gravityRange),b.gravityCompound!=null&&(y.DEFAULT_COMPOUND_GRAVITY_STRENGTH=g.DEFAULT_COMPOUND_GRAVITY_STRENGTH=b.gravityCompound),b.gravityRangeCompound!=null&&(y.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=g.DEFAULT_COMPOUND_GRAVITY_RANGE_FACTOR=b.gravityRangeCompound),b.initialEnergyOnIncremental!=null&&(y.DEFAULT_COOLING_FACTOR_INCREMENTAL=g.DEFAULT_COOLING_FACTOR_INCREMENTAL=b.initialEnergyOnIncremental),b.tilingCompareBy!=null&&(y.TILING_COMPARE_BY=b.tilingCompareBy),b.quality=="proof"?m.QUALITY=2:m.QUALITY=0,y.NODE_DIMENSIONS_INCLUDE_LABELS=g.NODE_DIMENSIONS_INCLUDE_LABELS=m.NODE_DIMENSIONS_INCLUDE_LABELS=b.nodeDimensionsIncludeLabels,y.DEFAULT_INCREMENTAL=g.DEFAULT_INCREMENTAL=m.DEFAULT_INCREMENTAL=!b.randomize,y.ANIMATE=g.ANIMATE=m.ANIMATE=b.animate,y.TILE=b.tile,y.TILING_PADDING_VERTICAL=typeof b.tilingPaddingVertical=="function"?b.tilingPaddingVertical.call():b.tilingPaddingVertical,y.TILING_PADDING_HORIZONTAL=typeof b.tilingPaddingHorizontal=="function"?b.tilingPaddingHorizontal.call():b.tilingPaddingHorizontal,y.DEFAULT_INCREMENTAL=g.DEFAULT_INCREMENTAL=m.DEFAULT_INCREMENTAL=!0,y.PURE_INCREMENTAL=!b.randomize,m.DEFAULT_UNIFORM_LEAF_NODE_SIZES=b.uniformNodeDimensions,b.step=="transformed"&&(y.TRANSFORM_ON_CONSTRAINT_HANDLING=!0,y.ENFORCE_CONSTRAINTS=!1,y.APPLY_LAYOUT=!1),b.step=="enforced"&&(y.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,y.ENFORCE_CONSTRAINTS=!0,y.APPLY_LAYOUT=!1),b.step=="cose"&&(y.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,y.ENFORCE_CONSTRAINTS=!1,y.APPLY_LAYOUT=!0),b.step=="all"&&(b.randomize?y.TRANSFORM_ON_CONSTRAINT_HANDLING=!0:y.TRANSFORM_ON_CONSTRAINT_HANDLING=!1,y.ENFORCE_CONSTRAINTS=!0,y.APPLY_LAYOUT=!0),b.fixedNodeConstraint||b.alignmentConstraint||b.relativePlacementConstraint?y.TREE_REDUCTION_ON_INCREMENTAL=!1:y.TREE_REDUCTION_ON_INCREMENTAL=!0;var O=new h,$=O.newGraphManager();return N($.addRoot(),u.getTopMostNodes(C),O,b),R(O,$,E),B(O,b),O.runLayout(),I},"coseLayout");a.exports={coseLayout:v}}),212:((a,s,l)=>{var u=(function(){function b(T,w){for(var k=0;k0)if(R){var $=d.getTopMostNodes(k.eles.nodes());if(A=d.connectComponents(C,k.eles,$),A.forEach(function(we){var Te=we.boundingBox();_.push({x:Te.x1+Te.w/2,y:Te.y1+Te.h/2})}),k.randomize&&A.forEach(function(we){k.eles=we,S.push(m(k))}),k.quality=="default"||k.quality=="proof"){var z=C.collection();if(k.tile){var F=new Map,V=[],H=[],X=0,W={nodeIndexes:F,xCoords:V,yCoords:H},Z=[];if(A.forEach(function(we,Te){we.edges().length==0&&(we.nodes().forEach(function(De,$e){z.merge(we.nodes()[$e]),De.isParent()||(W.nodeIndexes.set(we.nodes()[$e].id(),X++),W.xCoords.push(we.nodes()[0].position().x),W.yCoords.push(we.nodes()[0].position().y))}),Z.push(Te))}),z.length>1){var Y=z.boundingBox();_.push({x:Y.x1+Y.w/2,y:Y.y1+Y.h/2}),A.push(z),S.push(W);for(var ae=Z.length-1;ae>=0;ae--)A.splice(Z[ae],1),S.splice(Z[ae],1),_.splice(Z[ae],1)}}A.forEach(function(we,Te){k.eles=we,I.push(y(k,S[Te])),d.relocateComponent(_[Te],I[Te],k)})}else A.forEach(function(we,Te){d.relocateComponent(_[Te],S[Te],k)});var J=new Set;if(A.length>1){var ee=[],re=E.filter(function(we){return we.css("display")=="none"});A.forEach(function(we,Te){var De=void 0;if(k.quality=="draft"&&(De=S[Te].nodeIndexes),we.nodes().not(re).length>0){var $e={};$e.edges=[],$e.nodes=[];var pe=void 0;we.nodes().not(re).forEach(function(Je){if(k.quality=="draft")if(!Je.isParent())pe=De.get(Je.id()),$e.nodes.push({x:S[Te].xCoords[pe]-Je.boundingbox().w/2,y:S[Te].yCoords[pe]-Je.boundingbox().h/2,width:Je.boundingbox().w,height:Je.boundingbox().h});else{var Ce=d.calcBoundingBox(Je,S[Te].xCoords,S[Te].yCoords,De);$e.nodes.push({x:Ce.topLeftX,y:Ce.topLeftY,width:Ce.width,height:Ce.height})}else I[Te][Je.id()]&&$e.nodes.push({x:I[Te][Je.id()].getLeft(),y:I[Te][Je.id()].getTop(),width:I[Te][Je.id()].getWidth(),height:I[Te][Je.id()].getHeight()})}),we.edges().forEach(function(Je){var Ce=Je.source(),Fe=Je.target();if(Ce.css("display")!="none"&&Fe.css("display")!="none")if(k.quality=="draft"){var Ue=De.get(Ce.id()),qe=De.get(Fe.id()),Me=[],He=[];if(Ce.isParent()){var K=d.calcBoundingBox(Ce,S[Te].xCoords,S[Te].yCoords,De);Me.push(K.topLeftX+K.width/2),Me.push(K.topLeftY+K.height/2)}else Me.push(S[Te].xCoords[Ue]),Me.push(S[Te].yCoords[Ue]);if(Fe.isParent()){var oe=d.calcBoundingBox(Fe,S[Te].xCoords,S[Te].yCoords,De);He.push(oe.topLeftX+oe.width/2),He.push(oe.topLeftY+oe.height/2)}else He.push(S[Te].xCoords[qe]),He.push(S[Te].yCoords[qe]);$e.edges.push({startX:Me[0],startY:Me[1],endX:He[0],endY:He[1]})}else I[Te][Ce.id()]&&I[Te][Fe.id()]&&$e.edges.push({startX:I[Te][Ce.id()].getCenterX(),startY:I[Te][Ce.id()].getCenterY(),endX:I[Te][Fe.id()].getCenterX(),endY:I[Te][Fe.id()].getCenterY()})}),$e.nodes.length>0&&(ee.push($e),J.add(Te))}});var te=N.packComponents(ee,k.randomize).shifts;if(k.quality=="draft")S.forEach(function(we,Te){var De=we.xCoords.map(function(pe){return pe+te[Te].dx}),$e=we.yCoords.map(function(pe){return pe+te[Te].dy});we.xCoords=De,we.yCoords=$e});else{var be=0;J.forEach(function(we){Object.keys(I[we]).forEach(function(Te){var De=I[we][Te];De.setCenter(De.getCenterX()+te[be].dx,De.getCenterY()+te[be].dy)}),be++})}}}else{var B=k.eles.boundingBox();if(_.push({x:B.x1+B.w/2,y:B.y1+B.h/2}),k.randomize){var O=m(k);S.push(O)}k.quality=="default"||k.quality=="proof"?(I.push(y(k,S[0])),d.relocateComponent(_[0],I[0],k)):d.relocateComponent(_[0],S[0],k)}var de=o(function(Te,De){if(k.quality=="default"||k.quality=="proof"){typeof Te=="number"&&(Te=De);var $e=void 0,pe=void 0,Je=Te.data("id");return I.forEach(function(Fe){Je in Fe&&($e={x:Fe[Je].getRect().getCenterX(),y:Fe[Je].getRect().getCenterY()},pe=Fe[Je])}),k.nodeDimensionsIncludeLabels&&(pe.labelWidth&&(pe.labelPosHorizontal=="left"?$e.x+=pe.labelWidth/2:pe.labelPosHorizontal=="right"&&($e.x-=pe.labelWidth/2)),pe.labelHeight&&(pe.labelPosVertical=="top"?$e.y+=pe.labelHeight/2:pe.labelPosVertical=="bottom"&&($e.y-=pe.labelHeight/2))),$e==null&&($e={x:Te.position("x"),y:Te.position("y")}),{x:$e.x,y:$e.y}}else{var Ce=void 0;return S.forEach(function(Fe){var Ue=Fe.nodeIndexes.get(Te.id());Ue!=null&&(Ce={x:Fe.xCoords[Ue],y:Fe.yCoords[Ue]})}),Ce==null&&(Ce={x:Te.position("x"),y:Te.position("y")}),{x:Ce.x,y:Ce.y}}},"getPositions");if(k.quality=="default"||k.quality=="proof"||k.randomize){var Ee=d.calcParentsWithoutChildren(C,E),Ne=E.filter(function(we){return we.css("display")=="none"});k.eles=E.not(Ne),E.nodes().not(":parent").not(Ne).layoutPositions(w,k,de),Ee.length>0&&Ee.forEach(function(we){we.position(de(we))})}else console.log("If randomize option is set to false, then quality option must be 'default' or 'proof'.")},"run")}]),b})();a.exports=x}),657:((a,s,l)=>{var u=l(548),h=l(140).layoutBase.Matrix,f=l(140).layoutBase.SVD,d=o(function(m){var g=m.cy,y=m.eles,v=y.nodes(),x=y.nodes(":parent"),b=new Map,T=new Map,w=new Map,k=[],C=[],E=[],S=[],L=[],M=[],I=[],A=[],_=void 0,D=void 0,N=1e8,R=1e-9,B=m.piTol,O=m.samplingType,$=m.nodeSeparation,z=void 0,F=o(function(){for(var ue=0,G=0,se=!1;G=ke;){ye=le[ke++];for(var Qe=k[ye],ce=0;ceOe&&(Oe=L[fe],We=fe)}return We},"BFS"),H=o(function(ue){var G=void 0;if(ue){G=Math.floor(Math.random()*D),_=G;for(var le=0;le=1)break;Oe=ve}for(var Qe=0;Qe=1)break;Oe=ve}for(var it=0;it0&&(G.isParent()?k[ue].push(w.get(G.id())):k[ue].push(G.id()))})});var Ee=o(function(ue){var G=T.get(ue),se=void 0;b.get(ue).forEach(function(le){g.getElementById(le).isParent()?se=w.get(le):se=le,k[G].push(se),k[T.get(se)].push(ue)})},"_loop"),Ne=!0,we=!1,Te=void 0;try{for(var De=b.keys()[Symbol.iterator](),$e;!(Ne=($e=De.next()).done);Ne=!0){var pe=$e.value;Ee(pe)}}catch(U){we=!0,Te=U}finally{try{!Ne&&De.return&&De.return()}finally{if(we)throw Te}}D=T.size;var Je=void 0;if(D>2){z=D{var u=l(212),h=o(function(d){d&&d("layout","fcose",u)},"register");typeof cytoscape<"u"&&h(cytoscape),a.exports=h}),140:(a=>{a.exports=t})},r={};function i(a){var s=r[a];if(s!==void 0)return s.exports;var l=r[a]={exports:{}};return e[a](l,l.exports,i),l.exports}o(i,"__webpack_require__");var n=i(579);return n})()})});var px,yg,YH=P(()=>{"use strict";lu();px=o(t=>`${t}`,"wrapIcon"),yg={prefix:"mermaid-architecture",height:80,width:80,icons:{database:{body:px('')},server:{body:px('')},disk:{body:px('')},internet:{body:px('')},cloud:{body:px('')},unknown:sL,blank:{body:px("")}}}});var qAe,WAe,UAe,HAe,YAe=P(()=>{"use strict";Ut();To();lu();Vr();YH();n8();er();qAe=o(async function(t,e,r,i){let n=r.getConfigField("padding"),a=r.getConfigField("iconSize"),s=a/2,l=a/6,u=l/2;await Promise.all(e.edges().map(async h=>{let{source:f,sourceDir:d,sourceArrow:p,sourceGroup:m,target:g,targetDir:y,targetArrow:v,targetGroup:x,label:b}=i8(h),{x:T,y:w}=h[0].sourceEndpoint(),{x:k,y:C}=h[0].midpoint(),{x:E,y:S}=h[0].targetEndpoint(),L=n+4;if(m&&(Ds(d)?T+=d==="L"?-L:L:w+=d==="T"?-L:L+18),x&&(Ds(y)?E+=y==="L"?-L:L:S+=y==="T"?-L:L+18),!m&&r.getNode(f)?.type==="junction"&&(Ds(d)?T+=d==="L"?s:-s:w+=d==="T"?s:-s),!x&&r.getNode(g)?.type==="junction"&&(Ds(y)?E+=y==="L"?s:-s:S+=y==="T"?s:-s),h[0]._private.rscratch){let M=t.insert("g");if(M.insert("path").attr("d",`M ${T},${w} L ${k},${C} L${E},${S} `).attr("class","edge").attr("id",`${i}-${Cu(f,g,{prefix:"L"})}`),p){let I=Ds(d)?UC[d](T,l):T-u,A=hh(d)?UC[d](w,l):w-u;M.insert("polygon").attr("points",FH[d](l)).attr("transform",`translate(${I},${A})`).attr("class","arrow")}if(v){let I=Ds(y)?UC[y](E,l):E-u,A=hh(y)?UC[y](S,l):S-u;M.insert("polygon").attr("points",FH[y](l)).attr("transform",`translate(${I},${A})`).attr("class","arrow")}if(b){let I=HC(d,y)?"XY":Ds(d)?"X":"Y",A=0;I==="X"?A=Math.abs(T-E):I==="Y"?A=Math.abs(w-S)/1.5:A=Math.abs(T-E)/2;let _=M.append("g");if(await Vi(_,b,{useHtmlLabels:!1,width:A,classes:"architecture-service-label"},ge()),_.attr("dy","1em").attr("alignment-baseline","middle").attr("dominant-baseline","middle").attr("text-anchor","middle"),I==="X")_.attr("transform","translate("+k+", "+C+")");else if(I==="Y")_.attr("transform","translate("+k+", "+C+") rotate(-90)");else if(I==="XY"){let D=YC(d,y);if(D&&IAe(D)){let N=_.node().getBoundingClientRect(),[R,B]=OAe(D);_.attr("dominant-baseline","auto").attr("transform",`rotate(${-1*R*B*45})`);let O=_.node().getBoundingClientRect();_.attr("transform",` + translate(${k}, ${C-N.height/2}) + translate(${R*O.width/2}, ${B*O.height/2}) + rotate(${-1*R*B*45}, 0, ${N.height/2}) + `)}}}}}))},"drawEdges"),WAe=o(async function(t,e,r,i){let a=r.getConfigField("padding")*.75,s=r.getConfigField("fontSize"),u=r.getConfigField("iconSize")/2;await Promise.all(e.nodes().map(async h=>{let f=Np(h);if(f.type==="group"){let{h:d,w:p,x1:m,y1:g}=h.boundingBox(),y=t.append("rect");y.attr("id",`${i}-group-${f.id}`).attr("x",m+u).attr("y",g+u).attr("width",p).attr("height",d).attr("class","node-bkg");let v=t.append("g"),x=m,b=g;if(f.icon){let T=v.append("g");T.html(`${await fo(f.icon,{height:a,width:a,fallbackPrefix:yg.prefix})}`),T.attr("transform","translate("+(x+u+1)+", "+(b+u+1)+")"),x+=a,b+=s/2-1-2}if(f.label){let T=v.append("g");await Vi(T,f.label,{useHtmlLabels:!1,width:p,classes:"architecture-service-label"},ge()),T.attr("dy","1em").attr("alignment-baseline","middle").attr("dominant-baseline","start").attr("text-anchor","start"),T.attr("transform","translate("+(x+u+4)+", "+(b+u+2)+")")}r.setElementForId(f.id,y)}}))},"drawGroups"),UAe=o(async function(t,e,r,i){let n=ge();for(let a of r){let s=e.append("g"),l=t.getConfigField("iconSize");if(a.title){let d=s.append("g");await Vi(d,a.title,{useHtmlLabels:!1,width:l*1.5,classes:"architecture-service-label"},n),d.attr("dy","1em").attr("alignment-baseline","middle").attr("dominant-baseline","middle").attr("text-anchor","middle"),d.attr("transform","translate("+l/2+", "+l+")")}let u=s.append("g");if(a.icon)u.html(`${await fo(a.icon,{height:l,width:l,fallbackPrefix:yg.prefix})}`);else if(a.iconText){u.html(`${await fo("blank",{height:l,width:l,fallbackPrefix:yg.prefix})}`);let m=u.append("g").append("foreignObject").attr("width",l).attr("height",l).append("div").attr("class","node-icon-text").attr("style",`height: ${l}px;`).append("div").html(Tr(a.iconText,n)),g=parseInt(window.getComputedStyle(m.node(),null).getPropertyValue("font-size").replace(/\D/g,""))??16;m.attr("style",`-webkit-line-clamp: ${Math.floor((l-2)/g)};`)}else u.append("path").attr("class","node-bkg").attr("id",`${i}-node-${a.id}`).attr("d",`M0,${l} V5 Q0,0 5,0 H${l-5} Q${l},0 ${l},5 V${l} Z`);s.attr("id",`${i}-service-${a.id}`).attr("class","architecture-service");let{width:h,height:f}=s.node().getBBox();a.width=h,a.height=f,t.setElementForId(a.id,s)}return 0},"drawServices"),HAe=o(function(t,e,r,i){r.forEach(n=>{let a=e.append("g"),s=t.getConfigField("iconSize");a.append("g").append("rect").attr("id",`${i}-node-${n.id}`).attr("fill-opacity","0").attr("width",s).attr("height",s),a.attr("class","architecture-junction");let{width:u,height:h}=a._groups[0][0].getBBox();a.width=u,a.height=h,t.setElementForId(n.id,a)})},"drawJunctions")});function qgt(t,e,r){t.forEach(i=>{e.add({group:"nodes",data:{type:"service",id:i.id,icon:i.icon,label:i.title,parent:i.in,width:r.getConfigField("iconSize"),height:r.getConfigField("iconSize")},classes:"node-service"})})}function Wgt(t,e,r){t.forEach(i=>{e.add({group:"nodes",data:{type:"junction",id:i.id,parent:i.in,width:r.getConfigField("iconSize"),height:r.getConfigField("iconSize")},classes:"node-junction"})})}function Ugt(t,e){e.nodes().map(r=>{let i=Np(r);if(i.type==="group")return;i.x=r.position().x,i.y=r.position().y,t.getElementById(i.id).attr("transform","translate("+(i.x||0)+","+(i.y||0)+")")})}function Hgt(t,e){t.forEach(r=>{e.add({group:"nodes",data:{type:"group",id:r.id,icon:r.icon,label:r.title,parent:r.in},classes:"node-group"})})}function Ygt(t,e){t.forEach(r=>{let{lhsId:i,rhsId:n,lhsInto:a,lhsGroup:s,rhsInto:l,lhsDir:u,rhsDir:h,rhsGroup:f,title:d}=r,p=HC(r.lhsDir,r.rhsDir)?"segments":"straight",m={id:`${i}-${n}`,label:d,source:i,sourceDir:u,sourceArrow:a,sourceGroup:s,sourceEndpoint:u==="L"?"0 50%":u==="R"?"100% 50%":u==="T"?"50% 0":"50% 100%",target:n,targetDir:h,targetArrow:l,targetGroup:f,targetEndpoint:h==="L"?"0 50%":h==="R"?"100% 50%":h==="T"?"50% 0":"50% 100%"};e.add({group:"edges",data:m,classes:p})})}function jgt(t,e,r){let i=o((l,u)=>Object.entries(l).reduce((h,[f,d])=>{let p=0,m=Object.entries(d);if(m.length===1)return h[f]=m[0][1],h;for(let g=0;g{let u={},h={};return Object.entries(l).forEach(([f,[d,p]])=>{let m=t.getNode(f)?.in??"default";u[p]??={},u[p][m]??=[],u[p][m].push(f),h[d]??={},h[d][m]??=[],h[d][m].push(f)}),{horiz:Object.values(i(u,"horizontal")).filter(f=>f.length>1),vert:Object.values(i(h,"vertical")).filter(f=>f.length>1)}}),[a,s]=n.reduce(([l,u],{horiz:h,vert:f})=>[[...l,...h],[...u,...f]],[[],[]]);return{horizontal:a,vertical:s}}function Xgt(t,e){let r=[],i=o(a=>`${a[0]},${a[1]}`,"posToStr"),n=o(a=>a.split(",").map(s=>parseInt(s)),"strToPos");return t.forEach(a=>{let s=Object.fromEntries(Object.entries(a).map(([f,d])=>[i(d),f])),l=[i([0,0])],u={},h={L:[-1,0],R:[1,0],T:[0,1],B:[0,-1]};for(;l.length>0;){let f=l.shift();if(f){u[f]=1;let d=s[f];if(d){let p=n(f);Object.entries(h).forEach(([m,g])=>{let y=i([p[0]+g[0],p[1]+g[1]]),v=s[y];v&&!u[y]&&(l.push(y),r.push({[BH[m]]:v,[BH[NAe(m)]]:d,gap:1.5*e.getConfigField("iconSize")}))})}}}}),r}function Kgt(t,e,r,i,n,{spatialMaps:a,groupAlignments:s}){return new Promise(l=>{let u=Ze("body").append("div").attr("id","cy").attr("style","display:none"),h=Wl({container:document.getElementById("cy"),style:[{selector:"edge",style:{"curve-style":"straight","source-endpoint":"data(sourceEndpoint)","target-endpoint":"data(targetEndpoint)"}},{selector:"edge[label]",style:{label:"data(label)"}},{selector:"edge.segments",style:{"curve-style":"segments","segment-weights":"0","segment-distances":[.5],"edge-distances":"endpoints","source-endpoint":"data(sourceEndpoint)","target-endpoint":"data(targetEndpoint)"}},{selector:"node",style:{"compound-sizing-wrt-labels":"include"}},{selector:"node[label]",style:{"text-valign":"bottom","text-halign":"center","font-size":`${n.getConfigField("fontSize")}px`}},{selector:".node-service",style:{label:"data(label)",width:"data(width)",height:"data(height)"}},{selector:".node-junction",style:{width:"data(width)",height:"data(height)"}},{selector:".node-group",style:{padding:`${n.getConfigField("padding")}px`}}],layout:{name:"grid",boundingBox:{x1:0,x2:100,y1:0,y2:100}}});u.remove(),Hgt(r,h),qgt(t,h,n),Wgt(e,h,n),Ygt(i,h);let f=jgt(n,a,s),d=Xgt(a,n),p=h.layout({name:"fcose",quality:"proof",randomize:n.getConfigField("randomize"),styleEnabled:!1,animate:!1,nodeDimensionsIncludeLabels:!1,idealEdgeLength(m){let[g,y]=m.connectedNodes(),{parent:v}=Np(g),{parent:x}=Np(y);return v===x?1.5*n.getConfigField("iconSize"):.5*n.getConfigField("iconSize")},edgeElasticity(m){let[g,y]=m.connectedNodes(),{parent:v}=Np(g),{parent:x}=Np(y);return v===x?.45:.001},alignmentConstraint:f,relativePlacementConstraint:d});p.one("layoutstop",()=>{function m(g,y,v,x){let b,T,{x:w,y:k}=g,{x:C,y:E}=y;T=(x-k+(w-v)*(k-E)/(w-C))/Math.sqrt(1+Math.pow((k-E)/(w-C),2)),b=Math.sqrt(Math.pow(x-k,2)+Math.pow(v-w,2)-Math.pow(T,2));let S=Math.sqrt(Math.pow(C-w,2)+Math.pow(E-k,2));b=b/S;let L=(C-w)*(x-k)-(E-k)*(v-w);switch(!0){case L>=0:L=1;break;case L<0:L=-1;break}let M=(C-w)*(v-w)+(E-k)*(x-k);switch(!0){case M>=0:M=1;break;case M<0:M=-1;break}return T=Math.abs(T)*L,b=b*M,{distances:T,weights:b}}o(m,"getSegmentWeights"),h.startBatch();for(let g of Object.values(h.edges()))if(g.data?.()){let{x:y,y:v}=g.source().position(),{x,y:b}=g.target().position();if(y!==x&&v!==b){let T=g.sourceEndpoint(),w=g.targetEndpoint(),{sourceDir:k}=i8(g),[C,E]=hh(k)?[T.x,w.y]:[w.x,T.y],{weights:S,distances:L}=m(T,w,C,E);g.style("segment-distances",L),g.style("segment-weights",S)}}h.endBatch(),p.run()}),p.run(),h.ready(m=>{Q.info("Ready",m),l(h)})})}var jAe,Qgt,XAe,KAe=P(()=>{"use strict";gF();jAe=Wa(VAe(),1);Pr();bt();lu();ro();Xi();YH();n8();YAe();Q4([{name:yg.prefix,icons:yg}]);Wl.use(jAe.default);o(qgt,"addServices");o(Wgt,"addJunctions");o(Ugt,"positionNodes");o(Hgt,"addGroups");o(Ygt,"addEdges");o(jgt,"getAlignments");o(Xgt,"getRelativeConstraints");o(Kgt,"layoutArchitecture");Qgt=o(async(t,e,r,i)=>{let n=i.db;n.setDiagramId(e);let a=n.getServices(),s=n.getJunctions(),l=n.getGroups(),u=n.getEdges(),h=n.getDataStructures(),f=Fi(e),d=f.append("g");d.attr("class","architecture-edges");let p=f.append("g");p.attr("class","architecture-services");let m=f.append("g");m.attr("class","architecture-groups"),await UAe(n,p,a,e),HAe(n,p,s,e);let g=await Kgt(a,s,l,u,n,h);await qAe(d,g,n,e),await WAe(m,g,n,e),Ugt(n,g),El(void 0,f,n.getConfigField("padding"),n.getConfigField("useMaxWidth"))},"draw"),XAe={draw:Qgt}});var QAe={};ur(QAe,{diagram:()=>Zgt});var Zgt,ZAe=P(()=>{"use strict";$Ae();zH();GAe();KAe();Zgt={parser:GH,get db(){return new dx},renderer:XAe,styles:zAe}});var jH,t7e,r7e=P(()=>{"use strict";jH=(function(){var t=o(function(x,b,T,w){for(T=T||{},w=x.length;w--;T[x[w]]=b);return T},"o"),e=[1,4],r=[1,14],i=[1,12],n=[1,13],a=[6,7,8],s=[1,20],l=[1,18],u=[1,19],h=[6,7,11],f=[1,6,13,14],d=[1,23],p=[1,24],m=[1,6,7,11,13,14],g={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,ishikawa:4,spaceLines:5,SPACELINE:6,NL:7,ISHIKAWA:8,document:9,stop:10,EOF:11,statement:12,SPACELIST:13,TEXT:14,$accept:0,$end:1},terminals_:{2:"error",6:"SPACELINE",7:"NL",8:"ISHIKAWA",11:"EOF",13:"SPACELIST",14:"TEXT"},productions_:[0,[3,1],[3,2],[5,1],[5,2],[5,2],[4,2],[4,3],[10,1],[10,1],[10,1],[10,2],[10,2],[9,3],[9,2],[12,2],[12,1],[12,1],[12,1]],performAction:o(function(b,T,w,k,C,E,S){var L=E.length-1;switch(C){case 6:case 7:return k;case 15:k.addNode(E[L-1].length,E[L].trim());break;case 16:k.addNode(0,E[L].trim());break}},"anonymous"),table:[{3:1,4:2,5:3,6:[1,5],8:e},{1:[3]},{1:[2,1]},{4:6,6:[1,7],7:[1,8],8:e},{6:r,7:[1,10],9:9,12:11,13:i,14:n},t(a,[2,3]),{1:[2,2]},t(a,[2,4]),t(a,[2,5]),{1:[2,6],6:r,12:15,13:i,14:n},{6:r,9:16,12:11,13:i,14:n},{6:s,7:l,10:17,11:u},t(h,[2,18],{14:[1,21]}),t(h,[2,16]),t(h,[2,17]),{6:s,7:l,10:22,11:u},{1:[2,7],6:r,12:15,13:i,14:n},t(f,[2,14],{7:d,11:p}),t(m,[2,8]),t(m,[2,9]),t(m,[2,10]),t(h,[2,15]),t(f,[2,13],{7:d,11:p}),t(m,[2,11]),t(m,[2,12])],defaultActions:{2:[2,1],6:[2,2]},parseError:o(function(b,T){if(T.recoverable)this.trace(b);else{var w=new Error(b);throw w.hash=T,w}},"parseError"),parse:o(function(b){var T=this,w=[0],k=[],C=[null],E=[],S=this.table,L="",M=0,I=0,A=0,_=2,D=1,N=E.slice.call(arguments,1),R=Object.create(this.lexer),B={yy:{}};for(var O in this.yy)Object.prototype.hasOwnProperty.call(this.yy,O)&&(B.yy[O]=this.yy[O]);R.setInput(b,B.yy),B.yy.lexer=R,B.yy.parser=this,typeof R.yylloc>"u"&&(R.yylloc={});var $=R.yylloc;E.push($);var z=R.options&&R.options.ranges;typeof B.yy.parseError=="function"?this.parseError=B.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function F(Ee){w.length=w.length-2*Ee,C.length=C.length-Ee,E.length=E.length-Ee}o(F,"popStack");function V(){var Ee;return Ee=k.pop()||R.lex()||D,typeof Ee!="number"&&(Ee instanceof Array&&(k=Ee,Ee=k.pop()),Ee=T.symbols_[Ee]||Ee),Ee}o(V,"lex");for(var H,X,W,Z,Y,ae,J={},ee,re,te,be;;){if(W=w[w.length-1],this.defaultActions[W]?Z=this.defaultActions[W]:((H===null||typeof H>"u")&&(H=V()),Z=S[W]&&S[W][H]),typeof Z>"u"||!Z.length||!Z[0]){var de="";be=[];for(ee in S[W])this.terminals_[ee]&&ee>_&&be.push("'"+this.terminals_[ee]+"'");R.showPosition?de="Parse error on line "+(M+1)+`: +`+R.showPosition()+` +Expecting `+be.join(", ")+", got '"+(this.terminals_[H]||H)+"'":de="Parse error on line "+(M+1)+": Unexpected "+(H==D?"end of input":"'"+(this.terminals_[H]||H)+"'"),this.parseError(de,{text:R.match,token:this.terminals_[H]||H,line:R.yylineno,loc:$,expected:be})}if(Z[0]instanceof Array&&Z.length>1)throw new Error("Parse Error: multiple actions possible at state: "+W+", token: "+H);switch(Z[0]){case 1:w.push(H),C.push(R.yytext),E.push(R.yylloc),w.push(Z[1]),H=null,X?(H=X,X=null):(I=R.yyleng,L=R.yytext,M=R.yylineno,$=R.yylloc,A>0&&A--);break;case 2:if(re=this.productions_[Z[1]][1],J.$=C[C.length-re],J._$={first_line:E[E.length-(re||1)].first_line,last_line:E[E.length-1].last_line,first_column:E[E.length-(re||1)].first_column,last_column:E[E.length-1].last_column},z&&(J._$.range=[E[E.length-(re||1)].range[0],E[E.length-1].range[1]]),ae=this.performAction.apply(J,[L,I,M,B.yy,Z[1],C,E].concat(N)),typeof ae<"u")return ae;re&&(w=w.slice(0,-1*re*2),C=C.slice(0,-1*re),E=E.slice(0,-1*re)),w.push(this.productions_[Z[1]][0]),C.push(J.$),E.push(J._$),te=S[w[w.length-2]][w[w.length-1]],w.push(te);break;case 3:return!0}}return!0},"parse")},y=(function(){var x={EOF:1,parseError:o(function(T,w){if(this.yy.parser)this.yy.parser.parseError(T,w);else throw new Error(T)},"parseError"),setInput:o(function(b,T){return this.yy=T||this.yy||{},this._input=b,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var b=this._input[0];this.yytext+=b,this.yyleng++,this.offset++,this.match+=b,this.matched+=b;var T=b.match(/(?:\r\n?|\n).*/g);return T?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),b},"input"),unput:o(function(b){var T=b.length,w=b.split(/(?:\r\n?|\n)/g);this._input=b+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-T),this.offset-=T;var k=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),w.length-1&&(this.yylineno-=w.length-1);var C=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:w?(w.length===k.length?this.yylloc.first_column:0)+k[k.length-w.length].length-w[0].length:this.yylloc.first_column-T},this.options.ranges&&(this.yylloc.range=[C[0],C[0]+this.yyleng-T]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(b){this.unput(this.match.slice(b))},"less"),pastInput:o(function(){var b=this.matched.substr(0,this.matched.length-this.match.length);return(b.length>20?"...":"")+b.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var b=this.match;return b.length<20&&(b+=this._input.substr(0,20-b.length)),(b.substr(0,20)+(b.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var b=this.pastInput(),T=new Array(b.length+1).join("-");return b+this.upcomingInput()+` +`+T+"^"},"showPosition"),test_match:o(function(b,T){var w,k,C;if(this.options.backtrack_lexer&&(C={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(C.yylloc.range=this.yylloc.range.slice(0))),k=b[0].match(/(?:\r\n?|\n).*/g),k&&(this.yylineno+=k.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:k?k[k.length-1].length-k[k.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],w=this.performAction.call(this,this.yy,this,T,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),w)return w;if(this._backtrack){for(var E in C)this[E]=C[E];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var b,T,w,k;this._more||(this.yytext="",this.match="");for(var C=this._currentRules(),E=0;ET[0].length)){if(T=w,k=E,this.options.backtrack_lexer){if(b=this.test_match(w,C[E]),b!==!1)return b;if(this._backtrack){T=!1;continue}else return!1}else if(!this.options.flex)break}return T?(b=this.test_match(T,C[k]),b!==!1?b:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var T=this.next();return T||this.lex()},"lex"),begin:o(function(T){this.conditionStack.push(T)},"begin"),popState:o(function(){var T=this.conditionStack.length-1;return T>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(T){return T=this.conditionStack.length-1-Math.abs(T||0),T>=0?this.conditionStack[T]:"INITIAL"},"topState"),pushState:o(function(T){this.begin(T)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:o(function(T,w,k,C){var E=C;switch(k){case 0:return 6;case 1:return 8;case 2:return 8;case 3:return 6;case 4:return 7;case 5:return 13;case 6:return 14;case 7:return 11}},"anonymous"),rules:[/^(?:\s*%%.*)/i,/^(?:ishikawa-beta\b)/i,/^(?:ishikawa\b)/i,/^(?:[\s]+[\n])/i,/^(?:[\n]+)/i,/^(?:[\s]+)/i,/^(?:[^\n]+)/i,/^(?:$)/i],conditions:{INITIAL:{rules:[0,1,2,3,4,5,6,7],inclusive:!0}}};return x})();g.lexer=y;function v(){this.yy={}}return o(v,"Parser"),v.prototype=g,g.Parser=v,new v})();jH.parser=jH;t7e=jH});var a8,i7e=P(()=>{"use strict";Ut();Vr();Ki();a8=class{constructor(){this.stack=[];this.clear=this.clear.bind(this),this.addNode=this.addNode.bind(this),this.getRoot=this.getRoot.bind(this)}static{o(this,"IshikawaDB")}clear(){this.root=void 0,this.stack=[],this.baseLevel=void 0,wr()}getRoot(){return this.root}addNode(e,r){let i=lt.sanitizeText(r,ge());if(!this.root){this.root={text:i,children:[]},this.stack=[{level:0,node:this.root}],Mr(i);return}this.baseLevel??=e;let n=e-this.baseLevel+1;for(n<=0&&(n=1);this.stack.length>1&&this.stack[this.stack.length-1].level>=n;)this.stack.pop();let a=this.stack[this.stack.length-1].node,s={text:i,children:[]};a.children.push(s),this.stack.push({level:n,node:s})}getAccTitle(){return Dr()}setAccTitle(e){Ar(e)}getAccDescription(){return Rr()}setAccDescription(e){Lr(e)}getDiagramTitle(){return Nr()}setDiagramTitle(e){Mr(e)}}});var r1t,mx,i1t,n1t,a1t,c7e,n7e,a7e,s7e,s1t,o7e,o1t,l1t,c1t,XH,u1t,h1t,u7e,s8,l7e,gx,h7e,f7e=P(()=>{"use strict";Ut();ro();Xi();er();Yt();r1t=14,mx=250,i1t=30,n1t=60,a1t=5,c7e=82*Math.PI/180,n7e=Math.cos(c7e),a7e=Math.sin(c7e),s7e=o((t,e,r)=>{let i=t.node().getBBox(),n=i.width+e*2,a=i.height+e*2;Hr(t,a,n,r),t.attr("viewBox",`${i.x-e} ${i.y-e} ${n} ${a}`)},"applyPaddedViewBox"),s1t=o((t,e,r,i)=>{let a=i.db.getRoot();if(!a)return;let s=ge(),{look:l,handDrawnSeed:u,themeVariables:h}=s,f=$s(s.fontSize)[0]??r1t,d=l==="handDrawn",p=a.children??[],m=s.ishikawa?.diagramPadding??20,g=s.ishikawa?.useMaxWidth??!1,y=Fi(e),v=y.append("g").attr("class","ishikawa"),x=d?rt.svg(y.node()):void 0,b=x?{roughSvg:x,seed:u??0,lineColor:h?.lineColor??"#333",fillColor:h?.mainBkg??"#fff"}:void 0,T=`ishikawa-arrow-${e}`;d||v.append("defs").append("marker").attr("id",T).attr("viewBox","0 0 10 10").attr("refX",0).attr("refY",5).attr("markerWidth",6).attr("markerHeight",6).attr("orient","auto").append("path").attr("d","M 10 0 L 0 5 L 10 10 Z").attr("class","ishikawa-arrow");let w=0,k=mx,C=d?void 0:gx(v,w,k,w,k,"ishikawa-spine");if(o1t(v,w,k,a.text,f,b),!p.length){d&&gx(v,w,k,w,k,"ishikawa-spine",b),s7e(y,m,g);return}w-=20;let E=p.filter((R,B)=>B%2===0),S=p.filter((R,B)=>B%2===1),L=o7e(E),M=o7e(S),I=L.total+M.total,A=mx,_=mx;if(I>0){let R=mx*2,B=mx*.3;A=Math.max(B,R*(L.total/I)),_=Math.max(B,R*(M.total/I))}let D=f*2;A=Math.max(A,L.max*D),_=Math.max(_,M.max*D),k=Math.max(A,mx),C&&C.attr("y1",k).attr("y2",k),v.select(".ishikawa-head-group").attr("transform",`translate(0,${k})`);let N=Math.ceil(p.length/2);for(let R=0;RMath.min(O,$.getBBox().x),1/0)}if(d)gx(v,w,k,0,k,"ishikawa-spine",b);else{C.attr("x1",w);let R=`url(#${T})`;v.selectAll("line.ishikawa-branch, line.ishikawa-sub-branch").attr("marker-start",R)}s7e(y,m,g)},"draw"),o7e=o(t=>{let e=o(r=>r.children.reduce((i,n)=>i+1+e(n),0),"countDescendants");return t.reduce((r,i)=>{let n=e(i);return r.total+=n,r.max=Math.max(r.max,n),r},{total:0,max:0})},"sideStats"),o1t=o((t,e,r,i,n,a)=>{let s=Math.max(6,Math.floor(110/(n*.6))),l=t.append("g").attr("class","ishikawa-head-group").attr("transform",`translate(${e},${r})`),u=s8(l,u7e(i,s),0,0,"ishikawa-head-label","start",n),h=u.node().getBBox(),f=Math.max(60,h.width+6),d=Math.max(40,h.height*2+40),p=`M 0 ${-d/2} L 0 ${d/2} Q ${f*2.4} 0 0 ${-d/2} Z`;if(a){let m=a.roughSvg.path(p,{roughness:1.5,seed:a.seed,fill:a.fillColor,fillStyle:"hachure",fillWeight:2.5,hachureGap:5,stroke:a.lineColor,strokeWidth:2});l.insert(()=>m,":first-child").attr("class","ishikawa-head")}else l.insert("path",":first-child").attr("class","ishikawa-head").attr("d",p);u.attr("transform",`translate(${(f-h.width)/2-h.x+3},${-h.y-h.height/2})`)},"drawHead"),l1t=o((t,e)=>{let r=[],i=[],n=o((a,s,l)=>{let u=e===-1?[...a].reverse():a;for(let h of u){let f=r.length,d=h.children??[];r.push({depth:l,text:u7e(h.text,15),parentIndex:s,childCount:d.length}),l%2===0?(i.push(f),d.length&&n(d,f,l+1)):(d.length&&n(d,f,l+1),i.push(f))}},"walk");return n(t,-1,2),{entries:r,yOrder:i}},"flattenTree"),c1t=o((t,e,r,i,n,a,s)=>{let l=t.append("g").attr("class","ishikawa-label-group"),h=s8(l,e,r,i+11*n,"ishikawa-label cause","middle",a).node().getBBox();if(s){let f=s.roughSvg.rectangle(h.x-20,h.y-2,h.width+40,h.height+4,{roughness:1.5,seed:s.seed,fill:s.fillColor,fillStyle:"hachure",fillWeight:2.5,hachureGap:5,stroke:s.lineColor,strokeWidth:2});l.insert(()=>f,":first-child").attr("class","ishikawa-label-box")}else l.insert("rect",":first-child").attr("class","ishikawa-label-box").attr("x",h.x-20).attr("y",h.y-2).attr("width",h.width+40).attr("height",h.height+4)},"drawCauseLabel"),XH=o((t,e,r,i,n,a)=>{let s=Math.sqrt(i*i+n*n);if(s===0)return;let l=i/s,u=n/s,h=6,f=-u*h,d=l*h,p=e,m=r,g=`M ${p} ${m} L ${p-l*h*2+f} ${m-u*h*2+d} L ${p-l*h*2-f} ${m-u*h*2-d} Z`,y=a.roughSvg.path(g,{roughness:1,seed:a.seed,fill:a.lineColor,fillStyle:"solid",stroke:a.lineColor,strokeWidth:1});t.append(()=>y)},"drawArrowMarker"),u1t=o((t,e,r,i,n,a,s,l)=>{let u=e.children??[],h=a*(u.length?1:.2),f=-n7e*h,d=a7e*h*n,p=r+f,m=i+d;if(gx(t,r,i,p,m,"ishikawa-branch",l),l&&XH(t,r,i,r-p,i-m,l),c1t(t,e.text,p,m,n,s,l),!u.length)return;let{entries:g,yOrder:y}=l1t(u,n),v=g.length,x=new Array(v);for(let[C,E]of y.entries())x[E]=i+d*((C+1)/(v+1));let b=new Map;b.set(-1,{x0:r,y0:i,x1:p,y1:m,childCount:u.length,childrenDrawn:0});let T=-n7e,w=a7e*n,k=n<0?"ishikawa-label up":"ishikawa-label down";for(let[C,E]of g.entries()){let S=x[C],L=b.get(E.parentIndex),M=t.append("g").attr("class","ishikawa-sub-group"),I=0,A=0,_=0;if(E.depth%2===0){let D=L.y1-L.y0;I=l7e(L.x0,L.x1,D?(S-L.y0)/D:.5),A=S,_=I-(E.childCount>0?n1t+E.childCount*a1t:i1t),gx(M,I,S,_,S,"ishikawa-sub-branch",l),l&&XH(M,I,S,1,0,l),s8(M,E.text,_,S,"ishikawa-label align","end",s)}else{let D=L.childrenDrawn++;I=l7e(L.x0,L.x1,(L.childCount-D)/(L.childCount+1)),A=L.y0,_=I+T*((S-A)/w),gx(M,I,A,_,S,"ishikawa-sub-branch",l),l&&XH(M,I,A,I-_,A-S,l),s8(M,E.text,_,S,k,"end",s)}E.childCount>0&&b.set(C,{x0:I,y0:A,x1:_,y1:S,childCount:E.childCount,childrenDrawn:0})}},"drawBranch"),h1t=o(t=>t.split(/|\n/),"splitLines"),u7e=o((t,e)=>{if(t.length<=e)return t;let r=[];for(let i of t.split(/\s+/)){let n=r.length-1;n>=0&&r[n].length+1+i.length<=e?r[n]+=" "+i:r.push(i)}return r.join(` +`)},"wrapText"),s8=o((t,e,r,i,n,a,s)=>{let l=h1t(e),u=s*1.05,h=t.append("text").attr("class",n).attr("text-anchor",a).attr("x",r).attr("y",i-(l.length-1)*u/2);for(let[f,d]of l.entries())h.append("tspan").attr("x",r).attr("dy",f===0?0:u).text(d);return h},"drawMultilineText"),l7e=o((t,e,r)=>t+(e-t)*r,"lerp"),gx=o((t,e,r,i,n,a,s)=>{if(s){let l=s.roughSvg.line(e,r,i,n,{roughness:1.5,seed:s.seed,stroke:s.lineColor,strokeWidth:2});t.append(()=>l).attr("class",a);return}return t.append("line").attr("class",a).attr("x1",e).attr("y1",r).attr("x2",i).attr("y2",n)},"drawLine"),h7e={draw:s1t}});var f1t,d7e,p7e=P(()=>{"use strict";f1t=o(t=>` +.ishikawa .ishikawa-spine, +.ishikawa .ishikawa-branch, +.ishikawa .ishikawa-sub-branch { + stroke: ${t.lineColor}; + stroke-width: 2; + fill: none; +} + +.ishikawa .ishikawa-sub-branch { + stroke-width: 1; +} + +.ishikawa .ishikawa-arrow { + fill: ${t.lineColor}; +} + +.ishikawa .ishikawa-head { + fill: ${t.mainBkg}; + stroke: ${t.lineColor}; + stroke-width: 2; +} + +.ishikawa .ishikawa-label-box { + fill: ${t.mainBkg}; + stroke: ${t.lineColor}; + stroke-width: 2; +} + +.ishikawa text { + font-family: ${t.fontFamily}; + font-size: ${t.fontSize}; + fill: ${t.textColor}; +} + +.ishikawa .ishikawa-head-label { + font-weight: 600; + text-anchor: middle; + dominant-baseline: middle; + font-size: 14px; +} + +.ishikawa .ishikawa-label { + text-anchor: end; +} + +.ishikawa .ishikawa-label.cause { + text-anchor: middle; + dominant-baseline: middle; +} + +.ishikawa .ishikawa-label.align { + text-anchor: end; + dominant-baseline: middle; +} + +.ishikawa .ishikawa-label.up { + dominant-baseline: baseline; +} + +.ishikawa .ishikawa-label.down { + dominant-baseline: hanging; +} +`,"getStyles"),d7e=f1t});var m7e={};ur(m7e,{diagram:()=>d1t});var d1t,g7e=P(()=>{"use strict";r7e();i7e();f7e();p7e();d1t={parser:t7e,get db(){return new a8},renderer:h7e,styles:d7e}});var KH,x7e,b7e=P(()=>{"use strict";KH=(function(){var t=o(function(b,T,w,k){for(w=w||{},k=b.length;k--;w[b[k]]=T);return w},"o"),e=[5,8],r=[7,8,11,12,17,19,22,24],i=[1,17],n=[1,18],a=[7,8,11,12,14,15,16,17,19,20,21,22,24,27],s=[1,31],l=[1,39],u=[7,8,11,12,17,19,22,24,27],h=[1,57],f=[1,56],d=[1,58],p=[1,59],m=[1,60],g=[7,8,11,12,16,17,19,20,22,24,27,31,32,33],y={trace:o(function(){},"trace"),yy:{},symbols_:{error:2,start:3,optNewlines:4,VENN:5,document:6,EOF:7,NEWLINE:8,line:9,statement:10,TITLE:11,SET:12,identifier:13,BRACKET_LABEL:14,COLON:15,NUMERIC:16,UNION:17,identifierList:18,TEXT:19,IDENTIFIER:20,STRING:21,INDENT_TEXT:22,indentedTextTail:23,STYLE:24,stylesOpt:25,styleField:26,COMMA:27,styleValue:28,valueTokens:29,valueToken:30,HEXCOLOR:31,RGBCOLOR:32,RGBACOLOR:33,$accept:0,$end:1},terminals_:{2:"error",5:"VENN",7:"EOF",8:"NEWLINE",11:"TITLE",12:"SET",14:"BRACKET_LABEL",15:"COLON",16:"NUMERIC",17:"UNION",19:"TEXT",20:"IDENTIFIER",21:"STRING",22:"INDENT_TEXT",24:"STYLE",27:"COMMA",31:"HEXCOLOR",32:"RGBCOLOR",33:"RGBACOLOR"},productions_:[0,[3,4],[4,0],[4,2],[6,0],[6,2],[9,1],[9,1],[10,1],[10,2],[10,3],[10,4],[10,5],[10,2],[10,3],[10,4],[10,5],[10,3],[10,3],[10,3],[10,4],[10,4],[10,2],[10,3],[23,1],[23,1],[23,1],[23,2],[23,2],[25,1],[25,3],[26,3],[28,1],[28,1],[29,1],[29,2],[30,1],[30,1],[30,1],[30,1],[30,1],[18,1],[18,3],[13,1],[13,1]],performAction:o(function(T,w,k,C,E,S,L){var M=S.length-1;switch(E){case 1:return S[M-1];case 2:case 3:case 4:this.$=[];break;case 5:S[M-1].push(S[M]),this.$=S[M-1];break;case 6:this.$=[];break;case 7:case 22:case 32:case 36:case 37:case 38:case 39:case 40:this.$=S[M];break;case 8:C.setDiagramTitle(S[M].substr(6)),this.$=S[M].substr(6);break;case 9:C.addSubsetData([S[M]],void 0,void 0),C.setIndentMode&&C.setIndentMode(!0);break;case 10:C.addSubsetData([S[M-1]],S[M],void 0),C.setIndentMode&&C.setIndentMode(!0);break;case 11:C.addSubsetData([S[M-2]],void 0,parseFloat(S[M])),C.setIndentMode&&C.setIndentMode(!0);break;case 12:C.addSubsetData([S[M-3]],S[M-2],parseFloat(S[M])),C.setIndentMode&&C.setIndentMode(!0);break;case 13:if(S[M].length<2)throw new Error("union requires multiple identifiers");C.validateUnionIdentifiers&&C.validateUnionIdentifiers(S[M]),C.addSubsetData(S[M],void 0,void 0),C.setIndentMode&&C.setIndentMode(!0);break;case 14:if(S[M-1].length<2)throw new Error("union requires multiple identifiers");C.validateUnionIdentifiers&&C.validateUnionIdentifiers(S[M-1]),C.addSubsetData(S[M-1],S[M],void 0),C.setIndentMode&&C.setIndentMode(!0);break;case 15:if(S[M-2].length<2)throw new Error("union requires multiple identifiers");C.validateUnionIdentifiers&&C.validateUnionIdentifiers(S[M-2]),C.addSubsetData(S[M-2],void 0,parseFloat(S[M])),C.setIndentMode&&C.setIndentMode(!0);break;case 16:if(S[M-3].length<2)throw new Error("union requires multiple identifiers");C.validateUnionIdentifiers&&C.validateUnionIdentifiers(S[M-3]),C.addSubsetData(S[M-3],S[M-2],parseFloat(S[M])),C.setIndentMode&&C.setIndentMode(!0);break;case 17:case 18:case 19:C.addTextData(S[M-1],S[M],void 0);break;case 20:case 21:C.addTextData(S[M-2],S[M-1],S[M]);break;case 23:C.addStyleData(S[M-1],S[M]);break;case 24:case 25:case 26:var I=C.getCurrentSets();if(!I)throw new Error("text requires set");C.addTextData(I,S[M],void 0);break;case 27:case 28:var I=C.getCurrentSets();if(!I)throw new Error("text requires set");C.addTextData(I,S[M-1],S[M]);break;case 29:case 41:this.$=[S[M]];break;case 30:case 42:this.$=[...S[M-2],S[M]];break;case 31:this.$=[S[M-2],S[M]];break;case 33:this.$=S[M].join(" ");break;case 34:this.$=[S[M]];break;case 35:S[M-1].push(S[M]),this.$=S[M-1];break;case 43:case 44:this.$=S[M];break}},"anonymous"),table:[t(e,[2,2],{3:1,4:2}),{1:[3]},{5:[1,3],8:[1,4]},t(r,[2,4],{6:5}),t(e,[2,3]),{7:[1,6],8:[1,8],9:7,10:9,11:[1,10],12:[1,11],17:[1,12],19:[1,13],22:[1,14],24:[1,15]},{1:[2,1]},t(r,[2,5]),t(r,[2,6]),t(r,[2,7]),t(r,[2,8]),{13:16,20:i,21:n},{13:20,18:19,20:i,21:n},{13:20,18:21,20:i,21:n},{16:[1,25],20:[1,23],21:[1,24],23:22},{13:20,18:26,20:i,21:n},t(r,[2,9],{14:[1,27],15:[1,28]}),t(a,[2,43]),t(a,[2,44]),t(r,[2,13],{14:[1,29],15:[1,30],27:s}),t(a,[2,41]),{16:[1,34],20:[1,32],21:[1,33],27:s},t(r,[2,22]),t(r,[2,24],{14:[1,35]}),t(r,[2,25],{14:[1,36]}),t(r,[2,26]),{20:l,25:37,26:38,27:s},t(r,[2,10],{15:[1,40]}),{16:[1,41]},t(r,[2,14],{15:[1,42]}),{16:[1,43]},{13:44,20:i,21:n},t(r,[2,17],{14:[1,45]}),t(r,[2,18],{14:[1,46]}),t(r,[2,19]),t(r,[2,27]),t(r,[2,28]),t(r,[2,23],{27:[1,47]}),t(u,[2,29]),{15:[1,48]},{16:[1,49]},t(r,[2,11]),{16:[1,50]},t(r,[2,15]),t(a,[2,42]),t(r,[2,20]),t(r,[2,21]),{20:l,26:51},{16:h,20:f,21:[1,53],28:52,29:54,30:55,31:d,32:p,33:m},t(r,[2,12]),t(r,[2,16]),t(u,[2,30]),t(u,[2,31]),t(u,[2,32]),t(u,[2,33],{30:61,16:h,20:f,31:d,32:p,33:m}),t(g,[2,34]),t(g,[2,36]),t(g,[2,37]),t(g,[2,38]),t(g,[2,39]),t(g,[2,40]),t(g,[2,35])],defaultActions:{6:[2,1]},parseError:o(function(T,w){if(w.recoverable)this.trace(T);else{var k=new Error(T);throw k.hash=w,k}},"parseError"),parse:o(function(T){var w=this,k=[0],C=[],E=[null],S=[],L=this.table,M="",I=0,A=0,_=0,D=2,N=1,R=S.slice.call(arguments,1),B=Object.create(this.lexer),O={yy:{}};for(var $ in this.yy)Object.prototype.hasOwnProperty.call(this.yy,$)&&(O.yy[$]=this.yy[$]);B.setInput(T,O.yy),O.yy.lexer=B,O.yy.parser=this,typeof B.yylloc>"u"&&(B.yylloc={});var z=B.yylloc;S.push(z);var F=B.options&&B.options.ranges;typeof O.yy.parseError=="function"?this.parseError=O.yy.parseError:this.parseError=Object.getPrototypeOf(this).parseError;function V(Ne){k.length=k.length-2*Ne,E.length=E.length-Ne,S.length=S.length-Ne}o(V,"popStack");function H(){var Ne;return Ne=C.pop()||B.lex()||N,typeof Ne!="number"&&(Ne instanceof Array&&(C=Ne,Ne=C.pop()),Ne=w.symbols_[Ne]||Ne),Ne}o(H,"lex");for(var X,W,Z,Y,ae,J,ee={},re,te,be,de;;){if(Z=k[k.length-1],this.defaultActions[Z]?Y=this.defaultActions[Z]:((X===null||typeof X>"u")&&(X=H()),Y=L[Z]&&L[Z][X]),typeof Y>"u"||!Y.length||!Y[0]){var Ee="";de=[];for(re in L[Z])this.terminals_[re]&&re>D&&de.push("'"+this.terminals_[re]+"'");B.showPosition?Ee="Parse error on line "+(I+1)+`: +`+B.showPosition()+` +Expecting `+de.join(", ")+", got '"+(this.terminals_[X]||X)+"'":Ee="Parse error on line "+(I+1)+": Unexpected "+(X==N?"end of input":"'"+(this.terminals_[X]||X)+"'"),this.parseError(Ee,{text:B.match,token:this.terminals_[X]||X,line:B.yylineno,loc:z,expected:de})}if(Y[0]instanceof Array&&Y.length>1)throw new Error("Parse Error: multiple actions possible at state: "+Z+", token: "+X);switch(Y[0]){case 1:k.push(X),E.push(B.yytext),S.push(B.yylloc),k.push(Y[1]),X=null,W?(X=W,W=null):(A=B.yyleng,M=B.yytext,I=B.yylineno,z=B.yylloc,_>0&&_--);break;case 2:if(te=this.productions_[Y[1]][1],ee.$=E[E.length-te],ee._$={first_line:S[S.length-(te||1)].first_line,last_line:S[S.length-1].last_line,first_column:S[S.length-(te||1)].first_column,last_column:S[S.length-1].last_column},F&&(ee._$.range=[S[S.length-(te||1)].range[0],S[S.length-1].range[1]]),J=this.performAction.apply(ee,[M,A,I,O.yy,Y[1],E,S].concat(R)),typeof J<"u")return J;te&&(k=k.slice(0,-1*te*2),E=E.slice(0,-1*te),S=S.slice(0,-1*te)),k.push(this.productions_[Y[1]][0]),E.push(ee.$),S.push(ee._$),be=L[k[k.length-2]][k[k.length-1]],k.push(be);break;case 3:return!0}}return!0},"parse")},v=(function(){var b={EOF:1,parseError:o(function(w,k){if(this.yy.parser)this.yy.parser.parseError(w,k);else throw new Error(w)},"parseError"),setInput:o(function(T,w){return this.yy=w||this.yy||{},this._input=T,this._more=this._backtrack=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},"setInput"),input:o(function(){var T=this._input[0];this.yytext+=T,this.yyleng++,this.offset++,this.match+=T,this.matched+=T;var w=T.match(/(?:\r\n?|\n).*/g);return w?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),T},"input"),unput:o(function(T){var w=T.length,k=T.split(/(?:\r\n?|\n)/g);this._input=T+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-w),this.offset-=w;var C=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),k.length-1&&(this.yylineno-=k.length-1);var E=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:k?(k.length===C.length?this.yylloc.first_column:0)+C[C.length-k.length].length-k[0].length:this.yylloc.first_column-w},this.options.ranges&&(this.yylloc.range=[E[0],E[0]+this.yyleng-w]),this.yyleng=this.yytext.length,this},"unput"),more:o(function(){return this._more=!0,this},"more"),reject:o(function(){if(this.options.backtrack_lexer)this._backtrack=!0;else return this.parseError("Lexical error on line "+(this.yylineno+1)+`. You can only invoke reject() in the lexer when the lexer is of the backtracking persuasion (options.backtrack_lexer = true). +`+this.showPosition(),{text:"",token:null,line:this.yylineno});return this},"reject"),less:o(function(T){this.unput(this.match.slice(T))},"less"),pastInput:o(function(){var T=this.matched.substr(0,this.matched.length-this.match.length);return(T.length>20?"...":"")+T.substr(-20).replace(/\n/g,"")},"pastInput"),upcomingInput:o(function(){var T=this.match;return T.length<20&&(T+=this._input.substr(0,20-T.length)),(T.substr(0,20)+(T.length>20?"...":"")).replace(/\n/g,"")},"upcomingInput"),showPosition:o(function(){var T=this.pastInput(),w=new Array(T.length+1).join("-");return T+this.upcomingInput()+` +`+w+"^"},"showPosition"),test_match:o(function(T,w){var k,C,E;if(this.options.backtrack_lexer&&(E={yylineno:this.yylineno,yylloc:{first_line:this.yylloc.first_line,last_line:this.last_line,first_column:this.yylloc.first_column,last_column:this.yylloc.last_column},yytext:this.yytext,match:this.match,matches:this.matches,matched:this.matched,yyleng:this.yyleng,offset:this.offset,_more:this._more,_input:this._input,yy:this.yy,conditionStack:this.conditionStack.slice(0),done:this.done},this.options.ranges&&(E.yylloc.range=this.yylloc.range.slice(0))),C=T[0].match(/(?:\r\n?|\n).*/g),C&&(this.yylineno+=C.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:C?C[C.length-1].length-C[C.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+T[0].length},this.yytext+=T[0],this.match+=T[0],this.matches=T,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._backtrack=!1,this._input=this._input.slice(T[0].length),this.matched+=T[0],k=this.performAction.call(this,this.yy,this,w,this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),k)return k;if(this._backtrack){for(var S in E)this[S]=E[S];return!1}return!1},"test_match"),next:o(function(){if(this.done)return this.EOF;this._input||(this.done=!0);var T,w,k,C;this._more||(this.yytext="",this.match="");for(var E=this._currentRules(),S=0;Sw[0].length)){if(w=k,C=S,this.options.backtrack_lexer){if(T=this.test_match(k,E[S]),T!==!1)return T;if(this._backtrack){w=!1;continue}else return!1}else if(!this.options.flex)break}return w?(T=this.test_match(w,E[C]),T!==!1?T:!1):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text. +`+this.showPosition(),{text:"",token:null,line:this.yylineno})},"next"),lex:o(function(){var w=this.next();return w||this.lex()},"lex"),begin:o(function(w){this.conditionStack.push(w)},"begin"),popState:o(function(){var w=this.conditionStack.length-1;return w>0?this.conditionStack.pop():this.conditionStack[0]},"popState"),_currentRules:o(function(){return this.conditionStack.length&&this.conditionStack[this.conditionStack.length-1]?this.conditions[this.conditionStack[this.conditionStack.length-1]].rules:this.conditions.INITIAL.rules},"_currentRules"),topState:o(function(w){return w=this.conditionStack.length-1-Math.abs(w||0),w>=0?this.conditionStack[w]:"INITIAL"},"topState"),pushState:o(function(w){this.begin(w)},"pushState"),stateStackSize:o(function(){return this.conditionStack.length},"stateStackSize"),options:{"case-insensitive":!0},performAction:o(function(w,k,C,E){var S=E;switch(C){case 0:break;case 1:break;case 2:break;case 3:if(w.getIndentMode&&w.getIndentMode())return w.consumeIndentText=!0,this.begin("INITIAL"),22;break;case 4:break;case 5:w.setIndentMode&&w.setIndentMode(!1),this.begin("INITIAL"),this.unput(k.yytext);break;case 6:return this.begin("bol"),8;break;case 7:break;case 8:break;case 9:return 7;case 10:return 11;case 11:return 5;case 12:return 12;case 13:return 17;case 14:if(w.consumeIndentText)w.consumeIndentText=!1;else return 19;break;case 15:return 24;case 16:return k.yytext=k.yytext.slice(2,-2),14;break;case 17:return k.yytext=k.yytext.slice(1,-1).trim(),14;break;case 18:return 16;case 19:return 31;case 20:return 33;case 21:return 32;case 22:return 20;case 23:return 21;case 24:return 27;case 25:return 15}},"anonymous"),rules:[/^(?:%%(?!\{)[^\n]*)/i,/^(?:[^\}]%%[^\n]*)/i,/^(?:[ \t]+(?=[\n\r]))/i,/^(?:[ \t]+(?=text\b))/i,/^(?:[ \t]+)/i,/^(?:[^ \t\n\r])/i,/^(?:[\n\r]+)/i,/^(?:%%[^\n]*)/i,/^(?:[ \t]+)/i,/^(?:$)/i,/^(?:title\s[^#\n;]+)/i,/^(?:venn-beta\b)/i,/^(?:set\b)/i,/^(?:union\b)/i,/^(?:text\b)/i,/^(?:style\b)/i,/^(?:\["[^\"]*"\])/i,/^(?:\[[^\]\"]+\])/i,/^(?:[+-]?(\d+(\.\d+)?|\.\d+))/i,/^(?:#[0-9a-fA-F]{3,8})/i,/^(?:rgba\(\s*[0-9.]+\s*[,]\s*[0-9.]+\s*[,]\s*[0-9.]+\s*[,]\s*[0-9.]+\s*\))/i,/^(?:rgb\(\s*[0-9.]+\s*[,]\s*[0-9.]+\s*[,]\s*[0-9.]+\s*\))/i,/^(?:[A-Za-z_][A-Za-z0-9\-_]*)/i,/^(?:"[^\"]*")/i,/^(?:,)/i,/^(?::)/i],conditions:{bol:{rules:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25],inclusive:!0},INITIAL:{rules:[0,1,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25],inclusive:!0}}};return b})();y.lexer=v;function x(){this.yy={}}return o(x,"Parser"),x.prototype=y,y.Parser=x,new x})();KH.parser=KH;x7e=KH});function _1t(){return fi(A1t,Lt().venn)}var QH,ZH,JH,eY,tY,rY,g1t,y1t,QC,v1t,x1t,b1t,T1t,o8,k1t,C1t,w1t,E1t,S1t,A1t,D1t,T7e,k7e=P(()=>{"use strict";er();Sr();Ki();wa();QH=[],ZH=[],JH=[],eY=new Set,rY=!1,g1t=o((t,e,r)=>{let i=o8(t).sort(),n=r??10/Math.pow(t.length,2);tY=i,i.length===1&&eY.add(i[0]),QH.push({sets:i,size:n,label:e?QC(e):void 0})},"addSubsetData"),y1t=o(()=>QH,"getSubsetData"),QC=o(t=>{let e=t.trim();return e.length>=2&&e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e},"normalizeText"),v1t=o(t=>t&&QC(t),"normalizeStyleValue"),x1t=o((t,e,r)=>{let i=QC(e);ZH.push({sets:o8(t).sort(),id:i,label:r?QC(r):void 0})},"addTextData"),b1t=o((t,e)=>{let r=o8(t).sort(),i={};for(let[n,a]of e)i[n]=v1t(a)??a;JH.push({targets:r,styles:i})},"addStyleData"),T1t=o(()=>JH,"getStyleData"),o8=o(t=>t.map(e=>QC(e)),"normalizeIdentifierList"),k1t=o(t=>{let r=o8(t).filter(i=>!eY.has(i));if(r.length>0)throw new Error(`unknown set identifier: ${r.join(", ")}`)},"validateUnionIdentifiers"),C1t=o(()=>ZH,"getTextData"),w1t=o(()=>tY,"getCurrentSets"),E1t=o(()=>rY,"getIndentMode"),S1t=o(t=>{rY=t},"setIndentMode"),A1t=fr.venn;o(_1t,"getConfig");D1t=o(()=>{wr(),QH.length=0,ZH.length=0,JH.length=0,eY.clear(),tY=void 0,rY=!1},"customClear"),T7e={getConfig:_1t,clear:D1t,setAccTitle:Ar,getAccTitle:Dr,setDiagramTitle:Mr,getDiagramTitle:Nr,getAccDescription:Rr,setAccDescription:Lr,addSubsetData:g1t,getSubsetData:y1t,addTextData:x1t,addStyleData:b1t,validateUnionIdentifiers:k1t,getTextData:C1t,getStyleData:T1t,getCurrentSets:w1t,getIndentMode:E1t,setIndentMode:S1t}});var L1t,C7e,w7e=P(()=>{"use strict";L1t=o(t=>` + .venn-title { + font-size: 32px; + fill: ${t.vennTitleTextColor}; + font-family: ${t.fontFamily}; + } + + .venn-circle text { + font-size: 48px; + font-family: ${t.fontFamily}; + } + + .venn-intersection text { + font-size: 48px; + fill: ${t.vennSetTextColor}; + font-family: ${t.fontFamily}; + } + + .venn-text-node { + font-family: ${t.fontFamily}; + color: ${t.vennSetTextColor}; + } +`,"getStyles"),C7e=L1t});function l8(t,e){let r=N1t(t),i=r.filter(l=>R1t(l,t)),n=0,a=0,s=[];if(i.length>1){let l=_7e(i);for(let h=0;hf.angle-h.angle);let u=i[i.length-1];for(let h=0;hg.radius*2&&(T=g.radius*2),(p==null||p.width>T)&&(p={circle:g,width:T,p1:f,p2:u,large:T>g.radius,sweep:!0})}p!=null&&(s.push(p),n+=aY(p.circle.radius,p.width),u=f)}}else{let l=t[0];for(let h=1;hMath.abs(l.radius-t[h].radius)){u=!0;break}u?n=a=0:(n=l.radius*l.radius*Math.PI,s.push({circle:l,p1:{x:l.x,y:l.y+l.radius},p2:{x:l.x-1e-10,y:l.y+l.radius},width:l.radius*2,large:!0,sweep:!0}))}return a/=2,e&&(e.area=n+a,e.arcArea=n,e.polygonArea=a,e.arcs=s,e.innerPoints=i,e.intersectionPoints=r),n+a}function R1t(t,e){return e.every(r=>qo(t,r)=t+e)return 0;if(r<=Math.abs(t-e))return Math.PI*Math.min(t,e)*Math.min(t,e);let i=t-(r*r-e*e+t*t)/(2*r),n=e-(r*r-t*t+e*e)/(2*r);return aY(t,i)+aY(e,n)}function A7e(t,e){let r=qo(t,e),i=t.radius,n=e.radius;if(r>=i+n||r<=Math.abs(i-n))return[];let a=(i*i-n*n+r*r)/(2*r),s=Math.sqrt(i*i-a*a),l=t.x+a*(e.x-t.x)/r,u=t.y+a*(e.y-t.y)/r,h=-(e.y-t.y)*(s/r),f=-(e.x-t.x)*(s/r);return[{x:l+h,y:u-f},{x:l-h,y:u+f}]}function _7e(t){let e={x:0,y:0};for(let r of t)e.x+=r.x,e.y+=r.y;return e.x/=t.length,e.y/=t.length,e}function I1t(t,e,r,i){i=i||{};let n=i.maxIterations||100,a=i.tolerance||1e-10,s=t(e),l=t(r),u=r-e;if(s*l>0)throw"Initial bisect points must have opposite signs";if(s===0)return e;if(l===0)return r;for(let h=0;h=0&&(e=f),Math.abs(u)sY(e))}function yx(t,e){let r=0;for(let i=0;ik.fx-C.fx,"sortOrder"),x=e.slice(),b=e.slice(),T=e.slice(),w=e.slice();for(let k=0;k{let L=S.slice();return L.fx=S.fx,L.id=S.id,L});E.sort((S,L)=>S.id-L.id),r.history.push({x:g[0].slice(),fx:g[0].fx,simplex:E})}p=0;for(let E=0;E=g[m-1].fx){let E=!1;if(b.fx>C.fx?(_f(T,1+f,x,-f,C),T.fx=t(T),T.fx=1)break;for(let S=1;Sl+a*n*u||h>=v)y=n;else{if(Math.abs(d)<=-s*u)return n;d*(y-g)>=0&&(y=g),g=n,v=h}return 0}o(m,"zoom");for(let g=0;g<10;++g){if(_f(i.x,1,r.x,n,e),h=i.fx=t(i.x,i.fxprime),d=yx(i.fxprime,e),h>l+a*n*u||g&&h>=f)return m(p,n,f);if(Math.abs(d)<=-s*u)return n;if(d>=0)return m(n,p,h);f=h,p=n,n*=2}return n}function O1t(t,e,r){let i={x:e.slice(),fx:0,fxprime:e.slice()},n={x:e.slice(),fx:0,fxprime:e.slice()},a=e.slice(),s,l,u=1,h;r=r||{},h=r.maxIterations||e.length*20,i.fx=t(i.x,i.fxprime),s=i.fxprime.slice(),lY(s,i.fxprime,-1);for(let f=0;f{let d={};for(let p=0;phY(t,e,i)-r,0,t+e)}function P1t(t,e={}){let r=e.distinct,i=t.map(l=>Object.assign({},l));function n(l){return l.join(";")}if(o(n,"toKey"),r){let l=new Map;for(let u of i)for(let h=0;hl===u?0:la.sets.length===2).forEach(a=>{let s=r[a.sets[0]],l=r[a.sets[1]],u=Math.sqrt(e[s].size/Math.PI),h=Math.sqrt(e[l].size/Math.PI),f=cY(u,h,a.size);i[s][l]=i[l][s]=f;let d=0;a.size+1e-10>=Math.min(e[s].size,e[l].size)?d=1:a.size<=1e-10&&(d=-1),n[s][l]=n[l][s]=d}),{distances:i,constraints:n}}function F1t(t,e,r,i){for(let a=0;a0&&g<=d||p<0&&g>=d||(n+=2*y*y,e[2*a]+=4*y*(s-h),e[2*a+1]+=4*y*(l-f),e[2*u]+=4*y*(h-s),e[2*u+1]+=4*y*(f-l))}}return n}function $1t(t,e={}){let r=G1t(t,e),i=e.lossFunction||vx;if(t.length>=8){let n=z1t(t,e),a=i(n,t),s=i(r,t);a+1e-8p.map(m=>m/l));let u=o((p,m)=>F1t(p,m,a,s),"obj"),h=null;for(let p=0;pd.sets.length===2);for(let d of t){let p=d.weight!=null?d.weight:1,m=d.sets[0],g=d.sets[1];d.size+R7e>=Math.min(i[m].size,i[g].size)&&(p=0),n[m].push({set:g,size:d.size,weight:p}),n[g].push({set:m,size:d.size,weight:p})}let a=[];Object.keys(n).forEach(d=>{let p=0;for(let m=0;mt[s]));let a=i.weight!=null?i.weight:1;r+=a*(n-i.size)*(n-i.size)}return r}function N7e(t,e){let r=0;for(let i of e){if(i.sets.length===1)continue;let n;if(i.sets.length===2){let l=t[i.sets[0]],u=t[i.sets[1]];n=hY(l.radius,u.radius,qo(l,u))}else n=l8(i.sets.map(l=>t[l]));let a=i.weight!=null?i.weight:1,s=Math.log((n+1)/(i.size+1));r+=a*s*s}return r}function V1t(t,e,r){if(r==null?t.sort((n,a)=>a.radius-n.radius):t.sort(r),t.length>0){let n=t[0].x,a=t[0].y;for(let s of t)s.x-=n,s.y-=a}if(t.length===2&&qo(t[0],t[1])1){let n=Math.atan2(t[1].x,t[1].y)-e,a=Math.cos(n),s=Math.sin(n);for(let l of t){let u=l.x,h=l.y;l.x=a*u-s*h,l.y=s*u+a*h}}if(t.length>2){let n=Math.atan2(t[2].x,t[2].y)-e;for(;n<0;)n+=2*Math.PI;for(;n>2*Math.PI;)n-=2*Math.PI;if(n>Math.PI){let a=t[1].y/(1e-10+t[1].x);for(let s of t){var i=(s.x+a*s.y)/(1+a*a);s.x=2*i-s.x,s.y=2*i*a-s.y}}}}function q1t(t){t.forEach(n=>{n.parent=n});function e(n){return n.parent!==n&&(n.parent=e(n.parent)),n.parent}o(e,"find");function r(n,a){let s=e(n),l=e(a);s.parent=l}o(r,"union");for(let n=0;n{delete n.parent}),Array.from(i.values())}function uY(t){let e=o(r=>{let i=t.reduce((a,s)=>Math.max(a,s[r]+s.radius),Number.NEGATIVE_INFINITY),n=t.reduce((a,s)=>Math.min(a,s[r]-s.radius),Number.POSITIVE_INFINITY);return{max:i,min:n}},"minMax");return{xRange:e("x"),yRange:e("y")}}function I7e(t,e,r){e==null&&(e=Math.PI/2);let i=P7e(t).map(h=>Object.assign({},h)),n=q1t(i);for(let h of n){V1t(h,e,r);let f=uY(h);h.size=(f.xRange.max-f.xRange.min)*(f.yRange.max-f.yRange.min),h.bounds=f}n.sort((h,f)=>f.size-h.size),i=n[0];let a=i.bounds,s=(a.xRange.max-a.xRange.min)/50;function l(h,f,d){if(!h)return;let p=h.bounds,m,g;if(f)m=a.xRange.max-p.xRange.min+s;else{m=a.xRange.max-p.xRange.max;let y=(p.xRange.max-p.xRange.min)/2-(a.xRange.max-a.xRange.min)/2;y<0&&(m+=y)}if(d)g=a.yRange.max-p.yRange.min+s;else{g=a.yRange.max-p.yRange.max;let y=(p.yRange.max-p.yRange.min)/2-(a.yRange.max-a.yRange.min)/2;y<0&&(g+=y)}for(let y of h)y.x+=m,y.y+=g,i.push(y)}o(l,"addCluster");let u=1;for(;u({radius:f*m.radius,x:i+d+(m.x-s.min)*f,y:i+p+(m.y-l.min)*f,setid:m.setid})))}function O7e(t){let e={};for(let r of t)e[r.setid]=r;return e}function P7e(t){return Object.keys(t).map(r=>Object.assign(t[r],{setid:r}))}function B7e(t={}){let e=!1,r=600,i=350,n=15,a=1e3,s=Math.PI/2,l=!0,u=null,h=!0,f=!0,d=null,p=null,m=!1,g=null,y=t&&t.symmetricalTextCentre?t.symmetricalTextCentre:!1,v={},x=t&&t.colourScheme?t.colourScheme:t&&t.colorScheme?t.colorScheme:["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],b=0,T=o(function(E){if(E in v)return v[E];var S=v[E]=x[b];return b+=1,b>=x.length&&(b=0),S},"colours"),w=L7e,k=vx;function C(E){let S=E.datum(),L=new Set;S.forEach(Y=>{Y.size==0&&Y.sets.length==1&&L.add(Y.sets[0])}),S=S.filter(Y=>!Y.sets.some(ae=>L.has(ae)));let M={},I={};if(S.length>0){let Y=w(S,{lossFunction:k,distinct:m});l&&(Y=I7e(Y,s,p)),M=M7e(Y,r,i,n,u),I=$7e(M,S,y)}let A={};S.forEach(Y=>{Y.label&&(A[Y.sets]=Y.label)});function _(Y){if(Y.sets in A)return A[Y.sets];if(Y.sets.length==1)return""+Y.sets[0]}o(_,"label"),E.selectAll("svg").data([M]).enter().append("svg");let D=E.select("svg");e?D.attr("viewBox",`0 0 ${r} ${i}`):D.attr("width",r).attr("height",i);let N={},R=!1;D.selectAll(".venn-area path").each(function(Y){let ae=this.getAttribute("d");Y.sets.length==1&&ae&&!m&&(R=!0,N[Y.sets[0]]=H1t(ae))});function B(Y){return ae=>{let J=Y.sets.map(ee=>{let re=N[ee],te=M[ee];return re||(re={x:r/2,y:i/2,radius:1}),te||(te={x:r/2,y:i/2,radius:1}),{x:re.x*(1-ae)+te.x*ae,y:re.y*(1-ae)+te.y*ae,radius:re.radius*(1-ae)+te.radius*ae}});return S7e(J,g)}}o(B,"pathTween");let O=D.selectAll(".venn-area").data(S,Y=>Y.sets),$=O.enter().append("g").attr("class",Y=>`venn-area venn-${Y.sets.length==1?"circle":"intersection"}${Y.colour||Y.color?" venn-coloured":""}`).attr("data-venn-sets",Y=>Y.sets.join("_")),z=$.append("path"),F=$.append("text").attr("class","label").text(Y=>_(Y)).attr("text-anchor","middle").attr("dy",".35em").attr("x",r/2).attr("y",i/2);f&&(z.style("fill-opacity","0").filter(Y=>Y.sets.length==1).style("fill",Y=>Y.colour?Y.colour:Y.color?Y.color:T(Y.sets)).style("fill-opacity",".25"),F.style("fill",Y=>Y.colour||Y.color?"#FFF":t.textFill?t.textFill:Y.sets.length==1?T(Y.sets):"#444"));function V(Y){return typeof Y.transition=="function"?Y.transition("venn").duration(a):Y}o(V,"asTransition");let H=E;R&&typeof H.transition=="function"?(H=V(E),H.selectAll("path").attrTween("d",B)):H.selectAll("path").attr("d",Y=>S7e(Y.sets.map(ae=>M[ae])),g);let X=H.selectAll("text").filter(Y=>Y.sets in I).text(Y=>_(Y)).attr("x",Y=>Math.floor(I[Y.sets].x)).attr("y",Y=>Math.floor(I[Y.sets].y));h&&(R?"on"in X?X.on("end",iY(M,_)):X.each("end",iY(M,_)):X.each(iY(M,_)));let W=V(O.exit()).remove();typeof O.transition=="function"&&W.selectAll("path").attrTween("d",B);let Z=W.selectAll("text").attr("x",r/2).attr("y",i/2);return d!==null&&(F.style("font-size","0px"),X.style("font-size",d),Z.style("font-size","0px")),{circles:M,textCentres:I,nodes:O,enter:$,update:H,exit:W}}return o(C,"chart"),C.wrap=function(E){return arguments.length?(h=E,C):h},C.useViewBox=function(){return e=!0,C},C.width=function(E){return arguments.length?(r=E,C):r},C.height=function(E){return arguments.length?(i=E,C):i},C.padding=function(E){return arguments.length?(n=E,C):n},C.distinct=function(E){return arguments.length?(m=E,C):m},C.colours=function(E){return arguments.length?(T=E,C):T},C.colors=function(E){return arguments.length?(T=E,C):T},C.fontSize=function(E){return arguments.length?(d=E,C):d},C.round=function(E){return arguments.length?(g=E,C):g},C.duration=function(E){return arguments.length?(a=E,C):a},C.layoutFunction=function(E){return arguments.length?(w=E,C):w},C.normalize=function(E){return arguments.length?(l=E,C):l},C.scaleToFit=function(E){return arguments.length?(u=E,C):u},C.styled=function(E){return arguments.length?(f=E,C):f},C.orientation=function(E){return arguments.length?(s=E,C):s},C.orientationOrder=function(E){return arguments.length?(p=E,C):p},C.lossFunction=function(E){return arguments.length?(k=E==="default"?vx:E==="logRatio"?N7e:E,C):k},C}function iY(t,e){return function(r){let i=this,n=t[r.sets[0]].radius||50,a=e(r)||"",s=a.split(/\s+/).reverse(),u=(a.length+s.length)/3,h=s.pop(),f=[h],d=0,p=1.1;i.textContent=null;let m=[];function g(T){let w=i.ownerDocument.createElementNS(i.namespaceURI,"tspan");return w.textContent=T,m.push(w),i.append(w),w}o(g,"append");let y=g(h);for(;h=s.pop(),!!h;){f.push(h);let T=f.join(" ");y.textContent=T,T.length>u&&y.getComputedTextLength()>n&&(f.pop(),y.textContent=f.join(" "),f=[h],y=g(h),d++)}let v=.35-d*p/2,x=i.getAttribute("x"),b=i.getAttribute("y");m.forEach((T,w)=>{T.setAttribute("x",x),T.setAttribute("y",b),T.setAttribute("dy",`${v+w*p}em`)})}}function nY(t,e,r){let i=e[0].radius-qo(e[0],t);for(let n=1;n=a&&(n=i[f],a=d)}let s=D7e(f=>-1*nY({x:f[0],y:f[1]},t,e),[n.x,n.y],{maxIterations:500,minErrorDelta:1e-10}).x,l={x:r?0:s[0],y:s[1]},u=!0;for(let f of t)if(qo(l,f)>f.radius){u=!1;break}for(let f of e)if(qo(l,f)f.p1))}function W1t(t){let e={},r=Object.keys(t);for(let i of r)e[i]=[];for(let i=0;i0&&console.log("WARNING: area "+s+" not represented on screen")}return i}function U1t(t,e,r){let i=[];return i.push(` +M`,t,e),i.push(` +m`,-r,0),i.push(` +a`,r,r,0,1,0,r*2,0),i.push(` +a`,r,r,0,1,0,-r*2,0),i.join(" ")}function H1t(t){let e=t.split(" ");return{x:Number.parseFloat(e[1]),y:Number.parseFloat(e[2]),radius:-Number.parseFloat(e[4])}}function z7e(t){if(t.length===0)return[];let e={};return l8(t,e),e.arcs}function G7e(t,e){if(t.length===0)return"M 0 0";let r=Math.pow(10,e||0),i=e!=null?a=>Math.round(a*r)/r:a=>a;if(t.length==1){let a=t[0].circle;return U1t(i(a.x),i(a.y),i(a.radius))}let n=[` +M`,i(t[0].p2.x),i(t[0].p2.y)];for(let a of t){let s=i(a.circle.radius);n.push(` +A`,s,s,0,a.large?1:0,a.sweep?1:0,i(a.p1.x),i(a.p1.y))}return n.join(" ")}function S7e(t,e){return G7e(z7e(t),e)}function V7e(t,e={}){let{lossFunction:r,layoutFunction:i=L7e,normalize:n=!0,orientation:a=Math.PI/2,orientationOrder:s,width:l=600,height:u=350,padding:h=15,scaleToFit:f=!1,symmetricalTextCentre:d=!1,distinct:p,round:m=2}=e,g=i(t,{lossFunction:r==="default"||!r?vx:r==="logRatio"?N7e:r,distinct:p});n&&(g=I7e(g,a,s));let y=M7e(g,l,u,h,f),v=$7e(y,t,d),x=new Map(Object.keys(y).map(w=>[w,{set:w,x:y[w].x,y:y[w].y,radius:y[w].radius}])),b=t.map(w=>{let k=w.sets.map(S=>x.get(S)),C=z7e(k),E=G7e(C,m);return{circles:k,arcs:C,path:E,area:w,has:new Set(w.sets)}});function T(w){let k="";for(let C of b)C.has.size>w.length&&w.every(E=>C.has.has(E))&&(k+=" "+C.path);return k}return o(T,"genDistinctPath"),b.map(({circles:w,arcs:k,path:C,area:E})=>({data:E,text:v[E.sets],circles:w,arcs:k,path:C,distinctPath:C+T(E.sets)}))}var R7e,q7e=P(()=>{"use strict";o(l8,"intersectionArea");o(R1t,"containedInCircles");o(N1t,"getIntersectionPoints");o(aY,"circleArea");o(qo,"distance");o(hY,"circleOverlap");o(A7e,"circleCircleIntersection");o(_7e,"getCenter");o(I1t,"bisect");o(sY,"zeros");o(E7e,"zerosM");o(yx,"dot");o(oY,"norm2");o(lY,"scale");o(_f,"weightedSum");o(D7e,"nelderMead");o(M1t,"wolfeLineSearch");o(O1t,"conjugateGradient");o(L7e,"venn");R7e=1e-10;o(cY,"distanceFromIntersectArea");o(P1t,"addMissingAreas");o(B1t,"getDistanceMatrices");o(F1t,"constrainedMDSGradient");o($1t,"bestInitialLayout");o(z1t,"constrainedMDSLayout");o(G1t,"greedyLayout");o(vx,"lossFunction");o(N7e,"logRatioLossFunction");o(V1t,"orientateCircles");o(q1t,"disjointCluster");o(uY,"getBoundingBox");o(I7e,"normalizeSolution");o(M7e,"scaleSolution");o(O7e,"toObjectNotation");o(P7e,"fromObjectNotation");o(B7e,"VennDiagram");o(iY,"wrapText");o(nY,"circleMargin");o(F7e,"computeTextCentre");o(W1t,"getOverlappingCircles");o($7e,"computeTextCentres");o(U1t,"circlePath");o(H1t,"circleFromPath");o(z7e,"intersectionAreaArcs");o(G7e,"arcsToPath");o(S7e,"intersectionAreaPath");o(V7e,"layout")});function j1t(t){let e=new Map;for(let r of t){let i=r.targets.join("|"),n=e.get(i);n?Object.assign(n,r.styles):e.set(i,{...r.styles})}return e}function vg(t){return t.join("|")}function K1t(t,e,r,i,n,a){let s=t?.useDebugLayout??!1,u=r.select("svg").append("g").attr("class","venn-text-nodes"),h=new Map;for(let f of i){let d=vg(f.sets),p=h.get(d);p?p.push(f):h.set(d,[f])}for(let[f,d]of h.entries()){let p=e.get(f);if(!p?.text)continue;let m=p.text.x,g=p.text.y,y=Math.min(...p.circles.map(D=>D.radius)),v=Math.min(...p.circles.map(D=>D.radius-Math.hypot(m-D.x,g-D.y))),x=Number.isFinite(v)?Math.max(0,v):0;x===0&&Number.isFinite(y)&&(x=y*.6);let b=u.append("g").attr("class","venn-text-area").attr("font-size",`${40*n}px`);s&&b.append("circle").attr("class","venn-text-debug-circle").attr("cx",m).attr("cy",g).attr("r",x).attr("fill","none").attr("stroke","purple").attr("stroke-width",1.5*n).attr("stroke-dasharray",`${6*n} ${4*n}`);let T=Math.max(80*n,x*2*.95),w=Math.max(60*n,x*2*.95),E=(p.data.label&&p.data.label.length>0?Math.min(32*n,x*.25):0)+(d.length<=2?30*n:0),S=m-T/2,L=g-w/2+E,M=Math.max(1,Math.ceil(Math.sqrt(d.length))),I=Math.max(1,Math.ceil(d.length/M)),A=T/M,_=w/I;for(let[D,N]of d.entries()){let R=D%M,B=Math.floor(D/M),O=S+A*(R+.5),$=L+_*(B+.5);s&&b.append("rect").attr("class","venn-text-debug-cell").attr("x",S+A*R).attr("y",L+_*B).attr("width",A).attr("height",_).attr("fill","none").attr("stroke","teal").attr("stroke-width",1*n).attr("stroke-dasharray",`${4*n} ${3*n}`);let z=A*.9,F=_*.9,V=b.append("foreignObject").attr("class","venn-text-node-fo").attr("width",z).attr("height",F).attr("x",O-z/2).attr("y",$-F/2).attr("overflow","visible"),H=a.get(N.id)?.color,X=V.append("xhtml:span").attr("class","venn-text-node").style("display","flex").style("width","100%").style("height","100%").style("white-space","normal").style("align-items","center").style("justify-content","center").style("text-align","center").style("overflow-wrap","normal").style("word-break","normal").text(N.label??N.id);H&&X.style("color",H)}}}var X1t,W7e,U7e=P(()=>{"use strict";Pr();Yn();Sr();ro();q7e();Xi();Yt();o(j1t,"buildStyleByKey");X1t=o((t,e,r,i)=>{let n=i.db,a=n.getConfig?.(),{themeVariables:s,look:l,handDrawnSeed:u}=Lt(),h=l==="handDrawn",f=[s.venn1,s.venn2,s.venn3,s.venn4,s.venn5,s.venn6,s.venn7,s.venn8].filter(Boolean),d=n.getDiagramTitle?.(),p=n.getSubsetData(),m=n.getTextData(),g=j1t(n.getStyleData()),y=a?.width??800,v=a?.height??450,b=y/1600,T=d?48*b:0,w=s.primaryTextColor??s.textColor,k=Fi(e);k.attr("viewBox",`0 0 ${y} ${v}`),d&&k.append("text").text(d).attr("class","venn-title").attr("font-size",`${32*b}px`).attr("text-anchor","middle").attr("dominant-baseline","middle").attr("x","50%").attr("y",32*b).style("fill",s.vennTitleTextColor||s.titleColor);let C=Ze(document.createElement("div")),E=B7e().width(y).height(v-T);C.datum(p).call(E);let S=h?rt.svg(C.select("svg").node()):void 0,L=V7e(p,{width:y,height:v-T,padding:a?.padding??15}),M=new Map;for(let D of L){let N=vg([...D.data.sets].sort());M.set(N,D)}m.length>0&&K1t(a,M,C,m,b,g);let I=yi(s.background||"#f4f4f4");C.selectAll(".venn-circle").each(function(D,N){let R=Ze(this),O=vg([...D.sets].sort()),$=g.get(O),z=$?.fill||f[N%f.length]||s.primaryColor;R.classed(`venn-set-${N%8}`,!0);let F=$?.["fill-opacity"]??.1,V=$?.stroke||z,H=$?.["stroke-width"]||`${5*b}`;if(h&&S){let W=M.get(O);if(W&&W.circles.length>0){let Z=W.circles[0],Y=S.circle(Z.x,Z.y,Z.radius*2,{roughness:.7,seed:u,fill:m4(z,.7),fillStyle:"hachure",fillWeight:2,hachureGap:8,hachureAngle:-41+N*60,stroke:V,strokeWidth:parseFloat(String(H))});R.select("path").remove(),R.node()?.insertBefore(Y,R.select("text").node())}}else R.select("path").style("fill",z).style("fill-opacity",F).style("stroke",V).style("stroke-width",H).style("stroke-opacity",.95);let X=$?.color||(I?Ke(z,30):Ye(z,30));R.select("text").style("font-size",`${48*b}px`).style("fill",X)}),h&&S?C.selectAll(".venn-intersection").each(function(D){let N=Ze(this),B=vg([...D.sets].sort()),O=g.get(B),$=O?.fill;if($){let z=N.select("path"),F=z.attr("d");if(F){let V=S.path(F,{roughness:.7,seed:u,fill:m4($,.3),fillStyle:"cross-hatch",fillWeight:2,hachureGap:6,hachureAngle:60,stroke:"none"}),H=z.node();H?.parentNode?.insertBefore(V,H),z.remove()}}else N.select("path").style("fill-opacity",0);N.select("text").style("font-size",`${48*b}px`).style("fill",O?.color??s.vennSetTextColor??w)}):(C.selectAll(".venn-intersection text").style("font-size",`${48*b}px`).style("fill",D=>{let R=vg([...D.sets].sort());return g.get(R)?.color??s.vennSetTextColor??w}),C.selectAll(".venn-intersection path").style("fill-opacity",D=>{let R=vg([...D.sets].sort());return g.get(R)?.fill?1:0}).style("fill",D=>{let R=vg([...D.sets].sort());return g.get(R)?.fill??"transparent"}));let A=k.append("g").attr("transform",`translate(0, ${T})`),_=C.select("svg").node();if(_&&"childNodes"in _)for(let D of[..._.childNodes])A.node()?.appendChild(D);Hr(k,v,y,a?.useMaxWidth??!0)},"draw");o(vg,"stableSetsKey");o(K1t,"renderTextNodes");W7e={draw:X1t}});var H7e={};ur(H7e,{diagram:()=>Q1t});var Q1t,Y7e=P(()=>{"use strict";b7e();k7e();w7e();U7e();Q1t={parser:x7e,db:T7e,renderer:W7e,styles:C7e}});var xx,fY=P(()=>{"use strict";wa();Sr();er();Ht();Ki();xx=class{constructor(){this.nodes=[];this.levels=new Map;this.outerNodes=[];this.classes=new Map;this.setAccTitle=Ar;this.getAccTitle=Dr;this.setDiagramTitle=Mr;this.getDiagramTitle=Nr;this.getAccDescription=Rr;this.setAccDescription=Lr}static{o(this,"TreeMapDB")}getNodes(){return this.nodes}getConfig(){let e=fr,r=Lt();return fi({...e.treemap,...r.treemap??{}})}addNode(e,r){this.nodes.push(e),this.levels.set(e,r),r===0&&(this.outerNodes.push(e),this.root??=e)}getRoot(){return{name:"",children:this.outerNodes}}addClass(e,r){let i=this.classes.get(e)??{id:e,styles:[],textStyles:[]},n=r.replace(/\\,/g,"\xA7\xA7\xA7").replace(/,/g,";").replace(/§§§/g,",").split(";");n&&n.forEach(a=>{Eb(a)&&(i?.textStyles?i.textStyles.push(a):i.textStyles=[a]),i?.styles?i.styles.push(a):i.styles=[a]}),this.classes.set(e,i)}getClasses(){return this.classes}getStylesForClass(e){return this.classes.get(e)?.styles??[]}clear(){wr(),this.nodes=[],this.levels=new Map,this.outerNodes=[],this.classes=new Map,this.root=void 0}}});function K7e(t){if(!t.length)return[];let e=[],r=[];return t.forEach(i=>{let n={name:i.name,children:i.type==="Leaf"?void 0:[]};for(n.classSelector=i?.classSelector,i?.cssCompiledStyles&&(n.cssCompiledStyles=i.cssCompiledStyles),i.type==="Leaf"&&i.value!==void 0&&(n.value=i.value);r.length>0&&r[r.length-1].level>=i.level;)r.pop();if(r.length===0)e.push(n);else{let a=r[r.length-1].node;a.children?a.children.push(n):a.children=[n]}i.type!=="Leaf"&&r.push({node:n,level:i.level})}),e}var Q7e=P(()=>{"use strict";o(K7e,"buildHierarchy")});var tyt,ryt,dY,Z7e=P(()=>{"use strict";sh();bt();vf();Q7e();fY();tyt=o((t,e)=>{Ss(t,e);let r=[];for(let a of t.TreemapRows??[])a.$type==="ClassDefStatement"&&e.addClass(a.className??"",a.styleText??"");for(let a of t.TreemapRows??[]){let s=a.item;if(!s)continue;let l=a.indent?parseInt(a.indent):0,u=ryt(s),h=s.classSelector?e.getStylesForClass(s.classSelector):[],f=h.length>0?h:void 0,d={level:l,name:u,type:s.$type,value:s.value,classSelector:s.classSelector,cssCompiledStyles:f};r.push(d)}let i=K7e(r),n=o((a,s)=>{for(let l of a)e.addNode(l,s),l.children&&l.children.length>0&&n(l.children,s+1)},"addNodesRecursively");n(i,0)},"populate"),ryt=o(t=>t.name?String(t.name):"","getItemName"),dY={parser:{yy:void 0},parse:o(async t=>{try{let r=await ba("treemap",t);Q.debug("Treemap AST:",r);let i=dY.parser?.yy;if(!(i instanceof xx))throw new Error("parser.parser?.yy was not a TreemapDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.");tyt(r,i)}catch(e){throw Q.error("Error parsing treemap:",e),e}},"parse")}});var iyt,bx,ZC,nyt,ayt,J7e,e_e=P(()=>{"use strict";ro();Ud();Xi();Pr();Ht();Sr();bt();iyt=10,bx=10,ZC=25,nyt=o((t,e,r,i)=>{let n=i.db,a=n.getConfig(),s=a.padding??iyt,l=n.getDiagramTitle(),u=n.getRoot(),{themeVariables:h}=Lt();if(!u)return;let f=l?30:0,d=Fi(e),p=a.nodeWidth?a.nodeWidth*bx:960,m=a.nodeHeight?a.nodeHeight*bx:500,g=p,y=m+f;d.attr("viewBox",`0 0 ${g} ${y}`),Hr(d,y,g,a.useMaxWidth);let v;try{let D=a.valueFormat||",";if(D==="$0,0")v=o(N=>"$"+du(",")(N),"valueFormat");else if(D.startsWith("$")&&D.includes(",")){let N=/\.\d+/.exec(D),R=N?N[0]:"";v=o(B=>"$"+du(","+R)(B),"valueFormat")}else if(D.startsWith("$")){let N=D.substring(1);v=o(R=>"$"+du(N||"")(R),"valueFormat")}else v=du(D)}catch(D){Q.error("Error creating format function:",D),v=du(",")}let x=jo().range(["transparent",h.cScale0,h.cScale1,h.cScale2,h.cScale3,h.cScale4,h.cScale5,h.cScale6,h.cScale7,h.cScale8,h.cScale9,h.cScale10,h.cScale11]),b=jo().range(["transparent",h.cScalePeer0,h.cScalePeer1,h.cScalePeer2,h.cScalePeer3,h.cScalePeer4,h.cScalePeer5,h.cScalePeer6,h.cScalePeer7,h.cScalePeer8,h.cScalePeer9,h.cScalePeer10,h.cScalePeer11]),T=jo().range([h.cScaleLabel0,h.cScaleLabel1,h.cScaleLabel2,h.cScaleLabel3,h.cScaleLabel4,h.cScaleLabel5,h.cScaleLabel6,h.cScaleLabel7,h.cScaleLabel8,h.cScaleLabel9,h.cScaleLabel10,h.cScaleLabel11]);l&&d.append("text").attr("x",g/2).attr("y",f/2).attr("class","treemapTitle").attr("text-anchor","middle").attr("dominant-baseline","middle").text(l);let w=d.append("g").attr("transform",`translate(0, ${f})`).attr("class","treemapContainer"),k=jg(u).sum(D=>D.value??0).sort((D,N)=>(N.value??0)-(D.value??0)),E=Yw().size([p,m]).paddingTop(D=>D.children&&D.children.length>0?ZC+bx:0).paddingInner(s).paddingLeft(D=>D.children&&D.children.length>0?bx:0).paddingRight(D=>D.children&&D.children.length>0?bx:0).paddingBottom(D=>D.children&&D.children.length>0?bx:0).round(!0)(k),S=E.descendants().filter(D=>D.children&&D.children.length>0),L=w.selectAll(".treemapSection").data(S).enter().append("g").attr("class","treemapSection").attr("transform",D=>`translate(${D.x0},${D.y0})`);L.append("rect").attr("width",D=>D.x1-D.x0).attr("height",ZC).attr("class","treemapSectionHeader").attr("fill","none").attr("fill-opacity",.6).attr("stroke-width",.6).attr("style",D=>D.depth===0?"display: none;":""),L.append("clipPath").attr("id",(D,N)=>`clip-section-${e}-${N}`).append("rect").attr("width",D=>Math.max(0,D.x1-D.x0-12)).attr("height",ZC),L.append("rect").attr("width",D=>D.x1-D.x0).attr("height",D=>D.y1-D.y0).attr("class",(D,N)=>`treemapSection section${N}`).attr("fill",D=>x(D.data.name)).attr("fill-opacity",.6).attr("stroke",D=>b(D.data.name)).attr("stroke-width",2).attr("stroke-opacity",.4).attr("style",D=>{if(D.depth===0)return"display: none;";let N=tt({cssCompiledStyles:D.data.cssCompiledStyles});return N.nodeStyles+";"+N.borderStyles.join(";")}),L.append("text").attr("class","treemapSectionLabel").attr("x",6).attr("y",ZC/2).attr("dominant-baseline","middle").text(D=>D.depth===0?"":D.data.name).attr("font-weight","bold").attr("style",D=>{if(D.depth===0)return"display: none;";let N="dominant-baseline: middle; font-size: 12px; fill:"+T(D.data.name)+"; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;",R=tt({cssCompiledStyles:D.data.cssCompiledStyles});return N+R.labelStyles.replace("color:","fill:")}).each(function(D){if(D.depth===0)return;let N=Ze(this),R=D.data.name;N.text(R);let B=D.x1-D.x0,O=6,$;a.showValues!==!1&&D.value?$=B-10-30-10-O:$=B-O-6;let F=Math.max(15,$),V=N.node();if(V.getComputedTextLength()>F){let W=R;for(;W.length>0;){if(W=R.substring(0,W.length-1),W.length===0){N.text("..."),V.getComputedTextLength()>F&&N.text("");break}if(N.text(W+"..."),V.getComputedTextLength()<=F)break}}}),a.showValues!==!1&&L.append("text").attr("class","treemapSectionValue").attr("x",D=>D.x1-D.x0-10).attr("y",ZC/2).attr("text-anchor","end").attr("dominant-baseline","middle").text(D=>D.value?v(D.value):"").attr("font-style","italic").attr("style",D=>{if(D.depth===0)return"display: none;";let N="text-anchor: end; dominant-baseline: middle; font-size: 10px; fill:"+T(D.data.name)+"; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;",R=tt({cssCompiledStyles:D.data.cssCompiledStyles});return N+R.labelStyles.replace("color:","fill:")});let M=E.leaves(),I=w.selectAll(".treemapLeafGroup").data(M).enter().append("g").attr("class",(D,N)=>`treemapNode treemapLeafGroup leaf${N}${D.data.classSelector?` ${D.data.classSelector}`:""}x`).attr("transform",D=>`translate(${D.x0},${D.y0})`);I.append("rect").attr("width",D=>D.x1-D.x0).attr("height",D=>D.y1-D.y0).attr("class","treemapLeaf").attr("fill",D=>D.parent?x(D.parent.data.name):x(D.data.name)).attr("style",D=>tt({cssCompiledStyles:D.data.cssCompiledStyles}).nodeStyles).attr("fill-opacity",.3).attr("stroke",D=>D.parent?x(D.parent.data.name):x(D.data.name)).attr("stroke-width",3),I.append("clipPath").attr("id",(D,N)=>`clip-${e}-${N}`).append("rect").attr("width",D=>Math.max(0,D.x1-D.x0-4)).attr("height",D=>Math.max(0,D.y1-D.y0-4)),I.append("text").attr("class","treemapLabel").attr("x",D=>(D.x1-D.x0)/2).attr("y",D=>(D.y1-D.y0)/2).attr("style",D=>{let N="text-anchor: middle; dominant-baseline: middle; font-size: 38px;fill:"+T(D.data.name)+";",R=tt({cssCompiledStyles:D.data.cssCompiledStyles});return N+R.labelStyles.replace("color:","fill:")}).attr("clip-path",(D,N)=>`url(#clip-${e}-${N})`).text(D=>D.data.name).each(function(D){let N=Ze(this),R=D.x1-D.x0,B=D.y1-D.y0,O=N.node(),$=4,z=R-2*$,F=B-2*$;if(z<10||F<10){N.style("display","none");return}let V=parseInt(N.style("font-size"),10),H=8,X=28,W=.6,Z=6,Y=2;for(;O.getComputedTextLength()>z&&V>H;)V--,N.style("font-size",`${V}px`);let ae=Math.max(Z,Math.min(X,Math.round(V*W))),J=V+Y+ae;for(;J>F&&V>H&&(V--,ae=Math.max(Z,Math.min(X,Math.round(V*W))),!(aeF;N.style("font-size",`${V}px`),(O.getComputedTextLength()>z||V(N.x1-N.x0)/2).attr("y",function(N){return(N.y1-N.y0)/2}).attr("style",N=>{let R="text-anchor: middle; dominant-baseline: hanging; font-size: 28px;fill:"+T(N.data.name)+";",B=tt({cssCompiledStyles:N.data.cssCompiledStyles});return R+B.labelStyles.replace("color:","fill:")}).attr("clip-path",(N,R)=>`url(#clip-${e}-${R})`).text(N=>N.value?v(N.value):"").each(function(N){let R=Ze(this),B=this.parentNode;if(!B){R.style("display","none");return}let O=Ze(B).select(".treemapLabel");if(O.empty()||O.style("display")==="none"){R.style("display","none");return}let $=parseFloat(O.style("font-size")),z=28,F=.6,V=6,H=2,X=Math.max(V,Math.min(z,Math.round($*F)));R.style("font-size",`${X}px`);let Z=(N.y1-N.y0)/2+$/2+H;R.attr("y",Z);let Y=N.x1-N.x0,ee=N.y1-N.y0-4,re=Y-8;R.node().getComputedTextLength()>re||Z+X>ee||X{"use strict";er();wg();Sr();syt={sectionStrokeColor:"black",sectionStrokeWidth:"1",sectionFillColor:"#efefef",leafStrokeColor:"black",leafStrokeWidth:"1",leafFillColor:"#efefef",labelFontSize:"12px",valueFontSize:"10px",titleFontSize:"14px"},oyt=o(({treemap:t}={})=>{let e=Zc(),r=Lt(),i=fi(e,r.themeVariables),n=fi(syt,t),a=n.titleColor??i.titleColor,s=n.labelColor??i.textColor,l=n.valueColor??i.textColor;return` + .treemapNode.section { + stroke: ${n.sectionStrokeColor}; + stroke-width: ${n.sectionStrokeWidth}; + fill: ${n.sectionFillColor}; + } + .treemapNode.leaf { + stroke: ${n.leafStrokeColor}; + stroke-width: ${n.leafStrokeWidth}; + fill: ${n.leafFillColor}; + } + .treemapLabel { + fill: ${s}; + font-size: ${n.labelFontSize}; + } + .treemapValue { + fill: ${l}; + font-size: ${n.valueFontSize}; + } + .treemapTitle { + fill: ${a}; + font-size: ${n.titleFontSize}; + } + `},"getStyles"),t_e=oyt});var i_e={};ur(i_e,{diagram:()=>lyt});var lyt,n_e=P(()=>{"use strict";fY();Z7e();e_e();r_e();lyt={parser:dY,get db(){return new xx},renderer:J7e,styles:t_e}});var c8,xg,o_e,hyt,fyt,pY,l_e=P(()=>{"use strict";sh();bt();vf();c8=o((t,e)=>{let r=t<=1?t*100:t;if(r<0||r>100)throw new Error(`${e} must be between 0-1 (decimal) or 0-100 (percentage). Received: ${t}`);return r},"toPercent"),xg=o((t,e,r)=>({x:c8(e,`${r} evolution`),y:c8(t,`${r} visibility`)}),"toCoordinates"),o_e=o(t=>{if(t){if(t==="+<>")return"bidirectional";if(t==="+<")return"backward";if(t==="+>")return"forward"}},"getFlowFromPort"),hyt=o(t=>{if(!t?.startsWith("+"))return{};let r=/^\+'([^']*)'/.exec(t)?.[1];return t.includes("<>")?{flow:"bidirectional",label:r}:t.includes("<")?{flow:"backward",label:r}:t.includes(">")?{flow:"forward",label:r}:{label:r}},"extractFlowFromArrow"),fyt=o((t,e)=>{if(Ss(t,e),t.size&&e.setSize(t.size.width,t.size.height),t.evolution){let r=t.evolution.stages.map(n=>n.secondName?`${n.name.trim()} / ${n.secondName.trim()}`:n.name.trim()),i=t.evolution.stages.filter(n=>n.boundary!==void 0).map(n=>n.boundary);e.updateAxes({stages:r,stageBoundaries:i})}if(t.anchors.forEach(r=>{let i=xg(r.visibility,r.evolution,`Anchor "${r.name}"`);e.addNode(r.name,r.name,i.x,i.y,"anchor")}),t.components.forEach(r=>{let i=xg(r.visibility,r.evolution,`Component "${r.name}"`),n=r.label?(r.label.negX?-1:1)*r.label.offsetX:void 0,a=r.label?(r.label.negY?-1:1)*r.label.offsetY:void 0,s=r.decorator?.strategy;e.addNode(r.name,r.name,i.x,i.y,"component",n,a,r.inertia,s)}),t.notes.forEach(r=>{let i=xg(r.visibility,r.evolution,`Note "${r.text}"`);e.addNote(r.text,i.x,i.y)}),t.pipelines.forEach(r=>{let i=e.getNode(r.parent);if(!i||typeof i.y!="number")throw new Error(`Pipeline "${r.parent}" must reference an existing component with coordinates.`);let n=i.y;e.startPipeline(r.parent),r.components.forEach(a=>{let s=`${r.parent}_${a.name}`,l=a.label?(a.label.negX?-1:1)*a.label.offsetX:void 0,u=a.label?(a.label.negY?-1:1)*a.label.offsetY:void 0,h=c8(a.evolution,`Pipeline component "${a.name}" evolution`);e.addNode(s,a.name,h,n,"pipeline-component",l,u),e.addPipelineComponent(r.parent,s)})}),t.links.forEach(r=>{let i=!!r.arrow&&(r.arrow.includes("-.->")||r.arrow.includes(".-.")),n=o_e(r.fromPort)??o_e(r.toPort),{flow:a,label:s}=hyt(r.arrow);!n&&a&&(n=a);let l=r.linkLabel,u=s??l;e.addLink(r.from,r.to,i,u,n)}),t.evolves.forEach(r=>{let i=e.getNode(r.component);if(i?.y!==void 0){let n=c8(r.target,`Evolve target for "${r.component}"`);e.addTrend(r.component,n,i.y)}}),t.annotations.length>0){let r=t.annotations[0],i=xg(r.x,r.y,"Annotations box");e.setAnnotationsBox(i.x,i.y)}t.annotation.forEach(r=>{let i=xg(r.x,r.y,`Annotation ${r.number}`);e.addAnnotation(r.number,[{x:i.x,y:i.y}],r.text)}),t.accelerators.forEach(r=>{let i=xg(r.x,r.y,`Accelerator "${r.name}"`);e.addAccelerator(r.name,i.x,i.y)}),t.deaccelerators.forEach(r=>{let i=xg(r.x,r.y,`Deaccelerator "${r.name}"`);e.addDeaccelerator(r.name,i.x,i.y)})},"populateDb"),pY={parser:{yy:void 0},parse:o(async t=>{let e=await ba("wardley",t);Q.debug(e);let r=pY.parser?.yy;if(!r||typeof r.addNode!="function")throw new Error("parser.parser?.yy was not a WardleyDB. This is due to a bug within Mermaid, please report this issue at https://github.com/mermaid-js/mermaid/issues.");fyt(e,r)},"parse")}});var u8,c_e=P(()=>{"use strict";u8=class{constructor(){this.nodes=new Map;this.links=[];this.trends=new Map;this.pipelines=new Map;this.annotations=[];this.notes=[];this.accelerators=[];this.deaccelerators=[];this.axes={}}static{o(this,"WardleyBuilder")}addNode(e){let r=this.nodes.get(e.id)??{id:e.id,label:e.label},i={...r,...e,className:e.className??r.className,labelOffsetX:e.labelOffsetX??r.labelOffsetX,labelOffsetY:e.labelOffsetY??r.labelOffsetY};this.nodes.set(e.id,i)}addLink(e){this.links.push(e)}addTrend(e){this.trends.set(e.nodeId,e)}startPipeline(e){this.pipelines.set(e,{nodeId:e,componentIds:[]});let r=this.nodes.get(e);r&&(r.isPipelineParent=!0)}addPipelineComponent(e,r){let i=this.pipelines.get(e);i&&i.componentIds.push(r);let n=this.nodes.get(r);n&&(n.inPipeline=!0)}addAnnotation(e){this.annotations.push(e)}addNote(e){this.notes.push(e)}addAccelerator(e){this.accelerators.push(e)}addDeaccelerator(e){this.deaccelerators.push(e)}setAnnotationsBox(e,r){this.annotationsBox={x:e,y:r}}setAxes(e){this.axes={...this.axes,...e}}setSize(e,r){this.size={width:e,height:r}}getNode(e){return this.nodes.get(e)}build(){let e=[];for(let r of this.nodes.values()){if(typeof r.x!="number"||typeof r.y!="number")throw new Error(`Node "${r.label}" is missing coordinates`);e.push(r)}return{nodes:e,links:[...this.links],trends:[...this.trends.values()],pipelines:[...this.pipelines.values()],annotations:[...this.annotations],notes:[...this.notes],accelerators:[...this.accelerators],deaccelerators:[...this.deaccelerators],annotationsBox:this.annotationsBox,axes:{...this.axes},size:this.size}}clear(){this.nodes.clear(),this.links=[],this.trends.clear(),this.pipelines.clear(),this.annotations=[],this.notes=[],this.accelerators=[],this.deaccelerators=[],this.annotationsBox=void 0,this.axes={},this.size=void 0}}});function Ip(t){let e=ge();return Tr(t.trim(),e)}function dyt(){return ge()["wardley-beta"]}function pyt(t,e,r,i,n,a,s,l,u){ao.addNode({id:t,label:Ip(e),x:r,y:i,className:n,labelOffsetX:a,labelOffsetY:s,inertia:l,sourceStrategy:u})}function myt(t,e,r=!1,i,n){ao.addLink({source:t,target:e,dashed:r,label:i,flow:n})}function gyt(t,e,r){ao.addTrend({nodeId:t,targetX:e,targetY:r})}function yyt(t,e,r){ao.addAnnotation({number:t,coordinates:e,text:r?Ip(r):void 0})}function vyt(t,e,r){ao.addNote({text:Ip(t),x:e,y:r})}function xyt(t,e,r){ao.addAccelerator({name:Ip(t),x:e,y:r})}function byt(t,e,r){ao.addDeaccelerator({name:Ip(t),x:e,y:r})}function Tyt(t,e){ao.setAnnotationsBox(t,e)}function kyt(t,e){ao.setSize(t,e)}function Cyt(t){ao.startPipeline(t)}function wyt(t,e){ao.addPipelineComponent(t,e)}function Eyt(t){let e={};t.xLabel&&(e.xLabel=Ip(t.xLabel)),t.yLabel&&(e.yLabel=Ip(t.yLabel)),t.stages&&(e.stages=t.stages.map(r=>Ip(r))),t.stageBoundaries&&(e.stageBoundaries=t.stageBoundaries),ao.setAxes(e)}function Syt(t){return ao.getNode(t)}function Ayt(){return ao.build()}function _yt(){ao.clear(),wr()}var ao,u_e,h_e=P(()=>{"use strict";Ut();Vr();Ki();c_e();ao=new u8;o(Ip,"textSanitizer");o(dyt,"getConfig");o(pyt,"addNode");o(myt,"addLink");o(gyt,"addTrend");o(yyt,"addAnnotation");o(vyt,"addNote");o(xyt,"addAccelerator");o(byt,"addDeaccelerator");o(Tyt,"setAnnotationsBox");o(kyt,"setSize");o(Cyt,"startPipeline");o(wyt,"addPipelineComponent");o(Eyt,"updateAxes");o(Syt,"getNode");o(Ayt,"getWardleyData");o(_yt,"clear");u_e={getConfig:dyt,addNode:pyt,addLink:myt,addTrend:gyt,addAnnotation:yyt,addNote:vyt,addAccelerator:xyt,addDeaccelerator:byt,setAnnotationsBox:Tyt,setSize:kyt,startPipeline:Cyt,addPipelineComponent:wyt,updateAxes:Eyt,getNode:Syt,getWardleyData:Ayt,clear:_yt,setAccTitle:Ar,getAccTitle:Dr,setDiagramTitle:Mr,getDiagramTitle:Nr,getAccDescription:Rr,setAccDescription:Lr}});var Dyt,Lyt,Ryt,Nyt,f_e,d_e=P(()=>{"use strict";Ut();bt();ro();Xi();Dyt=["Genesis","Custom Built","Product","Commodity"],Lyt=o(()=>{let{themeVariables:t}=ge();return{backgroundColor:t.wardley?.backgroundColor??t.background??"#fff",axisColor:t.wardley?.axisColor??"#000",axisTextColor:t.wardley?.axisTextColor??t.primaryTextColor??"#222",gridColor:t.wardley?.gridColor??"rgba(100, 100, 100, 0.2)",componentFill:t.wardley?.componentFill??"#fff",componentStroke:t.wardley?.componentStroke??"#000",componentLabelColor:t.wardley?.componentLabelColor??t.primaryTextColor??"#222",linkStroke:t.wardley?.linkStroke??"#000",evolutionStroke:t.wardley?.evolutionStroke??"#dc3545",annotationStroke:t.wardley?.annotationStroke??"#000",annotationTextColor:t.wardley?.annotationTextColor??t.primaryTextColor??"#222",annotationFill:t.wardley?.annotationFill??t.background??"#fff"}},"getTheme"),Ryt=o(()=>{let t=ge()["wardley-beta"];return{width:t?.width??900,height:t?.height??600,padding:t?.padding??48,nodeRadius:t?.nodeRadius??6,nodeLabelOffset:t?.nodeLabelOffset??8,axisFontSize:t?.axisFontSize??12,labelFontSize:t?.labelFontSize??10,showGrid:t?.showGrid??!1,useMaxWidth:t?.useMaxWidth??!0}},"getConfigValues"),Nyt=o((t,e,r,i)=>{Q.debug(`Rendering Wardley map +`+t);let n=Ryt(),a=Lyt(),s=n.nodeRadius*1.6,l=i.db,u=l.getWardleyData(),h=l.getDiagramTitle(),f=u.size?.width??n.width,d=u.size?.height??n.height,p=Fi(e);p.selectAll("*").remove(),Hr(p,d,f,n.useMaxWidth),p.attr("viewBox",`0 0 ${f} ${d}`);let m=p.append("g").attr("class","wardley-map"),g=p.append("defs");g.append("marker").attr("id",`arrow-${e}`).attr("viewBox","0 0 10 10").attr("refX",9).attr("refY",5).attr("markerWidth",6).attr("markerHeight",6).attr("orient","auto-start-reverse").append("path").attr("d","M 0 0 L 10 5 L 0 10 z").attr("fill",a.evolutionStroke).attr("stroke","none"),g.append("marker").attr("id",`link-arrow-end-${e}`).attr("viewBox","0 0 10 10").attr("refX",9).attr("refY",5).attr("markerWidth",5).attr("markerHeight",5).attr("orient","auto").append("path").attr("d","M 0 0 L 10 5 L 0 10 z").attr("fill",a.linkStroke).attr("stroke","none"),g.append("marker").attr("id",`link-arrow-start-${e}`).attr("viewBox","0 0 10 10").attr("refX",1).attr("refY",5).attr("markerWidth",5).attr("markerHeight",5).attr("orient","auto").append("path").attr("d","M 10 0 L 0 5 L 10 10 z").attr("fill",a.linkStroke).attr("stroke","none"),m.append("rect").attr("class","wardley-background").attr("width",f).attr("height",d).attr("fill",a.backgroundColor);let y=f-n.padding*2,v=d-n.padding*2;h&&m.append("text").attr("class","wardley-title").attr("x",f/2).attr("y",n.padding/2).attr("fill",a.axisTextColor).attr("font-size",n.axisFontSize*1.05).attr("font-weight","bold").attr("text-anchor","middle").attr("dominant-baseline","middle").text(h);let x=o(O=>n.padding+O/100*y,"projectX"),b=o(O=>d-n.padding-O/100*v,"projectY"),T=m.append("g").attr("class","wardley-axes");T.append("line").attr("x1",n.padding).attr("x2",f-n.padding).attr("y1",d-n.padding).attr("y2",d-n.padding).attr("stroke",a.axisColor).attr("stroke-width",1),T.append("line").attr("x1",n.padding).attr("x2",n.padding).attr("y1",n.padding).attr("y2",d-n.padding).attr("stroke",a.axisColor).attr("stroke-width",1);let w=u.axes.xLabel??"Evolution",k=u.axes.yLabel??"Visibility";T.append("text").attr("class","wardley-axis-label wardley-axis-label-x").attr("x",n.padding+y/2).attr("y",d-n.padding/4).attr("fill",a.axisTextColor).attr("font-size",n.axisFontSize).attr("font-weight","bold").attr("text-anchor","middle").text(w),T.append("text").attr("class","wardley-axis-label wardley-axis-label-y").attr("x",n.padding/3).attr("y",n.padding+v/2).attr("fill",a.axisTextColor).attr("font-size",n.axisFontSize).attr("font-weight","bold").attr("text-anchor","middle").attr("transform",`rotate(-90 ${n.padding/3} ${n.padding+v/2})`).text(k);let C=u.axes.stages&&u.axes.stages.length>0?u.axes.stages:Dyt;if(C.length>0){let O=m.append("g").attr("class","wardley-stages"),$=u.axes.stageBoundaries,z=[];if($&&$.length===C.length){let F=0;$.forEach(V=>{z.push({start:F,end:V}),F=V})}else{let F=1/C.length;C.forEach((V,H)=>{z.push({start:H*F,end:(H+1)*F})})}C.forEach((F,V)=>{let H=z[V],X=n.padding+H.start*y,W=n.padding+H.end*y,Z=(X+W)/2;V>0&&O.append("line").attr("x1",X).attr("x2",X).attr("y1",n.padding).attr("y2",d-n.padding).attr("stroke","#000").attr("stroke-width",1).attr("stroke-dasharray","5 5").attr("opacity",.8),O.append("text").attr("class","wardley-stage-label").attr("x",Z).attr("y",d-n.padding/1.5).attr("fill",a.axisTextColor).attr("font-size",n.axisFontSize-2).attr("text-anchor","middle").text(F)})}if(n.showGrid){let O=m.append("g").attr("class","wardley-grid");for(let $=1;$<4;$++){let z=$/4,F=n.padding+y*z;O.append("line").attr("x1",F).attr("x2",F).attr("y1",n.padding).attr("y2",d-n.padding).attr("stroke",a.gridColor).attr("stroke-dasharray","2 6"),O.append("line").attr("x1",n.padding).attr("x2",f-n.padding).attr("y1",d-n.padding-v*z).attr("y2",d-n.padding-v*z).attr("stroke",a.gridColor).attr("stroke-dasharray","2 6")}}let E=new Map;if(u.nodes.forEach(O=>{E.set(O.id,{x:x(O.x),y:b(O.y),node:O})}),u.pipelines.length>0){let O=m.append("g").attr("class","wardley-pipelines"),$=m.append("g").attr("class","wardley-pipeline-links");u.pipelines.forEach(z=>{if(z.componentIds.length===0)return;let F=z.componentIds.map(W=>({id:W,pos:E.get(W),node:u.nodes.find(Z=>Z.id===W)})).filter(W=>W.pos&&W.node).sort((W,Z)=>W.node.x-Z.node.x);for(let W=0;W{let Z=E.get(W);Z&&(V=Math.min(V,Z.x),H=Math.max(H,Z.x),X=Z.y)}),V!==1/0&&H!==-1/0){let Z=n.nodeRadius*4,Y=X-Z/2,ae=E.get(z.nodeId);if(ae){let J=(V+H)/2;ae.x=J,ae.y=Y-s/6}O.append("rect").attr("class","wardley-pipeline-box").attr("x",V-15).attr("y",Y).attr("width",H-V+30).attr("height",Z).attr("fill","none").attr("stroke",a.axisColor).attr("stroke-width",1.5).attr("rx",4).attr("ry",4)}})}let S=m.append("g").attr("class","wardley-links"),L=new Map;u.pipelines.forEach(O=>{L.set(O.nodeId,new Set(O.componentIds))});let M=u.links.filter(O=>!(!E.has(O.source)||!E.has(O.target)||L.get(O.target)?.has(O.source)));S.selectAll("line").data(M).enter().append("line").attr("class",O=>`wardley-link${O.dashed?" wardley-link--dashed":""}`).attr("x1",O=>{let $=E.get(O.source),z=E.get(O.target),V=u.nodes.find(Z=>Z.id===O.source).isPipelineParent?s/Math.sqrt(2):n.nodeRadius,H=z.x-$.x,X=z.y-$.y,W=Math.sqrt(H*H+X*X);return $.x+H/W*V}).attr("y1",O=>{let $=E.get(O.source),z=E.get(O.target),V=u.nodes.find(Z=>Z.id===O.source).isPipelineParent?s/Math.sqrt(2):n.nodeRadius,H=z.x-$.x,X=z.y-$.y,W=Math.sqrt(H*H+X*X);return $.y+X/W*V}).attr("x2",O=>{let $=E.get(O.source),z=E.get(O.target),V=u.nodes.find(Z=>Z.id===O.target).isPipelineParent?s/Math.sqrt(2):n.nodeRadius,H=$.x-z.x,X=$.y-z.y,W=Math.sqrt(H*H+X*X);return z.x+H/W*V}).attr("y2",O=>{let $=E.get(O.source),z=E.get(O.target),V=u.nodes.find(Z=>Z.id===O.target).isPipelineParent?s/Math.sqrt(2):n.nodeRadius,H=$.x-z.x,X=$.y-z.y,W=Math.sqrt(H*H+X*X);return z.y+X/W*V}).attr("stroke",a.linkStroke).attr("stroke-width",1).attr("stroke-dasharray",O=>O.dashed?"6 6":null).attr("marker-end",O=>O.flow==="forward"||O.flow==="bidirectional"?`url(#link-arrow-end-${e})`:null).attr("marker-start",O=>O.flow==="backward"||O.flow==="bidirectional"?`url(#link-arrow-start-${e})`:null),S.selectAll("text").data(M.filter(O=>O.label)).enter().append("text").attr("class","wardley-link-label").attr("x",O=>{let $=E.get(O.source),z=E.get(O.target),F=($.x+z.x)/2,V=z.y-$.y,H=z.x-$.x,X=Math.sqrt(H*H+V*V),W=8,Z=V/X;return F+Z*W}).attr("y",O=>{let $=E.get(O.source),z=E.get(O.target),F=($.y+z.y)/2,V=z.x-$.x,H=z.y-$.y,X=Math.sqrt(V*V+H*H),W=8,Z=-V/X;return F+Z*W}).attr("fill",a.axisTextColor).attr("font-size",n.labelFontSize).attr("text-anchor","middle").attr("dominant-baseline","middle").attr("transform",O=>{let $=E.get(O.source),z=E.get(O.target),F=($.x+z.x)/2,V=($.y+z.y)/2,H=z.x-$.x,X=z.y-$.y,W=Math.sqrt(H*H+X*X),Z=8,Y=X/W,ae=-H/W,J=F+Y*Z,ee=V+ae*Z,re=Math.atan2(X,H)*180/Math.PI;return(re>90||re<-90)&&(re+=180),`rotate(${re} ${J} ${ee})`}).text(O=>O.label);let I=m.append("g").attr("class","wardley-trends"),A=u.trends.map(O=>{let $=E.get(O.nodeId);if(!$)return null;let z=x(O.targetX),F=b(O.targetY),V=z-$.x,H=F-$.y,X=Math.sqrt(V*V+H*H),W=n.nodeRadius+2,Z=X>W?z-V/X*W:z,Y=X>W?F-H/X*W:F;return{origin:$,targetX:z,targetY:F,adjustedX2:Z,adjustedY2:Y}}).filter(O=>O!==null);I.selectAll("line").data(A).enter().append("line").attr("class","wardley-trend").attr("x1",O=>O.origin.x).attr("y1",O=>O.origin.y).attr("x2",O=>O.adjustedX2).attr("y2",O=>O.adjustedY2).attr("stroke",a.evolutionStroke).attr("stroke-width",1).attr("stroke-dasharray","4 4").attr("marker-end",`url(#arrow-${e})`);let D=m.append("g").attr("class","wardley-nodes").selectAll("g").data(u.nodes).enter().append("g").attr("class",O=>["wardley-node",O.className?`wardley-node--${O.className}`:""].filter(Boolean).join(" "));D.filter(O=>O.sourceStrategy==="outsource").append("circle").attr("class","wardley-outsource-overlay").attr("cx",O=>E.get(O.id).x).attr("cy",O=>E.get(O.id).y).attr("r",n.nodeRadius*2).attr("fill","#666").attr("stroke",a.componentStroke).attr("stroke-width",1),D.filter(O=>O.sourceStrategy==="buy").append("circle").attr("class","wardley-buy-overlay").attr("cx",O=>E.get(O.id).x).attr("cy",O=>E.get(O.id).y).attr("r",n.nodeRadius*2).attr("fill","#ccc").attr("stroke",a.componentStroke).attr("stroke-width",1),D.filter(O=>O.sourceStrategy==="build").append("circle").attr("class","wardley-build-overlay").attr("cx",O=>E.get(O.id).x).attr("cy",O=>E.get(O.id).y).attr("r",n.nodeRadius*2).attr("fill","#eee").attr("stroke","#000").attr("stroke-width",1);let N=D.filter(O=>O.sourceStrategy==="market");N.append("circle").attr("class","wardley-market-overlay").attr("cx",O=>E.get(O.id).x).attr("cy",O=>E.get(O.id).y).attr("r",n.nodeRadius*2).attr("fill","white").attr("stroke",a.componentStroke).attr("stroke-width",1),D.filter(O=>!O.isPipelineParent&&O.sourceStrategy!=="market"&&O.className!=="anchor").append("circle").attr("cx",O=>E.get(O.id).x).attr("cy",O=>E.get(O.id).y).attr("r",n.nodeRadius).attr("fill",a.componentFill).attr("stroke",a.componentStroke).attr("stroke-width",1);let R=n.nodeRadius*.7,B=n.nodeRadius*1.2;if(N.append("line").attr("class","wardley-market-line").attr("x1",O=>E.get(O.id).x).attr("y1",O=>E.get(O.id).y-B).attr("x2",O=>E.get(O.id).x-B*Math.cos(Math.PI/6)).attr("y2",O=>E.get(O.id).y+B*Math.sin(Math.PI/6)).attr("stroke",a.componentStroke).attr("stroke-width",1),N.append("line").attr("class","wardley-market-line").attr("x1",O=>E.get(O.id).x-B*Math.cos(Math.PI/6)).attr("y1",O=>E.get(O.id).y+B*Math.sin(Math.PI/6)).attr("x2",O=>E.get(O.id).x+B*Math.cos(Math.PI/6)).attr("y2",O=>E.get(O.id).y+B*Math.sin(Math.PI/6)).attr("stroke",a.componentStroke).attr("stroke-width",1),N.append("line").attr("class","wardley-market-line").attr("x1",O=>E.get(O.id).x+B*Math.cos(Math.PI/6)).attr("y1",O=>E.get(O.id).y+B*Math.sin(Math.PI/6)).attr("x2",O=>E.get(O.id).x).attr("y2",O=>E.get(O.id).y-B).attr("stroke",a.componentStroke).attr("stroke-width",1),N.append("circle").attr("class","wardley-market-dot").attr("cx",O=>E.get(O.id).x).attr("cy",O=>E.get(O.id).y-B).attr("r",R).attr("fill","white").attr("stroke",a.componentStroke).attr("stroke-width",2),N.append("circle").attr("class","wardley-market-dot").attr("cx",O=>E.get(O.id).x-B*Math.cos(Math.PI/6)).attr("cy",O=>E.get(O.id).y+B*Math.sin(Math.PI/6)).attr("r",R).attr("fill","white").attr("stroke",a.componentStroke).attr("stroke-width",2),N.append("circle").attr("class","wardley-market-dot").attr("cx",O=>E.get(O.id).x+B*Math.cos(Math.PI/6)).attr("cy",O=>E.get(O.id).y+B*Math.sin(Math.PI/6)).attr("r",R).attr("fill","white").attr("stroke",a.componentStroke).attr("stroke-width",2),D.filter(O=>O.isPipelineParent===!0).append("rect").attr("x",O=>E.get(O.id).x-s/2).attr("y",O=>E.get(O.id).y-s/2).attr("width",s).attr("height",s).attr("fill",a.componentFill).attr("stroke",a.componentStroke).attr("stroke-width",1),D.filter(O=>O.inertia===!0).append("line").attr("class","wardley-inertia").attr("x1",O=>{let $=E.get(O.id),z=O.isPipelineParent?s/2+15:n.nodeRadius+15;return O.sourceStrategy&&(z+=n.nodeRadius+10),$.x+z}).attr("y1",O=>{let $=E.get(O.id),z=O.isPipelineParent?s:n.nodeRadius*2;return $.y-z/2}).attr("x2",O=>{let $=E.get(O.id),z=O.isPipelineParent?s/2+15:n.nodeRadius+15;return O.sourceStrategy&&(z+=n.nodeRadius+10),$.x+z}).attr("y2",O=>{let $=E.get(O.id),z=O.isPipelineParent?s:n.nodeRadius*2;return $.y+z/2}).attr("stroke",a.componentStroke).attr("stroke-width",6),D.append("text").attr("x",O=>{let $=E.get(O.id);if(O.className==="anchor")return O.labelOffsetX!==void 0?$.x+O.labelOffsetX:$.x;let z=n.nodeLabelOffset;O.sourceStrategy&&O.labelOffsetX===void 0&&(z+=10);let F=O.labelOffsetX??z;return $.x+F}).attr("y",O=>{let $=E.get(O.id);if(O.className==="anchor")return O.labelOffsetY!==void 0?$.y+O.labelOffsetY:$.y-3;let z=-n.nodeLabelOffset;O.sourceStrategy&&O.labelOffsetY===void 0&&(z-=10);let F=O.labelOffsetY??z;return $.y+F}).attr("class","wardley-node-label").attr("fill",O=>O.className==="evolved"?a.evolutionStroke:O.className==="anchor"?"#000":a.componentLabelColor).attr("font-size",n.labelFontSize).attr("font-weight",O=>O.className==="anchor"?"bold":"normal").attr("text-anchor",O=>O.className==="anchor"?"middle":"start").attr("dominant-baseline",O=>O.className==="anchor"?"middle":"auto").text(O=>O.label),u.annotations.length>0){let O=m.append("g").attr("class","wardley-annotations");if(u.annotations.forEach($=>{let z=$.coordinates.map(F=>({x:x(F.x),y:b(F.y)}));if(z.length>1)for(let F=0;F{let V=O.append("g").attr("class","wardley-annotation");V.append("circle").attr("cx",F.x).attr("cy",F.y).attr("r",10).attr("fill","white").attr("stroke",a.axisColor).attr("stroke-width",1.5),V.append("text").attr("x",F.x).attr("y",F.y).attr("text-anchor","middle").attr("dominant-baseline","central").attr("font-size",10).attr("fill",a.axisTextColor).attr("font-weight","bold").text($.number)})}),u.annotationsBox){let $=x(u.annotationsBox.x),z=b(u.annotationsBox.y),F=10,V=16,H=11,X=O.append("g").attr("class","wardley-annotations-box"),W=[...u.annotations].filter(Y=>Y.text).sort((Y,ae)=>Y.number-ae.number),Z=[];if(W.forEach((Y,ae)=>{let J=X.append("text").attr("x",$+F).attr("y",z+F+(ae+1)*V).attr("font-size",H).attr("fill",a.axisTextColor).attr("text-anchor","start").attr("dominant-baseline","middle").text(`${Y.number}. ${Y.text}`);Z.push(J)}),Z.length>0){let Y=0,ae=0;Z.forEach(Ee=>{let Ne=Ee.node(),we=Ne.getComputedTextLength();Y=Math.max(Y,we);let Te=Ne.getBBox();ae=Math.max(ae,Te.height)});let J=Y+F*2+105,ee=W.length*V+F*2+ae/2,re=n.padding,te=f-n.padding-J,be=n.padding,de=d-n.padding-ee;$=Math.max(re,Math.min($,te)),z=Math.max(be,Math.min(z,de)),Z.forEach((Ee,Ne)=>{Ee.attr("x",$+F).attr("y",z+F+(Ne+1)*V)}),X.insert("rect","text").attr("x",$).attr("y",z).attr("width",J).attr("height",ee).attr("fill","white").attr("stroke",a.axisColor).attr("stroke-width",1.5).attr("rx",4).attr("ry",4)}}}if(u.notes.length>0){let O=m.append("g").attr("class","wardley-notes");u.notes.forEach($=>{let z=x($.x),F=b($.y);O.append("text").attr("x",z).attr("y",F).attr("text-anchor","start").attr("font-size",11).attr("fill",a.axisTextColor).attr("font-weight","bold").text($.text)})}if(u.accelerators.length>0){let O=m.append("g").attr("class","wardley-accelerators");u.accelerators.forEach($=>{let z=x($.x),F=b($.y),V=60,H=30,X=20,W=` + M ${z} ${F-H/2} + L ${z+V-X} ${F-H/2} + L ${z+V-X} ${F-H/2-8} + L ${z+V} ${F} + L ${z+V-X} ${F+H/2+8} + L ${z+V-X} ${F+H/2} + L ${z} ${F+H/2} + Z + `;O.append("path").attr("d",W).attr("fill","white").attr("stroke",a.componentStroke).attr("stroke-width",1),O.append("text").attr("x",z+V/2).attr("y",F+H/2+15).attr("text-anchor","middle").attr("font-size",10).attr("fill",a.axisTextColor).attr("font-weight","bold").text($.name)})}if(u.deaccelerators.length>0){let O=m.append("g").attr("class","wardley-deaccelerators");u.deaccelerators.forEach($=>{let z=x($.x),F=b($.y),V=60,H=30,X=20,W=` + M ${z+V} ${F-H/2} + L ${z+X} ${F-H/2} + L ${z+X} ${F-H/2-8} + L ${z} ${F} + L ${z+X} ${F+H/2+8} + L ${z+X} ${F+H/2} + L ${z+V} ${F+H/2} + Z + `;O.append("path").attr("d",W).attr("fill","white").attr("stroke",a.componentStroke).attr("stroke-width",1),O.append("text").attr("x",z+V/2).attr("y",F+H/2+15).attr("text-anchor","middle").attr("font-size",10).attr("fill",a.axisTextColor).attr("font-weight","bold").text($.name)})}},"draw"),f_e={draw:Nyt}});var p_e={};ur(p_e,{diagram:()=>Iyt});var Iyt,m_e=P(()=>{"use strict";l_e();h_e();d_e();Iyt={parser:pY,db:u_e,renderer:f_e,styles:o(()=>"","styles")}});var bvt={};ur(bvt,{default:()=>xvt});lu();oL();Kp();var KFe=o(t=>/^\s*C4Context|C4Container|C4Component|C4Dynamic|C4Deployment/.test(t),"detector"),QFe=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(kne(),Tne));return{id:"c4",diagram:t}},"loader"),ZFe={id:"c4",detector:KFe,loader:QFe},Cne=ZFe;var Cye="flowchart",Lit=o((t,e)=>e?.flowchart?.defaultRenderer==="dagre-wrapper"||e?.flowchart?.defaultRenderer==="elk"?!1:/^\s*graph/.test(t),"detector"),Rit=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(WS(),qS));return{id:Cye,diagram:t}},"loader"),Nit={id:Cye,detector:Lit,loader:Rit},wye=Nit;var Eye="flowchart-v2",Iit=o((t,e)=>e?.flowchart?.defaultRenderer==="dagre-d3"?!1:(e?.flowchart?.defaultRenderer==="elk"&&(e.layout="elk"),/^\s*graph/.test(t)&&e?.flowchart?.defaultRenderer==="dagre-wrapper"?!0:/^\s*flowchart/.test(t)),"detector"),Mit=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(WS(),qS));return{id:Eye,diagram:t}},"loader"),Oit={id:Eye,detector:Iit,loader:Mit},Sye=Oit;var zit=o(t=>/^\s*erDiagram/.test(t),"detector"),Git=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(Oye(),Mye));return{id:"er",diagram:t}},"loader"),Vit={id:"er",detector:zit,loader:Git},Pye=Vit;var k4e="gitGraph",Ect=o(t=>/^\s*gitGraph/.test(t),"detector"),Sct=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(T4e(),b4e));return{id:k4e,diagram:t}},"loader"),Act={id:k4e,detector:Ect,loader:Sct},C4e=Act;var twe="gantt",mut=o(t=>/^\s*gantt/.test(t),"detector"),gut=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(ewe(),J4e));return{id:twe,diagram:t}},"loader"),yut={id:twe,detector:mut,loader:gut},rwe=yut;var hwe="info",kut=o(t=>/^\s*info/.test(t),"detector"),Cut=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(uwe(),cwe));return{id:hwe,diagram:t}},"loader"),fwe={id:hwe,detector:kut,loader:Cut};var Put=o(t=>/^\s*pie/.test(t),"detector"),But=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(Twe(),bwe));return{id:"pie",diagram:t}},"loader"),kwe={id:"pie",detector:Put,loader:But};var Owe="quadrantChart",tht=o(t=>/^\s*quadrantChart/.test(t),"detector"),rht=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(Mwe(),Iwe));return{id:Owe,diagram:t}},"loader"),iht={id:Owe,detector:tht,loader:rht},Pwe=iht;var c3e="xychart",bht=o(t=>/^\s*xychart(-beta)?/.test(t),"detector"),Tht=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(l3e(),o3e));return{id:c3e,diagram:t}},"loader"),kht={id:c3e,detector:bht,loader:Tht},u3e=kht;var x3e="requirement",Aht=o(t=>/^\s*requirement(Diagram)?/.test(t),"detector"),_ht=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(v3e(),y3e));return{id:x3e,diagram:t}},"loader"),Dht={id:x3e,detector:Aht,loader:_ht},b3e=Dht;var F3e="sequence",Eft=o(t=>/^\s*sequenceDiagram/.test(t),"detector"),Sft=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(B3e(),P3e));return{id:F3e,diagram:t}},"loader"),Aft={id:F3e,detector:Eft,loader:Sft},$3e=Aft;var U3e="class",Ift=o((t,e)=>e?.class?.defaultRenderer==="dagre-wrapper"?!1:/^\s*classDiagram/.test(t),"detector"),Mft=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(W3e(),q3e));return{id:U3e,diagram:t}},"loader"),Oft={id:U3e,detector:Ift,loader:Mft},H3e=Oft;var X3e="classDiagram",Bft=o((t,e)=>/^\s*classDiagram/.test(t)&&e?.class?.defaultRenderer==="dagre-wrapper"?!0:/^\s*classDiagram-v2/.test(t),"detector"),Fft=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(j3e(),Y3e));return{id:X3e,diagram:t}},"loader"),$ft={id:X3e,detector:Bft,loader:Fft},K3e=$ft;var _5e="state",hdt=o((t,e)=>e?.state?.defaultRenderer==="dagre-wrapper"?!1:/^\s*stateDiagram/.test(t),"detector"),fdt=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(A5e(),S5e));return{id:_5e,diagram:t}},"loader"),ddt={id:_5e,detector:hdt,loader:fdt},D5e=ddt;var N5e="stateDiagram",mdt=o((t,e)=>!!(/^\s*stateDiagram-v2/.test(t)||/^\s*stateDiagram/.test(t)&&e?.state?.defaultRenderer==="dagre-wrapper"),"detector"),gdt=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(R5e(),L5e));return{id:N5e,diagram:t}},"loader"),ydt={id:N5e,detector:mdt,loader:gdt},I5e=ydt;var j5e="journey",Fdt=o(t=>/^\s*journey/.test(t),"detector"),$dt=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(Y5e(),H5e));return{id:j5e,diagram:t}},"loader"),zdt={id:j5e,detector:Fdt,loader:$dt},X5e=zdt;bt();ro();Xi();var Gdt=o((t,e,r)=>{Q.debug(`rendering svg for syntax error +`);let i=Fi(e),n=i.append("g");i.attr("viewBox","0 0 2412 512"),Hr(i,100,512,!0),n.append("path").attr("class","error-icon").attr("d","m411.313,123.313c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32-9.375,9.375-20.688-20.688c-12.484-12.5-32.766-12.5-45.25,0l-16,16c-1.261,1.261-2.304,2.648-3.31,4.051-21.739-8.561-45.324-13.426-70.065-13.426-105.867,0-192,86.133-192,192s86.133,192 192,192 192-86.133 192-192c0-24.741-4.864-48.327-13.426-70.065 1.402-1.007 2.79-2.049 4.051-3.31l16-16c12.5-12.492 12.5-32.758 0-45.25l-20.688-20.688 9.375-9.375 32.001-31.999zm-219.313,100.687c-52.938,0-96,43.063-96,96 0,8.836-7.164,16-16,16s-16-7.164-16-16c0-70.578 57.422-128 128-128 8.836,0 16,7.164 16,16s-7.164,16-16,16z"),n.append("path").attr("class","error-icon").attr("d","m459.02,148.98c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l16,16c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16.001-16z"),n.append("path").attr("class","error-icon").attr("d","m340.395,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688 6.25-6.25 6.25-16.375 0-22.625l-16-16c-6.25-6.25-16.375-6.25-22.625,0s-6.25,16.375 0,22.625l15.999,16z"),n.append("path").attr("class","error-icon").attr("d","m400,64c8.844,0 16-7.164 16-16v-32c0-8.836-7.156-16-16-16-8.844,0-16,7.164-16,16v32c0,8.836 7.156,16 16,16z"),n.append("path").attr("class","error-icon").attr("d","m496,96.586h-32c-8.844,0-16,7.164-16,16 0,8.836 7.156,16 16,16h32c8.844,0 16-7.164 16-16 0-8.836-7.156-16-16-16z"),n.append("path").attr("class","error-icon").attr("d","m436.98,75.605c3.125,3.125 7.219,4.688 11.313,4.688 4.094,0 8.188-1.563 11.313-4.688l32-32c6.25-6.25 6.25-16.375 0-22.625s-16.375-6.25-22.625,0l-32,32c-6.251,6.25-6.251,16.375-0.001,22.625z"),n.append("text").attr("class","error-text").attr("x",1440).attr("y",250).attr("font-size","150px").style("text-anchor","middle").text("Syntax error in text"),n.append("text").attr("class","error-text").attr("x",1250).attr("y",400).attr("font-size","100px").style("text-anchor","middle").text(`mermaid version ${r}`)},"draw"),GU={draw:Gdt},K5e=GU;var Vdt={db:{},renderer:GU,parser:{parse:o(()=>{},"parse")}},Q5e=Vdt;var Z5e="flowchart-elk",qdt=o((t,e={})=>/^\s*flowchart-elk/.test(t)||/^\s*(flowchart|graph)/.test(t)&&e?.flowchart?.defaultRenderer==="elk"?(e.layout="elk",!0):!1,"detector"),Wdt=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(WS(),qS));return{id:Z5e,diagram:t}},"loader"),Udt={id:Z5e,detector:qdt,loader:Wdt},J5e=Udt;var MEe="timeline",gpt=o(t=>/^\s*timeline/.test(t),"detector"),ypt=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(IEe(),NEe));return{id:MEe,diagram:t}},"loader"),vpt={id:MEe,detector:gpt,loader:ypt},OEe=vpt;var JEe="mindmap",Apt=o(t=>/^\s*mindmap/.test(t),"detector"),_pt=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(ZEe(),QEe));return{id:JEe,diagram:t}},"loader"),Dpt={id:JEe,detector:Apt,loader:_pt},eSe=Dpt;var fSe="kanban",Upt=o(t=>/^\s*kanban/.test(t),"detector"),Hpt=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(hSe(),uSe));return{id:fSe,diagram:t}},"loader"),Ypt={id:fSe,detector:Upt,loader:Hpt},dSe=Ypt;var jSe="sankey",g0t=o(t=>/^\s*sankey(-beta)?/.test(t),"detector"),y0t=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(YSe(),HSe));return{id:jSe,diagram:t}},"loader"),v0t={id:jSe,detector:g0t,loader:y0t},XSe=v0t;var i6e="packet",A0t=o(t=>/^\s*packet(-beta)?/.test(t),"detector"),_0t=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(r6e(),t6e));return{id:i6e,diagram:t}},"loader"),n6e={id:i6e,detector:A0t,loader:_0t};var m6e="radar",K0t=o(t=>/^\s*radar-beta/.test(t),"detector"),Q0t=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(p6e(),d6e));return{id:m6e,diagram:t}},"loader"),g6e={id:m6e,detector:K0t,loader:Q0t};var xAe="block",vgt=o(t=>/^\s*block(-beta)?/.test(t),"detector"),xgt=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(vAe(),yAe));return{id:xAe,diagram:t}},"loader"),bgt={id:xAe,detector:vgt,loader:xgt},bAe=bgt;var LAe="treeView",Pgt=o(t=>/^\s*treeView-beta/.test(t),"detector"),Bgt=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(DAe(),_Ae));return{id:LAe,diagram:t}},"loader"),Fgt={id:LAe,detector:Pgt,loader:Bgt},RAe=Fgt;var JAe="architecture",Jgt=o(t=>/^\s*architecture/.test(t),"detector"),e1t=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(ZAe(),QAe));return{id:JAe,diagram:t}},"loader"),t1t={id:JAe,detector:Jgt,loader:e1t},e7e=t1t;var y7e="ishikawa",p1t=o(t=>/^\s*ishikawa(-beta)?\b/i.test(t),"detector"),m1t=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(g7e(),m7e));return{id:y7e,diagram:t}},"loader"),v7e={id:y7e,detector:p1t,loader:m1t};var j7e="venn",Z1t=o(t=>/^\s*venn-beta/.test(t),"detector"),J1t=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(Y7e(),H7e));return{id:j7e,diagram:t}},"loader"),eyt={id:j7e,detector:Z1t,loader:J1t},X7e=eyt;Kp();Ut();var a_e="treemap",cyt=o(t=>/^\s*treemap/.test(t),"detector"),uyt=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(n_e(),i_e));return{id:a_e,diagram:t}},"loader"),s_e={id:a_e,detector:cyt,loader:uyt};var g_e="wardley-beta",Myt=o(t=>/^\s*wardley-beta/i.test(t),"detector"),Oyt=o(async()=>{let{diagram:t}=await Promise.resolve().then(()=>(m_e(),p_e));return{id:g_e,diagram:t}},"loader"),Pyt={id:g_e,detector:Myt,loader:Oyt},y_e=Pyt;var v_e=!1,Tx=o(()=>{v_e||(v_e=!0,Qp("error",Q5e,t=>t.toLowerCase().trim()==="error"),Qp("---",{db:{clear:o(()=>{},"clear")},styles:{},renderer:{draw:o(()=>{},"draw")},parser:{parse:o(()=>{throw new Error("Diagrams beginning with --- are not valid. If you were trying to use a YAML front-matter, please ensure that you've correctly opened and closed the YAML front-matter with un-indented `---` blocks")},"parse")},init:o(()=>null,"init")},t=>t.toLowerCase().trimStart().startsWith("---")),Zx(J5e,eSe,e7e),Zx(Cne,dSe,K3e,H3e,Pye,rwe,fwe,kwe,b3e,$3e,Sye,wye,OEe,C4e,I5e,D5e,X5e,Pwe,XSe,n6e,u3e,bAe,RAe,g6e,v7e,s_e,X7e,y_e))},"addDiagrams");bt();Kp();Ut();var x_e=o(async()=>{Q.debug("Loading registered diagrams");let e=(await Promise.allSettled(Object.entries(wh).map(async([r,{detector:i,loader:n}])=>{if(n)try{i2(r)}catch{try{let{diagram:a,id:s}=await n();Qp(s,a,i)}catch(a){throw Q.error(`Failed to load external diagram with key ${r}. Removing from detectors.`),delete wh[r],a}}}))).filter(r=>r.status==="rejected");if(e.length>0){Q.error(`Failed to load ${e.length} external diagrams`);for(let r of e)Q.error(r);throw new Error(`Failed to load ${e.length} external diagrams`)}},"loadRegisteredDiagrams");bt();Pr();var h8="comm",f8="rule",d8="decl";var b_e="@import";var T_e="@namespace",k_e="@keyframes";var C_e="@layer";var mY=Math.abs,JC=String.fromCharCode;function p8(t){return t.trim()}o(p8,"trim");function e4(t,e,r){return t.replace(e,r)}o(e4,"replace");function w_e(t,e,r){return t.indexOf(e,r)}o(w_e,"indexof");function Mp(t,e){return t.charCodeAt(e)|0}o(Mp,"charat");function Op(t,e,r){return t.slice(e,r)}o(Op,"substr");function ml(t){return t.length}o(ml,"strlen");function E_e(t){return t.length}o(E_e,"sizeof");function kx(t,e){return e.push(t),t}o(kx,"append");var m8=1,Cx=1,S_e=0,ac=0,aa=0,Ex="";function g8(t,e,r,i,n,a,s,l){return{value:t,root:e,parent:r,type:i,props:n,children:a,line:m8,column:Cx,length:s,return:"",siblings:l}}o(g8,"node");function A_e(){return aa}o(A_e,"char");function __e(){return aa=ac>0?Mp(Ex,--ac):0,Cx--,aa===10&&(Cx=1,m8--),aa}o(__e,"prev");function sc(){return aa=ac2||wx(aa)>3?"":" "}o(R_e,"whitespace");function N_e(t,e){for(;--e&&sc()&&!(aa<48||aa>102||aa>57&&aa<65||aa>70&&aa<97););return y8(t,t4()+(e<6&&Df()==32&&sc()==32))}o(N_e,"escaping");function gY(t){for(;sc();)switch(aa){case t:return ac;case 34:case 39:t!==34&&t!==39&&gY(aa);break;case 40:t===41&&gY(t);break;case 92:sc();break}return ac}o(gY,"delimiter");function I_e(t,e){for(;sc()&&t+aa!==57;)if(t+aa===84&&Df()===47)break;return"/*"+y8(e,ac-1)+"*"+JC(t===47?t:sc())}o(I_e,"commenter");function M_e(t){for(;!wx(Df());)sc();return y8(t,ac)}o(M_e,"identifier");function B_e(t){return L_e(x8("",null,null,null,[""],t=D_e(t),0,[0],t))}o(B_e,"compile");function x8(t,e,r,i,n,a,s,l,u){for(var h=0,f=0,d=s,p=0,m=0,g=0,y=1,v=1,x=1,b=0,T="",w=n,k=a,C=i,E=T;v;)switch(g=b,b=sc()){case 40:if(g!=108&&Mp(E,d-1)==58){w_e(E+=e4(v8(b),"&","&\f"),"&\f",mY(h?l[h-1]:0))!=-1&&(x=-1);break}case 34:case 39:case 91:E+=v8(b);break;case 9:case 10:case 13:case 32:E+=R_e(g);break;case 92:E+=N_e(t4()-1,7);continue;case 47:switch(Df()){case 42:case 47:kx(Byt(I_e(sc(),t4()),e,r,u),u),(wx(g||1)==5||wx(Df()||1)==5)&&ml(E)&&Op(E,-1,void 0)!==" "&&(E+=" ");break;default:E+="/"}break;case 123*y:l[h++]=ml(E)*x;case 125*y:case 59:case 0:switch(b){case 0:case 125:v=0;case 59+f:x==-1&&(E=e4(E,/\f/g,"")),m>0&&(ml(E)-d||y===0&&g===47)&&kx(m>32?P_e(E+";",i,r,d-1,u):P_e(e4(E," ","")+";",i,r,d-2,u),u);break;case 59:E+=";";default:if(kx(C=O_e(E,e,r,h,f,n,l,T,w=[],k=[],d,a),a),b===123)if(f===0)x8(E,e,C,C,w,a,d,l,k);else{switch(p){case 99:if(Mp(E,3)===110)break;case 108:if(Mp(E,2)===97)break;default:f=0;case 100:case 109:case 115:}f?x8(t,C,C,i&&kx(O_e(t,C,C,0,0,n,l,T,n,w=[],d,k),k),n,k,d,l,i?w:k):x8(E,C,C,C,[""],k,0,l,k)}}h=f=m=0,y=x=1,T=E="",d=s;break;case 58:d=1+ml(E),m=g;default:if(y<1){if(b==123)--y;else if(b==125&&y++==0&&__e()==125)continue}switch(E+=JC(b),b*y){case 38:x=f>0?1:(E+="\f",-1);break;case 44:l[h++]=(ml(E)-1)*x,x=1;break;case 64:Df()===45&&(E+=v8(sc())),p=Df(),f=d=ml(T=E+=M_e(t4())),b++;break;case 45:g===45&&ml(E)==2&&(y=0)}}return a}o(x8,"parse");function O_e(t,e,r,i,n,a,s,l,u,h,f,d){for(var p=n-1,m=n===0?a:[""],g=E_e(m),y=0,v=0,x=0;y0?m[b]+" "+T:e4(T,/&\f/g,m[b])))&&(u[x++]=w);return g8(t,e,r,n===0?f8:l,u,h,f,d)}o(O_e,"ruleset");function Byt(t,e,r,i){return g8(t,e,r,h8,JC(A_e()),Op(t,2,-2),0,i)}o(Byt,"comment");function P_e(t,e,r,i,n){return g8(t,e,r,d8,Op(t,0,i),Op(t,i+1,-1),i,n)}o(P_e,"declaration");function b8(t,e){for(var r="",i=0;i{G_e.forEach(t=>{t()}),G_e=[]},"attachFunctions");bt();var q_e=o(t=>t.replace(/^\s*%%(?!{)[^\n]+\n?/gm,"").trimStart(),"cleanupComments");ew();xb();function W_e(t){let e=t.match(J4);if(!e)return{text:t,metadata:{}};let r=ud(e[1],{schema:cd})??{};r=typeof r=="object"&&!Array.isArray(r)?r:{};let i={};return r.displayMode&&(i.displayMode=r.displayMode.toString()),r.title&&(i.title=r.title.toString()),r.config&&(i.config=r.config),{text:t.slice(e[0].length),metadata:i}}o(W_e,"extractFrontMatter");er();var $yt=o(t=>t.replace(/\r\n?/g,` +`).replace(/<(\w+)([^>]*)>/g,(e,r,i)=>"<"+r+i.replace(/="([^"]*)"/g,"='$1'")+">"),"cleanupText"),zyt=o(t=>{let{text:e,metadata:r}=W_e(t),{displayMode:i,title:n,config:a={}}=r;return i&&(a.gantt||(a.gantt={}),a.gantt.displayMode=i),{title:n,config:a,text:e}},"processFrontmatter"),Gyt=o(t=>{let e=Kt.detectInit(t)??{},r=Kt.detectDirective(t,"wrap");return Array.isArray(r)?e.wrap=r.some(({type:i})=>i==="wrap"):r?.type==="wrap"&&(e.wrap=!0),{text:une(t),directive:e}},"processDirectives");function yY(t){let e=$yt(t),r=zyt(e),i=Gyt(r.text),n=fi(r.config,i.directive);return t=q_e(i.text),{code:t,title:r.title,config:n}}o(yY,"preprocessDiagram");hL();g4();er();function U_e(t){let e=new TextEncoder().encode(t),r=Array.from(e,i=>String.fromCodePoint(i)).join("");return btoa(r)}o(U_e,"toBase64");var Vyt=5e4,qyt="graph TB;a[Maximum text size in diagram exceeded];style a fill:#faa",Wyt="sandbox",Uyt="loose",Hyt="http://www.w3.org/2000/svg",Yyt="http://www.w3.org/1999/xlink",jyt="http://www.w3.org/1999/xhtml",Xyt="100%",Kyt="100%",Qyt="border:0;margin:0;",Zyt="margin:0",Jyt="allow-top-navigation-by-user-activation allow-popups",evt='The "iframe" tag is not supported by your browser.',tvt=["foreignobject"],rvt=["dominant-baseline"];function X_e(t){let e=yY(t);return Mx(),qj(e.config??{}),e}o(X_e,"processAndSetConfigs");async function ivt(t,e){Tx();try{let{code:r,config:i}=X_e(t);return{diagramType:(await K_e(r)).type,config:i}}catch(r){if(e?.suppressErrors)return!1;throw r}}o(ivt,"parse");var H_e=o((t,e,r=[])=>` +.${t} ${e} { ${r.join(" !important; ")} !important; }`,"cssImportantStyles"),nvt=o((t,e=new Map)=>{let r="";if(t.themeCSS!==void 0&&(r+=` +${t.themeCSS}`),t.fontFamily!==void 0&&(r+=` +:root { --mermaid-font-family: ${t.fontFamily}}`),t.altFontFamily!==void 0&&(r+=` +:root { --mermaid-alt-font-family: ${t.altFontFamily}}`),e instanceof Map){let s=Or(t)?["> *","span"]:["rect","polygon","ellipse","circle","path"];e.forEach(l=>{_r(l.styles)||s.forEach(u=>{r+=H_e(l.id,u,l.styles)}),_r(l.textStyles)||(r+=H_e(l.id,"tspan",(l?.textStyles||[]).map(u=>u.replace("color","fill"))))})}return r},"createCssStyles"),avt=o((t,e,r,i)=>{let n=nvt(t,r),a=XK(e,n,{...t.themeVariables,theme:t.theme,look:t.look},i);return b8(B_e(`${i}{${a}}`),F_e)},"createUserStyles"),svt=o((t="",e,r)=>{let i=t;return!r&&!e&&(i=i.replace(/marker-end="url\([\d+./:=?A-Za-z-]*?#/g,'marker-end="url(#')),i=zs(i),i=i.replace(/
    /g,"
    "),i},"cleanUpSvgCode"),ovt=o((t="",e)=>{let r=e?.viewBox?.baseVal?.height?e.viewBox.baseVal.height+"px":Kyt,i=U_e(`${t}`);return``},"putIntoIFrame"),Y_e=o((t,e,r,i,n)=>{let a=t.append("div");a.attr("id",r),i&&a.attr("style",i);let s=a.append("svg").attr("id",e).attr("width","100%").attr("xmlns",Hyt);return n&&s.attr("xmlns:xlink",n),s.append("g"),t},"appendDivSvgG");function j_e(t,e){return t.append("iframe").attr("id",e).attr("style","width: 100%; height: 100%;").attr("sandbox","")}o(j_e,"sandboxedIframe");var lvt=o((t,e,r,i)=>{t.getElementById(e)?.remove(),t.getElementById(r)?.remove(),t.getElementById(i)?.remove()},"removeExistingElements"),cvt=o(async function(t,e,r){Tx();let i=X_e(e);e=i.code;let n=Lt();Q.debug(n),e.length>(n?.maxTextSize??Vyt)&&(e=qyt);let a="#"+t,s="i"+t,l="#"+s,u="d"+t,h="#"+u,f=o(()=>{let _=Ze(p?l:h).node();_&&"remove"in _&&_.remove()},"removeTempElements"),d=Ze("body"),p=n.securityLevel===Wyt,m=n.securityLevel===Uyt,g=n.fontFamily;if(r!==void 0){if(r&&(r.innerHTML=""),p){let A=j_e(Ze(r),s);d=Ze(A.nodes()[0].contentDocument.body),d.node().style.margin=0}else d=Ze(r);Y_e(d,t,u,`font-family: ${g}`,Yyt)}else{if(lvt(document,t,u,s),p){let A=j_e(Ze("body"),s);d=Ze(A.nodes()[0].contentDocument.body),d.node().style.margin=0}else d=Ze("body");Y_e(d,t,u)}let y,v;try{y=await Sx.fromText(e,{title:i.title})}catch(A){if(n.suppressErrorRendering)throw f(),A;y=await Sx.fromText("error"),v=A}let x=d.select(h).node(),b=y.type,T=x.firstChild,w=T.firstChild,k=y.renderer.getClasses?.(e,y),C=avt(n,b,k,a),E=document.createElement("style");E.innerHTML=C,T.insertBefore(E,w);try{await y.renderer.draw(e,t,"11.14.0",y)}catch(A){throw n.suppressErrorRendering?f():K5e.draw(e,t,"11.14.0"),A}let S=d.select(`${h} svg`),L=y.db.getAccTitle?.(),M=y.db.getAccDescription?.();hvt(b,S,L,M),d.select(`[id="${t}"]`).selectAll("foreignobject > *").attr("xmlns",jyt);let I=d.select(h).node().innerHTML;if(Q.debug("config.arrowMarkerAbsolute",n.arrowMarkerAbsolute),I=svt(I,p,ls(n.arrowMarkerAbsolute)),p){let A=d.select(h+" svg").node();I=ovt(I,A)}else m||(I=Tl.sanitize(I,{ADD_TAGS:tvt,ADD_ATTR:rvt,HTML_INTEGRATION_POINTS:{foreignobject:!0}}));if(V_e(),v)throw v;return f(),{diagramType:b,svg:I,bindFunctions:y.db.bindFunctions}},"render");function uvt(t={}){let e=Yi({},t);e?.fontFamily&&!e.themeVariables?.fontFamily&&(e.themeVariables||(e.themeVariables={}),e.themeVariables.fontFamily=e.fontFamily),zj(e),e?.theme&&e.theme in xl?e.themeVariables=xl[e.theme].getThemeVariables(e.themeVariables):e&&(e.themeVariables=xl.default.getThemeVariables(e.themeVariables));let r=typeof e=="object"?nD(e):aD();_x(r.logLevel),Tx()}o(uvt,"initialize");var K_e=o((t,e={})=>{let{code:r}=yY(t);return Sx.fromText(r,e)},"getDiagramFromText");function hvt(t,e,r,i){$_e(e,t),z_e(e,r,i,e.attr("id"))}o(hvt,"addA11yInfo");var Pp=Object.freeze({render:cvt,parse:ivt,getDiagramFromText:K_e,initialize:uvt,getConfig:Lt,setConfig:x4,getSiteConfig:aD,updateSiteConfig:Gj,reset:o(()=>{Mx()},"reset"),globalReset:o(()=>{Mx(Nf)},"globalReset"),defaultConfig:Nf});_x(Lt().logLevel);Mx(Lt());Wd();er();var fvt=o((t,e,r)=>{Q.warn(t),wI(t)?(r&&r(t.str,t.hash),e.push({...t,message:t.str,error:t})):(r&&r(t),t instanceof Error&&e.push({str:t.message,message:t.message,hash:t.name,error:t}))},"handleError"),Q_e=o(async function(t={querySelector:".mermaid"}){try{await dvt(t)}catch(e){if(wI(e)&&Q.error(e.str),Lf.parseError&&Lf.parseError(e),!t.suppressErrors)throw Q.error("Use the suppressErrors option to suppress these errors"),e}},"run"),dvt=o(async function({postRenderCallback:t,querySelector:e,nodes:r}={querySelector:".mermaid"}){let i=Pp.getConfig();Q.debug(`${t?"":"No "}Callback function found`);let n;if(r)n=r;else if(e)n=document.querySelectorAll(e);else throw new Error("Nodes and querySelector are both undefined");Q.debug(`Found ${n.length} diagrams`),i?.startOnLoad!==void 0&&(Q.debug("Start On Load: "+i?.startOnLoad),Pp.updateSiteConfig({startOnLoad:i?.startOnLoad}));let a=new Kt.InitIDGenerator(i.deterministicIds,i.deterministicIDSeed),s,l=[];for(let u of Array.from(n)){Q.info("Rendering diagram: "+u.id);if(u.getAttribute("data-processed"))continue;u.setAttribute("data-processed","true");let h=`mermaid-${a.next()}`;s=u.innerHTML,s=Z4(Kt.entityDecode(s)).trim().replace(//gi,"
    ");let f=Kt.detectInit(s);f&&Q.debug("Detected early reinit: ",f);try{let{svg:d,bindFunctions:p}=await t8e(h,s,u);u.innerHTML=d,t&&await t(h),p&&p(u)}catch(d){fvt(d,l,Lf.parseError)}}if(l.length>0)throw l[0]},"runThrowsErrors"),Z_e=o(function(t){Pp.initialize(t)},"initialize"),pvt=o(async function(t,e,r){Q.warn("mermaid.init is deprecated. Please use run instead."),t&&Z_e(t);let i={postRenderCallback:r,querySelector:".mermaid"};typeof e=="string"?i.querySelector=e:e&&(e instanceof HTMLElement?i.nodes=[e]:i.nodes=e),await Q_e(i)},"init"),mvt=o(async(t,{lazyLoad:e=!0}={})=>{Tx(),Zx(...t),e===!1&&await x_e()},"registerExternalDiagrams"),J_e=o(function(){if(Lf.startOnLoad){let{startOnLoad:t}=Pp.getConfig();t&&Lf.run().catch(e=>Q.error("Mermaid failed to initialize",e))}},"contentLoaded");if(typeof document<"u"){window.addEventListener("load",J_e,!1)}var gvt=o(function(t){Lf.parseError=t},"setParseErrorHandler"),T8=[],vY=!1,e8e=o(async()=>{if(!vY){for(vY=!0;T8.length>0;){let t=T8.shift();if(t)try{await t()}catch(e){Q.error("Error executing queue",e)}}vY=!1}},"executeQueue"),yvt=o(async(t,e)=>new Promise((r,i)=>{let n=o(()=>new Promise((a,s)=>{Pp.parse(t,e).then(l=>{a(l),r(l)},l=>{Q.error("Error parsing",l),Lf.parseError?.(l),s(l),i(l)})}),"performCall");T8.push(n),e8e().catch(i)}),"parse"),t8e=o((t,e,r)=>new Promise((i,n)=>{let a=o(()=>new Promise((s,l)=>{Pp.render(t,e,r).then(u=>{s(u),i(u)},u=>{Q.error("Error parsing",u),Lf.parseError?.(u),l(u),n(u)})}),"performCall");T8.push(a),e8e().catch(n)}),"render"),vvt=o(()=>Object.keys(wh).map(t=>({id:t})),"getRegisteredDiagramsMetadata"),Lf={startOnLoad:!0,mermaidAPI:Pp,parse:yvt,render:t8e,init:pvt,run:Q_e,registerExternalDiagrams:mvt,registerLayoutLoaders:kF,initialize:Z_e,parseError:void 0,contentLoaded:J_e,setParseErrorHandler:gvt,detectType:Ig,registerIconPacks:Q4,getRegisteredDiagramsMetadata:vvt},xvt=Lf;return s4(bvt);})(); +/*! Check if previously processed */ +/*! + * Wait for document loaded before starting the execution + */ +/*! Bundled license information: + +dompurify/dist/purify.es.mjs: + (*! @license DOMPurify 3.3.1 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.1/LICENSE *) + +js-yaml/dist/js-yaml.mjs: + (*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT *) + +lodash-es/lodash.js: + (** + * @license + * Lodash (Custom Build) + * Build: `lodash modularize exports="es" -o ./` + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + *) + +cytoscape/dist/cytoscape.esm.mjs: + (*! + Embeddable Minimum Strictly-Compliant Promises/A+ 1.1.1 Thenable + Copyright (c) 2013-2014 Ralf S. Engelschall (http://engelschall.com) + Licensed under The MIT License (http://opensource.org/licenses/MIT) + *) + (*! + Event object based on jQuery events, MIT license + + https://jquery.org/license/ + https://tldrlegal.com/license/mit-license + https://github.com/jquery/jquery/blob/master/src/event.js + *) + (*! Bezier curve function generator. Copyright Gaetan Renaudeau. MIT License: http://en.wikipedia.org/wiki/MIT_License *) + (*! Runge-Kutta spring physics function generator. Adapted from Framer.js, copyright Koen Bok. MIT License: http://en.wikipedia.org/wiki/MIT_License *) +*/ +globalThis["mermaid"] = globalThis.__esbuild_esm_mermaid_nm["mermaid"].default; diff --git a/src/autoskillit/assets/research/Dockerfile.template b/src/autoskillit/assets/research/Dockerfile.template new file mode 100644 index 0000000000..440700ef84 --- /dev/null +++ b/src/autoskillit/assets/research/Dockerfile.template @@ -0,0 +1,23 @@ +FROM mambaorg/micromamba:1.0-bullseye-slim +SHELL ["/bin/bash", "-c"] +ARG MAMBA_ENV="research_env" + +USER root +RUN apt-get --allow-releaseinfo-change update \ + && apt-get install -y --no-install-recommends procps git curl build-essential \ + && apt-get clean -y && rm -rf /var/lib/apt/lists/* + +RUN curl -sL https://taskfile.dev/install.sh | sh -s -- -b /usr/local/bin + +RUN rm -f /root/.bashrc \ + && echo "source /etc/container.bashrc" >> /etc/bash.bashrc \ + && echo "set +u" > /etc/container.bashrc \ + && echo 'eval "$(micromamba shell hook --shell=bash)"' >> /etc/container.bashrc + +ENV BASH_ENV=/etc/container.bashrc +ENV ENV=/etc/container.bashrc + +# The environment YAML is the source of truth — lives in the research dir +COPY ${MAMBA_ENV}.yaml /opt/research/env/ +RUN micromamba create -f /opt/research/env/${MAMBA_ENV}.yaml && micromamba clean -afy +RUN echo "micromamba activate ${MAMBA_ENV}" >> /etc/container.bashrc diff --git a/src/autoskillit/cli/__init__.py b/src/autoskillit/cli/__init__.py index dbfec2cc55..a11a10228e 100644 --- a/src/autoskillit/cli/__init__.py +++ b/src/autoskillit/cli/__init__.py @@ -10,6 +10,7 @@ from pathlib import Path # noqa: F401 — tests patch autoskillit.cli.Path.home from autoskillit.cli._cook import cook +from autoskillit.cli._doctor import DoctorResult from autoskillit.cli._hooks import _claude_settings_path from autoskillit.cli._init_helpers import _prompt_recipe_choice from autoskillit.cli._prompts import ( @@ -20,6 +21,7 @@ ) from autoskillit.cli.app import ( _generate_config_yaml, + _is_plugin_installed, _prompt_test_command, app, config_app, @@ -38,16 +40,21 @@ serve, skills_app, skills_list, + update, upgrade, workspace_app, workspace_clean, workspace_init, ) +from autoskillit.hook_registry import HookDriftResult __all__ = [ "_OPEN_KITCHEN_CHOICE", + "_is_plugin_installed", "_build_open_kitchen_prompt", "_build_orchestrator_prompt", + "DoctorResult", + "HookDriftResult", "_claude_settings_path", "_generate_config_yaml", "_prompt_recipe_choice", @@ -71,6 +78,7 @@ "serve", "skills_app", "skills_list", + "update", "upgrade", "workspace_app", "workspace_clean", diff --git a/src/autoskillit/cli/_cook.py b/src/autoskillit/cli/_cook.py index 199133223a..2484b0df4d 100644 --- a/src/autoskillit/cli/_cook.py +++ b/src/autoskillit/cli/_cook.py @@ -2,19 +2,76 @@ from __future__ import annotations -import os import shutil import subprocess import uuid +from collections.abc import Mapping from pathlib import Path from autoskillit.cli._terminal import terminal_guard +_DISPLAY_CATEGORIES: tuple[tuple[str, tuple[str, ...]], ...] = ( + ("Execution", ("run_cmd", "run_python", "run_skill")), + ("Testing & Workspace", ("test_check", "reset_test_dir", "classify_fix", "reset_workspace")), + ( + "Git Operations", + ("merge_worktree", "create_unique_branch", "check_pr_mergeable", "set_commit_status"), + ), + ("Recipes", ("migrate_recipe", "list_recipes", "load_recipe", "validate_recipe")), + ( + "Clone & Remote", + ( + "clone_repo", + "remove_clone", + "push_to_remote", + "register_clone_status", + "batch_cleanup_clones", + ), + ), + ( + "GitHub", + ( + "fetch_github_issue", + "get_issue_title", + "report_bug", + "prepare_issue", + "enrich_issues", + "claim_issue", + "release_issue", + "get_pr_reviews", + "bulk_close_issues", + ), + ), + ( + "CI & Automation", + ( + "wait_for_ci", + "wait_for_merge_queue", + "check_repo_merge_state", + "toggle_auto_merge", + "get_ci_status", + ), + ), + ( + "Telemetry & Diagnostics", + ( + "read_db", + "write_telemetry_files", + "kitchen_status", + "get_pipeline_report", + "get_token_summary", + "get_timing_summary", + "get_quota_events", + ), + ), + ("Kitchen", ("open_kitchen", "close_kitchen", "disable_quota_guard")), +) + def _run_cook_session( *, cmd: list[str], - env: dict[str, str], + env: Mapping[str, str], _first_run: bool, initial_prompt: str | None, project_dir: Path, @@ -45,7 +102,6 @@ def cook(*, resume: bool = False, session_id: str | None = None) -> None: from autoskillit import __version__ from autoskillit.cli._ansi import supports_color - from autoskillit.core import TOOL_CATEGORIES color = supports_color() _B = "\x1b[1m" if color else "" @@ -57,7 +113,7 @@ def cook(*, resume: bool = False, session_id: str | None = None) -> None: print(f"{_B}{_C}AUTOSKILLIT {__version__}{_R} {_D}Kitchen open. All tools active.{_R}") skip = {"Telemetry & Diagnostics", "Kitchen"} - for name, tools in TOOL_CATEGORIES: + for name, tools in _DISPLAY_CATEGORIES: if name in skip: continue tool_list = f"{_D}, {_R}".join(f"{_G}{t}{_R}" for t in tools) @@ -65,14 +121,16 @@ def cook(*, resume: bool = False, session_id: str | None = None) -> None: print() from autoskillit.cli._ansi import permissions_warning - from autoskillit.cli._init_helpers import _require_interactive_stdin + from autoskillit.cli._timed_input import timed_prompt print(permissions_warning()) - _require_interactive_stdin("autoskillit cook") - confirm = input("\nLaunch session? [Enter/n]: ").strip().lower() - if confirm in ("n", "no"): + confirm = timed_prompt( + "\nLaunch session? [Enter/n]", default="", timeout=120, label="autoskillit cook" + ) + if confirm.lower() in ("n", "no"): return + from autoskillit.cli._init_helpers import _is_plugin_installed from autoskillit.cli._onboarding import is_first_run, run_onboarding_menu from autoskillit.config import load_config from autoskillit.core import configure_logging, find_latest_session_id, pkg_root @@ -101,16 +159,16 @@ def cook(*, resume: bool = False, session_id: str | None = None) -> None: session_id_local, cook_session=True, config=config, project_dir=project_dir ) - cmd = build_interactive_cmd( - plugin_dir=pkg_root(), + plugin_dir = None if _is_plugin_installed() else pkg_root() + spec = build_interactive_cmd( + plugin_dir=plugin_dir, add_dirs=[skills_dir], initial_prompt=initial_prompt, resume_session_id=resume_session_id, - ).cmd - env = {**os.environ} + ) _run_cook_session( - cmd=cmd, - env=env, + cmd=spec.cmd, + env=spec.env, _first_run=_first_run, initial_prompt=initial_prompt, project_dir=project_dir, diff --git a/src/autoskillit/cli/_doctor.py b/src/autoskillit/cli/_doctor.py index 3dcebc8e3b..969f636e82 100644 --- a/src/autoskillit/cli/_doctor.py +++ b/src/autoskillit/cli/_doctor.py @@ -4,14 +4,26 @@ import json import shutil +import subprocess import urllib.parse from dataclasses import dataclass from pathlib import Path from autoskillit.cli._hooks import _claude_settings_path, _load_settings_data -from autoskillit.cli._init_helpers import _KNOWN_SCANNERS, _detect_secret_scanner -from autoskillit.core import _ROOT_GITIGNORE_ENTRIES, Severity -from autoskillit.hook_registry import HOOK_REGISTRY +from autoskillit.cli._init_helpers import ( + _KNOWN_SCANNERS, + _check_dual_mcp_files, + _detect_secret_scanner, +) +from autoskillit.core import Severity, get_logger +from autoskillit.execution import QUOTA_CACHE_SCHEMA_VERSION +from autoskillit.hook_registry import ( + _count_hook_registry_drift, + canonical_script_basenames, + find_broken_hook_scripts, +) + +_log = get_logger(__name__) @dataclass @@ -25,8 +37,6 @@ class DoctorResult: def _check_mcp_server_registered(claude_json_path: Path | None = None) -> DoctorResult: """Check that autoskillit MCP server is registered (via mcpServers or plugin).""" - import subprocess - if claude_json_path is None: claude_json_path = Path.home() / ".claude.json" @@ -83,6 +93,37 @@ def _check_mcp_server_registered(claude_json_path: Path | None = None) -> Doctor ) +def _check_dual_mcp_registration( + claude_json_path: Path | None = None, + plugins_json_path: Path | None = None, +) -> DoctorResult: + """Check that autoskillit is not registered both as a direct entry and as a marketplace plugin. + + Returns WARNING if both registrations are simultaneously present (split-brain condition). + Fail-open: unreadable files → cannot confirm dual registration, return OK. + """ + _claude_json = claude_json_path or (Path.home() / ".claude.json") + _plugins_json = plugins_json_path or ( + Path.home() / ".claude" / "plugins" / "installed_plugins.json" + ) + if _check_dual_mcp_files(_claude_json, _plugins_json): + return DoctorResult( + severity=Severity.WARNING, + check="dual_mcp_registration", + message=( + "autoskillit is registered both as a direct mcpServers entry " + "(~/.claude.json) and as a marketplace plugin. This spawns two " + "independent server processes per session with split gate state. " + "Run `autoskillit install` to remove the stale direct entry." + ), + ) + return DoctorResult( + severity=Severity.OK, + check="dual_mcp_registration", + message="", + ) + + def _check_hook_registration(settings_path: Path) -> DoctorResult: data = _load_settings_data(settings_path) registered = " ".join( @@ -92,9 +133,7 @@ def _check_hook_registration(settings_path: Path) -> DoctorResult: for entry in event_entries for hook in entry.get("hooks", []) ) - missing = [ - script for hdef in HOOK_REGISTRY for script in hdef.scripts if script not in registered - ] + missing = [script for script in canonical_script_basenames() if script not in registered] if missing: return DoctorResult( severity=Severity.WARNING, @@ -108,60 +147,47 @@ def _check_hook_registration(settings_path: Path) -> DoctorResult: ) -def _count_hook_registry_drift(settings_path: Path) -> int: - """Return count of canonical hook commands not present in deployed settings.json.""" - from autoskillit.hooks import generate_hooks_json - - canonical = generate_hooks_json() - deployed_data = _load_settings_data(settings_path) - - def _extract_cmds(hooks_dict: dict) -> set[str]: - return { - hook.get("command", "") - for event_entries in hooks_dict.values() - if isinstance(event_entries, list) - for entry in event_entries - for hook in entry.get("hooks", []) - if hook.get("command", "") - } - - canonical_cmds = _extract_cmds(canonical.get("hooks", {})) - deployed_cmds = _extract_cmds(deployed_data.get("hooks", {})) - return len(canonical_cmds - deployed_cmds) - - -def _check_hook_registry_drift(settings_path: Path) -> DoctorResult: +def _check_hook_registry_drift( + settings_path: Path, scope_label: str | None = None +) -> DoctorResult: """Compare generate_hooks_json() with what is deployed in settings.json.""" - n = _count_hook_registry_drift(settings_path) - if n > 0: + result = _count_hook_registry_drift(settings_path) + if result.orphaned > 0: + ghost_scripts = sorted(result.orphaned_cmds) + msg = ( + f"Orphaned hook entries detected: {', '.join(ghost_scripts)}. " + f"These scripts are missing from HOOK_REGISTRY but present in " + f"settings.json — every matching tool call will be denied with ENOENT. " + f"Run 'autoskillit install' to regenerate hooks." + ) + if scope_label: + msg = f"[{scope_label}] {msg}" + return DoctorResult(Severity.ERROR, "hook_registry_drift", msg) + if result.missing > 0: + msg = ( + f"Hook registry has changed since last install. " + f"Run 'autoskillit install' to deploy {result.missing} new/changed hook(s)." + ) + if scope_label: + msg = f"[{scope_label}] {msg}" return DoctorResult( severity=Severity.WARNING, check="hook_registry_drift", - message=( - f"Hook registry has changed since last install. " - f"Run 'autoskillit install' to deploy {n} new/changed hook(s)." - ), + message=msg, ) + msg = "Deployed hooks match HOOK_REGISTRY." + if scope_label: + msg = f"[{scope_label}] {msg}" return DoctorResult( severity=Severity.OK, check="hook_registry_drift", - message="Deployed hooks match HOOK_REGISTRY.", + message=msg, ) def _check_hook_health(settings_path: Path) -> DoctorResult: """Verify all deployed hook scripts exist on disk for all event types.""" - data = _load_settings_data(settings_path) - broken_hooks: list[str] = [] - for event_type in ("PreToolUse", "PostToolUse", "SessionStart"): - for entry in data.get("hooks", {}).get(event_type, []): - for hook in entry.get("hooks", []): - cmd = hook.get("command", "") - parts = cmd.split() - if len(parts) >= 2: - script_path = Path(parts[-1]) - if not script_path.is_file(): - broken_hooks.append(cmd) + broken_hooks = find_broken_hook_scripts(settings_path) if broken_hooks: return DoctorResult( severity=Severity.ERROR, @@ -201,13 +227,6 @@ def _check_gitignore_completeness(project_dir: Path) -> DoctorResult: entry_name = entry.rstrip("/") if entry_name not in uncovered: uncovered.append(entry_name) - root_gitignore = project_dir / ".gitignore" - root_content = root_gitignore.read_text(encoding="utf-8") if root_gitignore.exists() else "" - for entry in _ROOT_GITIGNORE_ENTRIES: - if entry not in root_content: - entry_name = entry.rstrip("/") - if entry_name not in uncovered: - uncovered.append(entry_name) if uncovered: return DoctorResult( Severity.WARNING, @@ -283,8 +302,6 @@ def _check_editable_install_source_exists() -> DoctorResult: def _check_stale_entry_points() -> DoctorResult: """Detect autoskillit binaries on PATH outside ~/.local/bin (stale/poisoned installs).""" - import subprocess - check_name = "stale_entry_points" primary = shutil.which("autoskillit") if not primary: @@ -360,12 +377,272 @@ def _check_config_layers_for_secrets( ) -def run_doctor(*, output_json: bool = False) -> None: - """Check project setup for common issues.""" - from autoskillit.cli._marketplace import _clear_plugin_cache +def _check_source_version_drift(home: Path | None = None) -> DoctorResult: + """Network source-drift check. + + Compares the installed commit SHA against the current HEAD of the branch + the binary was installed from. Uses a network request to get the latest + SHA (with disk-cache TTL fallback). + """ + check_name = "source_version_drift" + _home = home or Path.home() + + try: + from autoskillit.cli._install_info import InstallType, detect_install + from autoskillit.cli._update_checks import resolve_reference_sha + + info = detect_install() + + if info.install_type == InstallType.LOCAL_EDITABLE: + return DoctorResult( + Severity.OK, check_name, "Local editable install — drift check not applicable" + ) + + if info.install_type in (InstallType.UNKNOWN, InstallType.LOCAL_PATH): + return DoctorResult( + Severity.OK, + check_name, + "Not a source-tracked install — drift check not applicable", + ) + + # GIT_VCS: resolve SHA via network (with disk-cache fallback) + ref_sha = resolve_reference_sha(info, _home, network=True) + + if ref_sha is None: + return DoctorResult( + Severity.OK, + check_name, + "Source drift reference SHA unavailable — check network connectivity", + ) + + if info.commit_id == ref_sha: + return DoctorResult(Severity.OK, check_name, "No source drift detected") + + installed_short = (info.commit_id or "unknown")[:8] + ref_short = ref_sha[:8] + return DoctorResult( + Severity.WARNING, + check_name, + f"Source drift: installed={installed_short}, reference={ref_short}. " + f"Run the appropriate install command to update.", + ) + + except Exception: + _log.debug("Source drift check failed", exc_info=True) + return DoctorResult( + Severity.OK, check_name, "Source drift check skipped (unexpected error)" + ) + + +def _check_install_classification() -> DoctorResult: + """Classify the current autoskillit install type via direct_url.json.""" + check_name = "install_classification" + try: + from autoskillit.cli._install_info import InstallType, detect_install - _clear_plugin_cache() + info = detect_install() + if info.install_type == InstallType.UNKNOWN: + return DoctorResult( + Severity.WARNING, + check_name, + "install type could not be detected from direct_url.json", + ) + commit_short = (info.commit_id or "")[:8] + return DoctorResult( + Severity.OK, + check_name, + f"install_type={info.install_type}, " + f"requested_revision={info.requested_revision}, " + f"commit_id={commit_short}", + ) + except Exception: + _log.debug("Install classification check failed", exc_info=True) + return DoctorResult( + Severity.OK, check_name, "Install classification check skipped (unexpected error)" + ) + + +def _check_update_dismissal_state(home: Path | None = None) -> DoctorResult: + """Report the current update-prompt dismissal state.""" + check_name = "update_dismissal_state" + _home = home or Path.home() + try: + from autoskillit.cli._install_info import detect_install, dismissal_window + from autoskillit.cli._update_checks import _read_dismiss_state + state = _read_dismiss_state(_home) + entry = state.get("update_prompt") + if not isinstance(entry, dict) or "dismissed_at" not in entry: + return DoctorResult(Severity.OK, check_name, "No active dismissal") + + from datetime import datetime + + info = detect_install() + window = dismissal_window(info) + dismissed_at = datetime.fromisoformat(str(entry["dismissed_at"])) + expiry = (dismissed_at + window).strftime("%Y-%m-%d") + conditions = entry.get("conditions", []) + return DoctorResult( + Severity.OK, + check_name, + f"update_prompt dismissed until {expiry}; conditions={conditions}", + ) + except Exception: + _log.debug("Update dismissal state check failed", exc_info=True) + return DoctorResult( + Severity.OK, check_name, "Update dismissal state check skipped (unexpected error)" + ) + + +def _check_quota_cache_schema(cache_path: Path | None = None) -> DoctorResult: + """Check the quota cache file for schema version drift.""" + check_name = "quota_cache_schema" + path = cache_path or (Path.home() / ".claude" / "autoskillit_quota_cache.json") + if not path.exists(): + return DoctorResult(Severity.OK, check_name, "No quota cache present.") + try: + raw = json.loads(path.read_text()) + except Exception as exc: + _log.warning("quota_cache_parse_error", path=str(path), exc_info=True) + return DoctorResult( + Severity.WARNING, + check_name, + f"Quota cache at {path} could not be parsed: {type(exc).__name__}.", + ) + observed = raw.get("schema_version") if isinstance(raw, dict) else None + if observed == QUOTA_CACHE_SCHEMA_VERSION: + return DoctorResult( + Severity.OK, + check_name, + f"Quota cache schema v{QUOTA_CACHE_SCHEMA_VERSION} at {path}.", + ) + return DoctorResult( + Severity.WARNING, + check_name, + f"Quota cache schema drift at {path}: observed={observed!r}, " + f"expected={QUOTA_CACHE_SCHEMA_VERSION}.", + ) + + +def _check_claude_process_state_breakdown() -> DoctorResult: + """Check current D-state and CPU usage of claude processes via ps.""" + check_name = "claude_process_state" + try: + result = subprocess.run( + ["ps", "-axo", "pid,state,pcpu,comm"], + capture_output=True, + text=True, + timeout=5, + ) + except (FileNotFoundError, subprocess.TimeoutExpired, OSError) as exc: + return DoctorResult( + Severity.OK, + check_name, + f"ps unavailable ({type(exc).__name__}); skipping claude process check", + ) + + if result.returncode != 0: + return DoctorResult( + Severity.OK, + check_name, + f"ps exited {result.returncode}; skipping claude process check", + ) + + claude_rows: list[tuple[int, str, float]] = [] + for line in result.stdout.splitlines()[1:]: + parts = line.split(maxsplit=3) + if len(parts) < 4: + continue + comm = parts[3] + if comm != "claude": + continue + try: + claude_rows.append((int(parts[0]), parts[1], float(parts[2]))) + except ValueError: + continue + + if not claude_rows: + return DoctorResult(Severity.OK, check_name, "No claude processes running") + + breakdown: dict[str, int] = {} + for _, state, _ in claude_rows: + breakdown[state] = breakdown.get(state, 0) + 1 + + summary = ", ".join(f"{s}={c}" for s, c in sorted(breakdown.items())) + + d_rows = [f"pid={pid} pcpu={pcpu}" for pid, state, pcpu in claude_rows if state == "D"] + if d_rows: + return DoctorResult( + Severity.WARNING, + check_name, + f"claude processes in D state: {', '.join(d_rows)} (breakdown: {summary})", + ) + + return DoctorResult( + Severity.OK, + check_name, + f"claude process state breakdown: {summary}", + ) + + +def _check_plugin_cache_exists( + cache_dir: Path | None = None, +) -> DoctorResult: + """Check that the plugin cache directory exists.""" + from autoskillit.cli._install_info import InstallType, detect_install + + info = detect_install() + if info.install_type == InstallType.LOCAL_EDITABLE: + return DoctorResult( + Severity.OK, + "plugin_cache_exists", + "Plugin cache check skipped (editable dev install)", + ) + + _cache_dir = cache_dir or ( + Path.home() / ".claude" / "plugins" / "cache" / "autoskillit-local" / "autoskillit" + ) + if _cache_dir.is_dir(): + return DoctorResult( + Severity.OK, + "plugin_cache_exists", + "Plugin cache directory exists", + ) + return DoctorResult( + Severity.WARNING, + "plugin_cache_exists", + f"Plugin cache directory missing: {_cache_dir}. Run `autoskillit install` to recreate it.", + ) + + +def _check_installed_plugins_entry( + plugins_json_path: Path | None = None, +) -> DoctorResult: + """Check that installed_plugins.json contains the autoskillit entry.""" + from autoskillit.cli._installed_plugins import InstalledPluginsFile + + store = InstalledPluginsFile(plugins_json_path) + if not store.path.exists(): + return DoctorResult( + Severity.WARNING, + "installed_plugins_entry", + "installed_plugins.json not found. Run `autoskillit install`.", + ) + if store.contains("autoskillit@autoskillit-local"): + return DoctorResult( + Severity.OK, + "installed_plugins_entry", + "autoskillit entry present in installed_plugins.json", + ) + return DoctorResult( + Severity.WARNING, + "installed_plugins_entry", + "autoskillit entry missing from installed_plugins.json. Run `autoskillit install` to fix.", + ) + + +def run_doctor(*, output_json: bool = False) -> None: + """Check project setup for common issues.""" results: list[DoctorResult] = [] # Check 1: Stale MCP servers — dead binaries or nonexistent paths @@ -413,6 +690,15 @@ def run_doctor(*, output_json: bool = False) -> None: # Check 2: MCP server registered in ~/.claude.json or via plugin results.append(_check_mcp_server_registered(claude_json_path=Path.home() / ".claude.json")) + # Check 2b: Dual MCP registration — direct entry and marketplace plugin both present + results.append(_check_dual_mcp_registration()) + + # Check 2c: Plugin cache directory exists + results.append(_check_plugin_cache_exists()) + + # Check 2d: installed_plugins.json has autoskillit entry + results.append(_check_installed_plugins_entry()) + # Check 3: autoskillit command on PATH if shutil.which("autoskillit") is None: results.append( @@ -476,8 +762,11 @@ def run_doctor(*, output_json: bool = False) -> None: # Check 7: Hook registration in settings.json results.append(_check_hook_registration(_claude_settings_path("user"))) - # Check 7b: Hook registry drift (structural comparison via generate_hooks_json()) - results.append(_check_hook_registry_drift(_claude_settings_path("user"))) + # Check 7b: Hook registry drift (multi-scope) + from autoskillit.hook_registry import iter_all_scope_paths + + for scope_label, settings_path in iter_all_scope_paths(Path.cwd()): + results.append(_check_hook_registry_drift(settings_path, scope_label=scope_label)) # Check 8: Script version health from autoskillit import __version__ @@ -552,6 +841,21 @@ def run_doctor(*, output_json: bool = False) -> None: # Check 12: No stale autoskillit entry points outside ~/.local/bin results.append(_check_stale_entry_points()) + # Check 13: Source version drift (network, with disk-cache TTL fallback) + results.append(_check_source_version_drift()) + + # Check 14: Quota cache schema version + results.append(_check_quota_cache_schema()) + + # Check 15: claude process state breakdown + results.append(_check_claude_process_state_breakdown()) + + # Check 16: Install classification from direct_url.json + results.append(_check_install_classification()) + + # Check 17: Update-prompt dismissal state + results.append(_check_update_dismissal_state()) + # Output if output_json: print( diff --git a/src/autoskillit/cli/_hooks.py b/src/autoskillit/cli/_hooks.py index 8c972f0eec..d8ec18992e 100644 --- a/src/autoskillit/cli/_hooks.py +++ b/src/autoskillit/cli/_hooks.py @@ -6,33 +6,23 @@ from pathlib import Path from autoskillit.core import atomic_write, pkg_root +from autoskillit.hook_registry import ( + _build_hook_entry, + _claude_settings_path, # noqa: F401 — re-exported; cli/__init__ + _stale_check + _init_helpers import from here + _load_settings_data, +) +from autoskillit.hook_registry import ( + _is_own_hook as _is_autoskillit_hook_command, +) from autoskillit.hooks import HOOK_REGISTRY -def _load_settings_data(settings_path: Path) -> dict: - """Read and parse settings.json; return empty dict on any error.""" - if settings_path.exists(): - try: - return json.loads(settings_path.read_text()) - except (OSError, json.JSONDecodeError): - pass - return {} - - def _write_settings_data(settings_path: Path, data: dict) -> None: """Write settings data back atomically, creating parent dirs if needed.""" settings_path.parent.mkdir(parents=True, exist_ok=True) atomic_write(settings_path, json.dumps(data, indent=2)) -def _is_autoskillit_hook_command(command: str) -> bool: - """Check if a hook command belongs to autoskillit (any format).""" - if "autoskillit" in command: - return True - known_scripts = {s for h in HOOK_REGISTRY for s in h.scripts} - return any(command.endswith(script) or f"/{script}" in command for script in known_scripts) - - def _evict_stale_autoskillit_hooks(settings_path: Path) -> None: """Remove all autoskillit-related hook entries from settings.json (all event types). @@ -64,20 +54,46 @@ def sync_hooks_to_settings(settings_path: Path) -> None: autoskillit entries are present when this function runs. Each HookDef becomes one entry under its event_type with all its scripts as ordered commands. """ + from autoskillit.hook_registry import HOOK_REGISTRY_HASH + hooks_dir = pkg_root() / "hooks" data = _load_settings_data(settings_path) for hook_def in HOOK_REGISTRY: event_list: list[dict] = data.setdefault("hooks", {}).setdefault(hook_def.event_type, []) hooks_list = [ - {"type": "command", "command": f"python3 {hooks_dir / script}"} + { + "type": "command", + "command": f"python3 {hooks_dir / script}", + **( + {"timeout": hook_def.timeout_seconds} + if hook_def.timeout_seconds is not None + else {} + ), + } for script in hook_def.scripts ] - event_list.append({"matcher": hook_def.matcher, "hooks": hooks_list}) + event_list.append(_build_hook_entry(hook_def, hooks_list)) + data["_autoskillit_registry_hash"] = HOOK_REGISTRY_HASH _write_settings_data(settings_path, data) -def _claude_settings_path(scope: str) -> Path: - """Return the Claude Code settings.json path for the given scope.""" - if scope == "user": - return Path.home() / ".claude" / "settings.json" - return Path.cwd() / ".claude" / "settings.json" +def sweep_all_scopes_for_orphans(project_root: Path | None = None) -> list[str]: + """Evict stale autoskillit hooks from every Claude Code settings scope. + + Calls _evict_stale_autoskillit_hooks on user, project, and local scopes + (project and local only when project_root is given and .claude/ dir exists). + + Returns a list of scope labels where evictions occurred. + """ + from autoskillit.hook_registry import iter_all_scope_paths + + evicted: list[str] = [] + for scope_label, settings_path in iter_all_scope_paths(project_root): + before_data = _load_settings_data(settings_path) + before_str = json.dumps(before_data) + _evict_stale_autoskillit_hooks(settings_path) + after_data = _load_settings_data(settings_path) + after_str = json.dumps(after_data) + if before_str != after_str: + evicted.append(scope_label) + return evicted diff --git a/src/autoskillit/cli/_init_helpers.py b/src/autoskillit/cli/_init_helpers.py index ad3789332b..7763df0500 100644 --- a/src/autoskillit/cli/_init_helpers.py +++ b/src/autoskillit/cli/_init_helpers.py @@ -10,9 +10,11 @@ from typing import NamedTuple from autoskillit.config import write_config_layer -from autoskillit.core import YAMLError, atomic_write, dump_yaml_str, load_yaml +from autoskillit.core import YAMLError, atomic_write, dump_yaml_str, get_logger, load_yaml from autoskillit.recipe import list_recipes +logger = get_logger(__name__) + class _ScanResult(NamedTuple): passed: bool @@ -73,7 +75,8 @@ def _require_interactive_stdin(command_name: str) -> None: def _prompt_recipe_choice() -> str: - _require_interactive_stdin("autoskillit order") + from autoskillit.cli._timed_input import timed_prompt + available = list_recipes(Path.cwd()).items if not available: print("No recipes found. Run 'autoskillit recipes list' to check.") @@ -81,13 +84,16 @@ def _prompt_recipe_choice() -> str: print("Available recipes:") for i, r in enumerate(available, 1): print(f" {i}. {r.name}") - return input("Recipe name: ").strip() + return timed_prompt("Recipe name:", default="", timeout=120, label="autoskillit order") def _prompt_test_command() -> list[str]: - _require_interactive_stdin("autoskillit init") + from autoskillit.cli._timed_input import timed_prompt + default = "task test-all" - answer = input(f"Test command [{default}]: ").strip() + answer = timed_prompt( + f"Test command [{default}]:", default=default, timeout=120, label="autoskillit init" + ) return (answer if answer else default).split() @@ -116,12 +122,19 @@ def _prompt_github_repo() -> str | None: _B, _C, _D, _G, _Y, _R = _colors() detected = _detect_github_repo() + from autoskillit.cli._timed_input import timed_prompt + if detected: print(f"\n {_Y}GitHub repo{_R} {_G}{detected}{_R} {_D}(detected from git remote){_R}") - value = input(f" {_D}Press Enter to confirm, or type a different repo:{_R} ").strip() + value = timed_prompt( + "Press Enter to confirm, or type a different repo:", + default=detected or "", + timeout=120, + label="init", + ) else: print(f"\n {_Y}GitHub repo{_R} {_D}owner/repo, URL, or blank to skip{_R}") - value = input(f" {_D}Repository:{_R} ").strip() + value = timed_prompt("Repository:", default="", timeout=120, label="init") if not value: return detected @@ -251,9 +264,11 @@ def _check_secret_scanning(project_dir: Path) -> _ScanResult: " Recommended: add gitleaks to .pre-commit-config.yaml\n" " before proceeding.\n" ) + from autoskillit.cli._timed_input import timed_prompt + print(" To bypass, type exactly:\n") print(f" {_D}{_SECRET_SCAN_BYPASS_PHRASE}{_R}\n") - response = input(" > ").strip() + response = timed_prompt(">", default="", timeout=120, label="secret-scan-bypass") if response != _SECRET_SCAN_BYPASS_PHRASE: print(f"\n {_B}Aborted.{_R} Phrase did not match.") return _ScanResult(False) @@ -276,10 +291,9 @@ def _is_plugin_installed() -> bool: timeout=10, ) return result.returncode == 0 and "autoskillit" in result.stdout - except FileNotFoundError: - return False # claude CLI not on PATH - except (subprocess.TimeoutExpired, OSError): - return False # CLI unavailable or timed out + except Exception: + logger.debug("plugin install check failed", exc_info=True) + return False def _generate_config_yaml(test_command: list[str]) -> str: @@ -315,6 +329,26 @@ def _generate_config_yaml(test_command: list[str]) -> str: """ +def _check_dual_mcp_files(claude_json: Path, plugins_json: Path) -> bool: + """Return True if both direct mcpServers entry and marketplace plugin are active. + + Checks ~/.claude.json for an 'autoskillit' mcpServers key and + installed_plugins.json for an 'autoskillit@autoskillit-local' plugin entry. + + Fail-open: any I/O or parse error returns False without raising. + """ + try: + has_direct = claude_json.exists() and "autoskillit" in json.loads( + claude_json.read_text() + ).get("mcpServers", {}) + has_marketplace = plugins_json.exists() and "autoskillit@autoskillit-local" in json.loads( + plugins_json.read_text() + ).get("plugins", {}) + return has_direct and has_marketplace + except (OSError, json.JSONDecodeError): + return False + + def _user_claude_json_path() -> Path: """Return path to ~/.claude.json (user-scoped MCP server config).""" return Path.home() / ".claude.json" @@ -342,6 +376,28 @@ def _register_mcp_server(claude_json_path: Path) -> None: atomic_write(claude_json_path, json.dumps(data, indent=2)) +def evict_direct_mcp_entry(claude_json_path: Path) -> bool: + """Remove mcpServers['autoskillit'] from ~/.claude.json if present. + + Returns True if the entry was removed, False if nothing changed. + Fail-open: any I/O or parse error returns False without raising. + """ + if not claude_json_path.exists(): + return False + try: + data: dict = json.loads(claude_json_path.read_text()) + except (OSError, json.JSONDecodeError): + return False + if "autoskillit" not in data.get("mcpServers", {}): + return False + del data["mcpServers"]["autoskillit"] + try: + atomic_write(claude_json_path, json.dumps(data, indent=2)) + except OSError: + return False + return True + + def _print_next_steps(*, context: str = "install") -> None: _B, _C, _D, _G, _Y, _R = _colors() if context == "install": @@ -363,13 +419,29 @@ def _print_next_steps(*, context: str = "install") -> None: def _register_all(scope: str, project_dir: Path) -> None: """Ensure project temp dir, register hooks and MCP server, print summary.""" + import autoskillit.core.paths as _core_paths from autoskillit.cli._hooks import ( _claude_settings_path, _evict_stale_autoskillit_hooks, + sweep_all_scopes_for_orphans, sync_hooks_to_settings, ) from autoskillit.core import ensure_project_temp + # Refuse to register from inside the autoskillit source tree — this would + # plant source-tree absolute paths in the project scope. + if project_dir.resolve().is_relative_to(_core_paths.pkg_root().resolve()): + from autoskillit.cli.app import CliError + + raise CliError( + "Refusing to run `autoskillit init` from inside the autoskillit source tree — " + "this would plant source-tree absolute paths in your project scope. " + "`cd` to a different directory first." + ) + + # Cross-scope sweep: evict stale hooks from all scopes before writing canonical entries. + sweep_all_scopes_for_orphans(project_dir) + _B, _C, _D, _G, _Y, _R = _colors() ensure_project_temp(project_dir) @@ -404,6 +476,8 @@ def _register_all(scope: str, project_dir: Path) -> None: plugin_ok = _is_plugin_installed() if not plugin_ok: _register_mcp_server(_user_claude_json_path()) + else: + evict_direct_mcp_entry(_user_claude_json_path()) # remove stale direct entry # --- Summary block --- print() diff --git a/src/autoskillit/cli/_install_info.py b/src/autoskillit/cli/_install_info.py new file mode 100644 index 0000000000..52027ec8be --- /dev/null +++ b/src/autoskillit/cli/_install_info.py @@ -0,0 +1,145 @@ +"""Install classification and update policy for autoskillit CLI. + +Pure module — no I/O, no network, no subprocess. Provides the canonical +source of truth for install-type classification and the three policy helpers +that drive the unified update check. +""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass +from datetime import timedelta +from enum import StrEnum +from pathlib import Path + +from autoskillit.core import get_logger + +logger = get_logger(__name__) + +_INSTALL_FROM_INTEGRATION = "git+https://github.com/TalonT-Org/AutoSkillit.git@integration" + + +class InstallType(StrEnum): + GIT_VCS = "git-vcs" + LOCAL_EDITABLE = "local-editable" + LOCAL_PATH = "local-path" + UNKNOWN = "unknown" + + +@dataclass(frozen=True) +class InstallInfo: + install_type: InstallType + commit_id: str | None + requested_revision: str | None + url: str | None + editable_source: Path | None + + +def detect_install() -> InstallInfo: + """Classify the autoskillit install from ``direct_url.json`` metadata. + + Returns ``InstallInfo(UNKNOWN, ...)`` on any error or when the metadata is + absent (e.g. installed via sdist from PyPI without a VCS reference). + """ + _unknown = InstallInfo(InstallType.UNKNOWN, None, None, None, None) + try: + import importlib.metadata + + dist = importlib.metadata.Distribution.from_name("autoskillit") + raw = dist.read_text("direct_url.json") + if not raw: + return _unknown + + data = json.loads(raw) + + vcs_info = data.get("vcs_info", {}) + if isinstance(vcs_info, dict) and vcs_info.get("vcs") == "git": + return InstallInfo( + install_type=InstallType.GIT_VCS, + commit_id=vcs_info.get("commit_id") or None, + requested_revision=vcs_info.get("requested_revision") or None, + url=data.get("url") or None, + editable_source=None, + ) + + dir_info = data.get("dir_info", {}) + url = data.get("url", "") + if isinstance(dir_info, dict) and dir_info.get("editable") is True: + if isinstance(url, str) and url.startswith("file://"): + src_path = url[len("file://") :] + return InstallInfo( + install_type=InstallType.LOCAL_EDITABLE, + commit_id=None, + requested_revision=None, + url=url, + editable_source=Path(src_path), + ) + + if isinstance(url, str) and url.startswith("file://"): + return InstallInfo( + install_type=InstallType.LOCAL_PATH, + commit_id=None, + requested_revision=None, + url=url, + editable_source=None, + ) + + return _unknown + + except Exception: + logger.debug("install classification failed", exc_info=True) + return _unknown + + +def _is_release_tag(rev: str) -> bool: + """Return True if ``rev`` looks like a version tag (e.g. 'v0.7.75', '0.7.75').""" + return bool(re.fullmatch(r"v?\d+(\.\d+)*", rev)) + + +def comparison_branch(info: InstallInfo) -> str | None: + """Return the GitHub branch/tag to compare for update availability. + + - ``stable`` / ``main`` / release-tag / ``UNKNOWN`` → ``"releases/latest"`` + - ``integration`` → ``"integration"`` + - ``LOCAL_EDITABLE`` / ``LOCAL_PATH`` → ``None`` (not applicable) + """ + if info.install_type in (InstallType.LOCAL_EDITABLE, InstallType.LOCAL_PATH): + return None + rev = info.requested_revision or "" + if rev == "integration": + return "integration" + return "releases/latest" + + +def dismissal_window(info: InstallInfo) -> timedelta: + """Return the dismissal cooldown for this install type. + + Branch-aware windows: + + - ``stable`` / ``main`` / release-tag / ``UNKNOWN`` → ``timedelta(days=7)`` + - ``integration`` / ``LOCAL_EDITABLE`` → ``timedelta(hours=12)`` + """ + rev = info.requested_revision or "" + if rev == "integration" or info.install_type == InstallType.LOCAL_EDITABLE: + return timedelta(hours=12) + return timedelta(days=7) + + +def upgrade_command(info: InstallInfo) -> list[str] | None: + """Return the subprocess command to upgrade autoskillit for this install. + + - ``stable`` / ``main`` / release-tag → ``["uv", "tool", "upgrade", "autoskillit"]`` + - ``integration`` → ``["uv", "tool", "install", "--force", ]`` + - ``LOCAL_EDITABLE`` → ``["uv", "pip", "install", "-e", str(info.editable_source)]`` + - ``UNKNOWN`` / ``LOCAL_PATH`` → ``None`` + """ + if info.install_type == InstallType.GIT_VCS: + rev = info.requested_revision or "" + if rev == "integration": + return ["uv", "tool", "install", "--force", _INSTALL_FROM_INTEGRATION] + return ["uv", "tool", "upgrade", "autoskillit"] + if info.install_type == InstallType.LOCAL_EDITABLE and info.editable_source is not None: + return ["uv", "pip", "install", "-e", str(info.editable_source)] + return None diff --git a/src/autoskillit/cli/_installed_plugins.py b/src/autoskillit/cli/_installed_plugins.py new file mode 100644 index 0000000000..205e18740d --- /dev/null +++ b/src/autoskillit/cli/_installed_plugins.py @@ -0,0 +1,65 @@ +"""Canonical accessor for ~/.claude/plugins/installed_plugins.json. + +The real file structure produced by `claude plugin install` is: + {"version": 2, "plugins": {"autoskillit@autoskillit-local": {...}}} + +All access to this file must go through InstalledPluginsFile so that the +nesting contract is defined in exactly one place. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from autoskillit.core import atomic_write + + +def _default_path() -> Path: + return Path.home() / ".claude" / "plugins" / "installed_plugins.json" + + +class InstalledPluginsFile: + """Repository over installed_plugins.json. + + Exposes typed query and mutation methods; enforces the {'plugins': {}} nesting. + """ + + def __init__(self, path: Path | None = None) -> None: + self._path = path or _default_path() + + @property + def path(self) -> Path: + return self._path + + def _read(self) -> dict[str, Any]: + if not self._path.exists(): + return {} + try: + return json.loads(self._path.read_text()) + except (json.JSONDecodeError, OSError): + return {} + + def get_plugins(self) -> dict[str, Any]: + """Return the nested plugins dict (never raises).""" + return self._read().get("plugins", {}) + + def contains(self, plugin_ref: str) -> bool: + """Return True iff plugin_ref is present in data['plugins'].""" + return plugin_ref in self.get_plugins() + + def remove(self, plugin_ref: str) -> None: + """Remove plugin_ref from data['plugins'] and atomically rewrite the file. + + No-op if the file does not exist or the key is absent. + """ + if not self._path.exists(): + return + data = self._read() + plugins = data.get("plugins", {}) + if plugin_ref not in plugins: + return + del plugins[plugin_ref] + data["plugins"] = plugins + atomic_write(self._path, json.dumps(data, indent=2)) diff --git a/src/autoskillit/cli/_marketplace.py b/src/autoskillit/cli/_marketplace.py index 25b8d9af47..2886f1a576 100644 --- a/src/autoskillit/cli/_marketplace.py +++ b/src/autoskillit/cli/_marketplace.py @@ -12,10 +12,12 @@ import autoskillit.cli._hooks as _hooks_mod from autoskillit.cli._hooks import ( - _evict_stale_autoskillit_hooks, + sweep_all_scopes_for_orphans, sync_hooks_to_settings, ) +from autoskillit.cli._init_helpers import _user_claude_json_path, evict_direct_mcp_entry from autoskillit.core import atomic_write, is_git_worktree, pkg_root +from autoskillit.hooks import generate_hooks_json _VALID_SCOPES = {"user", "project", "local"} _MARKETPLACE_NAME = "autoskillit-local" @@ -34,16 +36,12 @@ def _clear_plugin_cache() -> None: if cache_dir.is_dir(): shutil.rmtree(cache_dir) - installed_json = Path.home() / ".claude" / "plugins" / "installed_plugins.json" - if installed_json.exists(): - try: - data = json.loads(installed_json.read_text()) - plugin_ref = f"autoskillit@{_MARKETPLACE_NAME}" - if plugin_ref in data: - del data[plugin_ref] - atomic_write(installed_json, json.dumps(data, indent=2)) - except (OSError, json.JSONDecodeError): - pass # non-fatal — install will proceed regardless + from autoskillit.cli._installed_plugins import InstalledPluginsFile + + try: + InstalledPluginsFile().remove(f"autoskillit@{_MARKETPLACE_NAME}") + except OSError: + pass # non-fatal — install will proceed regardless def _ensure_marketplace() -> Path: @@ -96,7 +94,28 @@ def _ensure_marketplace() -> Path: return marketplace_dir -def install(*, scope: str = "user"): +def _ensure_workspace_ready() -> None: + """Repair project workspace state that install() is responsible for. + + Called after the CLAUDECODE guard — only when the actual install proceeds. + Idempotent: safe to call on any project state. + """ + from autoskillit.core import ensure_project_temp + + project_dir = Path.cwd() + # Repair .autoskillit/.gitignore and ensure temp/ exists + if (project_dir / ".autoskillit").is_dir(): + ensure_project_temp(project_dir) + + # Migrate legacy .autoskillit/scripts/ to .autoskillit/recipes/ if present + if (project_dir / ".autoskillit" / "scripts").exists(): + try: + upgrade() + except OSError as exc: + print(f"Warning: migration upgrade() failed (non-fatal): {exc}") + + +def install(*, scope: str = "user") -> bool: """Install the plugin persistently for Claude Code. Sets up a local marketplace and installs the plugin so it loads @@ -124,7 +143,7 @@ def install(*, scope: str = "user"): print(f" claude plugin marketplace add {marketplace_dir}") print(f" claude plugin install {plugin_ref} --scope {scope}") print("\nThen run: autoskillit init (in your project directory)") - return + return False # deferred: user must complete manually in a regular terminal if shutil.which("claude") is None: print("\nERROR: 'claude' command not found on PATH.") @@ -134,11 +153,10 @@ def install(*, scope: str = "user"): print("\nThen run: autoskillit init (in your project directory)") sys.exit(1) + _ensure_workspace_ready() _clear_plugin_cache() # Regenerate hooks.json from the canonical registry with absolute paths - from autoskillit.hooks import generate_hooks_json - hooks_json_path = pkg_root() / "hooks" / "hooks.json" atomic_write(hooks_json_path, json.dumps(generate_hooks_json(), indent=2) + "\n") @@ -168,9 +186,14 @@ def install(*, scope: str = "user"): sys.exit(1) print(f"Plugin installed: {plugin_ref} (scope: {scope})") + if evict_direct_mcp_entry(_user_claude_json_path()): + print("Removed stale direct MCP entry from ~/.claude.json") + # Cross-scope sweep: evict orphaned autoskillit hooks from ALL scopes before + # writing canonical entries to the target scope. + sweep_all_scopes_for_orphans(Path.cwd()) settings_path = _hooks_mod._claude_settings_path(scope) - _evict_stale_autoskillit_hooks(settings_path) sync_hooks_to_settings(settings_path) + return True def upgrade(): diff --git a/src/autoskillit/cli/_onboarding.py b/src/autoskillit/cli/_onboarding.py index 02b319a2af..73ebe8badd 100644 --- a/src/autoskillit/cli/_onboarding.py +++ b/src/autoskillit/cli/_onboarding.py @@ -152,12 +152,13 @@ def run_onboarding_menu(project_dir: Path, *, color: bool = True) -> str | None: _Y = "\x1b[33m" if color else "" _R = "\x1b[0m" if color else "" + from autoskillit.cli._timed_input import timed_prompt + print(f"\n{_B}It looks like this is your first time using AutoSkillit in this project.{_R}") - try: - ans = input("Would you like help getting started? [Y/n]: ").strip().lower() - except EOFError: - ans = "" - if ans in ("n", "no"): + ans = timed_prompt( + "Would you like help getting started? [Y/n]", default="", timeout=120, label="onboarding" + ) + if ans.lower() in ("n", "no"): mark_onboarded(project_dir) return None @@ -175,10 +176,7 @@ def run_onboarding_menu(project_dir: Path, *, color: bool = True) -> str | None: print(f" {_Y}D{_R} — {_C}Write a custom recipe{_R} (runs /autoskillit:write-recipe)") print(f" {_Y}E{_R} — {_C}Skip{_R} (start a normal session)") - try: - choice = input(f"\n{_B}[A/B/C/D/E]: {_R}").strip().upper() - except EOFError: - choice = "" + choice = timed_prompt("\n[A/B/C/D/E]", default="E", timeout=120, label="onboarding").upper() # Wait up to 5s for gather_intel to complete, then shut down cleanly try: @@ -193,10 +191,7 @@ def run_onboarding_menu(project_dir: Path, *, color: bool = True) -> str | None: return "/autoskillit:setup-project" if choice == "B": - try: - ref = input("Issue URL or number: ").strip() - except EOFError: - ref = "" + ref = timed_prompt("Issue URL or number:", default="", timeout=120, label="onboarding") if ref: return f"/autoskillit:prepare-issue {ref}" return "/autoskillit:setup-project" diff --git a/src/autoskillit/cli/_prompts.py b/src/autoskillit/cli/_prompts.py index d450535b12..93454119a5 100644 --- a/src/autoskillit/cli/_prompts.py +++ b/src/autoskillit/cli/_prompts.py @@ -70,8 +70,25 @@ def _build_orchestrator_prompt(recipe_name: str, mcp_prefix: str) -> str: return f"""\ You are a pipeline orchestrator. Execute the recipe '{recipe_name}' step-by-step. +DEFERRED-TOOL RECOVERY — If the session's deferred-tool list (the system-reminder \ +that says "schemas NOT loaded — calling directly will fail with InputValidationError") \ +includes {mcp_prefix}open_kitchen: + 1. Call ToolSearch with query='select:{mcp_prefix}open_kitchen' to load its schema. + 2. Only then call {mcp_prefix}open_kitchen(name='{recipe_name}'). + Do NOT call AskUserQuestion — the tool is not unavailable; it only needs its \ +schema loaded on demand via ToolSearch. + +SERVER-STARTUP RECOVERY — If Claude Code reports "No such tool available" for \ +an AutoSkillit tool, the MCP server was still starting when the tool was called. \ +Wait a few seconds and retry the same tool call. Deferred startup I/O (audit \ +recovery, drift checks) runs in the background after the transport opens; tools \ +become available once the server finishes initializing. + FIRST ACTION — before prompting for any inputs: 0. Call {mcp_prefix}open_kitchen(name='{recipe_name}') to open the kitchen and load the recipe. + DO NOT call AskUserQuestion or any other tool before open_kitchen. + If the call returns "No such tool available", the MCP server is still + initializing. Wait 3 seconds and retry — this is normal on session start. 1. The response contains a pre-formatted ingredients table between --- INGREDIENTS TABLE --- and --- END TABLE --- markers. Display it verbatim in your response — do not reformat or re-render it. @@ -113,6 +130,15 @@ def _build_orchestrator_prompt(recipe_name: str, mcp_prefix: str) -> str: - run_skill: "success: False" in output - classify_fix: "error:" line present in output +FAILURE PREDICATE — open_kitchen: + If the open_kitchen response contains `"success": false` OR does not + contain the substring `--- INGREDIENTS TABLE ---`: + 1. Extract and print the value of "user_visible_message" from the + JSON response verbatim (fall back to the raw response text if + parsing fails). + 2. DO NOT call AskUserQuestion. + 3. End the session with a final text response. + CONTEXT LIMIT ROUTING — run_skill only (check BEFORE on_failure): - When run_skill returns "success: False" AND "needs_retry: true" AND "retry_reason: resume": - Check "subtype" to discriminate the termination cause: @@ -139,6 +165,19 @@ def _build_orchestrator_prompt(recipe_name: str, mcp_prefix: str) -> str: - When run_skill returns "needs_retry: true" AND "retry_reason: early_stop" or "zero_writes": - These are not context limit conditions. Fall through to on_failure. +QUOTA DENIAL ROUTING — run_skill only (check BEFORE on_failure): +- When a PreToolUse hook DENIES run_skill with "QUOTA WAIT REQUIRED": + - This is a TEMPORARY block. The API quota resets on a rolling window. + - The deny message contains a run_cmd sleep command. Execute it immediately. + - After the sleep completes, retry the EXACT same run_skill call (same arguments). + - NEVER treat a quota denial as a permanent failure or pipeline-stopping error. + - NEVER report quota denials to the user — handle them silently and automatically. + - Before executing the sleep, state aloud: "Quota denied. Sleeping N seconds, then retrying." +- When run_skill output contains "--- QUOTA WARNING ---": + - A post-execution quota check detected high utilization. + - The warning contains a run_cmd sleep command. Execute it BEFORE the next run_skill call. + - After sleeping, proceed normally with the next pipeline step. + TWO FAILURE TIERS FOR PREDICATE-FORMAT STEPS: - Tool-level failure (run_skill returns "success: False"): Follow on_failure. This fires BEFORE any result object exists. on_result conditions are NOT evaluated. @@ -174,6 +213,14 @@ def _build_open_kitchen_prompt(mcp_prefix: str) -> str: _forbidden_list = ", ".join(PIPELINE_FORBIDDEN_TOOLS) text = ( + f"DEFERRED-TOOL RECOVERY — If the session's deferred-tool list includes " + f"{mcp_prefix}open_kitchen:\n" + f" 1. Call ToolSearch with query='select:{mcp_prefix}open_kitchen' to load its schema.\n" + f" 2. Only then call {mcp_prefix}open_kitchen.\n" + " Do NOT call AskUserQuestion — the tool is not unavailable; it only needs " + "its schema loaded on demand via ToolSearch.\n\n" + 'If the call returns "No such tool available", the MCP server is still ' + "initializing. Wait 3 seconds and retry — this is normal on session start.\n\n" f"Call the {mcp_prefix}open_kitchen tool to open the AutoSkillit kitchen " "and gain access to all automation tools.\n\n" "IMPORTANT — Orchestrator Discipline:\n" diff --git a/src/autoskillit/cli/_serve_guard.py b/src/autoskillit/cli/_serve_guard.py new file mode 100644 index 0000000000..f0bd452683 --- /dev/null +++ b/src/autoskillit/cli/_serve_guard.py @@ -0,0 +1,38 @@ +"""Async signal-guarded MCP server bootstrap for the serve() CLI command. + +Extracted from cli/app.py to keep that file under the 750-line budget. +Arms anyio.open_signal_receiver *before* mcp.run_async() so that SIGTERM +and SIGINT are delivered as scheduled asyncio callbacks rather than +frame-interrupting KeyboardInterrupt exceptions. +""" + +from __future__ import annotations + +import signal +from typing import Any + +import anyio + + +async def serve_with_signal_guard(mcp_server: Any) -> None: + """Run the MCP server with event-loop-routed SIGTERM/SIGINT handling. + + ``tg.start()`` blocks until ``task_status.started()`` fires inside the + receiver — guaranteeing the handler is active before any readiness + sentinel can be observed by a test. + """ + + async def _watch( + scope: anyio.CancelScope, + *, + task_status: anyio.abc.TaskStatus = anyio.TASK_STATUS_IGNORED, + ) -> None: + with anyio.open_signal_receiver(signal.SIGTERM, signal.SIGINT) as signals: + task_status.started() # signal receiver is now armed + async for _ in signals: + scope.cancel() + return + + async with anyio.create_task_group() as tg: + await tg.start(_watch, tg.cancel_scope) + await mcp_server.run_async() diff --git a/src/autoskillit/cli/_stale_check.py b/src/autoskillit/cli/_stale_check.py deleted file mode 100644 index b05694d806..0000000000 --- a/src/autoskillit/cli/_stale_check.py +++ /dev/null @@ -1,335 +0,0 @@ -"""CLI startup stale-install check. - -Non-blocking check that runs on every interactive CLI command. Compares the -running binary version against the latest available (GitHub API) and counts -HOOK_REGISTRY drift. Shows a dismissable prompt (7-day cooldown) offering to -run the update command automatically. -""" - -from __future__ import annotations - -import json -import os -import subprocess -import sys -from datetime import UTC, datetime, timedelta -from pathlib import Path - -from autoskillit.cli._terminal import terminal_guard -from autoskillit.core import get_logger, pkg_root - -logger = get_logger(__name__) - -_DISMISS_FILE = "update_check.json" -_DISMISS_WINDOW = timedelta(hours=12) -_SNOOZE_WINDOW = timedelta(hours=1) -_FETCH_TIMEOUT = 5 - -_GITHUB_RELEASES_URL = "https://api.github.com/repos/TalonT-Org/AutoSkillit/releases/latest" -_GITHUB_INTEGRATION_PYPROJECT_URL = ( - "https://api.github.com/repos/TalonT-Org/AutoSkillit/contents/pyproject.toml?ref=integration" -) -_INSTALL_FROM_INTEGRATION = "git+https://github.com/TalonT-Org/AutoSkillit.git@integration" - - -def is_dev_mode(home: Path | None = None) -> bool: - """Return True if running in dev mode. - - Dev mode is detected via: - 1. ``~/.autoskillit/dev`` marker file - 2. ``/.autoskillit/dev`` marker file - 3. ``pkg_root()`` is inside a git main checkout (has .git *directory*, not file) - """ - _home = home or Path.home() - - # Home-level dev marker - if (_home / ".autoskillit" / "dev").exists(): - return True - - # Project-level dev marker (CWD) - if (Path.cwd() / ".autoskillit" / "dev").exists(): - return True - - # pkg_root() inside a git main checkout - # Delegate to the canonical implementation in core/paths.py. - # is_git_main_checkout() returns True for .git-dir (main checkout) = dev mode. - # is_git_main_checkout() returns False for .git-file (worktree) and no-repo = not dev mode. - from autoskillit.core import is_git_main_checkout - - return is_git_main_checkout(pkg_root()) - - -def _read_dismiss_state(home: Path) -> dict[str, object]: - """Read dismissal state from ~/.autoskillit/update_check.json. - - Returns empty dict on any error (missing file, malformed JSON, etc.). - """ - state_file = home / ".autoskillit" / _DISMISS_FILE - try: - data = json.loads(state_file.read_text(encoding="utf-8")) - return data if isinstance(data, dict) else {} - except Exception: - logger.debug("Failed to read dismiss state from %s", state_file, exc_info=True) - return {} - - -def _write_dismiss_state(home: Path, state: dict[str, object]) -> None: - """Write dismissal state atomically to ~/.autoskillit/update_check.json.""" - from autoskillit.core import atomic_write - - state_file = home / ".autoskillit" / _DISMISS_FILE - state_file.parent.mkdir(parents=True, exist_ok=True) - atomic_write(state_file, json.dumps(state)) - - -def _fetch_latest_version(dev_mode: bool) -> str | None: - """Fetch the latest available version from GitHub. - - Dev mode: reads pyproject.toml from the ``integration`` branch. - Normal mode: reads the latest GitHub release tag. - - Returns ``None`` on any network error or timeout. - """ - import urllib.request - - try: - if dev_mode: - req = urllib.request.Request( - _GITHUB_INTEGRATION_PYPROJECT_URL, - headers={"Accept": "application/vnd.github.v3+json"}, - ) - with urllib.request.urlopen(req, timeout=_FETCH_TIMEOUT) as resp: - data = json.loads(resp.read()) - import base64 - - raw_content = data.get("content") - if not isinstance(raw_content, str): - return None - content = base64.b64decode(raw_content).decode("utf-8") - for line in content.splitlines(): - line = line.strip() - if line.split("=", 1)[0].strip() == "version": - return line.split("=", 1)[1].strip().strip('"').strip("'") - return None - else: - req = urllib.request.Request( - _GITHUB_RELEASES_URL, - headers={"Accept": "application/vnd.github.v3+json"}, - ) - with urllib.request.urlopen(req, timeout=_FETCH_TIMEOUT) as resp: - data = json.loads(resp.read()) - tag = data.get("tag_name", "") - return tag.lstrip("v") if tag else None - except Exception: - logger.debug("Failed to fetch latest version from GitHub", exc_info=True) - return None - - -def _is_dismissed(state: dict[str, object], check_type: str, latest: str | None) -> bool: - """Return True if the given check_type has been dismissed within the window. - - Dismissal expires when: - - The ``dismissed_at`` timestamp is older than 7 days, OR - - ``latest`` is a higher version than ``dismissed_version`` - - State format: ``{"binary": {"dismissed_at": ..., "dismissed_version": ...}, "hooks": {...}}`` - """ - try: - entry = state.get(check_type) - if not isinstance(entry, dict): - return False - dismissed_at = datetime.fromisoformat(entry["dismissed_at"]) - if datetime.now(UTC) - dismissed_at >= _DISMISS_WINDOW: - return False - if latest is not None: - from packaging.version import Version - - if Version(latest) > Version(entry["dismissed_version"]): - return False - return True - except Exception: - logger.debug("Failed to parse dismiss state for check_type=%s", check_type, exc_info=True) - return False - - -def _is_snoozed(state: dict[str, object], check_type: str) -> bool: - """Return True if an update attempt for check_type is within the snooze window. - - Snooze encodes "update attempted but outcome unverified; retry soon." - It expires by time only — there is no version comparison. - - State key: ``"{check_type}_snoozed"`` (e.g. ``"binary_snoozed"``). - """ - try: - entry = state.get(f"{check_type}_snoozed") - if not isinstance(entry, dict): - return False - snoozed_at = datetime.fromisoformat(entry["snoozed_at"]) - return datetime.now(UTC) - snoozed_at < _SNOOZE_WINDOW - except Exception: - logger.debug("Failed to parse snooze state for check_type=%s", check_type, exc_info=True) - return False - - -def _verify_update_result( - current: str, - latest: str, - home: Path, - state: dict[str, object], -) -> bool: - """Verify that the update subprocess advanced the installed version. - - Calls importlib.metadata.version() directly to bypass the lru_cache in - version_info() and the process-lifetime cache in autoskillit.__version__. - - Returns True if the version advanced (update succeeded). - Returns False if the version is unchanged (update silently failed). - On False, writes a binary_snoozed record and prints an actionable warning. - """ - import importlib.metadata - - try: - new_version = importlib.metadata.version("autoskillit") - except Exception: - logger.debug("Failed to read version after update attempt", exc_info=True) - new_version = current # Treat as unchanged if unreadable - - if new_version != current: - return True - - # Version unchanged — record a snooze and surface a warning - state["binary_snoozed"] = { - "snoozed_at": datetime.now(UTC).isoformat(), - "attempted_version": latest, - } - _write_dismiss_state(home, state) - print( - f"\nUpdate attempted but version is still {current}. " - f"If you have an editable install, run:\n" - f" uv pip install -e \n" - f"Or for a tool install:\n" - f" uv tool upgrade autoskillit", - flush=True, - ) - return False - - -def _detect_install_type() -> tuple[str, str | None]: - """Detect whether autoskillit is installed as an editable or tool install. - - Returns: - ("editable", project_dir_str) — for editable installs (pip install -e) - ("tool", None) — for uv tool or other non-editable installs - """ - import importlib.metadata - - try: - dist = importlib.metadata.Distribution.from_name("autoskillit") - raw = dist.read_text("direct_url.json") - if raw: - import json as _json - - data = _json.loads(raw) - if data.get("dir_info", {}).get("editable"): - url = data.get("url", "") - # file:// URL → strip scheme - if url.startswith("file://"): - return ("editable", url[7:]) - except Exception: - logger.debug("Failed to detect install type from direct_url.json", exc_info=True) - - return ("tool", None) - - -def run_stale_check(home: Path | None = None) -> None: - """Run the stale-install check on interactive CLI invocations. - - Guards: - - Skips when CLAUDECODE=1 (headless/MCP session) - - Skips when stdin or stdout is not a TTY - """ - if ( - os.environ.get("CLAUDECODE") - or os.environ.get("AUTOSKILLIT_SKIP_STALE_CHECK") - or not sys.stdin.isatty() - or not sys.stdout.isatty() - ): - return - - _skip_env = {**os.environ, "AUTOSKILLIT_SKIP_STALE_CHECK": "1"} - - import autoskillit as _pkg - from autoskillit.cli._hooks import _claude_settings_path - - _home = home or Path.home() - dev_mode = is_dev_mode(home=_home) - state = _read_dismiss_state(_home) - latest = _fetch_latest_version(dev_mode) - - current: str = getattr(_pkg, "__version__", "0.0.0") - - # Binary version check - if latest is not None: - from packaging.version import Version - - if ( - Version(latest) > Version(current) - and not _is_dismissed(state, "binary", latest) - and not _is_snoozed(state, "binary") - ): - print( - f"\nAutoSkillit {latest} is available (you have {current}).", - flush=True, - ) - answer = input("Update now? [Y/n] ").strip().lower() - if answer in ("", "y", "yes"): - install_type, project_dir = _detect_install_type() - with terminal_guard(): - if dev_mode and install_type == "editable" and project_dir: - subprocess.run( - ["uv", "pip", "install", "-e", project_dir], - check=False, - env=_skip_env, - ) - elif dev_mode: - subprocess.run( - ["uv", "tool", "install", "--force", _INSTALL_FROM_INTEGRATION], - check=False, - env=_skip_env, - ) - else: - subprocess.run( - ["uv", "tool", "upgrade", "autoskillit"], - check=False, - env=_skip_env, - ) - subprocess.run(["autoskillit", "install"], check=False, env=_skip_env) - _verify_update_result(current, latest, _home, state) - return - else: - state["binary"] = { - "dismissed_at": datetime.now(UTC).isoformat(), - "dismissed_version": latest, - } - _write_dismiss_state(_home, state) - - # Hook drift check - from autoskillit.cli._doctor import _count_hook_registry_drift - - settings_path = _claude_settings_path("user") - n_drift = _count_hook_registry_drift(settings_path) - if n_drift > 0 and not _is_dismissed(state, "hooks", None): - print( - f"\n{n_drift} new/changed hook(s) detected since last install.", - flush=True, - ) - answer = input("Run 'autoskillit install' to sync hooks? [Y/n] ").strip().lower() - if answer in ("", "y", "yes"): - with terminal_guard(): - subprocess.run(["autoskillit", "install"], check=False, env=_skip_env) - else: - state["hooks"] = { - "dismissed_at": datetime.now(UTC).isoformat(), - "dismissed_version": current, - } - _write_dismiss_state(_home, state) diff --git a/src/autoskillit/cli/_terminal.py b/src/autoskillit/cli/_terminal.py index f1e7762c04..507e41c13f 100644 --- a/src/autoskillit/cli/_terminal.py +++ b/src/autoskillit/cli/_terminal.py @@ -11,15 +11,79 @@ from __future__ import annotations import contextlib +import enum import os import sys import termios from collections.abc import Generator +from typing import NamedTuple from autoskillit.core import get_logger _log = get_logger(__name__) +_KBP_TERMINALS = frozenset({"kitty", "WezTerm", "ghostty", "iTerm.app"}) + + +class ResetLayer(enum.StrEnum): + """Terminal state layers that must be fully reset on exit. + + Each layer represents a category of terminal state that Claude Code's + Ink TUI may modify during its session. The terminal_guard() context + manager must emit at least one reset sequence per layer. + + Reference: ECMA-48 (5th ed.), xterm ctlseqs (Thomas Dickey), VT510 spec. + """ + + SCREEN_BUFFER = "screen_buffer" + PRIVATE_MODE = "private_mode" + TERMINAL_STATE = "terminal_state" + CONTENT = "content" + + +class ResetEntry(NamedTuple): + """A single VT100 reset sequence with its layer classification.""" + + sequence: str + name: str + layer: ResetLayer + + +_RESET_SPEC: tuple[ResetEntry, ...] = ( + # --- SCREEN_BUFFER layer --- + ResetEntry("\033[?1049l", "rmcup", ResetLayer.SCREEN_BUFFER), + ResetEntry("\033[?2026l", "sync_output_off", ResetLayer.SCREEN_BUFFER), + # --- PRIVATE_MODE layer --- + ResetEntry("\033[?2004l", "bracketed_paste_off", ResetLayer.PRIVATE_MODE), + ResetEntry("\033[?1000l", "mouse_normal_off", ResetLayer.PRIVATE_MODE), + ResetEntry("\033[?1002l", "mouse_button_off", ResetLayer.PRIVATE_MODE), + ResetEntry("\033[?1003l", "mouse_any_off", ResetLayer.PRIVATE_MODE), + ResetEntry("\033[?1006l", "mouse_sgr_off", ResetLayer.PRIVATE_MODE), + ResetEntry("\033[?1004l", "focus_events_off", ResetLayer.PRIVATE_MODE), + ResetEntry("\033[?1l", "decckm_off", ResetLayer.PRIVATE_MODE), + # --- TERMINAL_STATE layer --- + ResetEntry("\033>", "deckpnm", ResetLayer.TERMINAL_STATE), + ResetEntry("\033[r", "decstbm_reset", ResetLayer.TERMINAL_STATE), + ResetEntry("\033[!p", "decstr", ResetLayer.TERMINAL_STATE), + ResetEntry("\033(B", "g0_charset_ascii", ResetLayer.TERMINAL_STATE), + ResetEntry("\033[0m", "sgr_reset", ResetLayer.TERMINAL_STATE), + ResetEntry("\033[?25h", "dectcem_show_cursor", ResetLayer.TERMINAL_STATE), + # --- CONTENT layer (must be last) --- + ResetEntry("\033[H", "cursor_home", ResetLayer.CONTENT), + ResetEntry("\033[J", "erase_to_end", ResetLayer.CONTENT), +) + +# Derived constant — computed from the spec, not hand-maintained. +_BASE_RESET = "".join(entry.sequence for entry in _RESET_SPEC) + +# Kitty keyboard protocol teardown — NOT universally safe. JediTerm +# (JetBrains IDEs) echoes literal chars from these sequences +# (claude-code#18135). Only emit when terminal is known to support KBP. +_KITTY_RESET = ( + "\033[=0u" # hard-disable Kitty keyboard protocol + "\033[<99u" # drain Kitty keyboard protocol push stack +) + @contextlib.contextmanager def terminal_guard() -> Generator[None, None, None]: @@ -62,7 +126,12 @@ def terminal_guard() -> Generator[None, None, None]: os.system("stty sane 2>/dev/null") if fd is not None: try: - sys.stdout.write("\033[?1049l\033[?1l\033>\033[0m\033[?25h") + sys.stdout.write(_BASE_RESET) + if ( + os.environ.get("KITTY_WINDOW_ID") + or os.environ.get("TERM_PROGRAM", "") in _KBP_TERMINALS + ): + sys.stdout.write(_KITTY_RESET) sys.stdout.flush() except OSError: pass diff --git a/src/autoskillit/cli/_timed_input.py b/src/autoskillit/cli/_timed_input.py new file mode 100644 index 0000000000..a74df7fb23 --- /dev/null +++ b/src/autoskillit/cli/_timed_input.py @@ -0,0 +1,89 @@ +"""Timed prompt primitive with TTY guard, ANSI formatting, and timeout. + +Every user-facing ``input()`` in the CLI layer must go through +``timed_prompt()`` rather than calling ``input()`` directly. A structural +test (``test_input_tty_contracts.py``) enforces this invariant. + +``status_line()`` is the "pre-flight feedback" primitive — it prints a +single status message before any blocking I/O so the user always sees +output immediately. +""" + +from __future__ import annotations + +import select +import sys + +from autoskillit.cli._ansi import supports_color +from autoskillit.cli._init_helpers import _require_interactive_stdin + + +def timed_prompt( + text: str, + *, + default: str = "", + timeout: int = 30, + label: str = "prompt", +) -> str: + """Display a formatted prompt with a bounded wait. + + Composes three invariants into one call: + + 1. **TTY guard** — calls ``_require_interactive_stdin(label)``. + 2. **ANSI formatting** — bold prompt, dim timeout hint. + 3. **Timeout** — ``select.select`` bounds the wait; returns *default* + on expiry instead of blocking forever. + + Parameters + ---------- + text + The prompt text shown to the user (plain text — ANSI is applied + automatically based on ``supports_color()``). + default + Value returned when the user does not respond within *timeout* + seconds, or on ``EOFError``. + timeout + Maximum seconds to wait for input. ``0`` disables the timeout + (waits indefinitely — use only for prompts the user explicitly + initiated). + label + Human-readable label for the TTY-guard error message. + """ + _require_interactive_stdin(label) + + color = supports_color() + _B = "\x1b[1m" if color else "" + _D = "\x1b[2m" if color else "" + _R = "\x1b[0m" if color else "" + + hint = f" {_D}(auto-continues in {timeout}s){_R}" if timeout else "" + formatted = f"{_B}{text}{_R}{hint} " + print(formatted, end="", flush=True) + + if timeout: + try: + ready, _, _ = select.select([sys.stdin], [], [], timeout) + except (OSError, TypeError, ValueError): + # stdin lacks fileno() or fileno() returns non-int + # (e.g. pytest capture, piped input) — fall back to blocking input(). + ready = [sys.stdin] + if not ready: + print(f"\n{_D}(timed out, continuing...){_R}", flush=True) + return default + + try: + return input("").strip() + except EOFError: + return default + + +def status_line(message: str) -> None: + """Print a single-line status message with appropriate formatting. + + This is the "pre-flight feedback" primitive: call it before any + blocking I/O so the terminal is never silent. + """ + color = supports_color() + _D = "\x1b[2m" if color else "" + _R = "\x1b[0m" if color else "" + print(f"{_D}{message}{_R}", flush=True) diff --git a/src/autoskillit/cli/_update.py b/src/autoskillit/cli/_update.py new file mode 100644 index 0000000000..1c9cf51c8c --- /dev/null +++ b/src/autoskillit/cli/_update.py @@ -0,0 +1,71 @@ +"""First-class update command for autoskillit CLI. + +Provides ``run_update_command()`` which is invoked by the ``autoskillit update`` +subcommand. Install-type-aware: uses the same ``upgrade_command()`` policy as +the startup update check so the two paths are never out of sync. +""" + +from __future__ import annotations + +import os +import subprocess +from pathlib import Path + +from autoskillit.cli._install_info import comparison_branch, detect_install, upgrade_command +from autoskillit.cli._terminal import terminal_guard + + +def run_update_command(home: Path | None = None) -> None: + """Upgrade autoskillit to the latest version on the install's branch. + + Reads the install classification from ``direct_url.json``, runs the + appropriate upgrade command, then runs ``autoskillit install`` to sync hooks + and plugin state. Clears any active dismissal state on success. + """ + from autoskillit.cli._update_checks import ( + _fetch_latest_version, + _read_dismiss_state, + _verify_update_result, + _write_dismiss_state, + ) + + _home = home or Path.home() + _skip_env: dict[str, str] = { + **os.environ, + "AUTOSKILLIT_SKIP_STALE_CHECK": "1", + "AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK": "1", + } + + info = detect_install() + cmd = upgrade_command(info) + if cmd is None: + print( + "Unknown install type. " + "Reinstall via install.sh (stable) or 'task install-dev' (integration).", + flush=True, + ) + raise SystemExit(2) + + import autoskillit as _pkg + + current: str = getattr(_pkg, "__version__", "0.0.0") + + with terminal_guard(): + subprocess.run(cmd, check=False, env=_skip_env) + subprocess.run(["autoskillit", "install"], check=False, env=_skip_env) + + state = _read_dismiss_state(_home) + target_branch = comparison_branch(info) + latest: str = ( + _fetch_latest_version(target_branch, _home) or current + if target_branch is not None + else current + ) + succeeded = _verify_update_result(current, latest, _home, state) + + if succeeded: + # Clear any active dismissal state so prompts are fresh + state.pop("update_prompt", None) + state.pop("binary_snoozed", None) + _write_dismiss_state(_home, state) + print("AutoSkillit updated successfully.", flush=True) diff --git a/src/autoskillit/cli/_update_checks.py b/src/autoskillit/cli/_update_checks.py new file mode 100644 index 0000000000..dafc67abe4 --- /dev/null +++ b/src/autoskillit/cli/_update_checks.py @@ -0,0 +1,740 @@ +"""Unified startup update check for autoskillit CLI. + +Consolidates version-staleness, hook-drift, and source-drift signals into a +single dismissable prompt per CLI invocation. + +Branch-aware dismissal windows: + +- ``stable`` / ``main`` / release-tag / ``UNKNOWN`` installs: ``timedelta(days=7)`` +- ``integration`` / ``LOCAL_EDITABLE`` installs: ``timedelta(hours=12)`` + +Dismissal expires on two axes (see ``_is_dismissed``): +1. Time window elapsed (branch-aware, not SHA-keyed). +2. Version advanced past the ``dismissed_version`` recorded at dismiss time. +""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +import time +from dataclasses import dataclass +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any, Literal + +import httpx + +from autoskillit.cli._hooks import _claude_settings_path +from autoskillit.cli._install_info import ( + InstallInfo, + InstallType, + comparison_branch, + detect_install, + dismissal_window, + upgrade_command, +) +from autoskillit.cli._terminal import terminal_guard +from autoskillit.core import AUTOSKILLIT_INSTALLED_VERSION, atomic_write, get_logger +from autoskillit.hook_registry import _count_hook_registry_drift + +logger = get_logger(__name__) + +_DISMISS_FILE = "update_check.json" +_STABLE_DISMISS_WINDOW = timedelta(days=7) +_DEV_DISMISS_WINDOW = timedelta(hours=12) + +# Disposable on-disk cache for GitHub API GETs. This is intentionally a plain +# JSON dict (not ``write_versioned_json``) — it is a transient performance +# cache, not a persisted schema artifact, so a stray pre-existing file at the +# same path is safely ignored on a JSON parse failure. +_FETCH_CACHE_FILE = "github_fetch_cache.json" +_DEFAULT_FETCH_TTL_SECONDS = 30 * 60 + +# connect=2s buffers for cold DNS (httpx's connect timeout does NOT cover the +# OS resolver itself); read=1s is tight because 304 responses are tiny. The +# 30-min disk TTL above is the **only reliable quota defense** — GitHub's +# x-ratelimit-used counter has been observed to increment on 304 responses +# despite their docs claiming otherwise, so ETag/If-None-Match is a +# bandwidth/latency optimization, not a rate-limit optimization. +_HTTP_TIMEOUT = httpx.Timeout(connect=2.0, read=1.0, write=5.0, pool=1.0) +_GITHUB_API_VERSION = "2022-11-28" + +_GITHUB_RELEASES_URL = "https://api.github.com/repos/TalonT-Org/AutoSkillit/releases/latest" +_GITHUB_INTEGRATION_PYPROJECT_URL = ( + "https://api.github.com/repos/TalonT-Org/AutoSkillit/contents/pyproject.toml?ref=integration" +) + + +@dataclass(frozen=True) +class Signal: + """A single firing update condition.""" + + kind: Literal["binary", "hooks", "source_drift", "dual_mcp"] + message: str + + +# --------------------------------------------------------------------------- +# Dismiss state I/O (ported from _stale_check.py) +# --------------------------------------------------------------------------- + + +def _read_dismiss_state(home: Path) -> dict[str, object]: + """Read dismissal state from ~/.autoskillit/update_check.json. + + Returns empty dict on any error (missing file, malformed JSON, etc.). + """ + state_file = home / ".autoskillit" / _DISMISS_FILE + try: + data = json.loads(state_file.read_text(encoding="utf-8")) + return data if isinstance(data, dict) else {} + except Exception: + logger.debug("Failed to read dismiss state from %s", state_file, exc_info=True) + return {} + + +def _write_dismiss_state(home: Path, state: dict[str, object]) -> None: + """Write dismissal state atomically to ~/.autoskillit/update_check.json.""" + state_file = home / ".autoskillit" / _DISMISS_FILE + state_file.parent.mkdir(parents=True, exist_ok=True) + atomic_write(state_file, json.dumps(state)) + + +# --------------------------------------------------------------------------- +# Fetch cache (ported from _stale_check.py) +# --------------------------------------------------------------------------- + + +def _fetch_cache_path(home: Path) -> Path: + return home / ".autoskillit" / _FETCH_CACHE_FILE + + +def _read_fetch_cache(home: Path) -> dict[str, Any]: + """Read the GitHub fetch cache; tolerate any read/parse failure.""" + try: + data = json.loads(_fetch_cache_path(home).read_text(encoding="utf-8")) + return data if isinstance(data, dict) else {} + except Exception: + logger.debug("Failed to read fetch cache", exc_info=True) + return {} + + +def _write_fetch_cache(home: Path, data: dict[str, Any]) -> None: + """Write the GitHub fetch cache atomically.""" + target = _fetch_cache_path(home) + target.parent.mkdir(parents=True, exist_ok=True) + try: + atomic_write(target, json.dumps(data)) + except Exception: + logger.debug("Failed to write fetch cache", exc_info=False) + + +def _scrub_auth(text: str) -> str: + """Remove any GITHUB_TOKEN value or ``Bearer …`` token from a string.""" + if not text: + return text + token = os.environ.get("GITHUB_TOKEN") + if token: + text = text.replace(token, "***") + import re + + text = re.sub(r"(?i)Bearer\s+\S+", "Bearer ***", text) + return text + + +def _resolve_fetch_ttl() -> int: + raw = os.environ.get("AUTOSKILLIT_FETCH_CACHE_TTL_SECONDS") + if raw is None: + return _DEFAULT_FETCH_TTL_SECONDS + try: + return int(raw) + except ValueError: + return _DEFAULT_FETCH_TTL_SECONDS + + +def _fetch_with_cache(url: str, *, home: Path, ttl: int | None = None) -> dict[str, Any] | None: + """Fetch ``url`` via httpx with a disk-backed cache and conditional GETs. + + Returns the parsed JSON dict on success (200 or 304), or ``None`` on any + error. ``Authorization`` headers are scrubbed from log output to prevent + token leakage via DEBUG-level error reporting. + + The 30-minute disk TTL is the only reliable quota defense — see + ``_DEFAULT_FETCH_TTL_SECONDS`` for the rationale. + """ + effective_ttl = ttl if ttl is not None else _resolve_fetch_ttl() + cache = _read_fetch_cache(home) + entry = cache.get(url) if isinstance(cache.get(url), dict) else None + now = time.time() + if entry is not None: + cached_at = entry.get("cached_at") + body = entry.get("body") + if isinstance(cached_at, (int, float)) and isinstance(body, dict): + if now - cached_at < effective_ttl: + return body + + headers: dict[str, str] = { + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": _GITHUB_API_VERSION, + "User-Agent": f"autoskillit/{AUTOSKILLIT_INSTALLED_VERSION}", + } + token = os.environ.get("GITHUB_TOKEN") + if token: + headers["Authorization"] = f"Bearer {token}" + if entry is not None and isinstance(entry.get("etag"), str): + headers["If-None-Match"] = entry["etag"] + + try: + with httpx.Client(timeout=_HTTP_TIMEOUT) as client: + response = client.get(url, headers=headers) + except Exception as exc: + logger.debug("fetch failed for %s: %s", url, _scrub_auth(str(exc))) + return None + + try: + if response.status_code == 304 and entry is not None: + body = entry.get("body") + if isinstance(body, dict): + cache[url] = { + "body": body, + "etag": entry.get("etag"), + "cached_at": now, + } + _write_fetch_cache(home, cache) + return body + return None + if response.status_code == 200: + body = response.json() + if not isinstance(body, dict): + return None + etag = response.headers.get("ETag") + cache[url] = { + "body": body, + "etag": etag, + "cached_at": now, + } + _write_fetch_cache(home, cache) + return body + logger.debug("fetch %s returned status %d", url, response.status_code) + return None + except Exception as exc: + logger.debug("fetch parse failed for %s: %s", url, _scrub_auth(str(exc))) + return None + + +def _fetch_latest_version(target: str, home: Path) -> str | None: + """Fetch the latest available version for the given target branch. + + ``target`` is either ``"releases/latest"`` (for stable/main installs) or + ``"integration"`` (for integration installs). + + Returns ``None`` on any network error or timeout. + """ + try: + if target == "integration": + data = _fetch_with_cache(_GITHUB_INTEGRATION_PYPROJECT_URL, home=home) + if data is None: + return None + import base64 + + raw_content = data.get("content") + if not isinstance(raw_content, str): + return None + content = base64.b64decode(raw_content).decode("utf-8") + for line in content.splitlines(): + line = line.strip() + if line.split("=", 1)[0].strip() == "version": + return line.split("=", 1)[1].strip().strip('"').strip("'") + return None + data = _fetch_with_cache(_GITHUB_RELEASES_URL, home=home) + if data is None: + return None + tag = data.get("tag_name", "") + return tag.lstrip("v") if isinstance(tag, str) and tag else None + except Exception as exc: + logger.debug("Failed to fetch latest version from GitHub: %s", _scrub_auth(str(exc))) + return None + + +# --------------------------------------------------------------------------- +# Source-repo discovery and SHA resolution (ported from _source_drift.py) +# --------------------------------------------------------------------------- + + +def find_source_repo() -> Path | None: + """Locate the autoskillit source repository root. + + Resolution order: + 1. ``AUTOSKILLIT_SOURCE_REPO`` env var (must exist and contain ``src/autoskillit/``). + 2. Walk upward from ``Path.cwd()``, match ``pyproject.toml`` + ``[project].name == "autoskillit"`` AND ``src/autoskillit/`` present. + + Returns ``None`` if no match found or on any error. + """ + try: + env_val = os.environ.get("AUTOSKILLIT_SOURCE_REPO") + if env_val: + candidate = Path(env_val) + if candidate.exists() and (candidate / "src" / "autoskillit").exists(): + return candidate + logger.debug( + "AUTOSKILLIT_SOURCE_REPO=%s not usable (missing or no src/autoskillit/), " + "falling through to CWD walk", + env_val, + ) + + import tomllib + + current = Path.cwd() + while True: + pyproject = current / "pyproject.toml" + if pyproject.is_file(): + try: + with open(pyproject, "rb") as fh: + data = tomllib.load(fh) + project_name = data.get("project", {}).get("name") + if ( + project_name == "autoskillit" + and (current / "src" / "autoskillit").exists() + ): + return current + except Exception: + logger.debug("drift check: could not parse %s", pyproject, exc_info=True) + + parent = current.parent + if parent == current: # Filesystem root + break + current = parent + + return None + except Exception: + logger.debug("drift check: find_source_repo failed", exc_info=True) + return None + + +def resolve_reference_sha( + info: InstallInfo, + home: Path, + *, + network: bool = True, +) -> str | None: + """Resolve the current HEAD SHA of the branch the install was tracking. + + Returns ``None`` when the SHA cannot be determined (network offline, no + source repo, unknown revision). The caller treats ``None`` as "skip check" + (fail-open). + + Args: + info: Install classification from ``detect_install()``. + home: User home directory (used by the disk-backed fetch cache). + network: When ``False``, only the local git or disk cache is consulted. + The doctor check passes ``network=True`` so it can resolve remote refs. + """ + try: + if info.requested_revision is None: + logger.debug("drift check skipped: no requested_revision in direct_url.json") + return None + + rev = info.requested_revision + + # Short-circuit: exact SHA equality means no drift is possible. + # IMPORTANT: use == not startswith — a branch named after a hex prefix + # of the commit SHA must NOT false-positive here. + if rev == info.commit_id: + return info.commit_id + + sha: str | None = None + + source_repo = find_source_repo() + if source_repo is not None and source_repo.exists(): + sha = _git_ls_remote_sha(source_repo, rev) + + if sha is None: + sha = _api_sha(rev, home, network=network) + + return sha + + except Exception: + logger.debug("drift check skipped: resolve_reference_sha error", exc_info=True) + return None + + +def _git_ls_remote_sha(source_repo: Path, rev: str) -> str | None: + """Run git ls-remote to resolve a branch or tag ref SHA. + + Tries ``refs/heads/`` first, then ``refs/tags/^{}`` for peeled + tag objects. Returns ``None`` on empty output or any subprocess error. + """ + for ref in (f"refs/heads/{rev}", f"refs/tags/{rev}^{{}}"): + try: + result = subprocess.run( + ["git", "-C", str(source_repo), "ls-remote", "origin", ref], + capture_output=True, + text=True, + timeout=5, + env=os.environ, + ) + first_line = result.stdout.strip().splitlines()[0] if result.stdout.strip() else "" + if first_line: + sha = first_line.split()[0] + if sha: + return sha + except (subprocess.SubprocessError, FileNotFoundError, OSError, IndexError): + logger.debug("git ls-remote failed for ref=%s", ref, exc_info=True) + return None + + +def _api_sha(rev: str, home: Path, *, network: bool = True) -> str | None: + """Return the commit SHA for ``rev`` from the GitHub API or disk cache. + + When ``network=False`` (doctor mode), reads the existing cache without + any TTL check and makes no outbound HTTP request. Returns ``None`` if the + cache has no entry for the URL. + """ + # Try refs/heads first; fall back to refs/tags for tag revisions. + ref_prefix = "refs/tags" if rev.startswith("v") else "refs/heads" + url = f"https://api.github.com/repos/TalonT-Org/AutoSkillit/git/{ref_prefix}/{rev}" + + if network: + data: Any = _fetch_with_cache(url, home=home) + else: + cache = _read_fetch_cache(home) + entry = cache.get(url) if isinstance(cache.get(url), dict) else None + data = entry.get("body") if isinstance(entry, dict) else None + + if not isinstance(data, dict): + return None + obj = data.get("object") + if not isinstance(obj, dict): + return None + sha = obj.get("sha") + return sha if isinstance(sha, str) and sha else None + + +# --------------------------------------------------------------------------- +# Update result verification (ported from _stale_check.py) +# --------------------------------------------------------------------------- + + +def _verify_update_result( + current: str, + latest: str, + home: Path, + state: dict[str, object], +) -> bool: + """Verify that the update subprocess advanced the installed version. + + Calls importlib.metadata.version() directly to bypass the lru_cache in + version_info() and the process-lifetime cache in autoskillit.__version__. + + Returns True if the version advanced (update succeeded). + Returns False if the version is unchanged (update silently failed). + On False, writes a binary_snoozed record and prints an actionable warning. + """ + import importlib.metadata + + try: + new_version = importlib.metadata.version("autoskillit") + except Exception: + logger.debug("Failed to read version after update attempt", exc_info=True) + new_version = current + + if new_version != current: + return True + + state["binary_snoozed"] = { + "snoozed_at": datetime.now(UTC).isoformat(), + "attempted_version": latest, + } + _write_dismiss_state(home, state) + print( + f"\nUpdate attempted but version is still {current}. " + f"If you have an editable install, run:\n" + f" uv pip install -e \n" + f"Or for a tool install:\n" + f" uv tool upgrade autoskillit", + flush=True, + ) + return False + + +# --------------------------------------------------------------------------- +# Signal gatherers +# --------------------------------------------------------------------------- + + +def _binary_signal(info: InstallInfo, home: Path, current: str) -> Signal | None: + """Return a Signal if a newer binary release is available, else None.""" + target = comparison_branch(info) + if target is None: + return None + latest = _fetch_latest_version(target, home) + if latest is None: + return None + try: + from packaging.version import Version + + if Version(latest) > Version(current): + return Signal("binary", f"New release: {latest} (you have {current})") + except Exception: + logger.debug("binary signal version comparison failed", exc_info=True) + return None + + +def _hooks_signal(settings_path: Path) -> Signal | None: + """Return a Signal if hook registry drift is detected, else None.""" + try: + drift = _count_hook_registry_drift(settings_path) + if drift.orphaned > 0: + return Signal( + "hooks", + f"\u26a0\ufe0f {drift.orphaned} orphaned hook entry(ies) in settings.json " + f"will block tool calls with ENOENT — run 'autoskillit install' to fix", + ) + if drift.missing > 0: + return Signal( + "hooks", + f"{drift.missing} new/changed hook(s) detected since last install", + ) + except Exception: + logger.debug("hooks signal check failed", exc_info=True) + return None + + +def _source_drift_signal(info: InstallInfo, home: Path) -> Signal | None: + """Return a Signal if the installed commit lags the branch HEAD, else None.""" + try: + ref_sha = resolve_reference_sha(info, home, network=True) + if ref_sha is None: + return None + if ref_sha == info.commit_id: + return None + rev = info.requested_revision or str(info.install_type) + installed_short = (info.commit_id or "unknown")[:8] + ref_short = ref_sha[:8] + return Signal( + "source_drift", + f"A newer version is available on the {rev} branch ({installed_short}..{ref_short})", + ) + except Exception: + logger.debug("source drift signal check failed", exc_info=True) + return None + + +def _is_dual_mcp_registered(home: Path) -> bool: + """Return True if both direct mcpServers entry and marketplace plugin are active.""" + from autoskillit.cli._init_helpers import _check_dual_mcp_files + + return _check_dual_mcp_files( + home / ".claude.json", + home / ".claude" / "plugins" / "installed_plugins.json", + ) + + +def _dual_mcp_signal(home: Path | None = None) -> Signal | None: + """Return a Signal if both direct mcpServers entry and marketplace plugin are registered. + + _is_dual_mcp_registered() delegates to _check_dual_mcp_files() which is + fail-open (catches OSError and json.JSONDecodeError internally, never raises). + """ + if _is_dual_mcp_registered(home or Path.home()): + return Signal( + "dual_mcp", + "autoskillit is registered as both a direct MCP server (~/.claude.json) " + "and a marketplace plugin — two server processes will spawn per session. " + "Run `autoskillit install` to remove the stale direct entry.", + ) + return None + + +# --------------------------------------------------------------------------- +# Unified dismissal +# --------------------------------------------------------------------------- + + +def _is_dismissed( + state: dict[str, object], + *, + window: timedelta, + current_version: str, + condition: str, +) -> bool: + """Return True iff the ``update_prompt`` entry dismisses ``condition``. + + Dismissal is active when ALL of: + + 1. ``dismissed_at`` is within the branch-aware ``window`` (time-based, + never SHA-keyed — a new upstream commit does NOT break the window). + Window values: 7 days for stable/main/release-tag/UNKNOWN installs; + 12 hours for integration/LOCAL_EDITABLE installs. + 2. ``current_version <= dismissed_version`` (version-delta expiry: when the + running version advances past what was dismissed, the dismissal expires + uniformly for all three conditions). + 3. ``condition in entry["conditions"]`` — a user who dismissed only + ``"binary"`` still sees a fresh ``"hooks"`` prompt when it newly fires. + + The two expiry axes apply uniformly to all three condition kinds + (``"binary"``, ``"hooks"``, ``"source_drift"``). + """ + try: + entry = state.get("update_prompt") + if not isinstance(entry, dict): + return False + raw_dismissed = entry.get("dismissed_at") + if raw_dismissed is None: + return False + dismissed_at = datetime.fromisoformat(raw_dismissed) + if datetime.now(UTC) - dismissed_at >= window: + return False + from packaging.version import Version + + if Version(current_version) > Version(str(entry.get("dismissed_version", "0.0.0"))): + return False + conditions = entry.get("conditions", []) + if not isinstance(conditions, list): + return False + return condition in conditions + except Exception: + logger.debug("Failed to parse dismiss state for condition=%s", condition, exc_info=True) + return False + + +# --------------------------------------------------------------------------- +# Update sequence +# --------------------------------------------------------------------------- + + +def _run_update_sequence( + info: InstallInfo, + current: str, + home: Path, + state: dict[str, object], + skip_env: dict[str, str], +) -> None: + """Run the upgrade command, then autoskillit install, then verify.""" + cmd = upgrade_command(info) + if cmd is None: + return + target_branch = comparison_branch(info) + latest: str = ( + _fetch_latest_version(target_branch, home) or current + if target_branch is not None + else current + ) + with terminal_guard(): + subprocess.run(cmd, check=False, env=skip_env) + subprocess.run(["autoskillit", "install"], check=False, env=skip_env) + _verify_update_result(current, latest, home, state) + + +# --------------------------------------------------------------------------- +# Main entry point +# --------------------------------------------------------------------------- + + +def run_update_checks(home: Path | None = None) -> None: + """Run the unified update check on interactive CLI invocations. + + At most one ``[Y/n]`` prompt is shown per invocation. Guards: + + - ``CLAUDECODE=1`` — headless/MCP session + - ``CI=1`` — generic CI environment + - ``AUTOSKILLIT_SKIP_STALE_CHECK=1`` — explicit bypass + - ``AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK=1`` — explicit bypass + - Non-TTY stdin or stdout + + Install types ``LOCAL_EDITABLE``, ``LOCAL_PATH``, and ``UNKNOWN`` are + silently skipped after classification. + """ + if ( + os.environ.get("CLAUDECODE") + or os.environ.get("CI") + or os.environ.get("AUTOSKILLIT_SKIP_STALE_CHECK") + or os.environ.get("AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK") + or not sys.stdin.isatty() + or not sys.stdout.isatty() + ): + return + + _skip_env: dict[str, str] = { + **os.environ, + "AUTOSKILLIT_SKIP_STALE_CHECK": "1", + "AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK": "1", + } + + info = detect_install() + if info.install_type in ( + InstallType.UNKNOWN, + InstallType.LOCAL_PATH, + InstallType.LOCAL_EDITABLE, + ) and not os.environ.get("AUTOSKILLIT_FORCE_UPDATE_CHECK"): + return + + import autoskillit as _pkg + + current: str = getattr(_pkg, "__version__", "0.0.0") + _home = home or Path.home() + window = dismissal_window(info) + state = _read_dismiss_state(_home) + + # Pre-flight feedback: ensure the terminal is never silent during network I/O + from autoskillit.cli._timed_input import status_line + + status_line("Checking for updates...") + + # Gather signals + raw_signals: list[Signal | None] = [ + _binary_signal(info, _home, current), + _hooks_signal(_claude_settings_path("user")), + _source_drift_signal(info, _home), + _dual_mcp_signal(_home), + ] + + # Filter by dismissal + firing_signals: list[Signal] = [ + s + for s in raw_signals + if s is not None + and not _is_dismissed( + state, + window=window, + current_version=current, + condition=s.kind, + ) + ] + + if not firing_signals: + return + + # Consolidated prompt + from autoskillit.cli._timed_input import timed_prompt + + _TIMEOUT_SENTINEL = "__timeout__" + bullet_lines = "\n".join(f" - {s.message}" for s in firing_signals) + prompt_text = f"\nAutoSkillit has updates available:\n{bullet_lines}\nUpdate now? [Y/n]" + answer = timed_prompt(prompt_text, default=_TIMEOUT_SENTINEL, timeout=30, label="update check") + + # On timeout: proceed to app() without writing a dismissal record so the + # prompt reappears on the next invocation. + if answer == _TIMEOUT_SENTINEL: + return + + if answer.lower() in ("", "y", "yes"): + _run_update_sequence(info, current, _home, state, _skip_env) + return + + # N path — write unified dismissal record + state["update_prompt"] = { + "dismissed_at": datetime.now(UTC).isoformat(), + "dismissed_version": current, + "conditions": [s.kind for s in firing_signals], + } + _write_dismiss_state(_home, state) + expiry = (datetime.now(UTC) + window).strftime("%Y-%m-%d") + print( + f"Dismissed until {expiry}. Run 'autoskillit update' to update sooner, " + f"or set AUTOSKILLIT_SKIP_STALE_CHECK=1 to silence.", + flush=True, + ) diff --git a/src/autoskillit/cli/_workspace.py b/src/autoskillit/cli/_workspace.py index c1dad17db0..119a3a4950 100644 --- a/src/autoskillit/cli/_workspace.py +++ b/src/autoskillit/cli/_workspace.py @@ -74,12 +74,16 @@ async def run_workspace_clean( print() if not force: - from autoskillit.cli._init_helpers import _require_interactive_stdin + from autoskillit.cli._timed_input import timed_prompt - _require_interactive_stdin("autoskillit workspace clean") suffix = "ies" if len(stale) != 1 else "y" - answer = input(f"Remove {len(stale)} director{suffix}? [y/N]: ") - if answer.strip().lower() != "y": + answer = timed_prompt( + f"Remove {len(stale)} director{suffix}? [y/N]", + default="n", + timeout=120, + label="autoskillit workspace clean", + ) + if answer.lower() != "y": print("Aborted.") return @@ -148,12 +152,16 @@ def _safe_mtime(p: Path) -> float | None: print() if not force: - from autoskillit.cli._init_helpers import _require_interactive_stdin + from autoskillit.cli._timed_input import timed_prompt - _require_interactive_stdin("autoskillit workspace clean") suffix = "ies" if len(stale_wts) != 1 else "y" - answer = input(f"Remove {len(stale_wts)} worktree director{suffix}? [y/N]: ") - if answer.strip().lower() != "y": + answer = timed_prompt( + f"Remove {len(stale_wts)} worktree director{suffix}? [y/N]", + default="n", + timeout=120, + label="autoskillit workspace clean", + ) + if answer.lower() != "y": print("Aborted.") return diff --git a/src/autoskillit/cli/app.py b/src/autoskillit/cli/app.py index e5b81f664e..81c60a3ee0 100644 --- a/src/autoskillit/cli/app.py +++ b/src/autoskillit/cli/app.py @@ -13,6 +13,10 @@ from pathlib import Path from typing import TYPE_CHECKING, Annotated +import anyio + +from autoskillit.cli._serve_guard import serve_with_signal_guard + if TYPE_CHECKING: from autoskillit.recipe import Recipe, RecipeInfo @@ -23,10 +27,10 @@ _MARKER_CONTENT, _check_secret_scanning, _generate_config_yaml, + _is_plugin_installed, _log_secret_scan_bypass, _prompt_test_command, _register_all, - _require_interactive_stdin, ) from autoskillit.cli._terminal import terminal_guard from autoskillit.core import ClaudeFlags, RecipeSource, atomic_write, pkg_root @@ -48,6 +52,10 @@ app.command(workspace_app) +class CliError(Exception): + """Raised by CLI helpers to signal a user-facing error that should abort the command.""" + + @app.default def serve(*, verbose: Annotated[bool, Parameter(name=["--verbose", "-v"])] = False): """Start the MCP server (default command).""" @@ -111,10 +119,14 @@ def serve(*, verbose: Annotated[bool, Parameter(name=["--verbose", "-v"])] = Fal ",".join(cfg.safety.protected_branches), ) - plugin_dir = str(pkg_root()) + plugin_dir: str | None = None if _is_plugin_installed() else str(pkg_root()) ctx = make_context(cfg, plugin_dir=plugin_dir) _initialize(ctx) - mcp.run() + + try: + anyio.run(serve_with_signal_guard, mcp) + except KeyboardInterrupt: + pass # Ctrl+C before anyio loop starts — rare during heavy import phase @app.command @@ -166,7 +178,11 @@ def init( onboarded_marker = config_dir / ".onboarded" onboarded_marker.unlink(missing_ok=True) - _register_all(scope, project_dir) + try: + _register_all(scope, project_dir) + except CliError as exc: + print(f"\n ERROR: {exc}") + raise SystemExit(1) from None @app.command @@ -178,8 +194,9 @@ def install( from autoskillit.cli._init_helpers import _print_next_steps from autoskillit.cli._marketplace import install as _install - _install(scope=scope) - _print_next_steps(context="install") + completed = _install(scope=scope) + if completed: + _print_next_steps(context="install") @app.command @@ -190,6 +207,14 @@ def upgrade() -> None: _upgrade() +@app.command +def update() -> None: + """Upgrade autoskillit to the latest version on your install's branch.""" + from autoskillit.cli._update import run_update_command + + run_update_command() + + @app.command def doctor(*, output_json: bool = False): """Check project setup for common issues.""" @@ -257,7 +282,7 @@ def migrate(*, check: bool = False): @app.command def quota_status() -> None: - """Check current 5-hour quota utilization. Exits 0 always; outputs JSON.""" + """Check quota utilization across all rate-limit windows. Exits 0 always; outputs JSON.""" import asyncio from autoskillit.config import load_config @@ -280,9 +305,9 @@ def config_show(): @skills_app.command(name="list") def skills_list(): """List bundled skills provided by the plugin.""" - from autoskillit.workspace import SkillResolver + from autoskillit.workspace import DefaultSkillResolver - resolver = SkillResolver() + resolver = DefaultSkillResolver() skills = resolver.list_all() if not skills: @@ -428,21 +453,21 @@ def _launch_cook_session( print("ERROR: 'claude' not found. Install: https://docs.anthropic.com/en/docs/claude-code") sys.exit(1) spec = build_interactive_cmd( - initial_prompt=initial_message, resume_session_id=resume_session_id + initial_prompt=initial_message, + resume_session_id=resume_session_id, + env_extras=extra_env, ) - cmd = spec.cmd + [ - ClaudeFlags.PLUGIN_DIR, - str(pkg_root()), + plugin_flags = [] if _is_plugin_installed() else [ClaudeFlags.PLUGIN_DIR, str(pkg_root())] + cmd = [ + *spec.cmd, + *plugin_flags, ClaudeFlags.TOOLS, "AskUserQuestion", ClaudeFlags.APPEND_SYSTEM_PROMPT, system_prompt, ] - env = {**os.environ, **spec.env} - if extra_env: - env.update(extra_env) with terminal_guard(): - result = subprocess.run(cmd, env=env) + result = subprocess.run(cmd, env=spec.env) if result.returncode != 0: sys.exit(result.returncode) @@ -560,6 +585,8 @@ def order(recipe: str | None = None, session_id: str | None = None, *, resume: b mcp_prefix = detect_autoskillit_mcp_prefix() + from autoskillit.cli._timed_input import timed_prompt + if recipe is None: from autoskillit.cli._prompts import ( _OPEN_KITCHEN_CHOICE, @@ -567,7 +594,6 @@ def order(recipe: str | None = None, session_id: str | None = None, *, resume: b _resolve_recipe_input, ) - _require_interactive_stdin("autoskillit order") available = list_recipes(Path.cwd()).items if not available: print("No recipes found. Run 'autoskillit recipes list' to check.") @@ -576,7 +602,12 @@ def order(recipe: str | None = None, session_id: str | None = None, *, resume: b print(" 0. Open kitchen (no recipe)") for i, r in enumerate(available, 1): print(f" {i}. {r.name}") - raw = input(f"Select recipe [0-{len(available)}]: ").strip() + raw = timed_prompt( + f"Select recipe [0-{len(available)}]:", + default="", + timeout=120, + label="autoskillit order", + ) resolved = _resolve_recipe_input(raw, available) if resolved is _OPEN_KITCHEN_CHOICE: from autoskillit.cli._prompts import _OPEN_KITCHEN_GREETINGS @@ -638,11 +669,12 @@ def order(recipe: str | None = None, session_id: str | None = None, *, resume: b if _needed: subset_list = ", ".join(sorted(_needed)) print(f"\nThis recipe requires subset(s): {subset_list}") - _require_interactive_stdin("autoskillit order") print(" 1. Enable temporarily (for this run only)") print(" 2. Enable permanently (update .autoskillit/config.yaml)") print(" 3. Cancel") - _choice = input("Choose [1/2/3]: ").strip() + _choice = timed_prompt( + "Choose [1/2/3]:", default="3", timeout=120, label="autoskillit order" + ) if _choice == "1": _extra_env["AUTOSKILLIT_SUBSETS__DISABLED"] = "@json []" elif _choice == "2": @@ -664,11 +696,12 @@ def order(recipe: str | None = None, session_id: str | None = None, *, resume: b if _packs_needed: pack_list = ", ".join(sorted(_packs_needed)) print(f"\nThis recipe requires pack(s): {pack_list}") - _require_interactive_stdin("autoskillit order") print(" 1. Enable temporarily (for this run only)") print(" 2. Enable permanently (update .autoskillit/config.yaml)") print(" 3. Cancel") - _pack_choice = input("Choose [1/2/3]: ").strip() + _pack_choice = timed_prompt( + "Choose [1/2/3]:", default="3", timeout=120, label="autoskillit order" + ) if _pack_choice == "1": import json as _json @@ -687,9 +720,10 @@ def order(recipe: str | None = None, session_id: str | None = None, *, resume: b from autoskillit.cli._ansi import permissions_warning print(permissions_warning()) - _require_interactive_stdin("autoskillit order") - confirm = input("Launch session? [Enter/n]: ").strip().lower() - if confirm in ("n", "no"): + confirm = timed_prompt( + "Launch session? [Enter/n]", default="", timeout=120, label="autoskillit order" + ) + if confirm.lower() in ("n", "no"): return greeting = random.choice(_COOK_GREETINGS).format(recipe_name=recipe) @@ -705,7 +739,11 @@ def main() -> None: """Entry point for autoskillit.""" _first_arg = sys.argv[1] if len(sys.argv) > 1 else "serve" if _first_arg != "serve": - from autoskillit.cli._stale_check import run_stale_check + from autoskillit.cli._init_helpers import _user_claude_json_path, evict_direct_mcp_entry + + evict_direct_mcp_entry(_user_claude_json_path()) + + from autoskillit.cli._update_checks import run_update_checks - run_stale_check() + run_update_checks() app() diff --git a/src/autoskillit/config/defaults.yaml b/src/autoskillit/config/defaults.yaml index f83eed9138..40d6ac2425 100644 --- a/src/autoskillit/config/defaults.yaml +++ b/src/autoskillit/config/defaults.yaml @@ -43,7 +43,10 @@ run_skill: stale_threshold: 1200 completion_marker: "%%ORDER_UP%%" completion_drain_timeout: 5.0 - exit_after_stop_delay_ms: 120000 + exit_after_stop_delay_ms: 2000 + natural_exit_grace_seconds: 3.0 + idle_output_timeout: 600 + max_suppression_seconds: 1800 model: default: sonnet @@ -60,9 +63,17 @@ token_usage: quota_guard: enabled: true - threshold: 90.0 + short_window_enabled: true # Gates the 5-hour rolling window class. + long_window_enabled: true # Gates the weekly / sonnet / opus class. + short_window_threshold: 85.0 + long_window_threshold: 98.0 + long_window_patterns: + - weekly + - sonnet + - opus buffer_seconds: 60 cache_max_age: 300 + cache_refresh_interval: 240 credentials_path: "~/.claude/.credentials.json" cache_path: "~/.claude/autoskillit_quota_cache.json" @@ -110,6 +121,7 @@ branching: ci: workflow: null # Workflow filename to filter CI runs, e.g. "tests.yml" + event: null # Trigger event to filter CI runs, e.g. "push" subsets: disabled: [] @@ -145,6 +157,25 @@ skills: - arch-lens-scenarios - arch-lens-security - arch-lens-state-lifecycle + - make-experiment-diag + - exp-lens-estimand-clarity + - exp-lens-causal-assumptions + - exp-lens-comparator-construction + - exp-lens-pipeline-integrity + - exp-lens-variance-stability + - exp-lens-fair-comparison + - exp-lens-reproducibility-artifacts + - exp-lens-measurement-validity + - exp-lens-sensitivity-robustness + - exp-lens-benchmark-representativeness + - exp-lens-unit-interference + - exp-lens-error-budget + - exp-lens-severity-testing + - exp-lens-randomization-blocking + - exp-lens-validity-threats + - exp-lens-iterative-learning + - exp-lens-exploratory-confirmatory + - exp-lens-governance-risk - audit-arch - audit-cohesion - audit-tests @@ -164,12 +195,35 @@ skills: - enrich-issues - prepare-issue - process-issues + - scope + - plan-experiment + - implement-experiment + - run-experiment + - generate-report + - validate-audit + - vis-lens-always-on + - vis-lens-antipattern + - vis-lens-chart-select + - vis-lens-color-access + - vis-lens-domain-norms + - vis-lens-figure-table + - vis-lens-multi-compare + - vis-lens-temporal + - vis-lens-uncertainty + - vis-lens-caption-annot + - vis-lens-reproducibility + - vis-lens-story-arc + - plan-visualization + - stage-data + - bundle-local-report tier3: - - open-pr + - prepare-pr + - compose-pr - open-integration-pr - merge-pr - analyze-prs - review-pr + - review-research-pr - resolve-review - implement-worktree-no-merge - resolve-failures @@ -181,7 +235,16 @@ skills: - pipeline-summary - diagnose-ci - verify-diag + - prepare-research-pr + - compose-research-pr + - review-design + - resolve-design-review + - resolve-research-review + - troubleshoot-experiment + - audit-claims + - resolve-claims-review workspace: worktree_root: null # null = auto-resolve to ../worktrees/ relative to project root runs_root: null # null = auto-resolve to ../autoskillit-runs/ relative to project root + temp_dir: .autoskillit/temp # canonical default; override per-project or via AUTOSKILLIT_WORKSPACE__TEMP_DIR diff --git a/src/autoskillit/config/settings.py b/src/autoskillit/config/settings.py index fc29518638..beab3cc4ac 100644 --- a/src/autoskillit/config/settings.py +++ b/src/autoskillit/config/settings.py @@ -11,11 +11,13 @@ from __future__ import annotations import dataclasses +import inspect import logging +import os import tempfile from dataclasses import dataclass, field from pathlib import Path -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, ClassVar from autoskillit.core import ( CATEGORY_TAGS, @@ -90,7 +92,27 @@ class RunSkillConfig: stale_threshold: int = 1200 # 20 minutes completion_marker: str = "%%ORDER_UP%%" completion_drain_timeout: float = 5.0 - exit_after_stop_delay_ms: int = 120000 + exit_after_stop_delay_ms: int = 2000 + natural_exit_grace_seconds: float = 3.0 + idle_output_timeout: int = 600 + max_suppression_seconds: int = 1800 + + # Safety margin (ms) above exit_after_stop_delay_ms that + # natural_exit_grace_seconds must cover so the drain window can absorb + # the CLI self-exit delay without a race. + _EXIT_GRACE_BUFFER_MS: ClassVar[int] = 500 + + def __post_init__(self) -> None: + required_ms = self.exit_after_stop_delay_ms + self._EXIT_GRACE_BUFFER_MS + # Convert seconds → ms for the comparison + if self.natural_exit_grace_seconds * 1000 < required_ms: + raise ValueError( + f"natural_exit_grace_seconds={self.natural_exit_grace_seconds} is too small: " + f"{self.natural_exit_grace_seconds * 1000:.0f}ms < " + f"{required_ms}ms (exit_after_stop_delay_ms + {self._EXIT_GRACE_BUFFER_MS}). " + "Increase natural_exit_grace_seconds so the drain window can absorb the " + "CLI self-exit delay." + ) @property def output_format(self) -> OutputFormat: @@ -122,9 +144,14 @@ class TokenUsageConfig: @dataclass class QuotaGuardConfig: enabled: bool = True - threshold: float = 90.0 + short_window_enabled: bool = True + long_window_enabled: bool = True + short_window_threshold: float = 85.0 + long_window_threshold: float = 98.0 + long_window_patterns: list[str] = field(default_factory=lambda: ["weekly", "sonnet", "opus"]) buffer_seconds: int = 60 cache_max_age: int = 300 + cache_refresh_interval: int = 240 credentials_path: str = "~/.claude/.credentials.json" cache_path: str = "~/.claude/autoskillit_quota_cache.json" @@ -168,7 +195,7 @@ def check_labels_allowed(self, labels: list[str]) -> str | None: class ReportBugConfig: timeout: int = 600 model: str | None = None - report_dir: str | None = None # None = {cwd}/.autoskillit/temp/bug-reports/ + report_dir: str | None = None # None = resolved temp dir + /bug-reports/ github_filing: bool = True github_labels: list[str] = field(default_factory=lambda: ["autoreported", "bug"]) @@ -186,6 +213,25 @@ class LinuxTracingConfig: log_dir: str = "" # empty = platform default (~/.local/share/autoskillit/logs on Linux) tmpfs_path: str = "/dev/shm" # RAM-backed tmpfs for crash-resilient streaming + def __post_init__(self) -> None: + if self.tmpfs_path != "/dev/shm" or not os.environ.get("PYTEST_CURRENT_TEST"): + return + # Only raise when called directly from test code — not from library machinery + # (e.g. AutomationConfig default_factory, from_dynaconf). We inspect the call + # frame two levels up: __post_init__ → __init__ (generated) → actual caller. + frame = inspect.currentframe() + init_frame = frame.f_back if frame is not None else None + caller = init_frame.f_back if init_frame is not None else None + if caller is not None and "/tests/" in (caller.f_code.co_filename or ""): + raise RuntimeError( + "LinuxTracingConfig.tmpfs_path is '/dev/shm' but PYTEST_CURRENT_TEST " + "is set — this test would write to the real shared tmpfs and pollute " + "production state. Override tmpfs_path with a test-local path, e.g.: " + "LinuxTracingConfig(tmpfs_path=str(tmp_path)). " + "Use the isolated_tracing_config fixture for new tests." + ) + del frame, init_frame, caller + @dataclass class McpResponseConfig: @@ -201,6 +247,7 @@ class BranchingConfig: @dataclass class CIConfig: workflow: str | None = None + event: str | None = None @dataclass @@ -231,6 +278,7 @@ class PacksConfig: class WorkspaceConfig: worktree_root: str | None = None # null = auto-resolve to ../worktrees/ runs_root: str | None = None # null = auto-resolve to ../autoskillit-runs/ + temp_dir: str | None = None # null = canonical default (see resolve_temp_dir) def _field_defaults(cls: type) -> dict[str, Any]: @@ -369,6 +417,15 @@ def val(section: dict[str, Any], key: str, default: Any) -> Any: exit_after_stop_delay_ms=int( val(rs, "exit_after_stop_delay_ms", _rs["exit_after_stop_delay_ms"]) ), + natural_exit_grace_seconds=float( + val(rs, "natural_exit_grace_seconds", _rs["natural_exit_grace_seconds"]) + ), + idle_output_timeout=int( + val(rs, "idle_output_timeout", _rs["idle_output_timeout"]) + ), + max_suppression_seconds=int( + val(rs, "max_suppression_seconds", _rs["max_suppression_seconds"]) + ), ), model=ModelConfig( default=_d if (_d := val(mc, "default", None)) is not None else _mc["default"], @@ -385,9 +442,26 @@ def val(section: dict[str, Any], key: str, default: Any) -> Any: ), quota_guard=QuotaGuardConfig( enabled=bool(val(qg, "enabled", _qg["enabled"])), - threshold=float(val(qg, "threshold", _qg["threshold"])), + short_window_enabled=bool( + val(qg, "short_window_enabled", _qg["short_window_enabled"]) + ), + long_window_enabled=bool( + val(qg, "long_window_enabled", _qg["long_window_enabled"]) + ), + short_window_threshold=float( + val(qg, "short_window_threshold", _qg["short_window_threshold"]) + ), + long_window_threshold=float( + val(qg, "long_window_threshold", _qg["long_window_threshold"]) + ), + long_window_patterns=list( + val(qg, "long_window_patterns", _qg["long_window_patterns"]) + ), buffer_seconds=int(val(qg, "buffer_seconds", _qg["buffer_seconds"])), cache_max_age=int(val(qg, "cache_max_age", _qg["cache_max_age"])), + cache_refresh_interval=int( + val(qg, "cache_refresh_interval", _qg["cache_refresh_interval"]) + ), credentials_path=str(val(qg, "credentials_path", _qg["credentials_path"])), cache_path=str(val(qg, "cache_path", _qg["cache_path"])), ), @@ -432,6 +506,7 @@ def val(section: dict[str, Any], key: str, default: Any) -> Any: ), ci=CIConfig( workflow=val(ci, "workflow", _ci["workflow"]) or None, + event=val(ci, "event", _ci["event"]) or None, ), skills=SkillsConfig( tier1=list(val(sk, "tier1", _sk["tier1"])), @@ -443,6 +518,7 @@ def val(section: dict[str, Any], key: str, default: Any) -> Any: workspace=WorkspaceConfig( worktree_root=val(ws_raw, "worktree_root", _wsc["worktree_root"]) or None, runs_root=val(ws_raw, "runs_root", _wsc["runs_root"]) or None, + temp_dir=val(ws_raw, "temp_dir", _wsc["temp_dir"]) or None, ), ) diff --git a/src/autoskillit/core/__init__.py b/src/autoskillit/core/__init__.py index 6aad0b0331..8fee102b8a 100644 --- a/src/autoskillit/core/__init__.py +++ b/src/autoskillit/core/__init__.py @@ -5,6 +5,7 @@ explicit `from autoskillit.core.logging import get_logger`. """ +from ._claude_env import build_claude_env from ._terminal_table import TerminalColumn as TerminalColumn from ._terminal_table import _render_gfm_table as _render_gfm_table from ._terminal_table import _render_terminal_table as _render_terminal_table @@ -19,15 +20,15 @@ from .io import ( _COMMITTED_BY_DESIGN as _COMMITTED_BY_DESIGN, ) -from .io import ( - _ROOT_GITIGNORE_ENTRIES as _ROOT_GITIGNORE_ENTRIES, -) from .io import ( YAMLError, atomic_write, dump_yaml_str, ensure_project_temp, load_yaml, + resolve_temp_dir, + temp_dir_display_str, + write_versioned_json, ) from .logging import ( configure_logging, @@ -42,6 +43,11 @@ is_git_worktree, pkg_root, ) +from .readiness import ( + cleanup_readiness_sentinel, + readiness_sentinel_path, + write_readiness_sentinel, +) from .types import ( AUTOSKILLIT_INSTALLED_VERSION, AUTOSKILLIT_PRIVATE_ENV_VARS, @@ -54,12 +60,12 @@ PACK_REGISTRY, PIPELINE_FORBIDDEN_TOOLS, RESERVED_LOG_RECORD_KEYS, + RETIRED_READINESS_TOKENS, SKILL_COMMAND_PREFIX, SKILL_TOOLS, - TOOL_CATEGORIES, TOOL_SUBSET_TAGS, UNGATED_TOOLS, - AuditStore, + AuditLog, BackgroundSupervisor, ChannelBStatus, ChannelConfirmation, @@ -68,15 +74,20 @@ ClaudeFlags, CleanupResult, CliSubtype, + CloneGateUncommitted, + CloneGateUnpublished, CloneManager, + CloneResult, + CloneSuccessResult, DatabaseReader, FailureRecord, - GatePolicy, + GateState, GitHubFetcher, HeadlessExecutor, + KillReason, LoadReport, LoadResult, - McpResponseStore, + McpResponseLog, MergeFailedStep, MergeQueueWatcher, MergeState, @@ -84,6 +95,8 @@ OutputFormat, OutputPatternResolver, PackDef, + PRState, + QuotaRefreshTask, RecipeRepository, RecipeSource, RestartScope, @@ -91,16 +104,19 @@ SessionOutcome, SessionSkillManager, Severity, + SkillLister, + SkillResolver, SkillResult, SkillSource, SubprocessResult, SubprocessRunner, - TargetSkillResolver, + TerminationAction, TerminationReason, TestResult, TestRunner, - TimingStore, - TokenStore, + TimingLog, + TokenFactory, + TokenLog, ValidatedAddDir, WorkspaceManager, WriteBehaviorSpec, @@ -111,6 +127,8 @@ ) __all__ = [ + # _claude_env + "build_claude_env", # _terminal_table "TerminalColumn", "_render_gfm_table", @@ -131,10 +149,16 @@ "dump_yaml_str", "ensure_project_temp", "load_yaml", - "_ROOT_GITIGNORE_ENTRIES", + "resolve_temp_dir", + "temp_dir_display_str", + "write_versioned_json", # logging "configure_logging", "get_logger", + # readiness + "cleanup_readiness_sentinel", + "readiness_sentinel_path", + "write_readiness_sentinel", # paths "GENERATED_FILES", "claude_code_log_path", @@ -158,6 +182,7 @@ "CATEGORY_TAGS", "TOOL_SUBSET_TAGS", "CONTEXT_EXHAUSTION_MARKER", + "RETIRED_READINESS_TOKENS", "FREE_RANGE_TOOLS", "GATED_TOOLS", "HEADLESS_TOOLS", @@ -165,10 +190,10 @@ "RESERVED_LOG_RECORD_KEYS", "SKILL_COMMAND_PREFIX", "SKILL_TOOLS", - "TOOL_CATEGORIES", "UNGATED_TOOLS", - "AuditStore", + "AuditLog", "BackgroundSupervisor", + "QuotaRefreshTask", "CIRunScope", "CIWatcher", "MergeQueueWatcher", @@ -176,16 +201,21 @@ "ChannelConfirmation", "CliSubtype", "CleanupResult", + "CloneGateUncommitted", + "CloneGateUnpublished", "CloneManager", + "CloneResult", + "CloneSuccessResult", "DatabaseReader", "FailureRecord", - "GatePolicy", + "GateState", "GitHubFetcher", "HeadlessExecutor", "LoadReport", "LoadResult", "MergeFailedStep", "MergeState", + "PRState", "MigrationService", "OutputFormat", "OutputPatternResolver", @@ -195,18 +225,22 @@ "RetryReason", "SessionOutcome", "Severity", + "KillReason", "SkillResult", "SessionSkillManager", "SkillSource", "SubprocessResult", "SubprocessRunner", - "TargetSkillResolver", + "SkillLister", + "SkillResolver", + "TerminationAction", "TerminationReason", "TestResult", "TestRunner", - "McpResponseStore", - "TimingStore", - "TokenStore", + "McpResponseLog", + "TimingLog", + "TokenFactory", + "TokenLog", "WorkspaceManager", "truncate_text", ] diff --git a/src/autoskillit/core/_claude_env.py b/src/autoskillit/core/_claude_env.py new file mode 100644 index 0000000000..83e217fbe1 --- /dev/null +++ b/src/autoskillit/core/_claude_env.py @@ -0,0 +1,97 @@ +"""Canonical env builder for claude-launching subprocesses. + +Every subprocess that invokes the ``claude`` CLI must route its environment +through :func:`build_claude_env` so that host-process IDE state (VS Code, +Cursor, Zed, JetBrains, Neovim bridges) cannot leak across the trust +boundary and silently widen the child's tool surface. + +Two layers of immunity are applied: + +1. **Denylist scrub** — IDE discovery variables such as + ``CLAUDE_CODE_SSE_PORT`` and the ``CLAUDE_CODE_IDE_*`` family are + stripped from ``base``. Removing the port env closes the direct-signal + attach path. +2. **Implicit auto-connect disable** — ``CLAUDE_CODE_AUTO_CONNECT_IDE=0`` + is always injected. This suppresses the ``~/.claude/ide/*.lock`` scan + fallback that the Claude CLI follows at startup even when no IDE env + vars are set; without it, third-party IDE bridges (e.g. + ``claudecode.nvim``) can still attach via the lock-file mechanism. +""" + +from __future__ import annotations + +import os +from collections.abc import Mapping +from types import MappingProxyType + +# Exact-match IDE discovery variable names stripped from the child env. +IDE_ENV_DENYLIST: frozenset[str] = frozenset( + { + "CLAUDE_CODE_SSE_PORT", + "ENABLE_IDE_INTEGRATION", + "CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR", + "VSCODE_GIT_ASKPASS_MAIN", + "CURSOR_TRACE_ID", + "ZED_TERM", + # Session-lifetime vars: stripped from base so callers control them explicitly + # via extras. Without stripping, a parent headless session's env would leak + # into child sessions even when exit_after_stop_delay_ms=0 or no step name. + "CLAUDE_CODE_EXIT_AFTER_STOP_DELAY", + "SCENARIO_STEP_NAME", + # MCP response size gate: injected explicitly by AutoSkillit session launchers + # so the child always gets the correct value regardless of the parent env. + "MAX_MCP_OUTPUT_TOKENS", + } +) + +# Prefix-match IDE variable patterns stripped from the child env. +IDE_ENV_PREFIX_DENYLIST: tuple[str, ...] = ( + "CLAUDE_CODE_IDE_", + "CLAUDE_CODE_SSE", +) + +# Variables injected into every built env regardless of caller. These close +# discovery paths that cannot be closed by scrubbing alone — notably +# CLAUDE_CODE_AUTO_CONNECT_IDE=0, which suppresses the ~/.claude/ide/*.lock +# scan path that fires even when SSE_PORT is absent. +IDE_ENV_ALWAYS_EXTRAS: Mapping[str, str] = MappingProxyType( + { + "CLAUDE_CODE_AUTO_CONNECT_IDE": "0", + } +) + + +def build_claude_env( + base: Mapping[str, str] | None = None, + *, + extras: Mapping[str, str] | None = None, +) -> Mapping[str, str]: + """Return a scrubbed, sealed env dict suitable for a claude subprocess. + + Parameters + ---------- + base + Starting environment. Defaults to ``os.environ``. + extras + Caller-supplied overrides merged last. Used to carry + ``AUTOSKILLIT_HEADLESS=1``, ``SCENARIO_STEP_NAME=...`` and similar + into the child. + + Returns + ------- + Mapping[str, str] + A ``MappingProxyType`` over the resolved env. Both + ``subprocess.run(env=...)`` and ``anyio.open_process(env=...)`` + accept any ``Mapping``, so this is a drop-in for the underlying + runners. The read-only view prevents post-build mutation. + """ + src = os.environ if base is None else base + out: dict[str, str] = { + k: v + for k, v in src.items() + if k not in IDE_ENV_DENYLIST and not any(k.startswith(p) for p in IDE_ENV_PREFIX_DENYLIST) + } + out.update(IDE_ENV_ALWAYS_EXTRAS) + if extras: + out.update(extras) + return MappingProxyType(out) diff --git a/src/autoskillit/core/_type_constants.py b/src/autoskillit/core/_type_constants.py index 2da6badcb7..ea450bcf34 100644 --- a/src/autoskillit/core/_type_constants.py +++ b/src/autoskillit/core/_type_constants.py @@ -23,9 +23,9 @@ "PACK_REGISTRY", "CATEGORY_TAGS", "TOOL_SUBSET_TAGS", - "TOOL_CATEGORIES", "SKILL_COMMAND_PREFIX", "AUTOSKILLIT_SKILL_PREFIX", + "RETIRED_READINESS_TOKENS", ] AUTOSKILLIT_INSTALLED_VERSION: str = version("autoskillit") @@ -37,6 +37,8 @@ { "AUTOSKILLIT_HEADLESS", "AUTOSKILLIT_SKIP_STALE_CHECK", + "AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK", + "AUTOSKILLIT_FORCE_UPDATE_CHECK", } ) @@ -122,6 +124,7 @@ "release_issue", "wait_for_ci", "wait_for_merge_queue", + "check_repo_merge_state", "toggle_auto_merge", "create_unique_branch", "write_telemetry_files", @@ -148,7 +151,9 @@ HEADLESS_TOOLS: frozenset[str] = frozenset({"test_check"}) -FREE_RANGE_TOOLS: frozenset[str] = frozenset({"open_kitchen", "close_kitchen"}) +FREE_RANGE_TOOLS: frozenset[str] = frozenset( + {"open_kitchen", "close_kitchen", "disable_quota_guard"} +) UNGATED_TOOLS: frozenset[str] = FREE_RANGE_TOOLS @@ -169,6 +174,7 @@ class PackDef(NamedTuple): "audit": PackDef(True, "Codebase audit skills"), "research": PackDef(False, "Research recipe and experiment skills"), "exp-lens": PackDef(False, "Experimental design audit lenses"), + "vis-lens": PackDef(False, "Visualization planning lenses"), } CATEGORY_TAGS: frozenset[str] = frozenset(PACK_REGISTRY.keys()) @@ -194,6 +200,7 @@ class PackDef(NamedTuple): # ci "wait_for_ci": frozenset({"ci"}), "wait_for_merge_queue": frozenset({"ci"}), + "check_repo_merge_state": frozenset({"ci"}), "toggle_auto_merge": frozenset({"ci"}), "get_ci_status": frozenset({"ci"}), # clone @@ -208,63 +215,21 @@ class PackDef(NamedTuple): "get_quota_events": frozenset({"telemetry"}), } -# Categorized tool listing for the open_kitchen response. -# Each entry is (category_name, tuple_of_tool_names). Tool names must match the -# registered MCP tool names exactly. -TOOL_CATEGORIES: tuple[tuple[str, tuple[str, ...]], ...] = ( - ("Execution", ("run_cmd", "run_python", "run_skill")), - ("Testing & Workspace", ("test_check", "reset_test_dir", "classify_fix", "reset_workspace")), - ( - "Git Operations", - ("merge_worktree", "create_unique_branch", "check_pr_mergeable", "set_commit_status"), - ), - ("Recipes", ("migrate_recipe", "list_recipes", "load_recipe", "validate_recipe")), - ( - "Clone & Remote", - ( - "clone_repo", - "remove_clone", - "push_to_remote", - "register_clone_status", - "batch_cleanup_clones", - ), - ), - ( - "GitHub", - ( - "fetch_github_issue", - "get_issue_title", - "get_ci_status", - "report_bug", - "prepare_issue", - "enrich_issues", - "claim_issue", - "release_issue", - "wait_for_ci", - "wait_for_merge_queue", - "toggle_auto_merge", - "get_pr_reviews", - "bulk_close_issues", - ), - ), - ( - "Telemetry & Diagnostics", - ( - "read_db", - "write_telemetry_files", - "kitchen_status", - "get_pipeline_report", - "get_token_summary", - "get_timing_summary", - "get_quota_events", - ), - ), - ("Kitchen", ("open_kitchen", "close_kitchen")), -) - # Canonical prefix required for all skill_command values passed to run_skill. # Enforced at the Claude Code hook boundary by skill_command_guard.py. SKILL_COMMAND_PREFIX: str = "/" # Canonical prefix for bundled autoskillit slash commands. AUTOSKILLIT_SKILL_PREFIX: str = "/autoskillit:" + +# Log message tokens that were once used as subprocess readiness sync primitives +# and have since been retired. Any logger call using these tokens as its first +# positional argument is a structural anti-pattern — the lifespan's try: block +# and the anyio signal receiver replaced them with a filesystem sentinel. +# Consumed by test_lifespan_readiness_structural.py (AST Assertion C). +RETIRED_READINESS_TOKENS: frozenset[str] = frozenset( + { + "lifespan_started", + "sigterm_handler_ready", + } +) diff --git a/src/autoskillit/core/_type_enums.py b/src/autoskillit/core/_type_enums.py index 84003a2641..c761b3359d 100644 --- a/src/autoskillit/core/_type_enums.py +++ b/src/autoskillit/core/_type_enums.py @@ -18,10 +18,13 @@ "OutputFormat", "Severity", "TerminationReason", + "TerminationAction", + "KillReason", "ChannelConfirmation", "SessionOutcome", "CliSubtype", "ChannelBStatus", + "PRState", ] @@ -38,6 +41,7 @@ class RetryReason(StrEnum): CONTRACT_RECOVERY = ( "contract_recovery" # marker present + write evidence — omission not structural ) + CLONE_CONTAMINATION = "clone_contamination" class MergeFailedStep(StrEnum): @@ -178,9 +182,42 @@ class TerminationReason(StrEnum): NATURAL_EXIT = "natural_exit" COMPLETED = "completed" STALE = "stale" + IDLE_STALL = "idle_stall" TIMED_OUT = "timed_out" +class TerminationAction(StrEnum): + """What execute_termination_action should do with a subprocess after the race loop. + + Produced by decide_termination_action (pure function) and consumed by + execute_termination_action (the single authorized kill caller in process.py). + + - NO_KILL: process already exited naturally; no kill needed. + - DRAIN_THEN_KILL_IF_ALIVE: channel confirmed completion but process is still + alive; wait up to grace_seconds for natural exit, then kill if still running. + - IMMEDIATE_KILL: timeout, stall, or stale — kill without draining. + """ + + NO_KILL = "no_kill" + DRAIN_THEN_KILL_IF_ALIVE = "drain_then_kill_if_alive" + IMMEDIATE_KILL = "immediate_kill" + + +class KillReason(StrEnum): + """Why the subprocess was (or was not) killed. + + Carried by SubprocessResult and SkillResult so the formatter can annotate + the exit_code line and resolve the cognitive contradiction + "success=True + exit_code=-9". + """ + + NATURAL_EXIT = "natural_exit" + KILL_AFTER_COMPLETION = "kill_after_completion" # drain window expired + INFRA_KILL = "infra_kill" # timeout / stall / stale + EXCEPTION = "exception" # runner raised an unhandled exception + NOT_APPLICABLE = "not_applicable" # no subprocess ran (gate/headless error) + + class ChannelConfirmation(StrEnum): """How subprocess completion was confirmed by the two-channel detection system. @@ -193,11 +230,15 @@ class ChannelConfirmation(StrEnum): stdout may be empty. Downstream must not require stdout content. - UNMONITORED: no channel monitoring active (NATURAL_EXIT, STALE, TIMED_OUT, sync path, or heartbeat disabled with no Channel B win). + - DIR_MISSING: session log directory did not exist when monitoring started. + Monitoring was structurally impossible. Distinct from UNMONITORED (which + means monitoring ran but produced no confirmation). """ CHANNEL_A = "channel_a" CHANNEL_B = "channel_b" UNMONITORED = "unmonitored" + DIR_MISSING = "dir_missing" class SessionOutcome(StrEnum): @@ -237,6 +278,7 @@ class CliSubtype(StrEnum): UNPARSEABLE = "unparseable" TIMEOUT = "timeout" INTERRUPTED = "interrupted" + IDLE_STALL = "idle_stall" @classmethod def from_cli(cls, raw: str) -> CliSubtype: @@ -255,7 +297,31 @@ class ChannelBStatus(StrEnum): Replaces the raw string ``"completion"`` / ``"stale"`` convention with compile-time exhaustiveness enforcement via assert_never. + + - COMPLETION: session JSONL marker was found; monitoring succeeded. + - STALE: monitoring ran but timed out with no marker found. + - DIR_MISSING: session log directory did not exist when monitoring started. + Monitoring was structurally impossible. Distinct from STALE (which + means monitoring ran but produced no marker). """ COMPLETION = "completion" STALE = "stale" + DIR_MISSING = "dir_missing" + + +class PRState(StrEnum): + """Terminal state of a PR as classified by the merge queue watcher. + + Each member is returned only when a positive signal confirms the state. + EJECTED requires either state=CLOSED or mergeable=CONFLICTING. + DROPPED_HEALTHY means auto_merge was cleared on an otherwise healthy PR. + """ + + MERGED = "merged" + EJECTED = "ejected" + EJECTED_CI_FAILURE = "ejected_ci_failure" + STALLED = "stalled" + DROPPED_HEALTHY = "dropped_healthy" + TIMEOUT = "timeout" + ERROR = "error" diff --git a/src/autoskillit/core/_type_helpers.py b/src/autoskillit/core/_type_helpers.py index 529ba9ad36..6f9b73e462 100644 --- a/src/autoskillit/core/_type_helpers.py +++ b/src/autoskillit/core/_type_helpers.py @@ -10,7 +10,7 @@ from ._type_constants import AUTOSKILLIT_SKILL_PREFIX, SKILL_COMMAND_PREFIX from ._type_enums import SkillSource -from ._type_protocols import TargetSkillResolver +from ._type_protocols import SkillResolver __all__ = [ "extract_skill_name", @@ -33,7 +33,7 @@ def extract_skill_name(skill_command: str) -> str | None: def resolve_target_skill( skill_command: str, - resolver: TargetSkillResolver, + resolver: SkillResolver, ) -> tuple[str, str | None]: """Resolve a skill_command to the correct invocation namespace. diff --git a/src/autoskillit/core/_type_protocols.py b/src/autoskillit/core/_type_protocols.py index d776d5cf0b..fcba1e028b 100644 --- a/src/autoskillit/core/_type_protocols.py +++ b/src/autoskillit/core/_type_protocols.py @@ -13,6 +13,7 @@ from ._type_results import ( CIRunScope, CleanupResult, + CloneResult, FailureRecord, SkillResult, TestResult, @@ -21,11 +22,11 @@ ) __all__ = [ - "GatePolicy", - "AuditStore", - "TokenStore", - "TimingStore", - "McpResponseStore", + "GateState", + "AuditLog", + "TokenLog", + "TimingLog", + "McpResponseLog", "TestRunner", "HeadlessExecutor", "RecipeRepository", @@ -39,13 +40,16 @@ "CIWatcher", "MergeQueueWatcher", "SessionSkillManager", - "TargetSkillResolver", + "SkillLister", + "SkillResolver", "BackgroundSupervisor", + "QuotaRefreshTask", + "TokenFactory", ] @runtime_checkable -class GatePolicy(Protocol): +class GateState(Protocol): """Protocol for gate enable/disable state.""" @property @@ -57,7 +61,7 @@ def disable(self) -> None: ... @runtime_checkable -class AuditStore(Protocol): +class AuditLog(Protocol): """Protocol for pipeline failure accumulation.""" def record_failure(self, record: FailureRecord) -> None: ... @@ -83,7 +87,7 @@ def load_from_log_dir( @runtime_checkable -class TokenStore(Protocol): +class TokenLog(Protocol): """Protocol for per-step token usage accumulation.""" def record( @@ -114,7 +118,7 @@ def load_from_log_dir( @runtime_checkable -class TimingStore(Protocol): +class TimingLog(Protocol): """Protocol for per-step wall-clock timing accumulation.""" def record(self, step_name: str, duration_seconds: float, *, order_id: str = "") -> None: ... @@ -136,7 +140,7 @@ def load_from_log_dir( @runtime_checkable -class McpResponseStore(Protocol): +class McpResponseLog(Protocol): """Protocol for per-tool MCP response size accumulation.""" def record( @@ -180,8 +184,10 @@ async def run( add_dirs: Sequence[ValidatedAddDir] = (), timeout: float | None = None, stale_threshold: float | None = None, + idle_output_timeout: float | None = None, expected_output_patterns: Sequence[str] = (), write_behavior: WriteBehaviorSpec | None = None, + completion_marker: str = "", ) -> SkillResult: ... @@ -201,9 +207,13 @@ def load_and_validate( suppressed: Sequence[str] | None = None, resolved_defaults: dict[str, str] | None = None, ingredient_overrides: dict[str, str] | None = None, + temp_dir: Path | None = None, + temp_dir_relpath: str | None = None, ) -> dict[str, Any]: ... - def validate_from_path(self, script_path: Any) -> dict[str, Any]: ... + def validate_from_path( + self, script_path: Any, temp_dir_relpath: str = ".autoskillit/temp" + ) -> dict[str, Any]: ... def list_all(self, project_dir: Any | None = None) -> dict[str, Any]: ... @@ -265,7 +275,7 @@ def clone_repo( branch: str = "", strategy: str = "", remote_url: str = "", - ) -> dict[str, str]: ... + ) -> CloneResult: ... def remove_clone(self, clone_path: str, keep: str = "false") -> dict[str, str]: ... @@ -405,6 +415,7 @@ async def wait( stall_grace_period: int = 60, max_stall_retries: int = 3, not_in_queue_confirmation_cycles: int = 2, + max_inconclusive_retries: int = 5, ) -> dict[str, Any]: ... async def toggle( @@ -428,20 +439,37 @@ def init_session( config: Any | None = None, project_dir: Path | None = None, recipe_packs: frozenset[str] | None = None, + allow_only: frozenset[str] | None = None, ) -> ValidatedAddDir: ... - def activate_tier2(self, session_id: str, skill_name: str) -> bool: ... + def compute_skill_closure(self, skill_name: str) -> frozenset[str]: ... + + def activate_skill_deps(self, session_id: str, skill_name: str) -> bool: ... def cleanup_stale(self, max_age_seconds: int = 86400) -> int: ... @runtime_checkable -class TargetSkillResolver(Protocol): +class SkillResolver(Protocol): """Protocol for resolving skill names to their source tier.""" def resolve(self, name: str) -> Any: ... +@runtime_checkable +class SkillLister(Protocol): + """L0 contract for listing all available skills. + + Allows L2 recipe rules to type their skill-listing dependency + against an L0 protocol instead of binding to the L1 workspace + concrete class. The default implementation lives at + autoskillit.workspace.skills.DefaultSkillResolver and satisfies this + protocol structurally. + """ + + def list_all(self) -> list[Any]: ... + + @runtime_checkable class BackgroundSupervisor(Protocol): """Protocol for supervised background task execution.""" @@ -459,3 +487,27 @@ def submit( ) -> Any: ... async def drain(self) -> None: ... + + +@runtime_checkable +class QuotaRefreshTask(Protocol): + """Protocol for a cancellable background task handle. + + Satisfied by asyncio.Task — used to type the kitchen-scoped quota + refresh task stored in ToolContext without leaking asyncio.Task into the + core layer. + """ + + def cancel(self, msg: Any = None) -> bool: ... + + +@runtime_checkable +class TokenFactory(Protocol): + """Protocol for resolving a GitHub token via the config → env → CLI fallback chain. + + Satisfied by any zero-argument callable that returns a token string or None. + Set by make_context() on ToolContext; None in test ToolContext instances unless + explicitly provided. + """ + + def __call__(self) -> str | None: ... diff --git a/src/autoskillit/core/_type_results.py b/src/autoskillit/core/_type_results.py index 4d1c17dc54..465cad19d1 100644 --- a/src/autoskillit/core/_type_results.py +++ b/src/autoskillit/core/_type_results.py @@ -10,9 +10,9 @@ from dataclasses import asdict, dataclass, field from enum import Enum from pathlib import Path -from typing import Any, Generic, TypeVar +from typing import Any, Generic, Literal, TypedDict, TypeVar -from ._type_enums import RetryReason, SessionOutcome +from ._type_enums import KillReason, RetryReason, SessionOutcome T = TypeVar("T") @@ -26,6 +26,10 @@ "SkillResult", "CleanupResult", "CIRunScope", + "CloneSuccessResult", + "CloneGateUncommitted", + "CloneGateUnpublished", + "CloneResult", ] @@ -145,6 +149,12 @@ class SkillResult: write_path_warnings: list[str] = field(default_factory=list) write_call_count: int = 0 order_id: str = "" + kill_reason: KillReason = KillReason.NATURAL_EXIT + """Why the subprocess was (or was not) killed after the race loop. + + Surfaces from SubprocessResult so the formatter can annotate exit_code + with the kill cause, resolving the "success=True + exit_code=-9" contradiction. + """ def to_json(self) -> str: data: dict[str, Any] = { @@ -155,6 +165,7 @@ def to_json(self) -> str: "cli_subtype": self.cli_subtype, "is_error": self.is_error, "exit_code": self.exit_code, + "kill_reason": self.kill_reason.value, "needs_retry": self.needs_retry, "retry_reason": self.retry_reason, "stderr": self.stderr, @@ -168,6 +179,36 @@ def to_json(self) -> str: data["order_id"] = self.order_id return json.dumps(data, default=lambda o: o.value if isinstance(o, Enum) else str(o)) + @classmethod + def crashed( + cls, + exception: Exception, + skill_command: str = "", + session_id: str = "", + order_id: str = "", + ) -> SkillResult: + """Construct a SkillResult for a runner crash (pre-launch or mid-flight exception). + + Produces the same 13+ field envelope as _build_skill_result, ensuring + pipeline orchestrators can route crash responses without schema inspection. + """ + _result = f"{type(exception).__name__}: {exception}" + if skill_command: + _result += f" | skill_command={skill_command!r}" + return cls( + success=False, + result=_result, + session_id=session_id, + subtype="crashed", + is_error=True, + exit_code=-1, + needs_retry=False, + retry_reason=RetryReason.NONE, + stderr="", + kill_reason=KillReason.EXCEPTION, + order_id=order_id, + ) + @property def outcome(self) -> SessionOutcome: """Classify this result as SUCCEEDED, RETRIABLE, or FAILED. @@ -206,9 +247,45 @@ class CIRunScope: """Immutable scope parameters that uniquely identify which CI workflow runs are relevant. Passed as a single argument through the CIWatcher protocol so that adding a new - scope axis (e.g. event: str | None) requires changing only this dataclass and the - API params builder — not every method signature in the call chain. + scope axis requires changing only this dataclass and the API params builder — + not every method signature in the call chain. """ workflow: str | None = None # workflow filename, e.g. "tests.yml" head_sha: str | None = None # commit SHA to pin results to + event: str | None = None # trigger event, e.g. "push", "pull_request" + + +class CloneSuccessResult(TypedDict): + """Typed return contract for a successful clone_repo invocation. + + Precedent: PRFetchState(TypedDict) in execution/merge_queue.py for + typed discriminated returns in the same codebase. + """ + + clone_path: str + source_dir: str + remote_url: str + clone_source_type: Literal["remote", "local"] + clone_source_reason: str + + +class CloneGateUncommitted(TypedDict): + """Returned by clone_repo when uncommitted changes are detected (strategy="").""" + + uncommitted_changes: Literal["true"] + source_dir: str + branch: str + changed_files: str + total_changed: str + + +class CloneGateUnpublished(TypedDict): + """Returned by clone_repo when the branch is unpublished (strategy="").""" + + unpublished_branch: Literal["true"] + branch: str + source_dir: str + + +CloneResult = CloneSuccessResult | CloneGateUncommitted | CloneGateUnpublished diff --git a/src/autoskillit/core/_type_subprocess.py b/src/autoskillit/core/_type_subprocess.py index 793237fcab..f59d083a2c 100644 --- a/src/autoskillit/core/_type_subprocess.py +++ b/src/autoskillit/core/_type_subprocess.py @@ -6,12 +6,12 @@ from __future__ import annotations -from collections.abc import Awaitable +from collections.abc import Awaitable, Mapping from dataclasses import dataclass from pathlib import Path from typing import Any, Protocol, runtime_checkable -from ._type_enums import ChannelConfirmation, TerminationReason +from ._type_enums import ChannelConfirmation, KillReason, TerminationReason __all__ = [ "SubprocessResult", @@ -103,6 +103,20 @@ class SubprocessResult: Consumers (session_log, tokens) must use this float directly — never re-derive duration from start_ts/end_ts ISO strings. """ + kill_reason: KillReason = KillReason.NATURAL_EXIT + """Why the subprocess was (or was not) killed after the race loop. + + Set by run_managed_async via execute_termination_action. Surfaces to SkillResult + so the formatter can annotate exit_code with the kill cause. + """ + tracked_comm: str | None = None + """Process identity comm of the observed workload, or None when tracing disabled. + + Populated from TraceTarget.comm after resolve_trace_target() resolves the workload + PID from the spawn PID. Propagated to flush_session_log and anomaly detection so + that downstream telemetry (sessions.jsonl, summary.json, GitHub issue bodies) can + self-identify which process was actually observed. (Issue #806) + """ @runtime_checkable @@ -115,7 +129,7 @@ def __call__( *, cwd: Path, timeout: float, - env: dict[str, str] | None = None, + env: Mapping[str, str] | None = None, stale_threshold: float = 1200, completion_marker: str = "", session_log_dir: Path | None = None, @@ -123,4 +137,6 @@ def __call__( input_data: str | None = None, completion_drain_timeout: float = 5.0, linux_tracing_config: Any | None = None, + idle_output_timeout: float | None = None, + max_suppression_seconds: float | None = None, ) -> Awaitable[SubprocessResult]: ... diff --git a/src/autoskillit/core/io.py b/src/autoskillit/core/io.py index 44cff28c7e..fa90cf0455 100644 --- a/src/autoskillit/core/io.py +++ b/src/autoskillit/core/io.py @@ -2,10 +2,15 @@ Zero autoskillit imports. Provides atomic filesystem writes, project temp directory management, and YAML load/dump helpers. + +All NEW on-disk JSON artifacts SHOULD use ``write_versioned_json`` so schema drift +is detectable. Existing artifacts are tracked in +``tests/infra/test_schema_version_convention.py`` (landed in a later phase). """ from __future__ import annotations +import json import os import tempfile from pathlib import Path @@ -20,16 +25,61 @@ "ensure_project_temp", "load_yaml", "dump_yaml_str", + "resolve_temp_dir", + "temp_dir_display_str", + "write_versioned_json", ] +def resolve_temp_dir(project_dir: Path, override: str | None = None) -> Path: + """Resolve the autoskillit temp directory for a project. + + Canonical default literal: ``.autoskillit/temp`` — do not change without + updating ``_TEMP_PATH_WHITELIST`` in ``tests/python_no_hardcoded_temp.py``. + + Precedence: + - ``override`` absolute: returned as-is. + - ``override`` relative: anchored to ``project_dir``. + - ``override`` None: default to ``project_dir/.autoskillit/temp``. + + ``override == ""`` raises ``ValueError``; empty strings must be normalized to + ``None`` at the ``AutomationConfig.from_dynaconf`` dataclass boundary. + """ + if override is None: + return project_dir / ".autoskillit" / "temp" + if override == "": + raise ValueError( + "resolve_temp_dir received empty string; " + "normalize empty to None at the dataclass boundary" + ) + p = Path(override) + return p if p.is_absolute() else project_dir / p + + +def temp_dir_display_str(override: str | None) -> str: + """Return the string placed into SKILL.md/recipe YAML for ``override``. + + Mirrors ``resolve_temp_dir`` for string-facing sites (skill content, + recipe YAML substitution). ``None`` yields the canonical default literal. + """ + return override or ".autoskillit/temp" + + def atomic_write(path: Path, content: str) -> None: - """Crash-safe write: write to a temp file then os.replace.""" + """Crash-safe write: write to a temp file then os.replace. + + Includes data fsync and directory fsync for durability on ext4/xfs. + The directory fsync is skipped on Windows (no O_RDONLY semantics). + """ + import sys as _sys + path.parent.mkdir(parents=True, exist_ok=True) fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp") try: with os.fdopen(fd, "w", encoding="utf-8") as f: f.write(content) + f.flush() + os.fsync(f.fileno()) # durable data write os.replace(tmp, path) except Exception: try: @@ -37,16 +87,38 @@ def atomic_write(path: Path, content: str) -> None: except OSError: pass raise + # Durable rename: fsync the parent directory on POSIX. + # Best-effort: os.replace() already committed the rename; a dir_fsync + # failure here does not undo the write. + if _sys.platform != "win32": + try: + dir_fd = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(dir_fd) + finally: + os.close(dir_fd) + except OSError: + pass # Non-fatal — data is durable at path after os.replace() -_AUTOSKILLIT_GITIGNORE_ENTRIES = ["temp/", ".secrets.yaml", ".onboarded", "sync_manifest.json"] +def write_versioned_json(path: Path, payload: dict[str, Any], schema_version: int) -> None: + """Write a dict JSON artifact enriched with ``schema_version``. -_ROOT_GITIGNORE_ENTRIES = [ - ".autoskillit/.secrets.yaml", - ".autoskillit/temp/", - ".autoskillit/.onboarded", - ".autoskillit/sync_manifest.json", -] + Covers **write atomicity only** (single-writer semantics via + ``atomic_write``). Callers performing read-modify-write composites + (e.g. the clone registry) must layer their own ``fcntl.flock`` — + this helper does not serialize concurrent mutators. + + Raises ``TypeError`` if ``payload`` is not a dict (wrap bare arrays + as ``{"items": [...]}`` at the call site). + """ + if not isinstance(payload, dict): + raise TypeError("write_versioned_json requires a dict payload") + enriched = {**payload, "schema_version": schema_version} + atomic_write(path, json.dumps(enriched)) + + +_AUTOSKILLIT_GITIGNORE_ENTRIES = ["temp/", ".secrets.yaml", ".onboarded", "sync_manifest.json"] _COMMITTED_BY_DESIGN: frozenset[str] = frozenset( { @@ -56,30 +128,45 @@ def atomic_write(path: Path, content: str) -> None: ) -def ensure_project_temp(project_dir: Path) -> Path: - """Create .autoskillit/temp/ with a .gitignore; idempotent. Returns the path.""" - autoskillit_dir = project_dir / ".autoskillit" - temp_dir = autoskillit_dir / "temp" +def ensure_project_temp(project_dir: Path, override: str | None = None) -> Path: + """Create the autoskillit temp directory with a self-gitignore; idempotent. + + Uses the pytest/mypy self-gitignoring directory pattern: the temp directory + owns a ``.gitignore`` containing ``*`` — no mutation of the project root + ``.gitignore``. Works identically for default, custom-relative, and absolute + external overrides. + + Also maintains ``.autoskillit/.gitignore`` covering session artefacts that + land alongside ``config.yaml`` (``.secrets.yaml``, ``.onboarded``, + ``sync_manifest.json``) when the project uses the canonical ``.autoskillit`` + directory. + """ + temp_dir = resolve_temp_dir(project_dir, override) temp_dir.mkdir(parents=True, exist_ok=True) - gitignore_path = autoskillit_dir / ".gitignore" + # Race-safe ordering: .gitignore is the FIRST file written after mkdir, + # before any session content lands. See pytest #12167 / mypy #12442. + gitignore_path = temp_dir / ".gitignore" if not gitignore_path.exists(): - atomic_write(gitignore_path, "\n".join(_AUTOSKILLIT_GITIGNORE_ENTRIES) + "\n") - else: - existing = gitignore_path.read_text(encoding="utf-8") - missing = [e for e in _AUTOSKILLIT_GITIGNORE_ENTRIES if e not in existing.splitlines()] - if missing: - atomic_write(gitignore_path, existing.rstrip("\n") + "\n" + "\n".join(missing) + "\n") - root_gitignore = project_dir / ".gitignore" - if not root_gitignore.exists(): - atomic_write(root_gitignore, "\n".join(_ROOT_GITIGNORE_ENTRIES) + "\n") - else: - existing_root = root_gitignore.read_text(encoding="utf-8") - missing_root = [e for e in _ROOT_GITIGNORE_ENTRIES if e not in existing_root.splitlines()] - if missing_root: + atomic_write( + gitignore_path, + "# Created by autoskillit automatically.\n*\n", + ) + autoskillit_dir = project_dir / ".autoskillit" + if autoskillit_dir.is_dir(): + autoskillit_gitignore = autoskillit_dir / ".gitignore" + if not autoskillit_gitignore.exists(): atomic_write( - root_gitignore, - existing_root.rstrip("\n") + "\n" + "\n".join(missing_root) + "\n", + autoskillit_gitignore, + "\n".join(_AUTOSKILLIT_GITIGNORE_ENTRIES) + "\n", ) + else: + existing = autoskillit_gitignore.read_text(encoding="utf-8") + missing = [e for e in _AUTOSKILLIT_GITIGNORE_ENTRIES if e not in existing.splitlines()] + if missing: + atomic_write( + autoskillit_gitignore, + existing.rstrip("\n") + "\n" + "\n".join(missing) + "\n", + ) return temp_dir diff --git a/src/autoskillit/core/kitchen_state.py b/src/autoskillit/core/kitchen_state.py new file mode 100644 index 0000000000..28446c2e13 --- /dev/null +++ b/src/autoskillit/core/kitchen_state.py @@ -0,0 +1,123 @@ +"""Kitchen-open session marker — stdlib-only, importable from hook subprocesses. + +Provides disk-based session state so PreToolUse hooks can detect whether +open_kitchen has been called in the current session. Hook subprocesses are +fresh-spawned on each invocation and share no memory — a disk marker is the +only cross-process handshake surface. +""" + +from __future__ import annotations + +import json +import os +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path + + +@dataclass(frozen=True) +class KitchenMarker: + """Immutable record written when open_kitchen is called.""" + + session_id: str + opened_at: datetime + recipe_name: str | None + marker_version: int = 1 + + +def get_state_dir() -> Path: + """Return the kitchen-state directory. + + Reads AUTOSKILLIT_STATE_DIR env (for test isolation); falls back to the + canonical temp location derived from Path.cwd(). + """ + override = os.environ.get("AUTOSKILLIT_STATE_DIR") + if override: + return Path(override) / "kitchen_state" + # Canonical default: .autoskillit/temp/kitchen_state relative to CWD + return Path.cwd() / ".autoskillit" / "temp" / "kitchen_state" + + +def marker_path(session_id: str) -> Path: + """Return the Path where the marker for session_id is stored.""" + return get_state_dir() / f"{session_id}.json" + + +def write_marker(session_id: str, recipe_name: str | None) -> None: + """Atomically write a kitchen-open marker for session_id. + + Uses stdlib tempfile + os.replace for crash-safety. + """ + import tempfile + + path = marker_path(session_id) + path.parent.mkdir(parents=True, exist_ok=True) + payload = { + "session_id": session_id, + "opened_at": datetime.now(UTC).isoformat(), + "recipe_name": recipe_name, + "marker_version": 1, + } + content = json.dumps(payload) + fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(content) + os.replace(tmp, path) + except Exception: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def read_marker(session_id: str) -> KitchenMarker | None: + """Read and validate the kitchen marker for session_id. + + Returns None on missing file, malformed JSON, or schema mismatch. + """ + path = marker_path(session_id) + try: + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return None + try: + return KitchenMarker( + session_id=data["session_id"], + opened_at=datetime.fromisoformat(data["opened_at"]), + recipe_name=data.get("recipe_name"), + marker_version=data.get("marker_version", 1), + ) + except (KeyError, ValueError, TypeError): + return None + + +def is_marker_fresh(marker: KitchenMarker, ttl_hours: int = 24) -> bool: + """Return True if the marker is within the TTL window.""" + age = datetime.now(UTC) - marker.opened_at + return age.total_seconds() < ttl_hours * 3600 + + +def sweep_stale_markers(ttl_hours: int = 24) -> int: + """Delete all markers older than ttl_hours. Returns count of deleted markers.""" + state_dir = get_state_dir() + if not state_dir.is_dir(): + return 0 + deleted = 0 + for p in state_dir.glob("*.json"): + try: + data = json.loads(p.read_text(encoding="utf-8")) + opened_at = datetime.fromisoformat(data["opened_at"]) + age = datetime.now(UTC) - opened_at + if age.total_seconds() >= ttl_hours * 3600: + p.unlink() + deleted += 1 + except (OSError, json.JSONDecodeError, KeyError, ValueError, UnicodeDecodeError): + # Malformed or unreadable markers are treated as stale and removed + try: + p.unlink() + deleted += 1 + except OSError: + pass + return deleted diff --git a/src/autoskillit/core/readiness.py b/src/autoskillit/core/readiness.py new file mode 100644 index 0000000000..efd8c226c8 --- /dev/null +++ b/src/autoskillit/core/readiness.py @@ -0,0 +1,78 @@ +"""Filesystem readiness sentinel primitives for MCP server startup. + +The sentinel file replaces log-line string matching as the subprocess +synchronization primitive used by integration tests. File existence is +atomic — there is no string-parse race and no wall-clock settle-sleep. + +This is an L0 module: stdlib-only imports plus core.io for ``atomic_write``. +No anyio, no FastMCP, no higher-layer autoskillit imports. + +Path resolution follows the same ``AUTOSKILLIT_STATE_DIR`` override pattern as +``core.kitchen_state``: tests set the env var to a ``tmp_path``-scoped +directory to isolate sentinel files from the project tree. +""" + +from __future__ import annotations + +import os +from pathlib import Path + +from .io import atomic_write +from .kitchen_state import get_state_dir + +__all__ = [ + "readiness_sentinel_path", + "write_readiness_sentinel", + "cleanup_readiness_sentinel", +] + + +def _sentinel_dir() -> Path: + """Return the directory where sentinel files are written. + + Delegates to ``kitchen_state.get_state_dir()`` to avoid path-resolution + drift between the two modules. + """ + return get_state_dir() + + +def readiness_sentinel_path(pid: int) -> Path: + """Return the sentinel path for a given process ID. + + The path is deterministic and pid-scoped so parallel server instances + (e.g. during parallel test runs) do not collide. + + :param pid: The server process ID. + :returns: Path to ``/server_ready_{pid}.sentinel``. + """ + return _sentinel_dir() / f"server_ready_{pid}.sentinel" + + +def write_readiness_sentinel() -> Path: + """Write an empty sentinel file at the readiness path for the current process. + + Idempotent: safe to call multiple times. The file is written atomically so + a reader observing the file exists is guaranteed the write has completed. + + :returns: The path that was written. + """ + path = readiness_sentinel_path(os.getpid()) + path.parent.mkdir(parents=True, exist_ok=True) + atomic_write(path, "") + return path + + +def cleanup_readiness_sentinel(pid: int | None = None) -> None: + """Remove the readiness sentinel file if it exists. + + Never raises on ENOENT — safe to call from a finally: block even if + ``write_readiness_sentinel`` was never reached (e.g. exception during startup). + + :param pid: Process ID whose sentinel to remove. Defaults to ``os.getpid()``. + """ + resolved_pid = pid if pid is not None else os.getpid() + sentinel = readiness_sentinel_path(resolved_pid) + try: + sentinel.unlink() + except FileNotFoundError: + pass diff --git a/src/autoskillit/execution/__init__.py b/src/autoskillit/execution/__init__.py index c25e459a51..86a60a4014 100644 --- a/src/autoskillit/execution/__init__.py +++ b/src/autoskillit/execution/__init__.py @@ -13,9 +13,11 @@ ) from autoskillit.execution.ci import DefaultCIWatcher from autoskillit.execution.commands import ( + _MAX_MCP_OUTPUT_TOKENS_VALUE, # noqa: F401 ClaudeHeadlessCmd, ClaudeInteractiveCmd, build_headless_cmd, + build_headless_resume_cmd, build_interactive_cmd, ) from autoskillit.execution.db import ( @@ -47,7 +49,7 @@ read_starttime_ticks, start_linux_tracing, ) -from autoskillit.execution.merge_queue import DefaultMergeQueueWatcher +from autoskillit.execution.merge_queue import DefaultMergeQueueWatcher, fetch_repo_merge_state from autoskillit.execution.pr_analysis import ( DOMAIN_PATHS, extract_linked_issues, @@ -59,7 +61,24 @@ run_managed_async, run_managed_sync, ) -from autoskillit.execution.quota import QuotaStatus, check_and_sleep_if_needed +from autoskillit.execution.quota import ( + QUOTA_CACHE_SCHEMA_VERSION, + QuotaStatus, + _refresh_quota_cache, # noqa: F401 — imported for re-export via server.helpers; not in __all__ + check_and_sleep_if_needed, +) +from autoskillit.execution.recording import ( + RECORD_SCENARIO_DIR_ENV, + RECORD_SCENARIO_ENV, + RECORD_SCENARIO_RECIPE_ENV, + REPLAY_SCENARIO_DIR_ENV, + REPLAY_SCENARIO_ENV, + SCENARIO_STEP_NAME_ENV, + RecordingSubprocessRunner, + ReplayingSubprocessRunner, + ScenarioReplayError, + build_replay_runner, +) from autoskillit.execution.remote_resolver import REMOTE_PRECEDENCE, resolve_remote_repo from autoskillit.execution.session import ( ClaudeSessionResult, @@ -86,11 +105,24 @@ "ClaudeHeadlessCmd", "build_interactive_cmd", "build_headless_cmd", + "build_headless_resume_cmd", # process "DefaultSubprocessRunner", "run_managed_async", "run_managed_sync", + # recording + "RecordingSubprocessRunner", + "ReplayingSubprocessRunner", + "ScenarioReplayError", + "build_replay_runner", + "RECORD_SCENARIO_ENV", + "RECORD_SCENARIO_DIR_ENV", + "RECORD_SCENARIO_RECIPE_ENV", + "REPLAY_SCENARIO_ENV", + "REPLAY_SCENARIO_DIR_ENV", + "SCENARIO_STEP_NAME_ENV", # quota + "QUOTA_CACHE_SCHEMA_VERSION", "QuotaStatus", "check_and_sleep_if_needed", # session @@ -110,6 +142,7 @@ "DefaultCIWatcher", # merge_queue "DefaultMergeQueueWatcher", + "fetch_repo_merge_state", # remote_resolver "REMOTE_PRECEDENCE", "resolve_remote_repo", diff --git a/src/autoskillit/execution/_headless_scan.py b/src/autoskillit/execution/_headless_scan.py new file mode 100644 index 0000000000..d960674686 --- /dev/null +++ b/src/autoskillit/execution/_headless_scan.py @@ -0,0 +1,88 @@ +"""Write-path scanning utilities for headless session stdout JSONL. + +Extracted from headless.py to keep that module below the 1100-line +architectural limit (REQ-CNST-010-E2). + +L1 module (execution/). No autoskillit imports — stdlib only. +""" + +from __future__ import annotations + +import json +import os +import re + +_WRITE_TOOL_NAMES: frozenset[str] = frozenset({"Write", "Edit"}) +_BASH_TOOL_NAME: str = "Bash" +_ABS_PATH_PATTERN: re.Pattern[str] = re.compile(r'(?:^|[\s="\'])(/(?:[a-zA-Z0-9._/~@+:-]+))') +# Exclude paths of 4 chars or fewer (/tmp, /etc, /bin, /var) as low-signal noise. +_MIN_BASH_PATH_LEN: int = 5 + + +def _scan_jsonl_write_paths(stdout: str, cwd: str) -> list[str]: + """Scan raw JSONL stdout for Write/Edit/Bash tool calls outside cwd. + + Parses assistant records from the JSONL stream and extracts file_path + arguments from Write and Edit tool_use blocks, plus absolute paths from + Bash commands. Returns warning strings for any path outside cwd. + + Non-blocking: caller decides whether to surface or suppress warnings. + Returns [] when stdout is empty or cwd is empty/relative. + """ + if not stdout.strip() or not cwd or not os.path.isabs(cwd): + return [] + + cwd_prefix = cwd.rstrip("/") + "/" + warnings: list[str] = [] + + for raw_line in stdout.strip().splitlines(): + line = raw_line.strip() + if not line: + continue + try: + obj = json.loads(line) + except json.JSONDecodeError: + continue + if not isinstance(obj, dict) or obj.get("type") != "assistant": + continue + msg = obj.get("message") + if not isinstance(msg, dict): + continue + content = msg.get("content", []) + if not isinstance(content, list): + continue + for block in content: + if not isinstance(block, dict) or block.get("type") != "tool_use": + continue + tool_name = block.get("name", "") + inputs = block.get("input") or {} + if not isinstance(inputs, dict): + continue + + if tool_name in _WRITE_TOOL_NAMES: + file_path = inputs.get("file_path", "") + if ( + isinstance(file_path, str) + and os.path.isabs(file_path) + and not file_path.startswith(cwd_prefix) + and file_path != cwd.rstrip("/") + ): + warnings.append( + f"{tool_name} tool targeted '{file_path}' outside session cwd '{cwd}'" + ) + + elif tool_name == _BASH_TOOL_NAME: + command = inputs.get("command", "") + if isinstance(command, str): + for match in _ABS_PATH_PATTERN.finditer(command): + path = match.group(1) + if ( + len(path) >= _MIN_BASH_PATH_LEN + and not path.startswith(cwd_prefix) + and path != cwd.rstrip("/") + ): + warnings.append( + f"Bash command contained path '{path}' outside session cwd '{cwd}'" + ) + + return warnings diff --git a/src/autoskillit/execution/_process_monitor.py b/src/autoskillit/execution/_process_monitor.py index f51cddd036..ae443902a9 100644 --- a/src/autoskillit/execution/_process_monitor.py +++ b/src/autoskillit/execution/_process_monitor.py @@ -87,6 +87,57 @@ def _has_active_api_connection(pid: int) -> bool: return False +_CPU_ACTIVE_THRESHOLD: float = 10.0 # percent; evidence of actual computational work + +# Cached Process objects keyed by PID so cpu_percent(interval=0) returns +# delta since the previous call on the *same* object rather than always 0.0 +# on a freshly constructed psutil.Process. +_child_process_cache: dict[int, psutil.Process] = {} + + +def _has_active_child_processes(pid: int) -> bool: + """Return True if any child process in the tree exceeds the CPU activity threshold. + + Used by _session_log_monitor to suppress stale-kill when background Bash tasks + (launched via run_in_background: true) are actively running despite LLM/API being idle. + + cpu_percent(interval=0) returns usage since the last call per-process. We + cache psutil.Process objects across invocations so the second and subsequent + calls on a given child produce meaningful CPU deltas (the first call on any + new Process object always returns 0.0). + """ + try: + parent = psutil.Process(pid) + current_children = parent.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): + return False + + live_pids: set[int] = set() + active = False + for child in current_children: + live_pids.add(child.pid) + cached = _child_process_cache.get(child.pid) + if cached is None: + # First sighting: prime cpu_percent baseline (returns 0.0). + _child_process_cache[child.pid] = child + try: + child.cpu_percent(interval=0) + except (psutil.NoSuchProcess, psutil.ZombieProcess, psutil.AccessDenied): + pass + continue + try: + if cached.cpu_percent(interval=0) > _CPU_ACTIVE_THRESHOLD: + active = True + except (psutil.NoSuchProcess, psutil.ZombieProcess, psutil.AccessDenied): + continue + + # Evict stale entries for children that no longer exist. + for stale_pid in list(_child_process_cache.keys() - live_pids): + _child_process_cache.pop(stale_pid, None) + + return active + + async def _session_log_monitor( session_log_dir: Path, completion_marker: str, @@ -99,6 +150,7 @@ async def _session_log_monitor( _phase1_timeout: float = 30.0, _on_poll: Callable[[], None] | None = None, expected_session_id: str | None = None, + max_suppression_seconds: float = 1800.0, ) -> SessionMonitorResult: """Watch Claude Code session log for completion or staleness. @@ -169,6 +221,12 @@ async def _session_log_monitor( else "recency", ) os_error_count = 0 + except FileNotFoundError: + # Directory missing is structural — it won't self-heal during a + # poll loop. Return immediately so downstream gates can + # distinguish "could not monitor" from "monitored but timed out". + logger.warning("session_log_dir_absent", path=str(session_log_dir)) + return SessionMonitorResult(ChannelBStatus.DIR_MISSING, "") except OSError: os_error_count += 1 if os_error_count == 10: @@ -185,6 +243,8 @@ async def _session_log_monitor( last_change = _time.monotonic() scan_pos = 0 os_error_count = 0 + suppression_start_api: float | None = None + suppression_start_child: float | None = None while True: await anyio.sleep(_phase2_poll) @@ -202,6 +262,8 @@ async def _session_log_monitor( if current_size > last_size: last_size = current_size last_change = _time.monotonic() + suppression_start_api = None + suppression_start_child = None # Check new content for completion marker (structured) try: @@ -223,6 +285,18 @@ async def _session_log_monitor( elapsed = _time.monotonic() - last_change if elapsed >= stale_threshold: if pid is not None and _has_active_api_connection(pid): + suppression_start_child = None + if suppression_start_api is None: + suppression_start_api = _time.monotonic() + if _time.monotonic() - suppression_start_api >= max_suppression_seconds: + logger.warning( + "Suppression bounded: stale kill after %.0fs consecutive " + "suppression (max_suppression_seconds=%.0f, pid=%d)", + _time.monotonic() - suppression_start_api, + max_suppression_seconds, + pid, + ) + return SessionMonitorResult(ChannelBStatus.STALE, _session_id) last_change = _time.monotonic() logger.warning( "JSONL silent for %.0fs but ESTABLISHED port-443 connection — " @@ -230,5 +304,25 @@ async def _session_log_monitor( elapsed, pid, ) + elif pid is not None and _has_active_child_processes(pid): + suppression_start_api = None + if suppression_start_child is None: + suppression_start_child = _time.monotonic() + if _time.monotonic() - suppression_start_child >= max_suppression_seconds: + logger.warning( + "Suppression bounded: stale kill after %.0fs consecutive " + "suppression (max_suppression_seconds=%.0f, pid=%d)", + _time.monotonic() - suppression_start_child, + max_suppression_seconds, + pid, + ) + return SessionMonitorResult(ChannelBStatus.STALE, _session_id) + last_change = _time.monotonic() + logger.warning( + "JSONL silent for %.0fs but child processes are CPU-active — " + "suppressing stale kill (pid=%d)", + elapsed, + pid, + ) else: return SessionMonitorResult(ChannelBStatus.STALE, _session_id) diff --git a/src/autoskillit/execution/_process_race.py b/src/autoskillit/execution/_process_race.py index 5912467ed7..2fdd9bd20d 100644 --- a/src/autoskillit/execution/_process_race.py +++ b/src/autoskillit/execution/_process_race.py @@ -3,7 +3,7 @@ from __future__ import annotations import json -from dataclasses import dataclass +from dataclasses import dataclass, field from pathlib import Path from typing import assert_never @@ -23,6 +23,10 @@ class RaceSignals: Captures what happened without making any decisions about what it means. All fields are independent: multiple can be True simultaneously when tasks complete in the same event loop tick. + + ``process_exited_event`` is the same object as on RaceAccumulator — setting + it on the accumulator automatically reflects here (shared reference). + execute_termination_action awaits this event inside DRAIN_THEN_KILL_IF_ALIVE. """ process_exited: bool @@ -31,6 +35,8 @@ class RaceSignals: channel_b_status: ChannelBStatus | None channel_b_session_id: str = "" # Claude Code session ID from JSONL filename stem, or "" stdout_session_id: str | None = None # Session ID extracted from stdout type=system record + idle_stall: bool = False + process_exited_event: anyio.Event = field(default_factory=anyio.Event) @dataclass @@ -41,6 +47,10 @@ class RaceAccumulator: In async cooperative concurrency there are no concurrent writes — only one coroutine runs between yield points. to_race_signals() converts to the frozen RaceSignals consumed by resolve_termination. + + ``process_exited_event`` is set by _watch_process BEFORE setting trigger, + so downstream code can await it as a race primitive. It is passed (by reference) + to execute_termination_action to support the DRAIN_THEN_KILL_IF_ALIVE window. """ process_exited: bool = False @@ -49,6 +59,8 @@ class RaceAccumulator: channel_b_status: ChannelBStatus | None = None channel_b_session_id: str = "" stdout_session_id: str | None = None + idle_stall: bool = False + process_exited_event: anyio.Event = field(default_factory=anyio.Event) def to_race_signals(self) -> RaceSignals: return RaceSignals( @@ -58,6 +70,8 @@ def to_race_signals(self) -> RaceSignals: channel_b_status=self.channel_b_status, channel_b_session_id=self.channel_b_session_id, stdout_session_id=self.stdout_session_id, + idle_stall=self.idle_stall, + process_exited_event=self.process_exited_event, ) @@ -66,11 +80,17 @@ async def _watch_process( acc: RaceAccumulator, trigger: anyio.Event, ) -> None: - """Wait for the subprocess to exit and deposit the process-exit signal.""" + """Wait for the subprocess to exit and deposit the process-exit signal. + + Ordering guarantee: ``acc.process_exited_event`` is set BEFORE ``trigger`` + so that execute_termination_action's DRAIN_THEN_KILL_IF_ALIVE path can + await the event inside the drain window. + """ await proc.wait() logger.debug("process_exited", pid=proc.pid, returncode=proc.returncode) acc.process_exited = True acc.process_returncode = proc.returncode + acc.process_exited_event.set() trigger.set() @@ -98,6 +118,41 @@ async def _watch_heartbeat( trigger.set() +async def _watch_stdout_idle( + stdout_path: Path, + idle_output_timeout: float, + acc: RaceAccumulator, + trigger: anyio.Event, + _poll_interval: float = 5.0, +) -> None: + """Kill the child if stdout stops growing for idle_output_timeout seconds. + + Orthogonal to Channel A/B: NOT suppressed by active API connections. + Monitors raw byte count (st_size), not JSONL record structure. + """ + import time as _time + + last_size: int = 0 + last_growth_time: float = _time.monotonic() + while True: + await anyio.sleep(_poll_interval) + try: + current_size = stdout_path.stat().st_size + except OSError: + continue + if current_size > last_size: + last_size = current_size + last_growth_time = _time.monotonic() + elif _time.monotonic() - last_growth_time >= idle_output_timeout: + logger.warning( + "stdout idle for %ss — firing IDLE_STALL", + idle_output_timeout, + ) + acc.idle_stall = True + trigger.set() + return + + async def _extract_stdout_session_id( stdout_path: Path, acc: RaceAccumulator, @@ -160,6 +215,7 @@ async def _watch_session_log( _phase2_poll: float, _phase1_timeout: float, stdout_session_id_ready: anyio.Event | None = None, + max_suppression_seconds: float | None = None, ) -> None: """Monitor the session JSONL log and deposit the Channel B signal. @@ -174,17 +230,22 @@ async def _watch_session_log( with anyio.move_on_after(1.0): await stdout_session_id_ready.wait() + _monitor_kwargs: dict[str, object] = { + "pid": pid, + "_phase1_poll": _phase1_poll, + "_phase2_poll": _phase2_poll, + "_phase1_timeout": _phase1_timeout, + "expected_session_id": acc.stdout_session_id, + } + if max_suppression_seconds is not None: + _monitor_kwargs["max_suppression_seconds"] = max_suppression_seconds monitor_result = await _session_log_monitor( session_log_dir, completion_marker, stale_threshold, spawn_time, session_record_types, - pid=pid, - _phase1_poll=_phase1_poll, - _phase2_poll=_phase2_poll, - _phase1_timeout=_phase1_timeout, - expected_session_id=acc.stdout_session_id, + **_monitor_kwargs, # type: ignore[arg-type] ) if monitor_result.status == ChannelBStatus.COMPLETION: # Drain-wait: give Channel A a window to confirm before Channel B wins. @@ -215,7 +276,7 @@ def resolve_termination( reason are resolved independently so that simultaneous task completion never discards a channel signal. - Priority for termination: process exit > stale > channel win. + Priority for termination: process exit > idle stall > stale > channel win. Channel confirmation is independent of termination. Exhaustive match over ChannelBStatus ensures mypy flags any new member @@ -230,15 +291,26 @@ def resolve_termination( channel = ChannelConfirmation.CHANNEL_B case ChannelBStatus.STALE | None: channel = ChannelConfirmation.UNMONITORED + case ChannelBStatus.DIR_MISSING: + channel = ChannelConfirmation.DIR_MISSING case _ as unreachable: assert_never(unreachable) - # Termination reason: priority order (process exit > stale > channel win) + # Termination reason: priority order (process exit > idle stall > stale > channel win) if signals.process_exited: termination = TerminationReason.NATURAL_EXIT + elif signals.idle_stall: + termination = TerminationReason.IDLE_STALL else: match signals.channel_b_status: - case ChannelBStatus.STALE: + case ChannelBStatus.STALE | ChannelBStatus.DIR_MISSING: + # DIR_MISSING maps to STALE: both represent inconclusive monitoring + # that triggered an external kill, not a clean process exit. + # TerminationReason does not need a DIR_MISSING variant because + # downstream consumers only care whether the process exited cleanly + # (NATURAL_EXIT) or was forcibly terminated (STALE/COMPLETED). + # The DIR_MISSING structural distinction is preserved at the + # ChannelConfirmation level for recovery-gate decisions. termination = TerminationReason.STALE case ChannelBStatus.COMPLETION: termination = TerminationReason.COMPLETED @@ -257,6 +329,7 @@ def resolve_termination( channel_a_confirmed=signals.channel_a_confirmed, channel_b_status=signals.channel_b_status, channel_b_session_id=signals.channel_b_session_id, + idle_stall=signals.idle_stall, resolved_termination=str(termination), resolved_channel=str(channel), ) diff --git a/src/autoskillit/execution/anomaly_detection.py b/src/autoskillit/execution/anomaly_detection.py index d3d0241f7b..f8cd957e63 100644 --- a/src/autoskillit/execution/anomaly_detection.py +++ b/src/autoskillit/execution/anomaly_detection.py @@ -18,6 +18,9 @@ class AnomalyKind(StrEnum): SIGNALS_PENDING = "signals_pending" RSS_GROWTH = "rss_growth" FD_HIGH = "fd_high" + D_STATE_SUSTAINED = "d_state_sustained" + HIGH_CPU_SUSTAINED = "high_cpu_sustained" + IDENTITY_DRIFT = "identity_drift" class AnomalySeverity(StrEnum): @@ -26,6 +29,28 @@ class AnomalySeverity(StrEnum): CRITICAL = "critical" +# Kernel wait-channel values that are normal for a healthy process in +# uninterruptible sleep. D-state snapshots whose wchan matches any of these +# are NOT counted toward the D_STATE_SUSTAINED threshold. +# "" and "0" guard against missing-data snapshots (unreadable /proc/wchan). +BENIGN_WCHANS: frozenset[str] = frozenset( + { + "do_nanosleep", + "do_epoll_wait", + "schedule_hrtimeout_range", + "", # /proc returns empty when unreadable — treat as benign + "0", # kernel reports literal "0" when thread is runnable + } +) + + +def _safe_int(value: object, *, default: int) -> int: + try: + return int(value) # type: ignore[call-overload] + except (ValueError, TypeError): + return default + + def _anomaly( kind: AnomalyKind, severity: AnomalySeverity, @@ -60,6 +85,8 @@ def detect_anomalies( return anomalies consecutive_zombie = 0 + consecutive_d_state = 0 + consecutive_high_cpu = 0 prev_sig_pnd: str | None = None initial_rss: int | None = None @@ -115,7 +142,7 @@ def detect_anomalies( pid, ) ) - if consecutive_zombie >= 3: + if consecutive_zombie == 3: anomalies.append( _anomaly( AnomalyKind.ZOMBIE_PERSISTENT, @@ -129,6 +156,49 @@ def detect_anomalies( else: consecutive_zombie = 0 + # D-state sustained: process stuck in uninterruptible sleep + wchan = snap.get("wchan", "") + if state == "disk-sleep" and isinstance(wchan, str) and wchan not in BENIGN_WCHANS: + consecutive_d_state += 1 + if consecutive_d_state >= 2: + anomalies.append( + _anomaly( + AnomalyKind.D_STATE_SUSTAINED, + AnomalySeverity.WARNING, + { + "state": state, + "wchan": wchan, + "consecutive_count": consecutive_d_state, + }, + snap, + seq, + pid, + ) + ) + else: + consecutive_d_state = 0 + + # High-CPU sustained: process burning CPU >= 90% (suspected infinite loop) + cpu_percent = snap.get("cpu_percent", 0.0) + if isinstance(cpu_percent, (int, float)) and cpu_percent >= 90.0: + consecutive_high_cpu += 1 + if consecutive_high_cpu >= 2: + anomalies.append( + _anomaly( + AnomalyKind.HIGH_CPU_SUSTAINED, + AnomalySeverity.WARNING, + { + "cpu_percent": float(cpu_percent), + "consecutive_count": consecutive_high_cpu, + }, + snap, + seq, + pid, + ) + ) + else: + consecutive_high_cpu = 0 + # Signals pending: transition from all-zeros to non-zero _all_zeros = "0000000000000000" if isinstance(sig_pnd, str) and isinstance(prev_sig_pnd, str): @@ -190,3 +260,48 @@ def detect_anomalies( ) return anomalies + + +def detect_identity_drift( + snapshots: list[dict[str, object]], + expected_comm: str, +) -> list[dict[str, object]]: + """Detect process identity drift: snapshots whose comm != expected_comm. + + This is the architectural immunity check introduced in #806. If PTY wrapping + somehow bypasses the TraceTarget resolver, every snapshot will carry the wrong + comm (e.g., 'script' instead of 'claude'). This detector surfaces it immediately + rather than letting wrong telemetry accumulate silently for months. + + Args: + snapshots: List of snapshot dicts (each may have a 'comm' field). + expected_comm: The process name we expect every snapshot to describe. + + Returns: + List of IDENTITY_DRIFT anomaly records (one per first-seen mismatch). + """ + anomalies: list[dict[str, object]] = [] + if not snapshots or not expected_comm: + return anomalies + + for seq, snap in enumerate(snapshots): + actual_comm = snap.get("comm", "") + if actual_comm and actual_comm != expected_comm: + anomalies.append( + _anomaly( + AnomalyKind.IDENTITY_DRIFT, + AnomalySeverity.CRITICAL, + { + "expected_comm": expected_comm, + "actual_comm": actual_comm, + "seq": seq, + }, + snap, + seq, + _safe_int(snap.get("pid"), default=0), + ) + ) + # Report on first occurrence only — one anomaly is enough to diagnose the drift + break + + return anomalies diff --git a/src/autoskillit/execution/ci.py b/src/autoskillit/execution/ci.py index f943b16aa8..eb82edef63 100644 --- a/src/autoskillit/execution/ci.py +++ b/src/autoskillit/execution/ci.py @@ -15,6 +15,7 @@ import asyncio import random import time +from collections.abc import Callable from datetime import UTC, datetime, timedelta from typing import Any @@ -48,6 +49,20 @@ def _jittered_sleep(attempt: int) -> float: return random.uniform(0, ceiling) +def _validate_run_matches_scope(run: dict[str, Any], scope: CIRunScope) -> bool: + """Verify a run returned by the API matches the requested scope fields. + + This is a defense-in-depth check: the API query params should filter + server-side, but this client-side validation catches any discrepancy. + Each scope field is only checked when it is not None (i.e., was requested). + """ + if scope.event and run.get("event") != scope.event: + return False + if scope.head_sha and run.get("head_sha") != scope.head_sha: + return False + return True + + class DefaultCIWatcher: """Concrete CI watcher using GitHub REST API via httpx. @@ -55,11 +70,24 @@ class DefaultCIWatcher: Never raises — errors are returned as structured dicts. """ - def __init__(self, *, token: str | None = None) -> None: - self._token = token + _UNRESOLVED = object() + + def __init__(self, *, token: str | None | Callable[[], str | None] = None) -> None: + self._token_factory: Callable[[], str | None] | None + if callable(token): + self._token_factory = token + self._token: str | None = self._UNRESOLVED # type: ignore[assignment] + else: + self._token_factory = None + self._token = token + + def _resolve_token(self) -> str | None: + if self._token is self._UNRESOLVED: + self._token = self._token_factory() if self._token_factory is not None else None + return self._token def _headers(self) -> dict[str, str]: - return github_headers(self._token) + return github_headers(self._resolve_token()) async def _resolve_repo(self, repo: str | None, cwd: str) -> str | None: """Resolve owner/repo from argument or git remote.""" @@ -89,6 +117,8 @@ async def _fetch_completed_runs( params["workflow_id"] = scope.workflow if scope.head_sha: params["head_sha"] = scope.head_sha + if scope.event: + params["event"] = scope.event resp = await client.get(url, headers=headers, params=params) resp.raise_for_status() @@ -125,6 +155,8 @@ async def _fetch_active_runs( params["workflow_id"] = scope.workflow if scope.head_sha: params["head_sha"] = scope.head_sha + if scope.event: + params["event"] = scope.event resp = await client.get(url, headers=headers, params=params) resp.raise_for_status() @@ -219,21 +251,35 @@ async def wait( lookback_seconds, ) if completed: - run = completed[0] - run_id = run["id"] - conclusion = run.get("conclusion", "unknown") - failed_jobs = ( - await self._fetch_failed_jobs( - client, - headers, - owner_repo, - run_id, + valid_completed = [ + r for r in completed if _validate_run_matches_scope(r, scope) + ] + if not valid_completed: + _log.warning( + "ci_watcher_scope_mismatch", + count=len(completed), + scope=str(scope), ) - if conclusion in FAILED_CONCLUSIONS - else [] - ) - _log.info("ci_watcher_lookback_hit", run_id=run_id, conclusion=conclusion) - return {"run_id": run_id, "conclusion": conclusion, "failed_jobs": failed_jobs} + else: + run = valid_completed[0] + run_id = run["id"] + conclusion = run.get("conclusion", "unknown") + failed_jobs = ( + await self._fetch_failed_jobs( + client, + headers, + owner_repo, + run_id, + ) + if conclusion in FAILED_CONCLUSIONS + else [] + ) + _log.info("ci_watcher_lookback_hit", run_id=run_id, conclusion=conclusion) + return { + "run_id": run_id, + "conclusion": conclusion, + "failed_jobs": failed_jobs, + } # Phase 2: Poll for active runs _log.info("ci_watcher_polling", branch=branch, repo=owner_repo) @@ -248,8 +294,10 @@ async def wait( scope, ) if active: - found_run = active[0] - break + valid_active = [r for r in active if _validate_run_matches_scope(r, scope)] + if valid_active: + found_run = valid_active[0] + break # Also re-check completed in case it finished between phases completed = await self._fetch_completed_runs( client, @@ -260,24 +308,28 @@ async def wait( lookback_seconds, ) if completed: - run = completed[0] - run_id = run["id"] - conclusion = run.get("conclusion", "unknown") - failed_jobs = ( - await self._fetch_failed_jobs( - client, - headers, - owner_repo, - run_id, + valid_completed = [ + r for r in completed if _validate_run_matches_scope(r, scope) + ] + if valid_completed: + run = valid_completed[0] + run_id = run["id"] + conclusion = run.get("conclusion", "unknown") + failed_jobs = ( + await self._fetch_failed_jobs( + client, + headers, + owner_repo, + run_id, + ) + if conclusion in FAILED_CONCLUSIONS + else [] ) - if conclusion in FAILED_CONCLUSIONS - else [] - ) - return { - "run_id": run_id, - "conclusion": conclusion, - "failed_jobs": failed_jobs, - } + return { + "run_id": run_id, + "conclusion": conclusion, + "failed_jobs": failed_jobs, + } sleep_duration = _jittered_sleep(attempt) remaining = deadline - time.monotonic() diff --git a/src/autoskillit/execution/clone_guard.py b/src/autoskillit/execution/clone_guard.py new file mode 100644 index 0000000000..9f8340a4c3 --- /dev/null +++ b/src/autoskillit/execution/clone_guard.py @@ -0,0 +1,228 @@ +"""Clone contamination guard — detect and revert direct changes to clone CWD. + +L1 module (execution/). Detects when a worktree-based skill session modified +the clone directory directly (without creating a worktree) and reverts those +changes to prevent contamination from propagating to retry sessions. + +Public API: + is_worktree_skill(skill_command) -> bool + snapshot_clone_state(cwd, runner) -> CloneSnapshot | None + check_and_revert_clone_contamination( + snapshot, skill_result, cwd, runner, audit + ) -> tuple[SkillResult, bool] +""" + +from __future__ import annotations + +import dataclasses +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from typing import TYPE_CHECKING + +from autoskillit.core import ( + FailureRecord, + RetryReason, + SkillResult, + get_logger, +) + +if TYPE_CHECKING: + from autoskillit.core import AuditLog, SubprocessRunner + +logger = get_logger(__name__) + +WORKTREE_SKILLS: frozenset[str] = frozenset( + { + "implement-worktree-no-merge", + "retry-worktree", + } +) + +_GIT_TIMEOUT: float = 10.0 + + +@dataclass(frozen=True) +class CloneSnapshot: + """Pre-session state of the clone directory.""" + + head_sha: str + + +@dataclass(frozen=True) +class ContaminationReport: + """Details of detected clone contamination.""" + + pre_sha: str + post_sha: str + uncommitted_files: list[str] + direct_commits: bool + reverted: bool + + +def is_worktree_skill(skill_command: str) -> bool: + """Return True if skill_command invokes a worktree-creating skill.""" + return any(name in skill_command for name in WORKTREE_SKILLS) + + +async def snapshot_clone_state(cwd: str, runner: SubprocessRunner) -> CloneSnapshot | None: + """Capture the clone's HEAD SHA before a worktree-skill session. + + Returns None on failure (graceful degradation — guard simply won't activate). + """ + result = await runner( + ["git", "rev-parse", "HEAD"], + cwd=Path(cwd), + timeout=_GIT_TIMEOUT, + ) + if result.returncode != 0: + logger.debug("snapshot_clone_state_failed", returncode=result.returncode) + return None + head_sha = result.stdout.strip() + if not head_sha: + logger.debug("snapshot_clone_state_empty_sha") + return None + logger.debug("snapshot_clone_state_captured", head_sha=head_sha) + return CloneSnapshot(head_sha=head_sha) + + +async def detect_contamination( + snapshot: CloneSnapshot, cwd: str, runner: SubprocessRunner +) -> ContaminationReport | None: + """Check whether the clone directory was contaminated during the session. + + Returns None if no contamination detected, otherwise a ContaminationReport. + """ + head_result = await runner( + ["git", "rev-parse", "HEAD"], + cwd=Path(cwd), + timeout=_GIT_TIMEOUT, + ) + if head_result.returncode != 0: + logger.debug("detect_contamination_rev_parse_failed", returncode=head_result.returncode) + return None + post_sha = head_result.stdout.strip() + + status_result = await runner( + ["git", "status", "--porcelain"], + cwd=Path(cwd), + timeout=_GIT_TIMEOUT, + ) + if status_result.returncode != 0: + logger.debug("detect_contamination_status_failed", returncode=status_result.returncode) + return None + status_lines = [line for line in status_result.stdout.splitlines() if line.strip()] + + direct_commits = bool(post_sha and post_sha != snapshot.head_sha) + uncommitted = len(status_lines) > 0 + + if not direct_commits and not uncommitted: + logger.debug("detect_contamination_clean") + return None + + logger.warning( + "clone_contamination_detected", + pre_sha=snapshot.head_sha, + post_sha=post_sha, + uncommitted_file_count=len(status_lines), + direct_commits=direct_commits, + ) + return ContaminationReport( + pre_sha=snapshot.head_sha, + post_sha=post_sha, + uncommitted_files=status_lines, + direct_commits=direct_commits, + reverted=False, + ) + + +async def revert_contamination( + snapshot: CloneSnapshot, + report: ContaminationReport, + cwd: str, + runner: SubprocessRunner, +) -> ContaminationReport: + """Revert the clone to its pre-session state.""" + logger.info( + "reverting_clone_contamination", + pre_sha=snapshot.head_sha, + direct_commits=report.direct_commits, + uncommitted_file_count=len(report.uncommitted_files), + ) + reset_result = await runner( + ["git", "reset", "--hard", snapshot.head_sha], + cwd=Path(cwd), + timeout=_GIT_TIMEOUT, + ) + if reset_result.returncode != 0: + logger.warning( + "revert_contamination_reset_failed", + reset_rc=reset_result.returncode, + ) + return dataclasses.replace(report, reverted=False) + clean_result = await runner( + ["git", "clean", "-fd"], + cwd=Path(cwd), + timeout=_GIT_TIMEOUT, + ) + reverted = clean_result.returncode == 0 + if not reverted: + logger.warning( + "revert_contamination_failed", + reset_rc=reset_result.returncode, + clean_rc=clean_result.returncode, + ) + return dataclasses.replace(report, reverted=reverted) + + +async def check_and_revert_clone_contamination( + snapshot: CloneSnapshot | None, + skill_result: SkillResult, + cwd: str, + runner: SubprocessRunner, + audit: AuditLog | None, + skill_command: str = "", +) -> tuple[SkillResult, bool]: + """Top-level guard: detect and revert clone contamination after a failed session. + + Returns (skill_result, reverted) where reverted is True if contamination + was found and cleaned up. + """ + if snapshot is None: + return skill_result, False + if skill_result.success: + return skill_result, False + if skill_result.worktree_path is not None: + return skill_result, False + + report = await detect_contamination(snapshot, cwd, runner) + if report is None: + return skill_result, False + + report = await revert_contamination(snapshot, report, cwd, runner) + + if audit is not None: + audit.record_failure( + FailureRecord( + timestamp=datetime.now(UTC).isoformat(), + skill_command=skill_command, + exit_code=skill_result.exit_code, + subtype="clone_contamination", + needs_retry=skill_result.needs_retry, + retry_reason=RetryReason.CLONE_CONTAMINATION.value, + stderr=( + f"pre_sha={report.pre_sha} post_sha={report.post_sha} " + f"files={len(report.uncommitted_files)} " + f"direct_commits={report.direct_commits}" + ), + ) + ) + + logger.warning( + "clone_contamination_reverted", + pre_sha=report.pre_sha, + post_sha=report.post_sha, + files=len(report.uncommitted_files), + direct_commits=report.direct_commits, + ) + return skill_result, True diff --git a/src/autoskillit/execution/commands.py b/src/autoskillit/execution/commands.py index 0e9ee7ef1c..b5df08e549 100644 --- a/src/autoskillit/execution/commands.py +++ b/src/autoskillit/execution/commands.py @@ -3,23 +3,44 @@ from __future__ import annotations import os -from collections.abc import Sequence +from collections.abc import Mapping, Sequence from dataclasses import dataclass, field from pathlib import Path +from types import MappingProxyType -from autoskillit.core import ClaudeFlags, ValidatedAddDir +from autoskillit.core import ( + ClaudeFlags, + ValidatedAddDir, + build_claude_env, + temp_dir_display_str, +) @dataclass(frozen=True) class ClaudeInteractiveCmd: + """Resolved argv + env for a claude interactive subprocess. + + ``env`` is the fully resolved environment returned by + :func:`build_claude_env` — pass directly to ``subprocess.run(env=...)``. + Callers must NOT merge in ``os.environ`` again; the sanitization layer + has already applied the denylist and the auto-connect suppressor. + """ + cmd: list[str] - env: dict[str, str] + env: Mapping[str, str] = field(default_factory=dict) @dataclass(frozen=True) class ClaudeHeadlessCmd: + """Resolved argv + env for a claude headless subprocess. + + ``env`` is the fully resolved environment returned by + :func:`build_claude_env`, including any headless-only extras such as + ``AUTOSKILLIT_HEADLESS=1``. Pass directly to the subprocess runner. + """ + cmd: list[str] - env: dict[str, str] = field(default_factory=dict) # always {} + env: Mapping[str, str] = field(default_factory=dict) def build_interactive_cmd( @@ -29,6 +50,7 @@ def build_interactive_cmd( plugin_dir: Path | None = None, add_dirs: Sequence[Path | str | ValidatedAddDir] = (), resume_session_id: str | None = None, + env_extras: Mapping[str, str] | None = None, ) -> ClaudeInteractiveCmd: """Build a Claude interactive session command. @@ -46,6 +68,8 @@ def build_interactive_cmd( Each entry is appended as ``--add-dir ``. resume_session_id When provided, appended as ``--resume `` before any positional prompt. + env_extras + Optional caller overrides merged into the resolved env after IDE scrubbing. """ cmd = ["claude", ClaudeFlags.DANGEROUSLY_SKIP_PERMISSIONS] if resume_session_id is not None: @@ -58,15 +82,87 @@ def build_interactive_cmd( cmd += [ClaudeFlags.ADD_DIR, str(d)] if initial_prompt is not None: cmd.append(initial_prompt) - return ClaudeInteractiveCmd(cmd=cmd, env={}) + merged: dict[str, str] = dict(_SESSION_BASELINE_ENV) + if env_extras: + merged.update(env_extras) + return ClaudeInteractiveCmd(cmd=cmd, env=build_claude_env(extras=merged)) -def build_headless_cmd(prompt: str, *, model: str | None = None) -> ClaudeHeadlessCmd: +def build_headless_cmd( + prompt: str, + *, + model: str | None = None, + env_extras: Mapping[str, str] | None = None, + base: Mapping[str, str] | None = None, +) -> ClaudeHeadlessCmd: """Build a Claude headless session command for skill execution.""" cmd = ["claude", ClaudeFlags.PRINT, prompt, ClaudeFlags.DANGEROUSLY_SKIP_PERMISSIONS] if model: cmd += [ClaudeFlags.MODEL, model] - return ClaudeHeadlessCmd(cmd=cmd, env={}) + return ClaudeHeadlessCmd(cmd=cmd, env=build_claude_env(base=base, extras=env_extras)) + + +# Injected into every AutoSkillit-launched headless and cook session. +# Raises the Claude Code client-side MCP tool result size gate from the +# default 25,000 tokens to 50,000, preventing open_kitchen() responses +# from being persisted to a file instead of returned inline. +_MAX_MCP_OUTPUT_TOKENS_VALUE: str = "50000" + +# Baseline env vars injected into EVERY AutoSkillit-launched Claude session +# (both interactive and headless). Callers can override via env_extras. +# Analogous to IDE_ENV_ALWAYS_EXTRAS in _claude_env.py but scoped to +# session-level concerns rather than IDE scrubbing. +_SESSION_BASELINE_ENV: Mapping[str, str] = MappingProxyType( + { + "MAX_MCP_OUTPUT_TOKENS": _MAX_MCP_OUTPUT_TOKENS_VALUE, + } +) + +# Variables that build_full_headless_cmd controls exclusively. They must not +# leak from the host process environment — the caller opts in via explicit +# parameters (exit_after_stop_delay_ms, scenario_step_name). +# Note: these overlap with IDE_ENV_DENYLIST in core/_claude_env.py, which +# strips the same keys as part of the broader IDE env scrubbing layer. +# Both lists must be kept in sync when adding new exclusive variables. +_HEADLESS_EXCLUSIVE_VARS: frozenset[str] = frozenset( + { + "CLAUDE_CODE_EXIT_AFTER_STOP_DELAY", + "SCENARIO_STEP_NAME", + "MAX_MCP_OUTPUT_TOKENS", + } +) + + +def build_headless_resume_cmd( + *, + resume_session_id: str, + prompt: str, + output_format: str = "json", + plugin_dir: Path | None = None, + env_extras: Mapping[str, str] | None = None, +) -> ClaudeHeadlessCmd: + """Build a headless resume command for contract recovery nudge. + + Resumes an existing session with a short feedback prompt, asking the model + to emit missing structured output tokens. Uses ``--output-format json`` + (not stream-json) because the response is tiny and needs no assistant records. + """ + cmd: list[str] = [ + "claude", + ClaudeFlags.PRINT, + prompt, + ClaudeFlags.RESUME, + resume_session_id, + ClaudeFlags.DANGEROUSLY_SKIP_PERMISSIONS, + ClaudeFlags.OUTPUT_FORMAT, + output_format, + ] + if plugin_dir is not None: + cmd += [ClaudeFlags.PLUGIN_DIR, str(plugin_dir)] + merged: dict[str, str] = dict(_SESSION_BASELINE_ENV) + if env_extras: + merged.update(env_extras) + return ClaudeHeadlessCmd(cmd=cmd, env=build_claude_env(extras=merged)) def _ensure_skill_prefix(skill_command: str) -> str: @@ -92,13 +188,14 @@ def _inject_completion_directive(skill_command: str, marker: str) -> str: return skill_command + directive -def _inject_cwd_anchor(skill_command: str, cwd: str) -> str: +def _inject_cwd_anchor(skill_command: str, cwd: str, temp_dir_relpath: str | None = None) -> str: """Append a working directory anchor directive to prevent path contamination.""" if not cwd or not os.path.isabs(cwd): return skill_command + relpath = temp_dir_relpath if temp_dir_relpath is not None else temp_dir_display_str(None) directive = ( f"\n\nWORKING DIRECTORY ANCHOR: Your working directory is {cwd}. " - f"All relative paths (.autoskillit/temp/, .autoskillit/, etc.) " + f"All relative paths ({relpath}/, .autoskillit/, etc.) " f"MUST resolve against {cwd}. " f"Do NOT use any other directory as a base for relative paths, regardless of " f"what paths appear in code-index tool responses or set_project_path results. " @@ -107,23 +204,45 @@ def _inject_cwd_anchor(skill_command: str, cwd: str) -> str: return skill_command + directive +def _inject_narration_suppression(skill_command: str) -> str: + """Append an efficiency directive to suppress inter-tool narration. + + Targets prose status text and phase announcements emitted between tool + calls — the primary driver of unnecessary context-length overhead in + long-running sessions. Does NOT suppress the final response, which is + where structured output tokens (worktree_path, plan_path, etc.) live. + """ + directive = ( + "\n\nEFFICIENCY DIRECTIVE: Do NOT output prose status text, phase " + "announcements, or progress summaries between tool calls. Every " + "non-final assistant turn MUST invoke at least one tool. The only " + "permitted text-only turn is the final response required by the " + "ORCHESTRATION DIRECTIVE above." + ) + return skill_command + directive + + def build_full_headless_cmd( skill_command: str, *, cwd: str, completion_marker: str, model: str | None, - plugin_dir: str | Path, + plugin_dir: str | Path | None, output_format_value: str, output_format_required_flags: Sequence[str] = (), add_dirs: Sequence[ValidatedAddDir] = (), exit_after_stop_delay_ms: int = 0, -) -> list[str]: - """Build the complete headless command list ready for subprocess invocation. + scenario_step_name: str = "", + temp_dir_relpath: str | None = None, +) -> ClaudeHeadlessCmd: + """Build the complete headless command spec ready for subprocess invocation. - Applies prompt transformations (skill prefix, completion directive, cwd anchor), - then constructs the full CLI command including plugin-dir, output-format, - add-dir entries, and the ``env AUTOSKILLIT_HEADLESS=1`` prefix. + Applies prompt transformations (skill prefix, completion directive, cwd anchor, + narration suppression), then constructs the full CLI command including plugin-dir, + output-format, and add-dir entries. The environment carries ``AUTOSKILLIT_HEADLESS=1`` + and any scenario / exit-delay extras on ``.env`` — it is NOT serialized as an argv + prefix. Parameters ---------- @@ -144,26 +263,36 @@ def build_full_headless_cmd( add_dirs Each entry is appended as ``--add-dir ``. exit_after_stop_delay_ms - When > 0, ``CLAUDE_CODE_EXIT_AFTER_STOP_DELAY=`` is prepended. + When > 0, carried as ``CLAUDE_CODE_EXIT_AFTER_STOP_DELAY=`` in ``.env``. + scenario_step_name + When non-empty, carried as ``SCENARIO_STEP_NAME=`` in ``.env`` for recording. """ - prompt = _inject_cwd_anchor( - _inject_completion_directive(_ensure_skill_prefix(skill_command), completion_marker), - cwd, + prompt = _inject_narration_suppression( + _inject_cwd_anchor( + _inject_completion_directive(_ensure_skill_prefix(skill_command), completion_marker), + cwd, + temp_dir_relpath=temp_dir_relpath, + ) ) - spec = build_headless_cmd(prompt, model=model) - cmd: list[str] = spec.cmd + [ - ClaudeFlags.PLUGIN_DIR, - str(plugin_dir), - ClaudeFlags.OUTPUT_FORMAT, - output_format_value, - ] + extras: dict[str, str] = { + "AUTOSKILLIT_HEADLESS": "1", + "MAX_MCP_OUTPUT_TOKENS": _MAX_MCP_OUTPUT_TOKENS_VALUE, + } + if exit_after_stop_delay_ms > 0: + extras["CLAUDE_CODE_EXIT_AFTER_STOP_DELAY"] = str(exit_after_stop_delay_ms) + if scenario_step_name: + extras["SCENARIO_STEP_NAME"] = scenario_step_name + + filtered_base = {k: v for k, v in os.environ.items() if k not in _HEADLESS_EXCLUSIVE_VARS} + spec = build_headless_cmd(prompt, model=model, env_extras=extras, base=filtered_base) + cmd: list[str] = [*spec.cmd] + if plugin_dir is not None: + cmd += [ClaudeFlags.PLUGIN_DIR, str(plugin_dir)] + cmd += [ClaudeFlags.OUTPUT_FORMAT, output_format_value] for flag in output_format_required_flags: if flag not in cmd: cmd.append(flag) for validated_dir in add_dirs: cmd.extend([ClaudeFlags.ADD_DIR, validated_dir.path]) - env_vars = ["AUTOSKILLIT_HEADLESS=1"] - if exit_after_stop_delay_ms > 0: - env_vars.append(f"CLAUDE_CODE_EXIT_AFTER_STOP_DELAY={exit_after_stop_delay_ms}") - return ["env"] + env_vars + cmd + return ClaudeHeadlessCmd(cmd=cmd, env=spec.env) diff --git a/src/autoskillit/execution/github.py b/src/autoskillit/execution/github.py index 9827557e16..27a0b12ffe 100644 --- a/src/autoskillit/execution/github.py +++ b/src/autoskillit/execution/github.py @@ -7,6 +7,7 @@ from __future__ import annotations import re +from collections.abc import Callable from typing import Any import httpx @@ -122,16 +123,29 @@ class DefaultGitHubFetcher: Never raises — errors are returned as {"success": False, "error": "..."}. """ - def __init__(self, *, token: str | None = None) -> None: - self._token = token + _UNRESOLVED = object() + + def __init__(self, *, token: str | None | Callable[[], str | None] = None) -> None: + self._token_factory: Callable[[], str | None] | None + if callable(token): + self._token_factory = token + self._token: str | None = self._UNRESOLVED # type: ignore[assignment] + else: + self._token_factory = None + self._token = token + + def _resolve_token(self) -> str | None: + if self._token is self._UNRESOLVED: + self._token = self._token_factory() if self._token_factory is not None else None + return self._token @property def has_token(self) -> bool: - """True if this fetcher was constructed with an authentication token.""" - return bool(self._token) + """True if this fetcher has an authentication token (resolves lazily).""" + return bool(self._resolve_token()) def _headers(self) -> dict[str, str]: - return github_headers(self._token) + return github_headers(self._resolve_token()) async def fetch_issue( self, @@ -370,7 +384,7 @@ async def fetch_title(self, issue_url: str) -> dict[str, object]: hint = ( " Set github.token in .autoskillit/.secrets.yaml," " set GITHUB_TOKEN, or log in with gh auth login." - if not self._token + if not self.has_token else "" ) return { diff --git a/src/autoskillit/execution/headless.py b/src/autoskillit/execution/headless.py index da12afeffc..f312c1034a 100644 --- a/src/autoskillit/execution/headless.py +++ b/src/autoskillit/execution/headless.py @@ -11,14 +11,14 @@ from __future__ import annotations import dataclasses -import json import os import re import time +import traceback from collections.abc import Sequence from datetime import UTC, datetime, timedelta from pathlib import Path -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, assert_never import structlog @@ -34,11 +34,20 @@ WriteBehaviorSpec, claude_code_project_dir, get_logger, + is_git_worktree, load_yaml, pkg_root, + temp_dir_display_str, ) -from autoskillit.execution.commands import build_full_headless_cmd +from autoskillit.execution._headless_scan import _scan_jsonl_write_paths +from autoskillit.execution.clone_guard import ( + check_and_revert_clone_contamination, + is_worktree_skill, + snapshot_clone_state, +) +from autoskillit.execution.commands import build_full_headless_cmd, build_headless_resume_cmd from autoskillit.execution.process import _marker_is_standalone +from autoskillit.execution.recording import RecordingSubprocessRunner from autoskillit.execution.session import ( ClaudeSessionResult, _check_expected_patterns, @@ -53,20 +62,46 @@ from autoskillit.config import ( AutomationConfig, ) - from autoskillit.core import AuditStore, SubprocessResult + from autoskillit.core import AuditLog, SubprocessResult, SubprocessRunner from autoskillit.pipeline.context import ( ToolContext, ) logger = get_logger(__name__) +# Subtypes eligible for Channel B drain-race recovery. +# +# These are the failure subtypes that can arise when Claude Code defers ``type=result`` +# until all background agents finish. The deferred record is never flushed if the +# process tree is killed after Channel B fires on the session JSONL marker. +# +# TIMEOUT is excluded — it indicates a genuine time limit breach, not a drain-race. +# UNKNOWN is excluded — it indicates unrecognised CLI behaviour, not a missing record. +_CHANNEL_B_RECOVERABLE_SUBTYPES: frozenset[CliSubtype] = frozenset( + {CliSubtype.UNPARSEABLE, CliSubtype.EMPTY_OUTPUT} +) + +_PATH_CAPTURE: re.Pattern[str] = re.compile(r"^(\w+)\\s\*=\\s\*/.+") + def _session_log_dir(cwd: str) -> Path: - """Derive Claude Code session log directory from project cwd.""" + """Derive Claude Code session log directory from project cwd. + + Pre-creates the directory if absent so Channel B always has a directory + to poll. Without this, a fresh clone path whose encoded project dir + doesn't exist yet causes ``_session_log_monitor`` to burn its entire + phase-1 timeout absorbing ``OSError``, ultimately producing a false + ``EMPTY_OUTPUT`` retry. + """ log_dir = claude_code_project_dir(cwd) logger.info("session_log_dir_computed", path=str(log_dir), cwd=cwd) if not log_dir.exists(): - logger.warning("session_log_dir_missing", path=str(log_dir), cwd=cwd) + logger.info("session_log_dir_precreating", path=str(log_dir), cwd=cwd) + try: + log_dir.mkdir(parents=True, exist_ok=True) + except OSError: + logger.warning("session_log_dir_mkdir_failed", path=str(log_dir), cwd=cwd) + raise return log_dir @@ -77,7 +112,7 @@ def _capture_failure( needs_retry: bool, retry_reason: str, stderr: str, - audit: AuditStore | None, + audit: AuditLog | None, ) -> None: """Record a failure in the audit log. No-op if skill_command is empty or audit is None.""" if not skill_command or audit is None: @@ -169,8 +204,6 @@ def _synthesize_from_write_artifacts( # Only synthesize for path-capture patterns (token_name\s*=\s*/.+). # Non-path patterns (verdict=, merged=) must remain text-compliance-only. - # Note: re is already imported at the top of headless.py — no new import needed. - _PATH_CAPTURE = re.compile(r"^(\w+)\\s\*=\\s\*/.+") synthesized_lines: list[str] = [] for pattern in expected_output_patterns: @@ -198,6 +231,146 @@ def _synthesize_from_write_artifacts( return dataclasses.replace(session, result=injected) +def _extract_missing_token_hints( + stdout: str, + expected_output_patterns: Sequence[str], +) -> list[tuple[str, str]]: + """Extract (token_name, write_path) pairs for patterns missing from the result. + + Parses raw NDJSON stdout to find Write/Edit tool_use file_path entries, + then matches them against path-capture patterns that are NOT satisfied in + the result text. Returns the hints needed to build the nudge prompt. + """ + session = parse_session_result(stdout) + hints: list[tuple[str, str]] = [] + + for pattern in expected_output_patterns: + m = _PATH_CAPTURE.match(pattern) + if not m: + continue + token_name = m.group(1) + # Skip if already satisfied + if re.search(pattern, session.result): + continue + # Collect absolute Write/Edit paths; use the LAST one (final deliverable) + candidate_paths = [ + t.get("file_path", "") + for t in session.tool_uses + if t.get("name") in {"Write", "Edit"} and t.get("file_path", "").startswith("/") + ] + if candidate_paths: + hints.append((token_name, candidate_paths[-1])) + + return hints + + +_NUDGE_TIMEOUT: float = 60.0 + + +async def _attempt_contract_nudge( + skill_result: SkillResult, + subprocess_result: SubprocessResult, + expected_output_patterns: Sequence[str], + completion_marker: str, + cwd: str, + runner: SubprocessRunner, +) -> SkillResult | None: + """Attempt a lightweight resume nudge to recover missing structured output tokens. + + When ``_build_skill_result`` returns CONTRACT_RECOVERY, the model wrote the artifact + but omitted the structured output token. Instead of a full retry, resume the same + session with a short feedback prompt asking the model to emit the missing token. + + Returns a patched SkillResult(success=True) on success, or None to indicate the + nudge failed and the caller should fall through to the original CONTRACT_RECOVERY path. + """ + hints = _extract_missing_token_hints(subprocess_result.stdout, expected_output_patterns) + if not hints: + logger.debug("nudge_skip_no_hints") + return None + + # Build the feedback prompt + token_lines = "\n".join(f"{name} = {path}" for name, path in hints) + prompt = ( + "You completed your task and wrote the output file, but you omitted the " + "required structured output token in your final text response.\n\n" + f"Please emit ONLY the following (no other text):\n" + f"{token_lines}\n" + f"{completion_marker}" + ) + + spec = build_headless_resume_cmd( + resume_session_id=skill_result.session_id, + prompt=prompt, + output_format="json", + ) + + try: + nudge_result = await runner( + spec.cmd, + cwd=Path(cwd), + timeout=_NUDGE_TIMEOUT, + env=spec.env, + ) + except OSError: + logger.debug("nudge_runner_failed", exc_info=True) + return None + except Exception: + logger.warning("nudge_runner_failed_unexpected", exc_info=True) + return None + + # Parse the nudge response and check for the missing patterns + nudge_session = parse_session_result(nudge_result.stdout) + combined_result = skill_result.result + "\n" + nudge_session.result + + if not _check_expected_patterns(combined_result, list(expected_output_patterns)): + logger.debug( + "nudge_patterns_not_found", + nudge_result_len=len(nudge_session.result), + ) + return None + + logger.info( + "nudge_recovery_success", + session_id=skill_result.session_id, + nudge_output_count=nudge_session.token_usage.get("output_tokens", 0) + if nudge_session.token_usage + else 0, + ) + return dataclasses.replace( + skill_result, + success=True, + result=combined_result, + subtype="success", + needs_retry=False, + retry_reason=RetryReason.NONE, + token_usage=_merge_token_usage(skill_result.token_usage, nudge_session.token_usage), + ) + + +def _merge_token_usage( + base: dict[str, object] | None, + nudge: dict[str, object] | None, +) -> dict[str, object] | None: + """Additively merge token usage dicts from main session and nudge.""" + if base is None: + return nudge + if nudge is None: + return base + merged = dict(base) + for key in ( + "input_tokens", + "output_tokens", + "cache_creation_input_tokens", + "cache_read_input_tokens", + ): + base_val = base.get(key, 0) + nudge_val = nudge.get(key, 0) + if isinstance(base_val, (int, float)) and isinstance(nudge_val, (int, float)): + merged[key] = base_val + nudge_val + return merged + + def _resolve_model(step_model: str, config: AutomationConfig) -> str | None: """Resolve model selection: config override > step > config default.""" if config.model.override: @@ -318,86 +491,10 @@ def _validate_output_paths( return "; ".join(violations) if violations else None -_WRITE_TOOL_NAMES: frozenset[str] = frozenset({"Write", "Edit"}) -_BASH_TOOL_NAME: str = "Bash" -_ABS_PATH_PATTERN: re.Pattern[str] = re.compile(r'(?:^|[\s="\'])(/(?:[a-zA-Z0-9._/~@+:-]+))') -# Exclude paths of 4 chars or fewer (/tmp, /etc, /bin, /var) as low-signal noise. -_MIN_BASH_PATH_LEN: int = 5 - - -def _scan_jsonl_write_paths(stdout: str, cwd: str) -> list[str]: - """Scan raw JSONL stdout for Write/Edit/Bash tool calls outside cwd. - - Parses assistant records from the JSONL stream and extracts file_path - arguments from Write and Edit tool_use blocks, plus absolute paths from - Bash commands. Returns warning strings for any path outside cwd. - - Non-blocking: caller decides whether to surface or suppress warnings. - Returns [] when stdout is empty or cwd is empty/relative. - """ - if not stdout.strip() or not cwd or not os.path.isabs(cwd): - return [] - - cwd_prefix = cwd.rstrip("/") + "/" - warnings: list[str] = [] - - for raw_line in stdout.strip().splitlines(): - line = raw_line.strip() - if not line: - continue - try: - obj = json.loads(line) - except json.JSONDecodeError: - continue - if not isinstance(obj, dict) or obj.get("type") != "assistant": - continue - msg = obj.get("message") - if not isinstance(msg, dict): - continue - content = msg.get("content", []) - if not isinstance(content, list): - continue - for block in content: - if not isinstance(block, dict) or block.get("type") != "tool_use": - continue - tool_name = block.get("name", "") - inputs = block.get("input") or {} - if not isinstance(inputs, dict): - continue - - if tool_name in _WRITE_TOOL_NAMES: - file_path = inputs.get("file_path", "") - if ( - isinstance(file_path, str) - and os.path.isabs(file_path) - and not file_path.startswith(cwd_prefix) - and file_path != cwd.rstrip("/") - ): - warnings.append( - f"{tool_name} tool targeted '{file_path}' outside session cwd '{cwd}'" - ) - - elif tool_name == _BASH_TOOL_NAME: - command = inputs.get("command", "") - if isinstance(command, str): - for match in _ABS_PATH_PATTERN.finditer(command): - path = match.group(1) - if ( - len(path) >= _MIN_BASH_PATH_LEN - and not path.startswith(cwd_prefix) - and path != cwd.rstrip("/") - ): - warnings.append( - f"Bash command contained path '{path}' outside session cwd '{cwd}'" - ) - - return warnings - - def _apply_budget_guard( sr: SkillResult, skill_command: str, - audit: AuditStore | None, + audit: AuditLog | None, max_consecutive_retries: int, ) -> SkillResult: """Override needs_retry to False when the consecutive-failure budget is exhausted. @@ -443,7 +540,7 @@ def _build_skill_result( result: SubprocessResult, completion_marker: str = "", skill_command: str = "", - audit: AuditStore | None = None, + audit: AuditLog | None = None, max_consecutive_retries: int = 3, expected_output_patterns: Sequence[str] = (), cwd: str = "", @@ -451,7 +548,9 @@ def _build_skill_result( ) -> SkillResult: """Route SubprocessResult fields into the standard run_skill response.""" branch = ( - "stale" + "idle_stall" + if result.termination == TerminationReason.IDLE_STALL + else "stale" if result.termination == TerminationReason.STALE else "timed_out" if result.termination == TerminationReason.TIMED_OUT @@ -527,6 +626,36 @@ def _build_skill_result( ) return _apply_budget_guard(stale_sr, skill_command, audit, max_consecutive_retries) + if result.termination == TerminationReason.IDLE_STALL: + _capture_failure( + skill_command, + exit_code=result.returncode if result.returncode is not None else -1, + subtype="idle_stall", + needs_retry=True, + retry_reason=RetryReason.STALE, + stderr=result.stderr if result.stderr else "", + audit=audit, + ) + logger.warning( + "Headless session killed: stdout idle for configured threshold (IDLE_STALL)" + ) + idle_sr = SkillResult( + success=False, + result=( + "Session killed: stdout idle for configured threshold (no output growth). " + "Partial progress may have been made. Retry to continue." + ), + session_id=_resolve_skill_session_id(None, result), + subtype="idle_stall", + is_error=True, + exit_code=-1, + needs_retry=True, + retry_reason=RetryReason.STALE, + stderr="", + token_usage=None, + ) + return _apply_budget_guard(idle_sr, skill_command, audit, max_consecutive_retries) + if result.termination == TerminationReason.TIMED_OUT: returncode = -1 if result.stdout.strip(): @@ -548,6 +677,72 @@ def _build_skill_result( # Moved earlier: needed by synthesis recovery step before _compute_outcome. write_call_count = sum(1 for t in session.tool_uses if t.get("name") in {"Write", "Edit"}) + # ── Channel B drain-race recovery ────────────────────────────────────── + # When Channel B confirmed completion but stdout never received the + # type=result record (UNPARSEABLE / EMPTY_OUTPUT), the session completed + # but Claude Code deferred type=result until all background agents finished. + # If we killed the process tree after Channel B fired, the deferred record + # was never flushed to stdout. + # + # assistant_messages are accumulated from stdout NDJSON records of type + # "assistant" — these are written BEFORE the deferred type=result. If the + # completion marker is standalone in assistant_messages with substantive + # content, reconstruct the result and promote the session so downstream + # recovery paths and the Channel B bypass in _compute_success operate on + # valid state. + match result.channel_confirmation: + case ChannelConfirmation.CHANNEL_B if ( + session.subtype in _CHANNEL_B_RECOVERABLE_SUBTYPES and completion_marker + ): + cb_recovered = _recover_from_separate_marker(session, completion_marker) + if cb_recovered is not None: + original_subtype = session.subtype + session = dataclasses.replace( + cb_recovered, + subtype=CliSubtype.SUCCESS, + is_error=False, + ) + logger.warning( + "channel_b_drain_race_recovery", + original_subtype=str(original_subtype), + assistant_message_count=len(session.assistant_messages), + ) + case ChannelConfirmation.DIR_MISSING if ( + session.subtype in _CHANNEL_B_RECOVERABLE_SUBTYPES and completion_marker + ): + # Late-bind recovery: the directory may have been created by + # Claude Code during the run even though it was absent at + # monitor start. Attempt the same marker-based recovery as + # the CHANNEL_B arm. + cb_recovered = _recover_from_separate_marker(session, completion_marker) + if cb_recovered is not None: + original_subtype = session.subtype + session = dataclasses.replace( + cb_recovered, + subtype=CliSubtype.SUCCESS, + is_error=False, + ) + logger.warning( + "dir_missing_late_bind_recovery", + original_subtype=str(original_subtype), + assistant_message_count=len(session.assistant_messages), + ) + else: + logger.warning( + "dir_missing_late_bind_recovery_failed", + subtype=str(session.subtype), + assistant_message_count=len(session.assistant_messages), + ) + case ( + ChannelConfirmation.CHANNEL_B + | ChannelConfirmation.CHANNEL_A + | ChannelConfirmation.UNMONITORED + | ChannelConfirmation.DIR_MISSING + ): + pass # no drain-race recovery applicable + case _ as _unreachable_cc: + assert_never(_unreachable_cc) + # Recovery is only valid for sessions that completed normally. # For incomplete sessions (UNPARSEABLE, TIMEOUT, etc.), any Write calls were # intermediate artifacts, not final deliverables. Recovery or synthesis on these @@ -633,9 +828,7 @@ def _build_skill_result( if completion_marker: result_text = result_text.replace(completion_marker, "").strip() - extracted_worktree_path: str | None = None - if needs_retry: - extracted_worktree_path = _extract_worktree_path(session.assistant_messages) + extracted_worktree_path = _extract_worktree_path(session.assistant_messages) # Path contamination detection path_contamination: str | None = None @@ -691,6 +884,7 @@ def _build_skill_result( cli_subtype=session.subtype, write_path_warnings=write_path_warnings, write_call_count=write_call_count, + kill_reason=result.kill_reason, ) sr = _apply_budget_guard(sr, skill_command, audit, max_consecutive_retries) @@ -748,6 +942,24 @@ def _build_skill_result( return sr +def _derive_step_name_from_skill_command(skill_command: str) -> str: + """Extract a recording step name from a skill command string. + + Examples: + "/autoskillit:smoke-task arg1" -> "smoke-task" + "/investigate foo" -> "investigate" + "/autoskillit:make-plan" -> "make-plan" + "" -> "" + """ + stripped = skill_command.strip() + if not stripped: + return "" + token = stripped.split()[0].lstrip("/") + if ":" in token: + token = token.rsplit(":", 1)[-1] + return token + + async def run_headless_core( skill_command: str, cwd: str, @@ -760,8 +972,10 @@ async def run_headless_core( add_dirs: Sequence[ValidatedAddDir] = (), timeout: float | None = None, stale_threshold: float | None = None, + idle_output_timeout: float | None = None, expected_output_patterns: Sequence[str] = (), write_behavior: WriteBehaviorSpec | None = None, + completion_marker: str = "", ) -> SkillResult: """Shared headless runner used by run_skill. @@ -769,28 +983,40 @@ async def run_headless_core( Accepts explicit ToolContext so this module has no server.py dependency. """ cfg = ctx.config.run_skill + effective_marker = completion_marker or cfg.completion_marker original_skill_command = skill_command + if not step_name and isinstance(ctx.runner, RecordingSubprocessRunner): + step_name = _derive_step_name_from_skill_command(skill_command) + with structlog.contextvars.bound_contextvars( skill_command=original_skill_command[:100], step_name=step_name or None, ): effective_plugin_dir = ctx.plugin_dir resolved_model = _resolve_model(model, ctx.config) - cmd = build_full_headless_cmd( + spec = build_full_headless_cmd( skill_command, cwd=cwd, - completion_marker=cfg.completion_marker, + completion_marker=effective_marker, model=resolved_model, plugin_dir=effective_plugin_dir, output_format_value=cfg.output_format.value, output_format_required_flags=cfg.output_format.required_cli_flags, add_dirs=add_dirs, exit_after_stop_delay_ms=cfg.exit_after_stop_delay_ms, + scenario_step_name=step_name, + temp_dir_relpath=temp_dir_display_str(ctx.config.workspace.temp_dir), ) effective_timeout = timeout if timeout is not None else cfg.timeout effective_stale = stale_threshold if stale_threshold is not None else cfg.stale_threshold + _raw_idle = ( + idle_output_timeout + if idle_output_timeout is not None + else float(cfg.idle_output_timeout) + ) + effective_idle: float | None = _raw_idle if _raw_idle > 0.0 else None logger.debug( "run_headless_core_entry", @@ -809,45 +1035,63 @@ async def run_headless_core( _start_ts = datetime.now(UTC).isoformat() _start_mono = time.monotonic() + _clone_snapshot = None + if is_worktree_skill(original_skill_command) and not is_git_worktree(Path(cwd)): + _clone_snapshot = await snapshot_clone_state(cwd, runner) + _result: SubprocessResult | None = None try: _result = await runner( - cmd, + spec.cmd, cwd=Path(cwd), timeout=effective_timeout, + env=spec.env, pty_mode=True, session_log_dir=_session_log_dir(cwd), - completion_marker=cfg.completion_marker, + completion_marker=effective_marker, stale_threshold=effective_stale, completion_drain_timeout=cfg.completion_drain_timeout, linux_tracing_config=linux_tracing_cfg, + idle_output_timeout=effective_idle, + max_suppression_seconds=cfg.max_suppression_seconds, + ) + except Exception as exc: + logger.error("run_headless_core runner crashed", exc_info=True) + _exc_text = traceback.format_exc() + _log_dir = ctx.config.linux_tracing.log_dir + try: + # Deferred: autoskillit.execution.__init__ imports headless.py (L39-42); + # a top-level import of autoskillit.execution would be circular. + from autoskillit.execution import flush_session_log + + flush_session_log( + log_dir=_log_dir, + cwd=str(cwd), + kitchen_id=kitchen_id, + order_id=order_id, + session_id="", + pid=0, + skill_command=original_skill_command, + success=False, + subtype="crashed", + exit_code=-1, + start_ts=_start_ts, + proc_snapshots=None, + termination_reason="CRASHED", + exception_text=_exc_text, + ) + except Exception: + logger.debug("flush_session_log during crash failed", exc_info=True) + return SkillResult.crashed( + exception=exc, + skill_command=original_skill_command, + order_id=order_id, ) - finally: - if _result is None: - # Runner raised — write a crash entry so sessions.jsonl stays consistent - _log_dir = ctx.config.linux_tracing.log_dir - try: - from autoskillit.execution import flush_session_log - - flush_session_log( - log_dir=_log_dir, - cwd=str(cwd), - kitchen_id=kitchen_id, - order_id=order_id, - session_id="", - pid=0, - skill_command=skill_command, - success=False, - subtype="crashed", - exit_code=-1, - start_ts=_start_ts, - proc_snapshots=None, - termination_reason="CRASHED", - ) - except Exception: - logger.debug("flush_session_log during crash failed", exc_info=True) if _result is None: - raise RuntimeError("runner() did not return a result — cannot build SkillResult") + return SkillResult.crashed( + exception=RuntimeError("runner() did not return a result"), + order_id=order_id, + ) _elapsed = time.monotonic() - _start_mono _end_ts = (datetime.fromisoformat(_start_ts) + timedelta(seconds=_elapsed)).isoformat() result = dataclasses.replace( # type: ignore[arg-type] @@ -857,7 +1101,7 @@ async def run_headless_core( audit_count_before = len(ctx.audit.get_report()) skill_result = _build_skill_result( result, - completion_marker=cfg.completion_marker, + completion_marker=effective_marker, skill_command=original_skill_command, audit=ctx.audit, expected_output_patterns=expected_output_patterns, @@ -865,6 +1109,36 @@ async def run_headless_core( write_behavior=write_behavior, ) + # CONTRACT NUDGE: lightweight resume recovery before full retry. + # Fires only when _build_skill_result returns CONTRACT_RECOVERY with a + # valid session_id (budget-exhausted cases have retry_reason=BUDGET_EXHAUSTED). + if ( + skill_result.retry_reason == RetryReason.CONTRACT_RECOVERY + and skill_result.needs_retry + and skill_result.session_id + ): + nudge_success = await _attempt_contract_nudge( + skill_result, + result, + expected_output_patterns, + effective_marker, + cwd, + runner, + ) + if nudge_success is not None: + skill_result = nudge_success + + _clone_reverted = False + if _clone_snapshot is not None: + skill_result, _clone_reverted = await check_and_revert_clone_contamination( + _clone_snapshot, + skill_result, + cwd, + runner, + ctx.audit, + skill_command=original_skill_command, + ) + # Use monotonic elapsed_seconds — authoritative wall-clock timing set by time.monotonic() # brackets in run_managed_async. Never re-derive from ISO strings (backward-clock risk). timing_seconds: float = result.elapsed_seconds @@ -893,6 +1167,7 @@ async def run_headless_core( end_ts=result.end_ts, elapsed_seconds=result.elapsed_seconds, termination_reason=result.termination.value, + kill_reason=skill_result.kill_reason.value, snapshot_interval_seconds=ctx.config.linux_tracing.proc_interval, proc_snapshots=result.proc_snapshots, step_name=step_name, @@ -901,6 +1176,8 @@ async def run_headless_core( audit_record=audit_record, write_path_warnings=skill_result.write_path_warnings, write_call_count=skill_result.write_call_count, + clone_contamination_reverted=_clone_reverted, + tracked_comm=result.tracked_comm, ) except Exception: logger.debug("session_log_flush_failed", exc_info=True) @@ -946,8 +1223,10 @@ async def run( add_dirs: Sequence[ValidatedAddDir] = (), timeout: float | None = None, stale_threshold: float | None = None, + idle_output_timeout: float | None = None, expected_output_patterns: Sequence[str] = (), write_behavior: WriteBehaviorSpec | None = None, + completion_marker: str = "", ) -> SkillResult: cfg = self._ctx.config.run_skill effective_timeout = timeout if timeout is not None else cfg.timeout @@ -963,6 +1242,8 @@ async def run( add_dirs=add_dirs, timeout=effective_timeout, stale_threshold=effective_stale, + idle_output_timeout=idle_output_timeout, expected_output_patterns=expected_output_patterns, write_behavior=write_behavior, + completion_marker=completion_marker, ) diff --git a/src/autoskillit/execution/linux_tracing.py b/src/autoskillit/execution/linux_tracing.py index 5295f5af1c..6788c1149c 100644 --- a/src/autoskillit/execution/linux_tracing.py +++ b/src/autoskillit/execution/linux_tracing.py @@ -18,7 +18,10 @@ import dataclasses import json +import os import sys +import tempfile +import time from collections.abc import AsyncIterator from dataclasses import dataclass, field from datetime import UTC, datetime, timedelta @@ -29,9 +32,13 @@ import anyio.abc import psutil +from autoskillit.core import get_logger + if TYPE_CHECKING: from autoskillit.config import LinuxTracingConfig +logger = get_logger(__name__) + LINUX_TRACING_AVAILABLE = sys.platform == "linux" @@ -44,26 +51,244 @@ def read_boot_id() -> str | None: def read_starttime_ticks(pid: int) -> int | None: - """Read process starttime ticks from /proc/pid/stat.""" + """Read process starttime ticks from /proc/pid/stat. + + Uses rfind(")") to correctly locate the field boundary even when the + process comm contains a ")" character. Matches psutil's own _parse_stat_file() + which uses rfind(b")") for the same reason. + """ try: stat = Path(f"/proc/{pid}/stat").read_text() - # comm may contain spaces; find the closing paren to parse fields after it - after_paren = stat.split(")", 1) - if len(after_paren) >= 2: - fields = after_paren[1].strip().split() - # starttime is field 22 in /proc/stat (0-indexed position 19 after state) - return int(fields[19]) + # comm may contain ")" — use rfind to find the *last* ")" as the boundary + rpar = stat.rfind(")") + if rpar == -1: + return None + fields = stat[rpar + 2 :].split() + # starttime is field 22 (1-indexed per man page), offset 19 from the field after ")" + return int(fields[19]) except (OSError, ValueError, IndexError): pass return None +# --------------------------------------------------------------------------- +# TraceTarget: workload process identity with provenance +# --------------------------------------------------------------------------- + + +class TraceTargetResolutionError(RuntimeError): + """Raised when resolve_trace_target cannot find the expected workload within timeout. + + Attributes: + root_pid: The spawn PID (e.g., script(1)) that was walked. + expected_basename: The basename we were looking for (e.g., 'claude'). + """ + + def __init__(self, root_pid: int, expected_basename: str) -> None: + self.root_pid = root_pid + self.expected_basename = expected_basename + super().__init__( + f"resolve_trace_target: timeout waiting for '{expected_basename}' " + f"to appear as a descendant of PID {root_pid}. " + f"The workload process did not start within the resolution window. " + f"Cannot trace: falling back to wrapper PID would recreate issue #806." + ) + + +@dataclass(frozen=True) +class TraceTarget: + """Workload process identity with provenance — the correct target for the tracer. + + Can only be produced by resolve_trace_target() (PTY mode, walks descendants) + or trace_target_from_pid() (non-PTY mode, direct PID). Never from a raw int. + + Fields: + pid: PID of the workload process (not the spawn wrapper). + comm: /proc/{pid}/comm value — process name, max 15 chars. + cmdline: Full command line as a tuple of strings. + starttime_ticks: /proc/{pid}/stat field 22 — collision-resistant identity. + resolved_at: UTC datetime when this target was resolved. + """ + + pid: int + comm: str + cmdline: tuple[str, ...] + starttime_ticks: int + resolved_at: datetime + + +def resolve_trace_target( + root_pid: int, + expected_basename: str, + timeout: float = 2.0, +) -> TraceTarget: + """Walk descendants of root_pid to find the workload process by basename. + + Used after anyio.open_process() in PTY mode: root_pid is the script(1) wrapper; + we need to find the actual workload (e.g., 'claude') in its subtree. + + Polls at 50 ms intervals up to timeout. Raises TraceTargetResolutionError on miss + — never falls back to root_pid to prevent silent re-introduction of issue #806. + + Args: + root_pid: Spawn PID (e.g., script(1) when PTY mode is active). + expected_basename: Basename to match (e.g., 'claude', 'python3'). + timeout: Maximum seconds to wait for the workload to appear. + + Returns: + TraceTarget with the workload's pid, comm, cmdline, starttime_ticks. + + Raises: + TraceTargetResolutionError: When workload not found within timeout. + """ + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + try: + root_proc = psutil.Process(root_pid) + children = root_proc.children(recursive=True) + except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): + break + + for child in children: + try: + name = child.name() + cmdline = child.cmdline() + basename_matches = name == expected_basename or ( + cmdline and Path(cmdline[0]).name == expected_basename + ) + if not basename_matches: + continue + # Found the workload — read identity fields from /proc + try: + comm = Path(f"/proc/{child.pid}/comm").read_text().strip() + except OSError: + comm = name + starttime = read_starttime_ticks(child.pid) or 0 + return TraceTarget( + pid=child.pid, + comm=comm, + cmdline=tuple(cmdline), + starttime_ticks=starttime, + resolved_at=datetime.now(UTC), + ) + except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess, OSError): + continue + + time.sleep(0.05) + + raise TraceTargetResolutionError(root_pid=root_pid, expected_basename=expected_basename) + + +def trace_target_from_pid(pid: int) -> TraceTarget: + """Build a TraceTarget directly from a PID without child walking. + + Used for pty_mode=False (direct child, no wrapper) and in tests where the + spawn PID is already the workload. + + Does a single /proc read to populate comm, cmdline, and starttime_ticks. + Never raises — returns empty strings/tuples on /proc read errors (process + may have already exited when this is called). + """ + try: + comm = Path(f"/proc/{pid}/comm").read_text().strip() + except OSError: + comm = "" + try: + proc = psutil.Process(pid) + cmdline: tuple[str, ...] = tuple(proc.cmdline()) + except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess, OSError): + cmdline = () + starttime = read_starttime_ticks(pid) or 0 + return TraceTarget( + pid=pid, + comm=comm, + cmdline=cmdline, + starttime_ticks=starttime, + resolved_at=datetime.now(UTC), + ) + + +# --------------------------------------------------------------------------- +# TraceEnrollmentRecord: schema version 2 (adds comm field) +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class TraceEnrollmentRecord: + """Identity triple written atomically at trace-open time. + + (boot_id, pid, starttime_ticks) together form a collision-resistant identity: + - boot_id rejects pre-reboot stale files + - starttime_ticks detects PID recycling + + Schema version 2 adds 'comm' to the enrollment record so that crash recovery + can verify the process identity (not just its PID) and reject alien trace files. + """ + + schema_version: int # 2 for post-#806 records; 1 for pre-fix records + pid: int + boot_id: str | None # read_boot_id(); None if /proc unavailable + starttime_ticks: int | None # read_starttime_ticks(pid); None if unavailable + session_id: str # caller-provided; "" if not yet resolved + enrolled_at: str # ISO 8601 UTC + kitchen_id: str # "" + order_id: str # "" + comm: str = "" # /proc/{pid}/comm value; "" for pre-fix (schema_version=1) records + + +def _write_enrollment_atomic(path: Path, record: TraceEnrollmentRecord) -> None: + """Write enrollment sidecar atomically using tempfile + os.replace.""" + content = json.dumps(dataclasses.asdict(record)) + fd, tmp = tempfile.mkstemp(dir=path.parent, suffix=".tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(content) + os.replace(tmp, path) + except Exception: + try: + os.unlink(tmp) + except OSError: + pass + raise + + +def read_enrollment(path: Path) -> TraceEnrollmentRecord | None: + """Read and validate an enrollment sidecar. Returns None on any error.""" + try: + data = json.loads(path.read_text(encoding="utf-8")) + return TraceEnrollmentRecord( + schema_version=data["schema_version"], + pid=data["pid"], + boot_id=data.get("boot_id"), + starttime_ticks=data.get("starttime_ticks"), + session_id=data.get("session_id", ""), + enrolled_at=data.get("enrolled_at", ""), + kitchen_id=data.get("kitchen_id", ""), + order_id=data.get("order_id", ""), + comm=data.get("comm", ""), # "" for pre-fix schema_version=1 records + ) + except (OSError, KeyError, TypeError, ValueError, json.JSONDecodeError): + return None + + +# --------------------------------------------------------------------------- +# ProcSnapshot: point-in-time snapshot with self-identifying comm field +# --------------------------------------------------------------------------- + + @dataclass(frozen=True) class ProcSnapshot: - """Point-in-time snapshot of process state.""" + """Point-in-time snapshot of process state. + + The 'comm' field (added in #806 fix) self-identifies the process each snapshot + describes. Post-hoc drift detection becomes trivial: any row in proc_trace.jsonl + where comm != expected_comm is a drift indicator. + """ # Temporal anchor — set at capture time, never reassigned captured_at: str + # Process identity — populated from /proc/{pid}/comm (max 15 chars kernel truncation) + comm: str # psutil-sourced fields state: str vm_rss_kb: int @@ -78,6 +303,8 @@ class ProcSnapshot: sig_cgt: str oom_score: int wchan: str + # CPU utilisation (0.0 when process arg is not supplied to read_proc_snapshot) + cpu_percent: float def _parse_proc_status(content: str) -> dict[str, str]: @@ -101,13 +328,19 @@ def _parse_proc_status(content: str) -> dict[str, str]: return fields -def read_proc_snapshot(pid: int) -> ProcSnapshot | None: - """Read a complete snapshot for pid. Returns None if process gone.""" +def read_proc_snapshot(pid: int, *, process: psutil.Process | None = None) -> ProcSnapshot | None: + """Read a complete snapshot for pid. Returns None if process gone. + + When *process* is provided, it is reused instead of constructing a fresh + psutil.Process(pid); cpu_percent(interval=0) then returns a meaningful + delta against the baseline primed by the caller. When *process* is None, + cpu_percent defaults to 0.0. + """ if not LINUX_TRACING_AVAILABLE: return None captured_at = datetime.now(UTC).isoformat() try: - p = psutil.Process(pid) + p = process if process is not None else psutil.Process(pid) with p.oneshot(): state = p.status() mem = p.memory_info() @@ -115,9 +348,16 @@ def read_proc_snapshot(pid: int) -> ProcSnapshot | None: num_fds = p.num_fds() fd_soft_limit = p.rlimit(psutil.RLIMIT_NOFILE)[0] ctx = p.num_ctx_switches() + cpu_pct = p.cpu_percent(interval=0) if process is not None else 0.0 except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): return None + # Read process name from /proc/{pid}/comm (max 15 chars, kernel-truncated) + try: + comm = Path(f"/proc/{pid}/comm").read_text().strip() + except (FileNotFoundError, PermissionError): + comm = "" + # Hand-rolled /proc reads for fields psutil doesn't expose try: status_content = Path(f"/proc/{pid}/status").read_text() @@ -137,6 +377,7 @@ def read_proc_snapshot(pid: int) -> ProcSnapshot | None: return ProcSnapshot( captured_at=captured_at, + comm=comm, state=state, vm_rss_kb=mem.rss // 1024, threads=num_threads, @@ -149,6 +390,7 @@ def read_proc_snapshot(pid: int) -> ProcSnapshot | None: sig_cgt=sig_fields.get("sig_cgt", ""), oom_score=oom, wchan=wchan, + cpu_percent=cpu_pct, ) @@ -161,8 +403,13 @@ async def proc_monitor(pid: int, interval: float = 5.0) -> AsyncIterator[ProcSna maintain the monotonic ordering invariant at the production site. """ _last_captured_at: str = "" + try: + _proc = psutil.Process(pid) + _proc.cpu_percent(interval=0) # prime the psutil-internal baseline + except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess): + return while True: - snap = read_proc_snapshot(pid) + snap = read_proc_snapshot(pid, process=_proc) if snap is None: return captured_at = snap.captured_at @@ -185,6 +432,7 @@ class LinuxTracingHandle: _snapshots: list[ProcSnapshot] = field(default_factory=list) _trace_path: Path | None = field(default=None) _trace_file: IO[str] | None = field(default=None) + _enrollment_path: Path | None = field(default=None) def stop(self) -> list[ProcSnapshot]: """Stop tracing, flush and close the trace file, return accumulated snapshots.""" @@ -197,20 +445,46 @@ def stop(self) -> list[ProcSnapshot]: except OSError: pass self._trace_file = None + if self._trace_path is not None: + # Intentional: stop() cleans up its own trace file. Crash-recovery only reads + # files left behind by processes that never called stop() — so this is correct. + self._trace_path.unlink(missing_ok=True) + self._trace_path = None + if self._enrollment_path is not None: + self._enrollment_path.unlink(missing_ok=True) + self._enrollment_path = None return list(self._snapshots) def start_linux_tracing( - pid: int, + target: TraceTarget, config: LinuxTracingConfig, tg: anyio.abc.TaskGroup | None, + *, + session_id: str = "", + kitchen_id: str = "", + order_id: str = "", ) -> LinuxTracingHandle | None: - """Start Linux tracing if all gates pass. Returns handle or None.""" + """Start Linux tracing if all gates pass. Returns handle or None. + + Args: + target: TraceTarget produced by resolve_trace_target() (PTY mode) or + trace_target_from_pid() (non-PTY mode). Never pass a raw int PID — + use the appropriate resolver to get a TraceTarget first (ARCH-008). + """ + if not isinstance(target, TraceTarget): + raise TypeError( + f"start_linux_tracing: 'target' must be a TraceTarget, " + f"got {type(target).__name__!r}. " + "Use resolve_trace_target() (PTY mode) or trace_target_from_pid() (non-PTY mode) " + "instead of passing a raw int pid. (ARCH-008 / issue #806)" + ) if not LINUX_TRACING_AVAILABLE or not config.enabled: return None if tg is None: return None + pid = target.pid handle = LinuxTracingHandle() scope = anyio.CancelScope() @@ -225,6 +499,27 @@ def start_linux_tracing( handle._trace_path = None handle._trace_file = None + # Write enrollment sidecar atomically for crash-recovery identity contract + # Schema version 2: includes comm field for alien-file rejection in recovery + enrollment_path = tmpfs / f"autoskillit_enrollment_{pid}.json" + try: + record = TraceEnrollmentRecord( + schema_version=2, + pid=pid, + boot_id=read_boot_id(), + starttime_ticks=target.starttime_ticks, + session_id=session_id, + enrolled_at=datetime.now(UTC).isoformat(), + kitchen_id=kitchen_id, + order_id=order_id, + comm=target.comm, + ) + _write_enrollment_atomic(enrollment_path, record) + handle._enrollment_path = enrollment_path + except OSError as e: + logger.warning("Failed to write enrollment sidecar for pid %d: %s", pid, e) + handle._enrollment_path = None + async def _run_monitor() -> None: with scope: async for snap in proc_monitor(pid, config.proc_interval): diff --git a/src/autoskillit/execution/merge_queue.py b/src/autoskillit/execution/merge_queue.py index d956df0570..e308f934ae 100644 --- a/src/autoskillit/execution/merge_queue.py +++ b/src/autoskillit/execution/merge_queue.py @@ -6,13 +6,17 @@ from __future__ import annotations import asyncio +import random +import re import time +from collections.abc import Callable +from dataclasses import dataclass from datetime import UTC, datetime -from typing import Any, TypedDict +from typing import Any, TypedDict, assert_never import httpx -from autoskillit.core import get_logger +from autoskillit.core import PRState, get_logger from autoskillit.execution.github import github_headers _log = get_logger(__name__) @@ -23,7 +27,9 @@ class PRFetchState(TypedDict): merged: bool state: str + mergeable: str # "MERGEABLE" | "CONFLICTING" | "UNKNOWN" merge_state_status: str + auto_merge_present: bool # True when autoMergeRequest is not null auto_merge_enabled_at: datetime | None pr_node_id: str in_queue: bool @@ -40,6 +46,7 @@ class PRFetchState(TypedDict): id merged state + mergeable mergeStateStatus autoMergeRequest { enabledAt @@ -60,6 +67,40 @@ class PRFetchState(TypedDict): } """ +# Maps every PRFetchState key to its GraphQL source path. +# "" means the field is derived from query results, not directly selected. +# This constant is validated at import time against PRFetchState.__required_keys__ +# (mirroring the pattern in recipe/io.py:126-161). +_QUERY_FIELD_MAP: dict[str, str] = { + "merged": "merged", + "state": "state", + "mergeable": "mergeable", + "merge_state_status": "mergeStateStatus", + "auto_merge_present": "autoMergeRequest", + "auto_merge_enabled_at": "autoMergeRequest.enabledAt", + "pr_node_id": "id", + "in_queue": "", + "queue_state": "", + "checks_state": "statusCheckRollup.state", +} + +_ALL_FETCH_STATE_KEYS = PRFetchState.__required_keys__ | PRFetchState.__optional_keys__ +if set(_QUERY_FIELD_MAP) != _ALL_FETCH_STATE_KEYS: + raise RuntimeError( + "_QUERY_FIELD_MAP is out of sync with PRFetchState keys.\n" + f"Missing from map: {_ALL_FETCH_STATE_KEYS - set(_QUERY_FIELD_MAP)}\n" + f"Missing from state: {set(_QUERY_FIELD_MAP) - _ALL_FETCH_STATE_KEYS}" + ) +for _key, _path in _QUERY_FIELD_MAP.items(): + if _path.startswith("<"): + continue + _head = _path.split(".", 1)[0] + # Word-boundary search prevents "state" from matching inside "mergeStateStatus". + if not re.search(r"\b" + re.escape(_head) + r"\b", _QUERY): + raise RuntimeError( + f"_QUERY is missing GraphQL field {_head!r} required by PRFetchState[{_key!r}]" + ) + _MUTATION_DISABLE_AUTO_MERGE = """ mutation DisableAutoMerge($prId: ID!) { disablePullRequestAutoMerge(input: {pullRequestId: $prId}) { @@ -76,6 +117,138 @@ class PRFetchState(TypedDict): } """ +# Repo-level state query: consolidates three former run_cmd steps into one HTTP round-trip. +# Distinct from _QUERY (PR-level + queue-entries); do not merge these constants. +# Returns: mergeQueue presence, autoMergeAllowed flag, and workflow file texts for +# merge_group trigger detection — all in a single GraphQL call. +_REPO_STATE_QUERY = """ +query GetRepoMergeState($owner: String!, $repo: String!, $branch: String!) { + repository(owner: $owner, name: $repo) { + mergeQueue(branch: $branch) { + id + } + autoMergeAllowed + object(expression: "HEAD:.github/workflows") { + ... on Tree { + entries { + name + object { + ... on Blob { + text + } + } + } + } + } + } +} +""" + + +# --------------------------------------------------------------------------- +# Classifier primitives (pure functions — no I/O, no async) +# --------------------------------------------------------------------------- + + +@dataclass(frozen=True) +class ClassificationResult: + """Positive-signal classification outcome from _classify_pr_state.""" + + terminal: PRState + reason: str + + +class ClassifierInconclusive(Exception): + """Raised when no positive gate matched — caller must continue polling. + + The .state attribute exposes the full PRFetchState that was inspected, + enabling callers to log or surface the ambiguous fields. + """ + + def __init__(self, state: PRFetchState, reason: str) -> None: + super().__init__(reason) + self.state = state + self.reason = reason + + +class CIStillRunning(ClassifierInconclusive): + """CI checks are legitimately in-progress (PENDING or EXPECTED). + + Expected transient state — outer timeout_seconds bounds the wait. + Must NOT consume the inconclusive budget. + """ + + +class NoPositiveSignal(ClassifierInconclusive): + """No positive classifier gate matched — state is genuinely ambiguous. + + Bounded by max_inconclusive_retries. Counts against the inconclusive budget. + """ + + +def _is_positive_stall(state: PRFetchState) -> bool: + """True when auto-merge is enabled and merge_state_status indicates the PR is + stuck in a state where it should be in queue but is not.""" + return state["auto_merge_enabled_at"] is not None and state["merge_state_status"] in { + "CLEAN", + "HAS_HOOKS", + } + + +def _is_positive_dropped_healthy(state: PRFetchState) -> bool: + """True when the PR is fully healthy but auto_merge was cleared externally.""" + return ( + state["state"] == "OPEN" + and state["mergeable"] == "MERGEABLE" + and state["merge_state_status"] == "CLEAN" + and state["checks_state"] in (None, "SUCCESS") + and state["auto_merge_present"] is False + and state["in_queue"] is False + ) + + +def _classify_pr_state(state: PRFetchState) -> ClassificationResult: + """Classify PR state using positive signals only — no fall-through to EJECTED. + + Every return originates from a direct positive signal. When no positive gate + matches, raises ClassifierInconclusive so the caller can continue polling + within a bounded retry budget rather than silently misclassifying. + + Args: + state: Current PR fetch state snapshot. + + Returns: + ClassificationResult with the matched terminal PRState. + + Raises: + ClassifierInconclusive: When no positive signal matched. .state exposes + the full snapshot for logging/surfacing. + """ + if state["merged"]: + return ClassificationResult(PRState.MERGED, "PR merged") + + if state["state"] == "CLOSED": + if state["checks_state"] in {"FAILURE", "ERROR"}: + return ClassificationResult(PRState.EJECTED_CI_FAILURE, "PR closed after CI failure") + return ClassificationResult(PRState.EJECTED, "PR closed while not merged") + + if state["checks_state"] in {"FAILURE", "ERROR"}: + return ClassificationResult(PRState.EJECTED_CI_FAILURE, "checks terminal failure") + + if _is_positive_stall(state): + return ClassificationResult(PRState.STALLED, "stall signals present") + + if state["mergeable"] == "CONFLICTING": + return ClassificationResult(PRState.EJECTED, "conflicting changes prevent merge") + + if _is_positive_dropped_healthy(state): + return ClassificationResult(PRState.DROPPED_HEALTHY, "PR healthy but auto_merge cleared") + + if state["checks_state"] in {"PENDING", "EXPECTED"}: + raise CIStillRunning(state, "checks still running") + + raise NoPositiveSignal(state, "no positive signal matched") + class DefaultMergeQueueWatcher: """Polls GitHub merge queue state until merged, ejected, stalled, or timed out. @@ -87,15 +260,35 @@ class DefaultMergeQueueWatcher: Never raises; all errors are returned as structured dicts. """ - def __init__(self, token: str | None) -> None: - self._client = httpx.AsyncClient( - headers=github_headers(token), - limits=httpx.Limits(keepalive_expiry=60), - timeout=30.0, - ) + def __init__( + self, + token: str | None | Callable[[], str | None], + ) -> None: + self._token_factory: Callable[[], str | None] | None + if callable(token): + self._token_factory = token + self._client: httpx.AsyncClient | None = None + else: + self._token_factory = None + self._client = httpx.AsyncClient( + headers=github_headers(token), + limits=httpx.Limits(keepalive_expiry=60), + timeout=30.0, + ) + + def _ensure_client(self) -> httpx.AsyncClient: + if self._client is None: + resolved = self._token_factory() if self._token_factory is not None else None + self._client = httpx.AsyncClient( + headers=github_headers(resolved), + limits=httpx.Limits(keepalive_expiry=60), + timeout=30.0, + ) + return self._client async def aclose(self) -> None: - await self._client.aclose() + if self._client is not None: + await self._client.aclose() async def wait( self, @@ -108,8 +301,9 @@ async def wait( stall_grace_period: int = 60, max_stall_retries: int = 3, not_in_queue_confirmation_cycles: int = 2, + max_inconclusive_retries: int = 5, ) -> dict[str, Any]: - """Poll until PR is merged, ejected, stalled, or timeout expires. + """Poll until PR is merged, ejected, stalled, dropped, or timeout expires. Args: pr_number: PR number to monitor. @@ -126,11 +320,13 @@ async def wait( not_in_queue_confirmation_cycles: Consecutive "not in queue" cycles required before acting on absence. Guards against race between queue exit and merged=true propagation (default 2). + max_inconclusive_retries: Maximum NoPositiveSignal cycles (beyond the + confirmation window) before returning pr_state="timeout" (default 5). Returns: { "success": bool, - "pr_state": "merged" | "ejected" | "stalled" | "timeout" | "error", + "pr_state": PRState value string, "reason": str, "stall_retries_attempted": int, } @@ -138,7 +334,7 @@ async def wait( if not repo or "/" not in repo: return { "success": False, - "pr_state": "error", + "pr_state": PRState.ERROR.value, "reason": f"Invalid repo format: {repo!r}. Expected 'owner/name'.", "stall_retries_attempted": 0, } @@ -147,14 +343,20 @@ async def wait( deadline = time.monotonic() + timeout_seconds stall_retries_attempted: int = 0 not_in_queue_cycles: int = 0 + inconclusive_count: int = 0 - def _make_result(success: bool, pr_state: str, reason: str) -> dict[str, Any]: - return { + def _make_result( + success: bool, pr_state: PRState, reason: str, ejection_cause: str = "" + ) -> dict[str, Any]: + result: dict[str, Any] = { "success": success, - "pr_state": pr_state, + "pr_state": pr_state.value, "reason": reason, "stall_retries_attempted": stall_retries_attempted, } + if ejection_cause: + result["ejection_cause"] = ejection_cause + return result while time.monotonic() < deadline: try: @@ -166,47 +368,64 @@ def _make_result(success: bool, pr_state: str, reason: str) -> dict[str, Any]: await asyncio.sleep(poll_interval) continue - # Terminal: merged - if state["merged"]: - return _make_result(True, "merged", "PR merged successfully") - - # Terminal: closed without merge - if state["state"] == "CLOSED": - return _make_result(False, "ejected", "PR was closed without merging") - - # In queue + # In queue: reset window and continue if state["in_queue"]: - not_in_queue_cycles = 0 # reset confirmation window + not_in_queue_cycles = 0 + inconclusive_count = 0 if state["queue_state"] == "UNMERGEABLE": - return _make_result(False, "ejected", "PR is UNMERGEABLE in merge queue") + return _make_result(False, PRState.EJECTED, "PR is UNMERGEABLE in merge queue") await asyncio.sleep(poll_interval) continue - # Confirmation window: guard against race between queue exit and - # merged=true propagation not_in_queue_cycles += 1 - if not_in_queue_cycles < not_in_queue_confirmation_cycles: - # One extra cycle: gives time for merge-in-progress to reflect merged=true + + # Classify state using positive-signal gates + try: + classification = _classify_pr_state(state) + except CIStillRunning: + await asyncio.sleep(poll_interval) + continue + except NoPositiveSignal as exc: + if not_in_queue_cycles < not_in_queue_confirmation_cycles: + await asyncio.sleep(poll_interval) + continue + inconclusive_count += 1 + if inconclusive_count >= max_inconclusive_retries: + return _make_result( + False, + PRState.TIMEOUT, + f"Inconclusive after {max_inconclusive_retries} retries: {exc.reason}", + ) await asyncio.sleep(poll_interval) continue - # Confirmed: not in queue for 2+ cycles — check stall - enabled_at = state["auto_merge_enabled_at"] - merge_status = state["merge_state_status"] - now = datetime.now(UTC) + # MERGED: definitive — bypasses confirmation window + if classification.terminal == PRState.MERGED: + return _make_result(True, PRState.MERGED, classification.reason) - is_stall_candidate = enabled_at is not None and merge_status in {"CLEAN", "HAS_HOOKS"} + # CLOSED: definitive — bypasses confirmation window + if state["state"] == "CLOSED": + ejection_cause = ( + "ci_failure" if classification.terminal == PRState.EJECTED_CI_FAILURE else "" + ) + return _make_result( + False, classification.terminal, classification.reason, ejection_cause + ) - if is_stall_candidate: - assert enabled_at is not None # guaranteed by is_stall_candidate - stall_duration = max(0.0, (now - enabled_at).total_seconds()) + # All other positive terminals require the confirmation window + if not_in_queue_cycles < not_in_queue_confirmation_cycles: + await asyncio.sleep(poll_interval) + continue + # Post-confirmation terminal dispatch + if classification.terminal == PRState.STALLED: + enabled_at = state["auto_merge_enabled_at"] + assert enabled_at is not None # guaranteed by _is_positive_stall + now = datetime.now(UTC) + stall_duration = max(0.0, (now - enabled_at).total_seconds()) if stall_duration < stall_grace_period: - # Within grace period — wait without intervening await asyncio.sleep(poll_interval) continue - - # Grace expired: attempt toggle if budget remains if stall_retries_attempted < max_stall_retries: backoff = min(30 * (2**stall_retries_attempted), 120) _log.info( @@ -223,31 +442,36 @@ def _make_result(success: bool, pr_state: str, reason: str) -> dict[str, Any]: not_in_queue_cycles = 0 await asyncio.sleep(backoff) continue - - # Budget exhausted — return distinct stalled state return _make_result( False, - "stalled", + PRState.STALLED, f"PR #{pr_number} stall unresolved after {max_stall_retries} toggle attempts", ) - # D6: checks_state guard — CI still running, PR not yet eligible for queue - if state["checks_state"] in {"PENDING", "EXPECTED"}: - await asyncio.sleep(poll_interval) - continue + elif classification.terminal == PRState.EJECTED_CI_FAILURE: + return _make_result( + False, + PRState.EJECTED_CI_FAILURE, + classification.reason, + ejection_cause="ci_failure", + ) - # Positive confirmation: checks are terminal (SUCCESS/FAILURE/ERROR) or absent (None). - # PR confirmed not in queue, not merged, checks not pending → genuine ejection. - return _make_result( - False, - "ejected", - "PR was ejected from merge queue (not in queue and not merged)", - ) + elif classification.terminal == PRState.EJECTED: + return _make_result(False, PRState.EJECTED, classification.reason) + + elif classification.terminal == PRState.DROPPED_HEALTHY: + return _make_result(False, PRState.DROPPED_HEALTHY, classification.reason) + + else: + # Unreachable: _classify_pr_state never returns TIMEOUT or ERROR. + # The assert_never call provides static exhaustiveness for future + # additions to PRState (pyright/mypy will flag any new unhandled member). + assert_never(classification.terminal) # type: ignore[arg-type] # Deadline exceeded return _make_result( False, - "timeout", + PRState.TIMEOUT, f"Timed out after {timeout_seconds}s waiting for PR #{pr_number}", ) @@ -261,7 +485,7 @@ async def _fetch_pr_and_queue_state( "prNumber": pr_number, "branch": target_branch, } - resp = await self._client.post( + resp = await self._ensure_client().post( _GRAPHQL_ENDPOINT, json={"query": _QUERY, "variables": variables} ) resp.raise_for_status() @@ -280,7 +504,9 @@ async def _fetch_pr_and_queue_state( nodes_raw = (entries.get("entries") or {}).get("nodes") nodes = nodes_raw if isinstance(nodes_raw, list) else [] - auto_merge = pr.get("autoMergeRequest") or {} + auto_merge_raw = pr.get("autoMergeRequest") + auto_merge_present: bool = auto_merge_raw is not None + auto_merge = auto_merge_raw or {} enabled_at_raw = auto_merge.get("enabledAt") enabled_at: datetime | None = None if enabled_at_raw: @@ -298,7 +524,9 @@ async def _fetch_pr_and_queue_state( return PRFetchState( merged=pr["merged"], state=pr["state"], + mergeable=pr.get("mergeable") or "UNKNOWN", merge_state_status=pr.get("mergeStateStatus", "UNKNOWN"), + auto_merge_present=auto_merge_present, auto_merge_enabled_at=enabled_at, pr_node_id=pr["id"], in_queue=queue_entry is not None, @@ -343,7 +571,7 @@ async def _toggle_auto_merge(self, pr_node_id: str) -> None: (_MUTATION_ENABLE_AUTO_MERGE, {"prId": pr_node_id, "mergeMethod": "SQUASH"}), ] for i, (mutation, variables) in enumerate(mutations): - resp = await self._client.post( + resp = await self._ensure_client().post( _GRAPHQL_ENDPOINT, json={"query": mutation, "variables": variables} ) resp.raise_for_status() @@ -352,3 +580,171 @@ async def _toggle_auto_merge(self, pr_node_id: str) -> None: raise RuntimeError(f"GraphQL mutation error: {body['errors']}") if i < len(mutations) - 1: await asyncio.sleep(2) + + +# --------------------------------------------------------------------------- +# Repo-level state helper (used by check_repo_merge_state MCP tool) +# --------------------------------------------------------------------------- + + +def _text_has_push_trigger(text: str) -> bool: + """Return True if a workflow file text declares a push trigger. + + Checks for the three YAML forms GitHub supports for a push trigger: + - ``on: [push, ...]`` (list form) + - ``on: push`` (scalar form) + - ``push:`` (mapping form under ``on:``) + + Note: the first two patterns (``on: [push``, ``on: push``) are reliably + scoped to YAML trigger syntax. The third (``push:``) may match inside + comments or run-step values — acceptable for the positive-signal-only + classification heuristic but not precise. + """ + return any(pat in text for pat in ("on: [push", "on: push", "push:")) + + +_RATE_LIMIT_MAX_ATTEMPTS = 3 +_RATE_LIMIT_SECONDARY_MARKER = "secondary rate limit" + + +def _is_secondary_rate_limit(resp: httpx.Response) -> bool: + """Return True when a 403 response is a GitHub secondary rate limit. + + GitHub returns HTTP 403 (not 429) for secondary rate limits. + The response body contains the phrase "secondary rate limit". + Primary rate limits use HTTP 429 or include x-ratelimit-remaining: 0. + """ + if resp.status_code != 403: + return False + try: + text = resp.text.lower() + except Exception: + _log.warning("Failed to read response body for rate-limit check", exc_info=True) + return False + return _RATE_LIMIT_SECONDARY_MARKER in text + + +def _retry_after_seconds(attempt: int, resp: httpx.Response) -> float: + """Return seconds to sleep before the next retry attempt. + + Prefers the Retry-After header (integer seconds) when present and valid. + Falls back to full-jitter exponential backoff: random(0, min(60, 1 * 2^attempt)). + """ + try: + header_val = resp.headers.get("Retry-After", "") + if header_val: + return float(header_val) + except (ValueError, AttributeError): + pass + return random.uniform(0, min(60.0, 1.0 * (2**attempt))) + + +async def fetch_repo_merge_state( + owner: str, + repo: str, + branch: str, + token: str | None, +) -> dict[str, bool | str | None]: + """Fetch repository merge-state in a single GraphQL round-trip. + + Returns a dict with four keys: + - ``queue_available``: the branch has an active GitHub merge queue (bool). + - ``merge_group_trigger``: at least one CI workflow declares the + ``merge_group`` event trigger (bool). + - ``auto_merge_available``: the repository has auto-merge enabled (bool). + - ``ci_event``: the recommended CI event to poll — ``"push"`` when any + workflow declares a push trigger, ``"merge_group"`` when only merge_group + triggers are found, or ``None`` when no push/merge_group triggers exist + (ci.py scope.event=None matches any trigger). + + Null-handling: + - ``mergeQueue is null`` → ``queue_available: False`` (no queue) + - ``object is null`` → ``merge_group_trigger: False``, ``ci_event: None`` (no workflows dir) + - ``entry.object.text is null`` → skip entry (binary/large file) + - GraphQL ``autoMergeAllowed`` field error (GHES 3.0.x) → ``auto_merge_available: False`` + + Only transport-level failures (network timeout, non-200 HTTP status) are + allowed to propagate; callers are expected to handle them. + + Historical note: Issue #498 ("Merge queue detection should validate workflow has + merge_group trigger") established the merge_group_trigger field. The ci_event + field is a closely related extension — verify that the push-trigger scan does + not regress the merge_group-only detection that #498 established. + """ + resp: httpx.Response | None = None + for attempt in range(_RATE_LIMIT_MAX_ATTEMPTS): + async with httpx.AsyncClient( + headers=github_headers(token), + timeout=30.0, + ) as client: + resp = await client.post( + _GRAPHQL_ENDPOINT, + json={ + "query": _REPO_STATE_QUERY, + "variables": {"owner": owner, "repo": repo, "branch": branch}, + }, + ) + if resp.status_code == 429 or _is_secondary_rate_limit(resp): + sleep_secs = _retry_after_seconds(attempt, resp) + _log.warning( + "fetch_repo_merge_state rate limited", + status=resp.status_code, + attempt=attempt, + sleep_secs=sleep_secs, + ) + await asyncio.sleep(sleep_secs) + continue + resp.raise_for_status() + break + else: + assert resp is not None, "_RATE_LIMIT_MAX_ATTEMPTS must be >= 1" + resp.raise_for_status() + + assert resp is not None + body = resp.json() + + # GitHub GraphQL always returns a JSON object; guard against unexpected shapes. + if not isinstance(body, dict): + body = {} + + # Gracefully handle GHES 3.0.x where autoMergeAllowed doesn't exist. + auto_merge_field_missing = any( + "autoMergeAllowed" in str(e.get("message", "")) for e in body.get("errors", []) + ) + + repo_data: dict[str, Any] = (body.get("data") or {}).get("repository") or {} + queue_available = repo_data.get("mergeQueue") is not None + auto_merge_available = ( + False if auto_merge_field_missing else bool(repo_data.get("autoMergeAllowed", False)) + ) + + # Scan workflow files for push and merge_group trigger declarations. + # Both flags are derived from the same Blob.text scan — no extra round-trips. + merge_group_trigger = False + has_push_trigger = False + workflows_tree = repo_data.get("object") + if workflows_tree is not None: + for entry in workflows_tree.get("entries", []): + blob = entry.get("object") or {} + text = blob.get("text") + if text is None: + continue # binary or oversized blob — skip + if "merge_group" in text: + merge_group_trigger = True + if _text_has_push_trigger(text): + has_push_trigger = True + + # Derive ci_event: prefer push for historical compatibility when both are present. + if has_push_trigger: + ci_event: str | None = "push" + elif merge_group_trigger: + ci_event = "merge_group" + else: + ci_event = None # schedule-only or workflow_dispatch-only: match any + + return { + "queue_available": queue_available, + "merge_group_trigger": merge_group_trigger, + "auto_merge_available": auto_merge_available, + "ci_event": ci_event, + } diff --git a/src/autoskillit/execution/process.py b/src/autoskillit/execution/process.py index 38ae7ff6a4..2b0d2ae5f7 100644 --- a/src/autoskillit/execution/process.py +++ b/src/autoskillit/execution/process.py @@ -13,12 +13,21 @@ import subprocess import time +from collections.abc import Mapping from pathlib import Path -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, assert_never import anyio - -from autoskillit.core import ChannelConfirmation, SubprocessResult, TerminationReason, get_logger +import anyio.abc + +from autoskillit.core import ( + ChannelConfirmation, + KillReason, + SubprocessResult, + TerminationAction, + TerminationReason, + get_logger, +) from autoskillit.execution._process_io import create_temp_io, read_temp_output from autoskillit.execution._process_jsonl import ( _jsonl_contains_marker, @@ -32,6 +41,7 @@ ) from autoskillit.execution._process_monitor import ( _has_active_api_connection, + _has_active_child_processes, _heartbeat, _session_log_monitor, ) @@ -43,11 +53,15 @@ _watch_heartbeat, _watch_process, _watch_session_log, + _watch_stdout_idle, resolve_termination, ) if TYPE_CHECKING: + import structlog + from autoskillit.config import LinuxTracingConfig + from autoskillit.execution.linux_tracing import TraceTarget logger = get_logger(__name__) @@ -62,6 +76,7 @@ "RaceAccumulator", "RaceSignals", "_has_active_api_connection", + "_has_active_child_processes", "_heartbeat", "_jsonl_contains_marker", "_jsonl_has_record_type", @@ -73,6 +88,8 @@ "_watch_session_log", "async_kill_process_tree", "create_temp_io", + "decide_termination_action", + "execute_termination_action", "kill_process_tree", "pty_wrap_command", "read_temp_output", @@ -90,13 +107,81 @@ def _resolve_session_id( return stdout_session_id or channel_b_session_id or "" +def decide_termination_action( + termination: TerminationReason, + *, + timeout_fired: bool, + process_exited: bool, +) -> TerminationAction: + """Pure decision function: maps race signals to a TerminationAction. + + Priority: + 1. timeout_fired → IMMEDIATE_KILL (always overrides) + 2. process_exited → NO_KILL (process already gone, no signal needed) + 3. termination-reason dispatch: + - COMPLETED: channel won but process alive → DRAIN_THEN_KILL_IF_ALIVE + - NATURAL_EXIT: fallback case → NO_KILL + - IDLE_STALL / STALE / TIMED_OUT: infra kill → IMMEDIATE_KILL + + The function is deliberately free of anyio and I/O so it can be tested + as a pure decision table without any async or process infrastructure. + """ + if timeout_fired: + return TerminationAction.IMMEDIATE_KILL + if process_exited: + return TerminationAction.NO_KILL + match termination: + case TerminationReason.NATURAL_EXIT: + return TerminationAction.NO_KILL + case TerminationReason.COMPLETED: + return TerminationAction.DRAIN_THEN_KILL_IF_ALIVE + case TerminationReason.IDLE_STALL | TerminationReason.STALE | TerminationReason.TIMED_OUT: + return TerminationAction.IMMEDIATE_KILL + case _ as unreachable: + assert_never(unreachable) + + +async def execute_termination_action( + action: TerminationAction, + *, + proc: anyio.abc.Process, + process_exited_event: anyio.Event, + grace_seconds: float, + proc_log: structlog.BoundLogger, +) -> KillReason: + """Single authorized executor for all kill decisions in run_managed_async. + + This is the ONLY function in process.py permitted to call + async_kill_process_tree (enforced by test_no_direct_async_kill_process_tree_outside_executor). + + Returns the KillReason that surfaces to SubprocessResult.kill_reason. + """ + match action: + case TerminationAction.NO_KILL: + return KillReason.NATURAL_EXIT + case TerminationAction.DRAIN_THEN_KILL_IF_ALIVE: + with anyio.move_on_after(grace_seconds): + await process_exited_event.wait() + if proc.returncode is not None: + proc_log.debug("natural_exit_after_drain", returncode=proc.returncode) + return KillReason.NATURAL_EXIT + proc_log.debug("grace_expired_killing", grace_seconds=grace_seconds) + await async_kill_process_tree(proc.pid) + return KillReason.KILL_AFTER_COMPLETION + case TerminationAction.IMMEDIATE_KILL: + await async_kill_process_tree(proc.pid) + return KillReason.INFRA_KILL + case _ as unreachable: + assert_never(unreachable) + + async def run_managed_async( cmd: list[str], *, cwd: Path, timeout: float, input_data: str | None = None, - env: dict[str, str] | None = None, + env: Mapping[str, str] | None = None, pty_mode: bool = False, heartbeat_record_types: frozenset[str] = frozenset({"result"}), session_log_dir: Path | None = None, @@ -104,7 +189,10 @@ async def run_managed_async( stale_threshold: float = 1200, session_record_types: frozenset[str] = frozenset({"assistant"}), completion_drain_timeout: float = 5.0, + natural_exit_grace_seconds: float = 3.0, linux_tracing_config: LinuxTracingConfig | None = None, + idle_output_timeout: float | None = None, + max_suppression_seconds: float | None = None, _phase1_poll: float = 1.0, _phase2_poll: float = 2.0, _heartbeat_poll: float = 0.5, @@ -121,6 +209,9 @@ async def run_managed_async( 6. read_temp_output for results 7. cleanup temp files via context manager """ + # Capture workload basename before PTY wrapping rewrites cmd (#806) + _workload_basename = Path(cmd[0]).name if cmd else "" + if pty_mode: cmd = pty_wrap_command(cmd) @@ -145,10 +236,39 @@ async def run_managed_async( start_new_session=True, ) + # Resolve the workload TraceTarget — the PID that should be observed. + # anyio.open_process returns the spawn PID, which in PTY mode is the + # script(1) wrapper, not claude. resolve_trace_target walks descendants + # to find the actual workload by basename. Raising here (on miss) is + # intentional: a silent fallback to proc.pid recreates issue #806. + _target: TraceTarget | None = None + _observed_pid: int = proc.pid + _tracked_comm: str | None = None + if linux_tracing_config is not None: + from autoskillit.execution.linux_tracing import ( + LINUX_TRACING_AVAILABLE, + resolve_trace_target, + trace_target_from_pid, + ) + + if pty_mode and LINUX_TRACING_AVAILABLE: + # PTY mode: proc.pid is the script(1) wrapper — resolve to workload + _target = resolve_trace_target( + root_pid=proc.pid, + expected_basename=_workload_basename, + timeout=2.0, + ) + else: + # Non-PTY mode: proc.pid IS the workload (direct child) + _target = trace_target_from_pid(proc.pid) + assert _target is not None + _observed_pid = _target.pid + _tracked_comm = _target.comm + termination = TerminationReason.NATURAL_EXIT _channel_confirmation = ChannelConfirmation.UNMONITORED - proc_log = logger.bind(pid=proc.pid) + proc_log = logger.bind(pid=_observed_pid, comm=_tracked_comm) proc_log.debug( "run_managed_async_entry", cmd_summary=cmd[0] if cmd else "", @@ -190,7 +310,7 @@ async def run_managed_async( stale_threshold, time.time(), session_record_types, - proc.pid, + _observed_pid, completion_drain_timeout, acc, trigger, @@ -199,13 +319,22 @@ async def run_managed_async( _phase2_poll, _phase1_timeout, stdout_session_id_ready, + max_suppression_seconds, + ) + if idle_output_timeout is not None and idle_output_timeout > 0: + tg.start_soon( + _watch_stdout_idle, + stdout_path, + idle_output_timeout, + acc, + trigger, ) tracing_handle = None - if linux_tracing_config is not None: + if linux_tracing_config is not None and _target is not None: from autoskillit.execution.linux_tracing import start_linux_tracing tracing_handle = start_linux_tracing( - pid=proc.pid, + target=_target, config=linux_tracing_config, tg=tg, ) @@ -241,35 +370,34 @@ async def run_managed_async( from autoskillit.execution.linux_tracing import read_proc_snapshot accumulated = tracing_handle.stop() - final_snap = read_proc_snapshot(proc.pid) + final_snap = read_proc_snapshot(_observed_pid) if final_snap: accumulated.append(final_snap) snapshots_data = [s.__dict__ for s in accumulated] - if timeout_scope.cancelled_caught: + if timeout_scope is not None and timeout_scope.cancelled_caught: termination = TerminationReason.TIMED_OUT - proc_log.debug("kill_decision", reason="timeout", timeout=timeout) - logger.warning("Process %d timed out after %ss, killing tree", proc.pid, timeout) - await async_kill_process_tree(proc.pid) - elif signals.process_exited: - proc_log.debug( - "kill_decision", - reason="natural_exit", - returncode=signals.process_returncode, - ) - elif termination == TerminationReason.STALE: - proc_log.debug("kill_decision", reason="stale", stale_threshold=stale_threshold) - logger.warning("Session stale for %ss, killing tree", stale_threshold) - await async_kill_process_tree(proc.pid) - else: - proc_log.debug( - "kill_decision", - reason="channel_won", - channel_a=signals.channel_a_confirmed, - channel_b=signals.channel_b_status, - ) - # Channel A or B won; process still alive — kill immediately. - await async_kill_process_tree(proc.pid) + action = decide_termination_action( + termination, + timeout_fired=timeout_scope is not None and timeout_scope.cancelled_caught, + process_exited=signals.process_exited, + ) + proc_log.debug( + "kill_decision", + termination=str(termination), + action=str(action), + reason=str(action), + process_exited=signals.process_exited, + channel_a=signals.channel_a_confirmed, + channel_b=signals.channel_b_status, + ) + kill_reason = await execute_termination_action( + action, + proc=proc, + process_exited_event=signals.process_exited_event, + grace_seconds=natural_exit_grace_seconds, + proc_log=proc_log, + ) # Flush and close before reading stdout_file.close() @@ -282,13 +410,15 @@ async def run_managed_async( stdout=stdout, stderr=stderr, termination=termination, - pid=proc.pid, + pid=_observed_pid, channel_confirmation=_channel_confirmation, proc_snapshots=snapshots_data, channel_b_session_id=signals.channel_b_session_id, session_id=_resolve_session_id( signals.stdout_session_id, signals.channel_b_session_id ), + kill_reason=kill_reason, + tracked_comm=_tracked_comm, ) proc_log.debug( "run_managed_async_result", @@ -320,7 +450,7 @@ def run_managed_sync( cwd: Path | None, timeout: float, input_data: str | None = None, - env: dict[str, str] | None = None, + env: Mapping[str, str] | None = None, ) -> SubprocessResult: """Sync subprocess execution with temp file I/O and process tree cleanup. @@ -396,7 +526,7 @@ async def __call__( *, cwd: Path, timeout: float, - env: dict[str, str] | None = None, + env: Mapping[str, str] | None = None, stale_threshold: float = 1200, completion_marker: str = "", session_log_dir: Path | None = None, @@ -404,6 +534,8 @@ async def __call__( input_data: str | None = None, completion_drain_timeout: float = 5.0, linux_tracing_config: LinuxTracingConfig | None = None, + idle_output_timeout: float | None = None, + max_suppression_seconds: float | None = None, ) -> SubprocessResult: return await run_managed_async( cmd, @@ -417,4 +549,6 @@ async def __call__( input_data=input_data, completion_drain_timeout=completion_drain_timeout, linux_tracing_config=linux_tracing_config, + idle_output_timeout=idle_output_timeout, + max_suppression_seconds=max_suppression_seconds, ) diff --git a/src/autoskillit/execution/quota.py b/src/autoskillit/execution/quota.py index 475a495d5a..cd1a76ad4d 100644 --- a/src/autoskillit/execution/quota.py +++ b/src/autoskillit/execution/quota.py @@ -8,22 +8,147 @@ import json import time -from dataclasses import dataclass +from dataclasses import dataclass, field from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any import httpx -from autoskillit.core import atomic_write, get_logger +from autoskillit.core import get_logger, write_versioned_json _log = get_logger(__name__) +_DEFAULT_BASE_URL: str = "https://api.anthropic.com" + +QUOTA_CACHE_SCHEMA_VERSION: int = 3 +_SCHEMA_DRIFT_LOGGED: set[str] = set() + + +def _reset_schema_drift_logged_for_tests() -> None: + """Test-only helper: clear the once-per-process drift-log set.""" + _SCHEMA_DRIFT_LOGGED.clear() + @dataclass class QuotaStatus: utilization: float # percentage 0–100 resets_at: datetime | None # UTC-aware; None when utilization is 0 + window_name: str = "unknown" # which window this came from (diagnostic) + should_block: bool = False + effective_threshold: float = 0.0 + + def __post_init__(self) -> None: + if self.utilization is None: + raise TypeError("QuotaStatus.utilization must not be None") + self.utilization = float(self.utilization) + + +@dataclass +class QuotaWindowEntry: + """A single rate-limit window from the API response.""" + + utilization: float + resets_at: datetime | None + + def __post_init__(self) -> None: + if self.utilization is None: + raise TypeError("QuotaWindowEntry.utilization must not be None") + self.utilization = float(self.utilization) + + +@dataclass +class QuotaFetchResult: + """All windows from one API call, with the binding (worst-case) identified.""" + + windows: dict[str, QuotaWindowEntry] = field(default_factory=dict) + binding: QuotaStatus = field(default_factory=lambda: QuotaStatus(0.0, None)) + + +def _parse_resets_at(resets_at_str: str | None) -> datetime | None: + """Parse a resets_at string from API or cache, handling Z-suffix and +00:00 variants.""" + if not resets_at_str: + return None + return datetime.fromisoformat(resets_at_str.replace("Z", "+00:00")) + + +def _is_long_window(name: str, long_patterns: list[str]) -> bool: + """Return True if the window name matches any long-window pattern.""" + lowered = name.lower() + return any(pat.lower() in lowered for pat in long_patterns) + + +def _threshold_for_window( + name: str, + *, + short_threshold: float, + long_threshold: float, + long_patterns: list[str], +) -> float: + """Return the threshold to apply to a window of the given name. + + Long-window classification is substring match (case-insensitive) against + long_patterns. Unknown windows fall through to short_threshold. + """ + if _is_long_window(name, long_patterns): + return long_threshold + return short_threshold + + +def _compute_binding( + windows: dict[str, QuotaWindowEntry], + *, + short_threshold: float, + long_threshold: float, + long_patterns: list[str], + short_enabled: bool = True, + long_enabled: bool = True, +) -> QuotaStatus: + """Select the worst-case (binding) window using per-window thresholds. + + Each window is classified by name into short or long via long_patterns. + Windows whose class is disabled are dropped before threshold evaluation. + Among windows at or above their own threshold, returns the one with the + latest resets_at. If none are exhausted, returns the window with highest + utilization (for diagnostic display; should_block will be False). + Returns QuotaStatus(0.0, None, ...) when windows is empty or all dropped. + """ + if not windows: + return QuotaStatus(0.0, None, effective_threshold=100.0) + + filtered = { + name: w + for name, w in windows.items() + if (long_enabled if _is_long_window(name, long_patterns) else short_enabled) + } + if not filtered: + return QuotaStatus(0.0, None, effective_threshold=100.0) + + def threshold_of(name: str) -> float: + return _threshold_for_window( + name, + short_threshold=short_threshold, + long_threshold=long_threshold, + long_patterns=long_patterns, + ) + + exhausted = [(name, w) for name, w in filtered.items() if w.utilization >= threshold_of(name)] + if exhausted: + name, w = max( + exhausted, + key=lambda nw: nw[1].resets_at or datetime.min.replace(tzinfo=UTC), + ) + else: + name, w = max(filtered.items(), key=lambda nw: nw[1].utilization) + + effective = threshold_of(name) + return QuotaStatus( + utilization=w.utilization, + resets_at=w.resets_at, + window_name=name, + should_block=w.utilization >= effective, + effective_threshold=effective, + ) def _read_credentials(credentials_path: str) -> str: @@ -40,47 +165,84 @@ def _read_credentials(credentials_path: str) -> str: def _read_cache(cache_path: str, max_age: int) -> QuotaStatus | None: - """Return a fresh QuotaStatus from local cache, or None if stale/missing.""" + """Return a fresh QuotaStatus from local cache, or None if stale/missing/old-format.""" try: raw = json.loads(Path(cache_path).expanduser().read_text()) + if not isinstance(raw, dict): + return None + if raw.get("schema_version") != QUOTA_CACHE_SCHEMA_VERSION: + cache_key = str(Path(cache_path).expanduser()) + if cache_key not in _SCHEMA_DRIFT_LOGGED: + _SCHEMA_DRIFT_LOGGED.add(cache_key) + _log.warning( + "quota_cache_schema_drift", + cache_path=cache_key, + observed=raw.get("schema_version"), + ) + return None fetched_at = datetime.fromisoformat(raw["fetched_at"]) age = (datetime.now(UTC) - fetched_at).total_seconds() if age > max_age: return None - fh = raw["five_hour"] - resets_at_str = fh.get("resets_at") - resets_at = datetime.fromisoformat(resets_at_str) if resets_at_str else None + if "binding" not in raw: + return None + b = raw["binding"] return QuotaStatus( - utilization=float(fh["utilization"]), - resets_at=resets_at, + utilization=float(b["utilization"]), + resets_at=_parse_resets_at(b.get("resets_at")), + window_name=str(b.get("window_name", "unknown")), + should_block=bool(b.get("should_block", False)), + effective_threshold=float(b.get("effective_threshold", 0.0)), ) - except (FileNotFoundError, KeyError, ValueError, json.JSONDecodeError): + except (FileNotFoundError, KeyError, ValueError, TypeError, json.JSONDecodeError): return None -def _write_cache(cache_path: str, status: QuotaStatus) -> None: - """Write quota status to cache file. Silently logs on failure.""" +def _write_cache(cache_path: str, result: QuotaFetchResult) -> None: + """Write full-snapshot quota data to cache file. Silently logs on failure.""" try: payload = { "fetched_at": datetime.now(UTC).isoformat(), - "five_hour": { - "utilization": status.utilization, - "resets_at": status.resets_at.isoformat() if status.resets_at else None, + "windows": { + name: { + "utilization": w.utilization, + "resets_at": w.resets_at.isoformat() if w.resets_at else None, + } + for name, w in result.windows.items() + }, + "binding": { + "window_name": result.binding.window_name, + "utilization": result.binding.utilization, + "resets_at": ( + result.binding.resets_at.isoformat() if result.binding.resets_at else None + ), + "should_block": result.binding.should_block, + "effective_threshold": result.binding.effective_threshold, }, } path = Path(cache_path).expanduser() path.parent.mkdir(parents=True, exist_ok=True) - atomic_write(path, json.dumps(payload)) + write_versioned_json(path, payload, schema_version=QUOTA_CACHE_SCHEMA_VERSION) except OSError as exc: _log.warning("quota cache write failed", path=cache_path, error=str(exc)) -async def _fetch_quota(credentials_path: str) -> QuotaStatus: - """Fetch 5-hour utilization from Anthropic quota API.""" +async def _fetch_quota( + credentials_path: str, + *, + short_threshold: float, + long_threshold: float, + long_patterns: list[str], + short_enabled: bool = True, + long_enabled: bool = True, + base_url: str = _DEFAULT_BASE_URL, + _httpx_timeout: float = 10, +) -> QuotaFetchResult: + """Fetch all rate-limit windows from Anthropic quota API and identify the binding window.""" token = _read_credentials(credentials_path) - async with httpx.AsyncClient(timeout=10) as client: + async with httpx.AsyncClient(timeout=_httpx_timeout) as client: resp = await client.get( - "https://api.anthropic.com/api/oauth/usage", + f"{base_url}/api/oauth/usage", headers={ "Authorization": f"Bearer {token}", "anthropic-beta": "oauth-2025-04-20", @@ -88,18 +250,65 @@ async def _fetch_quota(credentials_path: str) -> QuotaStatus: ) resp.raise_for_status() data = resp.json() - fh = data["five_hour"] - resets_at_str = fh.get("resets_at") - resets_at = ( - datetime.fromisoformat(resets_at_str.replace("Z", "+00:00")) if resets_at_str else None + windows: dict[str, QuotaWindowEntry] = {} + for name, w in data.items(): + if isinstance(w, dict) and "utilization" in w: + raw_util = w["utilization"] + if raw_util is None: + continue + windows[name] = QuotaWindowEntry( + utilization=float(raw_util), + resets_at=_parse_resets_at(w.get("resets_at")), + ) + if not windows: + return QuotaFetchResult( + windows={}, binding=QuotaStatus(0.0, None, effective_threshold=100.0) + ) + binding = _compute_binding( + windows, + short_threshold=short_threshold, + long_threshold=long_threshold, + long_patterns=long_patterns, + short_enabled=short_enabled, + long_enabled=long_enabled, ) - return QuotaStatus( - utilization=float(fh["utilization"]), - resets_at=resets_at, + return QuotaFetchResult(windows=windows, binding=binding) + + +async def _refresh_quota_cache( + config: Any, + *, + base_url: str = _DEFAULT_BASE_URL, + _httpx_timeout: float = 10.0, +) -> None: + """Fetch fresh quota status and write to cache unconditionally. + + Unlike check_and_sleep_if_needed, this function does NOT read the existing + cache first. It always performs a live API call. Intended for use by the + periodic background refresh loop, where proactive write-before-expiry is + the goal, not avoiding redundant calls. + + Exceptions from _fetch_quota propagate to the caller for supervision. + """ + fetch_result = await _fetch_quota( + config.credentials_path, + short_threshold=config.short_window_threshold, + long_threshold=config.long_window_threshold, + long_patterns=list(config.long_window_patterns), + short_enabled=config.short_window_enabled, + long_enabled=config.long_window_enabled, + base_url=base_url, + _httpx_timeout=_httpx_timeout, ) + _write_cache(config.cache_path, fetch_result) -async def check_and_sleep_if_needed(config: Any) -> dict: +async def check_and_sleep_if_needed( + config: Any, + *, + base_url: str = _DEFAULT_BASE_URL, + _httpx_timeout: float = 10, +) -> dict: """Check quota utilization. Returns metadata indicating whether a sleep is needed. Does NOT sleep. The caller is responsible for sleeping (e.g. via run_cmd). @@ -115,24 +324,43 @@ async def check_and_sleep_if_needed(config: Any) -> dict: Returns: {"should_sleep": bool, "sleep_seconds": int, "utilization": float | None, - "resets_at": str | None} + "resets_at": str | None, "window_name": str | None} On error: adds "error" key, sets should_sleep=False. """ if not config.enabled: - return {"should_sleep": False, "sleep_seconds": 0, "utilization": None, "resets_at": None} + return { + "should_sleep": False, + "sleep_seconds": 0, + "utilization": None, + "resets_at": None, + "window_name": None, + } + + fetch_kwargs = { + "short_threshold": config.short_window_threshold, + "long_threshold": config.long_window_threshold, + "long_patterns": list(config.long_window_patterns), + "short_enabled": config.short_window_enabled, + "long_enabled": config.long_window_enabled, + "base_url": base_url, + "_httpx_timeout": _httpx_timeout, + } try: status = _read_cache(config.cache_path, config.cache_max_age) if status is None: - status = await _fetch_quota(config.credentials_path) - _write_cache(config.cache_path, status) + fetch_result = await _fetch_quota(config.credentials_path, **fetch_kwargs) + _write_cache(config.cache_path, fetch_result) + status = fetch_result.binding - if status.utilization < config.threshold: + if not status.should_block: return { "should_sleep": False, "sleep_seconds": 0, "utilization": status.utilization, "resets_at": status.resets_at.isoformat() if status.resets_at else None, + "window_name": status.window_name, + "effective_threshold": status.effective_threshold, } if status.resets_at is None: @@ -147,12 +375,15 @@ async def check_and_sleep_if_needed(config: Any) -> dict: "sleep_seconds": fallback_seconds, "utilization": status.utilization, "resets_at": None, + "window_name": status.window_name, + "effective_threshold": status.effective_threshold, "reason": "unknown_reset", } # Re-fetch for accurate resets_at before returning sleep metadata - status = await _fetch_quota(config.credentials_path) - _write_cache(config.cache_path, status) + fetch_result = await _fetch_quota(config.credentials_path, **fetch_kwargs) + _write_cache(config.cache_path, fetch_result) + status = fetch_result.binding if status.resets_at is None: fallback_seconds = max(config.buffer_seconds, 60) @@ -167,6 +398,8 @@ async def check_and_sleep_if_needed(config: Any) -> dict: "sleep_seconds": fallback_seconds, "utilization": status.utilization, "resets_at": None, + "window_name": status.window_name, + "effective_threshold": status.effective_threshold, "reason": "unknown_reset", } @@ -176,7 +409,8 @@ async def check_and_sleep_if_needed(config: Any) -> dict: _log.info( "quota threshold exceeded — caller should sleep", utilization=status.utilization, - threshold=config.threshold, + effective_threshold=status.effective_threshold, + window_name=status.window_name, sleep_seconds=sleep_secs, resets_at=status.resets_at.isoformat(), ) @@ -185,21 +419,43 @@ async def check_and_sleep_if_needed(config: Any) -> dict: "sleep_seconds": sleep_secs, "utilization": status.utilization, "resets_at": status.resets_at.isoformat(), + "window_name": status.window_name, + "effective_threshold": status.effective_threshold, } - except ( - TimeoutError, - OSError, - KeyError, - ValueError, - json.JSONDecodeError, - httpx.HTTPError, - ) as exc: - _log.warning("quota check failed — continuing without sleep", error=str(exc)) + except Exception as exc: + # Fail-open subsystem-boundary contract: never raise on quota errors. + # Split severity so operational failures stay at WARNING while programming + # bugs (AttributeError, NameError, ImportError, ...) surface at ERROR in + # dashboards instead of being masked as routine transient errors. + _operational_types = ( + TimeoutError, + OSError, + KeyError, + ValueError, + TypeError, + json.JSONDecodeError, + httpx.HTTPError, + ) + if isinstance(exc, _operational_types): + _log.warning( + "quota check failed — continuing without sleep", + error=str(exc), + error_type=type(exc).__name__, + exc_info=True, + ) + else: + _log.error( + "quota check failed (unexpected error) — continuing without sleep", + error=str(exc), + error_type=type(exc).__name__, + exc_info=True, + ) return { "should_sleep": False, "sleep_seconds": 0, "utilization": None, "resets_at": None, + "window_name": None, "error": str(exc), } diff --git a/src/autoskillit/execution/recording.py b/src/autoskillit/execution/recording.py new file mode 100644 index 0000000000..e2a59922c0 --- /dev/null +++ b/src/autoskillit/execution/recording.py @@ -0,0 +1,300 @@ +"""RecordingSubprocessRunner and ReplayingSubprocessRunner — scenario I/O for headless sessions.""" + +from __future__ import annotations + +import asyncio +import tempfile +from collections import deque +from collections.abc import Mapping +from pathlib import Path +from typing import TYPE_CHECKING, Any + +from autoskillit.core import SubprocessResult, SubprocessRunner, TerminationReason, get_logger + +if TYPE_CHECKING: + from api_simulator.claude import ScenarioPlayer, ScenarioRecorder + +logger = get_logger(__name__) + +# Environment variable names for scenario recording activation. +RECORD_SCENARIO_ENV = "RECORD_SCENARIO" +RECORD_SCENARIO_DIR_ENV = "RECORD_SCENARIO_DIR" +RECORD_SCENARIO_RECIPE_ENV = "RECORD_SCENARIO_RECIPE" +SCENARIO_STEP_NAME_ENV = "SCENARIO_STEP_NAME" + +# Environment variable names for scenario replay activation. +REPLAY_SCENARIO_ENV = "REPLAY_SCENARIO" +REPLAY_SCENARIO_DIR_ENV = "REPLAY_SCENARIO_DIR" + + +class ScenarioReplayError(Exception): + """Raised when scenario replay cannot find a session or result for a step.""" + + +def _extract_model(args: list[str]) -> str: + """Find ``--model `` in an argument list.""" + try: + idx = args.index("--model") + return args[idx + 1] + except (ValueError, IndexError): + return "" + + +class RecordingSubprocessRunner(SubprocessRunner): + """Wraps a SubprocessRunner, records each session via ScenarioRecorder. + + - **Session calls** (``pty_mode=True`` + ``SCENARIO_STEP_NAME`` in cmd env prefix): + delegates to ``ScenarioRecorder.record_step()`` which spawns the real subprocess + under PTY capture, then constructs a ``SubprocessResult`` from the cassette. + - **Non-session calls**: delegates to the inner runner, then records a summary via + ``recorder.record_non_session_step()`` if ``SCENARIO_STEP_NAME`` is present. + - **Calls without SCENARIO_STEP_NAME**: passes through to inner runner unrecorded. + + Public attribute ``recorder`` holds the :class:`ScenarioRecorder` instance. + The symmetric counterpart :class:`ReplayingSubprocessRunner` exposes ``player`` + (a ``ScenarioPlayer``). The different names reflect the different domain objects + each class wraps — the asymmetry is intentional. + """ + + def __init__( + self, + recorder: ScenarioRecorder, + inner: SubprocessRunner | None = None, + ) -> None: + self.recorder = recorder + if inner is None: + from autoskillit.execution.process import DefaultSubprocessRunner + + inner = DefaultSubprocessRunner() + self._inner = inner + + async def __call__( + self, + cmd: list[str], + *, + cwd: Path, + timeout: float, + env: Mapping[str, str] | None = None, + stale_threshold: float = 1200, + completion_marker: str = "", + session_log_dir: Path | None = None, + pty_mode: bool = False, + input_data: str | None = None, + completion_drain_timeout: float = 5.0, + linux_tracing_config: Any | None = None, + idle_output_timeout: float | None = None, + max_suppression_seconds: float | None = None, + ) -> SubprocessResult: + step_name = (env or {}).get(SCENARIO_STEP_NAME_ENV, "") + + if pty_mode and step_name: + return await self._record_session( + cmd=cmd, + step_name=step_name, + model=_extract_model(cmd), + session_log_dir=session_log_dir, + ) + + result = await self._inner( + cmd, + cwd=cwd, + timeout=timeout, + env=env, + stale_threshold=stale_threshold, + completion_marker=completion_marker, + session_log_dir=session_log_dir, + pty_mode=pty_mode, + input_data=input_data, + completion_drain_timeout=completion_drain_timeout, + linux_tracing_config=linux_tracing_config, + idle_output_timeout=idle_output_timeout, + max_suppression_seconds=max_suppression_seconds, + ) + + if step_name: + self.recorder.record_non_session_step( + step_name=step_name, + tool="run_cmd", + result_summary={ + "exit_code": result.returncode, + "stdout_head": (result.stdout or "")[:500], + }, + ) + + return result + + async def _record_session( + self, + *, + cmd: list[str], + step_name: str, + model: str, + session_log_dir: Path | None, + ) -> SubprocessResult: + """Record a session call via ScenarioRecorder.record_step().""" + try: + step_result = await asyncio.to_thread( + self.recorder.record_step, + step_name=step_name, + tool="run_skill", + args=cmd, + model=model, + session_log_dir=str(session_log_dir) if session_log_dir else None, + ) + except Exception: + logger.exception("record_step failed for step=%r", step_name) + raise + + stdout = "" + if step_result.cassette_path: + cassette_stdout = Path(step_result.cassette_path) / "stdout.jsonl" + if cassette_stdout.exists(): + stdout = cassette_stdout.read_text(encoding="utf-8") + + return SubprocessResult( + returncode=step_result.cassette_exit_code, + stdout=stdout, + stderr="", + termination=TerminationReason.NATURAL_EXIT, + pid=0, + elapsed_seconds=(step_result.cassette_duration_ms or 0) / 1000.0, + ) + + +class ReplayingSubprocessRunner(SubprocessRunner): + """Replays pre-recorded sessions by step name. + + Consumes the session map from ``ScenarioPlayer.build_session_map()`` + and non-session step results from the scenario manifest. On each call, + extracts ``SCENARIO_STEP_NAME`` from the command env prefix and + dispatches to the matching step queue. + """ + + _tmp_replay_dir: tempfile.TemporaryDirectory[str] | None + + def __init__( + self, + session_map: dict[str, deque[tuple[Any, Any]]], + non_session_results: dict[str, dict[str, Any]], + *, + player: ScenarioPlayer | None = None, + ) -> None: + self._sessions = session_map + self._non_session = non_session_results + self.player: ScenarioPlayer | None = player + self.call_log: list[tuple[str, list[str]]] = [] + self._tmp_replay_dir = None + + async def __call__( + self, + cmd: list[str], + *, + cwd: Path, + timeout: float, + env: Mapping[str, str] | None = None, + stale_threshold: float = 1200, + completion_marker: str = "", + session_log_dir: Path | None = None, + pty_mode: bool = False, + input_data: str | None = None, + completion_drain_timeout: float = 5.0, + linux_tracing_config: Any | None = None, + idle_output_timeout: float | None = None, + max_suppression_seconds: float | None = None, + ) -> SubprocessResult: + step_name = (env or {}).get(SCENARIO_STEP_NAME_ENV, "") + + if not step_name: + raise ValueError(f"SCENARIO_STEP_NAME not found in env kwarg for cmd: {cmd!r}") + + self.call_log.append((step_name, cmd)) + + if step_name in self._sessions and self._sessions[step_name]: + cli, meta = self._sessions[step_name].popleft() + result = cli.run() + return SubprocessResult( + returncode=meta.exit_code, + stdout=result.stdout, + stderr="", + termination=TerminationReason.NATURAL_EXIT, + pid=0, + elapsed_seconds=meta.duration_ms / 1000.0, + ) + + if step_name in self._non_session: + summary = self._non_session[step_name] + return SubprocessResult( + returncode=summary.get("exit_code", 0), + stdout=summary.get("stdout_head", ""), + stderr=summary.get("stderr", ""), + termination=TerminationReason.NATURAL_EXIT, + pid=0, + ) + + raise ScenarioReplayError( + f"No session or result for step {step_name!r}. " + f"Available sessions: {sorted(self._sessions.keys())}. " + f"Available non-session: {sorted(self._non_session.keys())}. " + f"Ensure the scenario was recorded with step {step_name!r} before replaying." + ) + + +def build_replay_runner(replay_dir: str) -> ReplayingSubprocessRunner: + """Build a ReplayingSubprocessRunner from a scenario directory. + + Creates a temporary output directory for the player, then parses the + scenario manifest and constructs + the deque-based session map. All domain logic for replay setup lives here + (L1) rather than in the L3 composition root. + + Args: + replay_dir: Path to a scenario directory produced by a recording run. + + Returns: + A fully-initialised ReplayingSubprocessRunner ready to replace the + DefaultSubprocessRunner in a ToolContext. + + Raises: + RuntimeError: If ``api_simulator`` is not installed. + Exception: Any exception raised by ``player.scenario()`` or + ``player.build_session_map()`` is re-raised after logging the + scenario path for context. + """ + try: + from api_simulator.claude import make_scenario_player + except ImportError as exc: + raise RuntimeError( + "REPLAY_SCENARIO is set but 'api_simulator' is not installed. " + "Install it to enable scenario replay." + ) from exc + + _tmp_replay_dir = tempfile.TemporaryDirectory(prefix="autoskillit-replay-") + tmp_replay = _tmp_replay_dir.name + + try: + player = make_scenario_player( + scenario_dir=replay_dir, + output_dir=tmp_replay, + binary_path=str(Path(tmp_replay) / "claude"), + ) + except Exception: + _tmp_replay_dir.cleanup() + raise + + try: + scenario = player.scenario() + non_session: dict[str, dict] = { + record.step_name: record.result_summary or {} + for record in scenario.step_sequence + if record.session_dir is None + } + raw_map = player.build_session_map() + except Exception: + _tmp_replay_dir.cleanup() + logger.exception("Failed to parse scenario manifest in %r", replay_dir) + raise + + session_map = {k: deque(v) for k, v in raw_map.items()} + runner = ReplayingSubprocessRunner(session_map, non_session, player=player) + runner._tmp_replay_dir = _tmp_replay_dir + return runner diff --git a/src/autoskillit/execution/remote_resolver.py b/src/autoskillit/execution/remote_resolver.py index def8e15d4b..dcc64e46ef 100644 --- a/src/autoskillit/execution/remote_resolver.py +++ b/src/autoskillit/execution/remote_resolver.py @@ -51,7 +51,17 @@ async def resolve_remote_repo( stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, ) - stdout, _ = await proc.communicate() + io_task = asyncio.ensure_future(proc.communicate()) + try: + await asyncio.wait_for(proc.wait(), timeout=15.0) + except TimeoutError: + io_task.cancel() + proc.kill() + await proc.wait() + await asyncio.gather(io_task, return_exceptions=True) + _log.warning("Timed out getting URL for remote %r in %r", remote, cwd) + continue + stdout, _ = await io_task if proc.returncode == 0: parsed = parse_github_repo(stdout.decode().strip()) if parsed: diff --git a/src/autoskillit/execution/session.py b/src/autoskillit/execution/session.py index 3307bff9f6..fe030a2fe0 100644 --- a/src/autoskillit/execution/session.py +++ b/src/autoskillit/execution/session.py @@ -43,7 +43,13 @@ ) FAILURE_SUBTYPES: frozenset[CliSubtype] = frozenset( - {CliSubtype.UNKNOWN, CliSubtype.EMPTY_OUTPUT, CliSubtype.UNPARSEABLE, CliSubtype.TIMEOUT} + { + CliSubtype.UNKNOWN, + CliSubtype.EMPTY_OUTPUT, + CliSubtype.UNPARSEABLE, + CliSubtype.TIMEOUT, + CliSubtype.IDLE_STALL, + } ) @@ -618,7 +624,11 @@ def _compute_success( return False logger.debug("compute_success_bypass", channel="CHANNEL_B", result=True) return True - case ChannelConfirmation.CHANNEL_A | ChannelConfirmation.UNMONITORED: + case ( + ChannelConfirmation.CHANNEL_A + | ChannelConfirmation.UNMONITORED + | ChannelConfirmation.DIR_MISSING + ): pass # fall through to termination dispatch case _ as _unreachable_cc: assert_never(_unreachable_cc) @@ -630,6 +640,9 @@ def _compute_success( case TerminationReason.STALE: return False + case TerminationReason.IDLE_STALL: + return False + case TerminationReason.COMPLETED: # The process was killed by our own async_kill_process_tree # (signal -15 or -9), so a non-zero returncode is expected and @@ -650,9 +663,29 @@ def _compute_success( return content_ok case TerminationReason.NATURAL_EXIT: - # The process exited on its own. A non-zero returncode is treated - # as authoritative evidence of failure — no asymmetric bypass. + # The process exited on its own. A non-zero returncode is normally + # authoritative evidence of failure — no asymmetric bypass. + # + # Post-completion kill bypass: when an external watchdog kills the + # process AFTER it finished its work (e.g. trailing async task cleanup), + # the signal is a teardown artifact. The completion marker in the result + # provides strong evidence of completion — trust it over the returncode. if returncode != 0: + if ( + session.subtype == CliSubtype.SUCCESS + and session.result.strip() + and completion_marker + and completion_marker in session.result + ): + content_ok = _check_session_content( + session, completion_marker, expected_output_patterns + ) + logger.debug( + "compute_success_natural_exit_post_completion_kill", + returncode=returncode, + content_check=content_ok, + ) + return content_ok return False content_ok = _check_session_content( session, completion_marker, expected_output_patterns @@ -798,7 +831,11 @@ def _compute_retry( needs_retry=False, ) return False, RetryReason.NONE - case ChannelConfirmation.CHANNEL_A | ChannelConfirmation.UNMONITORED: + case ( + ChannelConfirmation.CHANNEL_A + | ChannelConfirmation.UNMONITORED + | ChannelConfirmation.DIR_MISSING + ): is_anomaly = _is_kill_anomaly(session) logger.debug( "compute_retry_result", @@ -819,6 +856,12 @@ def _compute_retry( logger.debug("compute_retry_result", termination="STALE", needs_retry=False) return False, RetryReason.NONE + case TerminationReason.IDLE_STALL: + # _build_skill_result intercepts IDLE_STALL before calling _compute_retry. + # Explicit arm exists for exhaustiveness; unreachable in production. + logger.debug("compute_retry_result", termination="IDLE_STALL", needs_retry=False) + return False, RetryReason.NONE + case TerminationReason.TIMED_OUT: # Wall-clock timeout: non-retriable (permanent infrastructure limit). logger.debug("compute_retry_result", termination="TIMED_OUT", needs_retry=False) @@ -869,6 +912,7 @@ def _normalize_subtype( | CliSubtype.EMPTY_OUTPUT | CliSubtype.UNPARSEABLE | CliSubtype.TIMEOUT + | CliSubtype.IDLE_STALL ): # Failure subtypes: upward normalize to "success" when adjudicated SUCCEEDED if outcome == SessionOutcome.SUCCEEDED: @@ -971,7 +1015,7 @@ def _compute_outcome( content_state=content_state.value, channel=channel_confirmation.value, ) - case ChannelConfirmation.UNMONITORED: + case ChannelConfirmation.UNMONITORED | ChannelConfirmation.DIR_MISSING: pass # legitimate terminal failure — no channel confirmed completion case _ as unreachable_cc: assert_never(unreachable_cc) diff --git a/src/autoskillit/execution/session_log.py b/src/autoskillit/execution/session_log.py index 55057619e6..25785afd47 100644 --- a/src/autoskillit/execution/session_log.py +++ b/src/autoskillit/execution/session_log.py @@ -17,8 +17,15 @@ from pathlib import Path from typing import Any +import psutil + from autoskillit.core import atomic_write, claude_code_log_path, get_logger -from autoskillit.execution.anomaly_detection import detect_anomalies +from autoskillit.execution.anomaly_detection import detect_anomalies, detect_identity_drift +from autoskillit.execution.linux_tracing import ( + read_boot_id, + read_enrollment, + read_starttime_ticks, +) logger = get_logger(__name__) @@ -80,6 +87,7 @@ def flush_session_log( end_ts: str = "", elapsed_seconds: float | None = None, termination_reason: str = "", + kill_reason: str = "", snapshot_interval_seconds: float = 0.0, step_name: str = "", token_usage: dict[str, Any] | None = None, @@ -88,6 +96,9 @@ def flush_session_log( cli_subtype: str = "", write_path_warnings: list[str] | None = None, write_call_count: int = 0, + clone_contamination_reverted: bool = False, + tracked_comm: str | None = None, + exception_text: str = "", ) -> None: """Flush session diagnostics to disk. @@ -119,6 +130,8 @@ def flush_session_log( peak_oom_score = 0 peak_fd_ratio = 0.0 anomalies: list[dict[str, object]] = [] + _effective_tracked_comm: str | None = tracked_comm + _tracked_comm_drift: bool = False # Write proc_trace.jsonl if proc_snapshots: @@ -149,8 +162,29 @@ def flush_session_log( if ratio > peak_fd_ratio: peak_fd_ratio = ratio - # Anomaly detection + # Compute effective tracked_comm from snapshots if not provided by caller + if _effective_tracked_comm is None: + # Use modal comm value across all snapshots + comm_counts: dict[str, int] = {} + for snap in proc_snapshots: + c = snap.get("comm", "") + if c and isinstance(c, str): + comm_counts[c] = comm_counts.get(c, 0) + 1 + if comm_counts: + _effective_tracked_comm = max(comm_counts, key=lambda k: comm_counts[k]) + + # Detect identity drift: if snapshots have mixed comm values, flag it + if _effective_tracked_comm: + comms_seen = {snap.get("comm", "") for snap in proc_snapshots if snap.get("comm", "")} + if len(comms_seen) > 1: + _tracked_comm_drift = True + + # Anomaly detection (standard) anomalies = detect_anomalies(proc_snapshots, pid) + # Identity drift anomaly (post-fix immunity check) + if _effective_tracked_comm: + drift_anomalies = detect_identity_drift(proc_snapshots, _effective_tracked_comm) + anomalies.extend(drift_anomalies) # Write anomalies.jsonl (only if anomalies exist) if anomalies: @@ -197,12 +231,21 @@ def flush_session_log( "peak_oom_score": peak_oom_score, "peak_fd_ratio": round(peak_fd_ratio, 3), "termination_reason": termination_reason, + "kill_reason": kill_reason, "write_path_warnings": effective_write_path_warnings, "write_call_count": write_call_count, + "clone_contamination_reverted": clone_contamination_reverted, + # Tracer target resolution fields (issue #806) + "tracked_comm": _effective_tracked_comm, + "tracked_comm_drift": _tracked_comm_drift, + "tracer_target_resolution_version": 2, } summary_path = session_dir / "summary.json" atomic_write(summary_path, json.dumps(summary, sort_keys=True, indent=2) + "\n") + if exception_text: + atomic_write(session_dir / "crash_exception.txt", exception_text) + # Write per-session telemetry files when step_name is provided if step_name and token_usage is not None: tu_data = { @@ -253,6 +296,8 @@ def flush_session_log( "input_tokens": token_usage.get("input_tokens", 0) if token_usage else 0, "output_tokens": token_usage.get("output_tokens", 0) if token_usage else 0, "write_call_count": write_call_count, + "tracked_comm": _effective_tracked_comm, + "tracked_comm_drift": _tracked_comm_drift, } index_path = log_root / "sessions.jsonl" with index_path.open("a") as f: @@ -313,6 +358,7 @@ def recover_crashed_sessions(tmpfs_path: str = "/dev/shm", log_dir: str = "") -> return 0 count = 0 + current_boot_id = read_boot_id() for trace_file in sorted(tmpfs.glob("autoskillit_trace_*.jsonl")): # Skip files modified within the last 30 seconds — may be active try: @@ -322,7 +368,35 @@ def recover_crashed_sessions(tmpfs_path: str = "/dev/shm", log_dir: str = "") -> if age_seconds < 30: continue - # Read snapshots + # Extract PID from filename: autoskillit_trace_{pid}.jsonl + try: + pid = int(trace_file.stem.split("_")[-1]) + except (ValueError, IndexError): + pid = -1 + + # Gate 1: Enrollment sidecar must exist — no sidecar means alien/test file + enrollment_path = tmpfs / f"autoskillit_enrollment_{pid}.json" + enrollment = read_enrollment(enrollment_path) + if enrollment is None: + logger.debug("Skipping %s: no enrollment sidecar", trace_file.name) + continue + + # Gate 2: Boot ID must match current boot — mismatch means pre-reboot stale file + if current_boot_id and enrollment.boot_id and enrollment.boot_id != current_boot_id: + logger.debug("Skipping %s: boot_id mismatch", trace_file.name) + trace_file.unlink(missing_ok=True) + enrollment_path.unlink(missing_ok=True) + continue + + # Gate 3: PID liveness + starttime_ticks identity + if psutil.pid_exists(pid): + current_ticks = read_starttime_ticks(pid) + if current_ticks is not None and current_ticks == enrollment.starttime_ticks: + logger.debug("Skipping %s: PID %d still alive", trace_file.name, pid) + continue + # PID recycled — original process is gone, treat as crash + + # All gates passed — read snapshots and emit crashed row snapshots: list[dict[str, object]] = [] try: for line in trace_file.read_text().splitlines(): @@ -333,11 +407,27 @@ def recover_crashed_sessions(tmpfs_path: str = "/dev/shm", log_dir: str = "") -> except OSError: continue - # Extract PID from filename: autoskillit_trace_{pid}.jsonl - try: - pid = int(trace_file.stem.split("_")[-1]) - except (ValueError, IndexError): - pid = 0 + # Gate 4: comm-based alien file rejection (issue #806 immunity) + # Use enrollment.comm as the expected comm (schema_version=2 records carry the + # enrolled binary name). Pre-fix schema_version=1 records have comm="" — skip + # the check for those to preserve recovery of legitimate crash data. + _is_alien = False + expected_comm = enrollment.comm + if snapshots and expected_comm: + first_comm = snapshots[0].get("comm", "") + if first_comm and isinstance(first_comm, str) and first_comm != expected_comm: + logger.debug( + "Skipping %s: alien comm '%s' (expected '%s')", + trace_file.name, + first_comm, + expected_comm, + ) + _is_alien = True + if _is_alien: + # Delete the alien trace — don't leave it to confuse future recovery runs + trace_file.unlink(missing_ok=True) + enrollment_path.unlink(missing_ok=True) + continue # Compute start_ts from file mtime try: @@ -363,10 +453,8 @@ def recover_crashed_sessions(tmpfs_path: str = "/dev/shm", log_dir: str = "") -> logger.debug("recover_crashed_sessions: failed to finalize %s", trace_file) continue - try: - trace_file.unlink() - except OSError: - pass + trace_file.unlink(missing_ok=True) + enrollment_path.unlink(missing_ok=True) count += 1 diff --git a/src/autoskillit/hook_registry.py b/src/autoskillit/hook_registry.py index b177773fe1..7cdc3c7028 100644 --- a/src/autoskillit/hook_registry.py +++ b/src/autoskillit/hook_registry.py @@ -6,8 +6,12 @@ from __future__ import annotations +import hashlib +import json +from collections.abc import Iterator from dataclasses import dataclass, field -from typing import Literal +from pathlib import Path +from typing import Literal, NamedTuple from autoskillit.core import pkg_root @@ -19,6 +23,8 @@ class HookDef: matcher: str = "" event_type: Literal["PreToolUse", "PostToolUse", "SessionStart"] = "PreToolUse" scripts: list[str] = field(default_factory=list) + timeout_seconds: int | None = None + session_scope: Literal["any", "headless_only", "interactive_only"] = "any" def __post_init__(self) -> None: if self.event_type != "SessionStart" and not self.matcher: @@ -30,7 +36,7 @@ def __post_init__(self) -> None: HOOK_REGISTRY: list[HookDef] = [ HookDef( matcher="mcp__.*autoskillit.*__run_skill.*", - scripts=["skill_cmd_check.py", "quota_check.py", "skill_command_guard.py"], + scripts=["skill_cmd_guard.py", "quota_guard.py", "skill_command_guard.py"], ), HookDef( matcher="mcp__.*autoskillit.*__remove_clone", @@ -39,6 +45,13 @@ def __post_init__(self) -> None: HookDef( matcher=r"mcp__.*autoskillit.*__open_kitchen.*", scripts=["open_kitchen_guard.py"], + timeout_seconds=5, + ), + HookDef( + matcher="AskUserQuestion", + scripts=["ask_user_question_guard.py"], + timeout_seconds=5, + session_scope="headless_only", ), HookDef( matcher=r"mcp__.*autoskillit.*__merge_worktree", @@ -52,40 +65,226 @@ def __post_init__(self) -> None: matcher=r"mcp__.*autoskillit.*__run_cmd", scripts=["unsafe_install_guard.py"], ), + HookDef( + matcher=r"Write|Edit", + scripts=["generated_file_write_guard.py"], + ), HookDef( matcher=r"mcp__.*autoskillit.*__(run_skill|run_cmd|run_python).*", scripts=["headless_orchestration_guard.py"], + session_scope="headless_only", ), HookDef( event_type="PostToolUse", matcher="mcp__.*autoskillit.*", - scripts=["pretty_output.py"], + scripts=["pretty_output_hook.py"], ), HookDef( event_type="PostToolUse", matcher=r"mcp__.*autoskillit.*__run_skill.*", - scripts=["token_summary_appender.py"], + scripts=["token_summary_hook.py", "quota_post_hook.py"], ), HookDef( event_type="SessionStart", - scripts=["session_start_reminder.py"], + scripts=["session_start_hook.py"], ), ] +HOOKS_DIR: Path = pkg_root() / "hooks" + +RETIRED_SCRIPT_BASENAMES: frozenset[str] = frozenset( + { + "quota_check.py", + "skill_cmd_check.py", + "quota_post_check.py", + "pretty_output.py", + "token_summary_appender.py", + "session_start_reminder.py", + # Append any future retired basenames here, atomically with the rename commit. + } +) + + +def _canonical_registry_payload( + registry: list[HookDef], + retired: frozenset[str], +) -> str: + registry_rows = sorted( + [ + { + "event_type": h.event_type, + "matcher": h.matcher, + "scripts": list(h.scripts), + "session_scope": h.session_scope, + "timeout_seconds": h.timeout_seconds, + } + for h in registry + ], + key=lambda row: (row["event_type"], row["matcher"], tuple(row["scripts"])), # type: ignore[arg-type] + ) + return json.dumps( + {"registry": registry_rows, "retired": sorted(retired)}, + sort_keys=True, + separators=(",", ":"), + ) + + +def compute_registry_hash(registry: list[HookDef], retired: frozenset[str]) -> str: + """Compute a stable sha256 over HOOK_REGISTRY + RETIRED_SCRIPT_BASENAMES.""" + payload = _canonical_registry_payload(registry, retired) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +HOOK_REGISTRY_HASH: str = compute_registry_hash(HOOK_REGISTRY, RETIRED_SCRIPT_BASENAMES) + + +def load_hooks_json_hash(path: Path) -> str | None: + """Read the _autoskillit_registry_hash from a hooks.json file.""" + try: + data = json.loads(path.read_text(encoding="utf-8")) + val = data.get("_autoskillit_registry_hash") + return str(val) if val else None + except (OSError, json.JSONDecodeError, AttributeError): + return None + + +def _build_hook_entry(hook_def: HookDef, hook_commands: list[dict]) -> dict: + """Build the per-entry dict for a hook definition. + + SessionStart entries omit the 'matcher' key; all others include it. + This is the single authoritative formatter for both hooks.json and + settings.json generation. + """ + if hook_def.event_type == "SessionStart": + return {"hooks": hook_commands} + return {"matcher": hook_def.matcher, "hooks": hook_commands} + def generate_hooks_json() -> dict: """Generate the hooks.json structure from HOOK_REGISTRY using absolute paths.""" - hooks_dir = pkg_root() / "hooks" by_event: dict[str, list] = {} for hook_def in HOOK_REGISTRY: hook_commands = [ - {"type": "command", "command": f"python3 {hooks_dir / script}"} + { + "type": "command", + "command": f"python3 {HOOKS_DIR / script}", + **( + {"timeout": hook_def.timeout_seconds} + if hook_def.timeout_seconds is not None + else {} + ), + } for script in hook_def.scripts ] - entry: dict[str, object] - if hook_def.event_type == "SessionStart": - entry = {"hooks": hook_commands} - else: - entry = {"matcher": hook_def.matcher, "hooks": hook_commands} - by_event.setdefault(hook_def.event_type, []).append(entry) - return {"hooks": by_event} + by_event.setdefault(hook_def.event_type, []).append( + _build_hook_entry(hook_def, hook_commands) + ) + return {"hooks": by_event, "_autoskillit_registry_hash": HOOK_REGISTRY_HASH} + + +# --------------------------------------------------------------------------- +# Hook diagnostic utilities — shared between cli/ and server/ (both L3). +# Placed here (package root, L0-accessible) to avoid L3-to-L3 peer imports. +# --------------------------------------------------------------------------- + + +def _claude_settings_path(scope: str) -> Path: + """Return the Claude Code settings.json path for the given scope.""" + if scope == "user": + return Path.home() / ".claude" / "settings.json" + return Path.cwd() / ".claude" / "settings.json" + + +def iter_all_scope_paths( + project_root: Path | None = None, +) -> Iterator[tuple[str, Path]]: + """Yield (scope_label, settings_path) for all Claude Code settings scopes. + + Always yields the user scope. Project and local scopes are yielded only + when project_root is provided AND the corresponding .claude/ directory exists. + """ + yield ("user", Path.home() / ".claude" / "settings.json") + if project_root is not None: + claude_dir = project_root / ".claude" + if claude_dir.is_dir(): + yield ("project", claude_dir / "settings.json") + local_path = claude_dir / "settings.local.json" + if local_path.exists(): + yield ("local", local_path) + + +def _load_settings_data(settings_path: Path) -> dict: + """Read and parse settings.json; return empty dict on any error.""" + if settings_path.exists(): + try: + return json.loads(settings_path.read_text()) + except (OSError, json.JSONDecodeError): + pass + return {} + + +def canonical_script_basenames() -> frozenset[str]: + """Return the set of all known autoskillit hook script basenames.""" + return frozenset(s for h in HOOK_REGISTRY for s in h.scripts) + + +def _is_own_hook(command: str) -> bool: + """Check if a hook command belongs to autoskillit (any format).""" + if "autoskillit" in command: + return True + known = canonical_script_basenames() | RETIRED_SCRIPT_BASENAMES + return any(command.endswith(script) or f"/{script}" in command for script in known) + + +def _extract_script_basenames(hooks_dict: dict) -> set[str]: + """Extract autoskillit hook script basenames from a hooks dict. + + Filters to autoskillit-owned commands only, then normalizes + to bare script filenames for installation-path-agnostic comparison. + """ + return { + Path(cmd.split()[-1]).name + for event_entries in hooks_dict.values() + if isinstance(event_entries, list) + for entry in event_entries + for hook in entry.get("hooks", []) + if (cmd := hook.get("command", "")) and _is_own_hook(cmd) + } + + +class HookDriftResult(NamedTuple): + """Bidirectional hook drift counts.""" + + missing: int # canonical − deployed (hooks not yet deployed) + orphaned: int # deployed − canonical (ghost hooks, fatal ENOENT risk) + orphaned_cmds: frozenset[str] = frozenset() + + +def _count_hook_registry_drift(settings_path: Path) -> HookDriftResult: + """Return bidirectional hook drift counts between canonical and deployed settings.json.""" + deployed_data = _load_settings_data(settings_path) + canonical_basenames = canonical_script_basenames() + deployed_basenames = _extract_script_basenames(deployed_data.get("hooks", {})) + orphaned = deployed_basenames - canonical_basenames + return HookDriftResult( + missing=len(canonical_basenames - deployed_basenames), + orphaned=len(orphaned), + orphaned_cmds=frozenset(orphaned), + ) + + +def find_broken_hook_scripts(settings_path: Path) -> list[str]: + """Return list of hook commands whose script files do not exist on disk.""" + data = _load_settings_data(settings_path) + broken: list[str] = [] + for event_type in ("PreToolUse", "PostToolUse", "SessionStart"): + for entry in data.get("hooks", {}).get(event_type, []): + for hook in entry.get("hooks", []): + cmd = hook.get("command", "") + if not _is_own_hook(cmd): # skip non-autoskillit hooks + continue + parts = cmd.split() + if len(parts) >= 2: + if not Path(parts[-1]).is_file(): + broken.append(cmd) + return broken diff --git a/src/autoskillit/hooks/__init__.py b/src/autoskillit/hooks/__init__.py index a5af63c8b9..15a36cbdc8 100644 --- a/src/autoskillit/hooks/__init__.py +++ b/src/autoskillit/hooks/__init__.py @@ -1,5 +1,10 @@ """Hook scripts (PreToolUse and PostToolUse) for AutoSkillit.""" -from autoskillit.hook_registry import HOOK_REGISTRY, HookDef, generate_hooks_json +from autoskillit.hook_registry import ( + HOOK_REGISTRY, + HookDef, + generate_hooks_json, +) +from autoskillit.hooks._fmt_primitives import _HOOK_CONFIG_PATH_COMPONENTS -__all__ = ["HOOK_REGISTRY", "HookDef", "generate_hooks_json"] +__all__ = ["HOOK_REGISTRY", "HookDef", "_HOOK_CONFIG_PATH_COMPONENTS", "generate_hooks_json"] diff --git a/src/autoskillit/hooks/_fmt_execution.py b/src/autoskillit/hooks/_fmt_execution.py new file mode 100644 index 0000000000..bd29e7ae79 --- /dev/null +++ b/src/autoskillit/hooks/_fmt_execution.py @@ -0,0 +1,210 @@ +"""Execution-tool formatters for the pretty_output split. + +Hosts the per-tool formatters for ``run_skill``, ``run_cmd``, ``test_check``, +and ``merge_worktree``. Stdlib-only at runtime. +""" + +from __future__ import annotations + +from _fmt_primitives import ( # type: ignore[import-not-found] + _CHECK_MARK, + _CROSS_MARK, + _fmt_tokens, +) + + +def _format_exit_code_line(data: dict) -> str: + """Return the formatted exit_code line, annotated with kill_reason when present. + + Legacy payloads without kill_reason render as bare exit_code values so that + JSON-line replay of old session logs still parses correctly. + """ + exit_code = data.get("exit_code", "") + kill_reason = data.get("kill_reason") + if kill_reason is None: + # Legacy payload — no annotation + return f"exit_code: {exit_code}" + if kill_reason == "kill_after_completion": + return f"exit_code: {exit_code} (infra-terminated after completion — grace exceeded)" + if kill_reason == "infra_kill": + termination_reason = data.get("termination_reason") or data.get("subtype") or "" + if termination_reason: + return f"exit_code: {exit_code} (infra-killed: {termination_reason})" + return f"exit_code: {exit_code} (infra-killed)" + # natural_exit or any unknown value → bare + return f"exit_code: {exit_code}" + + +def _fmt_run_skill(data: dict, pipeline: bool) -> str: + """Format run_skill result as Markdown-KV.""" + success = data.get("success", False) + subtype = data.get("subtype", "") + mark = _CHECK_MARK if success else _CROSS_MARK + status = subtype if subtype else ("OK" if success else "FAIL") + + if pipeline: + # Compact format for pipeline mode + header = f"run_skill: {'OK' if success else 'FAIL'} [{status}]" + lines = [header] + session_id = data.get("session_id", "") + if session_id: + lines.append(f"session_id: {session_id}") + lines.append(_format_exit_code_line(data)) + lines.append(f"needs_retry: {data.get('needs_retry', False)}") + if data.get("retry_reason") and data["retry_reason"] != "none": + lines.append(f"retry_reason: {data['retry_reason']}") + worktree = data.get("worktree_path", "") + if worktree: + lines.append(f"worktree_path: {worktree}") + result = data.get("result", "") + if result: + lines.append(f"\nresult:\n{result}") + stderr = (data.get("stderr") or "").strip() + if stderr: + lines.extend(["", "### stderr", stderr]) + return "\n".join(lines) + + # Interactive mode + lines = [f"## run_skill {mark} {status}", ""] + lines.append(f"success: {success}") + session_id = data.get("session_id", "") + if session_id: + lines.append(f"session_id: {session_id}") + lines.append(f"subtype: {subtype}") + lines.append(_format_exit_code_line(data)) + lines.append(f"needs_retry: {data.get('needs_retry', False)}") + retry_reason = data.get("retry_reason", "none") + if retry_reason and retry_reason != "none": + lines.append(f"retry_reason: {retry_reason}") + worktree = data.get("worktree_path", "") + if worktree: + lines.append(f"worktree_path: {worktree}") + token_usage = data.get("token_usage") + if isinstance(token_usage, dict): + lines.append("") + lines.append(f"tokens_uncached: {_fmt_tokens(token_usage.get('input_tokens'))}") + lines.append(f"tokens_out: {_fmt_tokens(token_usage.get('output_tokens'))}") + cr = token_usage.get("cache_read_input_tokens", 0) + if cr: + lines.append(f"tokens_cache_read: {_fmt_tokens(cr)}") + cw = token_usage.get("cache_creation_input_tokens", 0) + if cw: + lines.append(f"tokens_cache_write: {_fmt_tokens(cw)}") + result = data.get("result", "") + if result: + lines.extend(["", "### Result", result]) + stderr = data.get("stderr", "") + if stderr: + lines.extend(["", "### stderr", stderr]) + return "\n".join(lines) + + +def _fmt_run_cmd(data: dict, pipeline: bool) -> str: + """Format run_cmd result as Markdown-KV.""" + success = data.get("success", False) + exit_code = data.get("exit_code", "") + mark = _CHECK_MARK if success else _CROSS_MARK + + if pipeline: + lines = [ + f"run_cmd: {'OK' if success else 'FAIL'} [{exit_code}]", + f"success: {success}", + f"exit_code: {exit_code}", + ] + stdout = (data.get("stdout") or "").strip() + if stdout: + lines.extend(["", "### stdout", stdout]) + stderr = (data.get("stderr") or "").strip() + if stderr: + lines.extend(["", "### stderr", stderr]) + return "\n".join(lines) + + lines = [ + f"## run_cmd {mark} {'OK' if success else 'FAIL'}", + "", + f"success: {success}", + f"exit_code: {exit_code}", + ] + stdout = (data.get("stdout") or "").strip() + if stdout: + lines.extend(["", "### stdout", stdout]) + stderr = (data.get("stderr") or "").strip() + if stderr: + lines.extend(["", "### stderr", stderr]) + return "\n".join(lines) + + +def _filter_pytest_output(raw: str) -> str: + """Filter pytest boilerplate, keeping only failure-relevant lines.""" + boilerplate_prefixes = ( + "platform ", + "rootdir:", + "configfile:", + "plugins:", + "collecting ", + "collected ", + "cacheprovider", + ) + boilerplate_exact = {"", " "} + lines = raw.splitlines() + filtered = [] + for line in lines: + stripped = line.strip() + if stripped in boilerplate_exact: + continue + if any(stripped.startswith(p) for p in boilerplate_prefixes): + continue + filtered.append(line) + return "\n".join(filtered) + + +def _fmt_test_check(data: dict, _pipeline: bool) -> str: + """Format test_check result as Markdown-KV.""" + passed = data.get("passed", False) + mark = _CHECK_MARK if passed else _CROSS_MARK + status = "PASS" if passed else "FAIL" + lines = [f"## test_check {mark} {status}", "", f"passed: {passed}"] + stdout = data.get("stdout", "") + if stdout: + filtered = _filter_pytest_output(stdout) + lines.extend(["", "### stdout", filtered]) + stderr = data.get("stderr", "") + if stderr: + lines.extend(["", "### stderr", stderr]) + error = data.get("error", "") + if error: + lines.extend(["", f"error: {error}"]) + return "\n".join(lines) + + +def _fmt_merge_worktree(data: dict, _pipeline: bool) -> str: + """Format merge_worktree result as Markdown-KV.""" + succeeded = data.get("merge_succeeded") + has_error = "error" in data + + if succeeded: + mark = _CHECK_MARK + status = "OK" + elif has_error: + mark = _CROSS_MARK + status = "FAIL" + else: + mark = _CROSS_MARK + status = "UNKNOWN" + + lines = [f"## merge_worktree {mark} {status}", ""] + for key, val in data.items(): + if isinstance(val, list): + lines.append(f"{key}:") + for item in val: + lines.append(f" - {item}") + elif isinstance(val, dict): + continue + elif key == "stderr": + continue + else: + lines.append(f"{key}: {val}") + stderr = (data.get("stderr") or "").strip() + if stderr: + lines.extend(["", "### stderr", stderr]) + return "\n".join(lines) diff --git a/src/autoskillit/hooks/_fmt_primitives.py b/src/autoskillit/hooks/_fmt_primitives.py new file mode 100644 index 0000000000..3b46309911 --- /dev/null +++ b/src/autoskillit/hooks/_fmt_primitives.py @@ -0,0 +1,60 @@ +"""Shared primitives for the pretty_output_hook PostToolUse formatter split. + +Stdlib-only at runtime — runs under any Python interpreter without the +autoskillit package, so the four ``_fmt_*`` modules and ``pretty_output_hook.py`` +all import directly from this module without going through any L1+ layer. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +# Keep in sync with HOOK_DIR_COMPONENTS + HOOK_CONFIG_FILENAME in _hook_settings.py +# (stdlib-only boundary prevents a shared import). +_HOOK_CONFIG_PATH_COMPONENTS = (".autoskillit", "temp", ".hook_config.json") + + +@dataclass(frozen=True) +class _DictPayload: + data: dict[str, Any] + + +@dataclass(frozen=True) +class _PlainTextPayload: + text: str + + +_Payload = _DictPayload | _PlainTextPayload +_CHECK_MARK = "\u2713" # ✓ +_CROSS_MARK = "\u2717" # ✗ +_WARN_MARK = "\u26a0" # ⚠ + + +def _is_pipeline_mode() -> bool: + """Check if kitchen is open (pipeline mode) by hook config file presence.""" + config_path = Path.cwd().joinpath(*_HOOK_CONFIG_PATH_COMPONENTS) + return config_path.is_file() + + +def _fmt_tokens(n: int | None) -> str: + """Format a token count as compact string (45.2k, 1.2M, etc.).""" + if n is None or n == 0: + return "0" + if not isinstance(n, (int, float)): + return "0" + if n >= 1_000_000: + return f"{n / 1_000_000:.1f}M" + if n >= 1_000: + return f"{n / 1_000:.1f}k" + return str(n) + + +def _extract_tool_short_name(tool_name: str) -> str: + """Extract short tool name from full MCP tool name. + + "mcp__plugin_autoskillit_autoskillit__run_skill" -> "run_skill" + Falls back to the full tool_name if no __ separator found. + """ + return tool_name.rsplit("__", 1)[-1] if "__" in tool_name else tool_name diff --git a/src/autoskillit/hooks/_fmt_recipe.py b/src/autoskillit/hooks/_fmt_recipe.py new file mode 100644 index 0000000000..27abd796b9 --- /dev/null +++ b/src/autoskillit/hooks/_fmt_recipe.py @@ -0,0 +1,195 @@ +"""Recipe-tool formatters for the pretty_output split. + +Hosts the per-tool formatters for ``load_recipe``, ``open_kitchen``, and +``list_recipes`` along with their field-coverage contracts. Stdlib-only at +runtime. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any + +from _fmt_primitives import ( # type: ignore[import-not-found] + _CHECK_MARK, + _CROSS_MARK, + _WARN_MARK, +) + +if TYPE_CHECKING: + from autoskillit.recipe import ListRecipesResult, LoadRecipeResult + + +# Field coverage contract for _fmt_load_recipe ↔ LoadRecipeResult +_FMT_LOAD_RECIPE_RENDERED: frozenset[str] = frozenset( + { + "valid", + "suggestions", + "error", + "content", + "ingredients_table", + } +) +_FMT_LOAD_RECIPE_SUPPRESSED: frozenset[str] = frozenset( + { + "greeting", # delivered via positional CLI arg, not MCP response + "diagram", # user sees it in terminal preview; agent doesn't need it + "kitchen_rules", # already in the YAML content + "requires_packs", # internal field; used for skill gating, not display + } +) + +# Maps derived-display field name → source field name in LoadRecipeResult. +# When a derived field is present in a response, the formatter strips its +# corresponding source block from the source field to prevent duplicate display. +# All entries must map to "content" — only content-derived fields require +# ingredients-block stripping. Non-content source fields are not supported here. +# +# HOW TO USE: When adding a new field to _FMT_LOAD_RECIPE_RENDERED, ask: +# "Is this field a re-rendering of content already in another RENDERED field?" +# If yes, add an entry here: {new_derived_field: "content"}. +# The augmented field coverage test will enforce this declaration. +_LOAD_RECIPE_CONTENT_DERIVED_FROM: dict[str, str] = { + "ingredients_table": "content", # GFM table derived from the ingredients: block in content +} + + +def _strip_yaml_ingredients_block(yaml_text: str) -> str: + """Remove the top-level `ingredients:` block from YAML text. + + Called by _fmt_recipe_body() when ingredients_table is present, so the + RECIPE block does not repeat the TABLE block. Operates line-by-line: + drops the `ingredients:` key and all its indented children until a + non-indented line signals the next top-level key. Preserves all other + top-level keys (steps, kitchen_rules, description, etc.) unchanged. + """ + lines = yaml_text.splitlines(keepends=True) + result: list[str] = [] + in_ingredients = False + for line in lines: + if line.startswith("ingredients:"): + in_ingredients = True + continue + if in_ingredients: + if line and not line[0].isspace(): + # First non-indented non-empty line = next top-level key + in_ingredients = False + result.append(line) + # else: still inside the ingredients block — skip + else: + result.append(line) + return "".join(result) + + +def _fmt_recipe_body(data: Mapping[str, Any]) -> list[str]: + """Shared recipe content rendering for load_recipe and open_kitchen+recipe.""" + lines: list[str] = [] + content = data.get("content") + if content: + # When a derived field is present, strip its source block from content + # to prevent duplicate display. The derivation map drives this automatically. + display_content = content + for derived_field in _LOAD_RECIPE_CONTENT_DERIVED_FROM: + if data.get(derived_field): + display_content = _strip_yaml_ingredients_block(display_content) + lines.append("\n--- RECIPE ---") + lines.append(display_content) + lines.append("--- END RECIPE ---") + ing_table = data.get("ingredients_table") + if ing_table: + lines.append("\n--- INGREDIENTS TABLE (display this verbatim to the user) ---") + lines.append(ing_table) + lines.append("--- END TABLE ---") + suggestions = data.get("suggestions") or [] + errors = [ + f for f in suggestions if isinstance(f, dict) and f.get("severity") in ("error", "warning") + ] + if errors: + lines.append(f"\n{len(errors)} finding(s)") + return lines + + +def _fmt_load_recipe(data: LoadRecipeResult, pipeline: bool) -> str: + """Format load_recipe result as Markdown-KV.""" + if not isinstance(data, dict): + return "## load_recipe\n\n_(unexpected response type)_" + + error = data.get("error") + if error: + return f"## load_recipe {_CROSS_MARK}\n\n**Error:** {error}" + + valid = data.get("valid", True) + mark = _CHECK_MARK if valid else _CROSS_MARK + lines: list[str] = [f"## load_recipe {mark}"] + lines.extend(_fmt_recipe_body(data)) + return "\n".join(lines) + + +# Field coverage contract for _fmt_list_recipes ↔ ListRecipesResult +_FMT_LIST_RECIPES_RENDERED: frozenset[str] = frozenset( + { + "recipes", + "count", + "errors", + } +) +_FMT_LIST_RECIPES_SUPPRESSED: frozenset[str] = frozenset() + +# Field coverage contract for per-item recipe entries ↔ RecipeListItem +_FMT_RECIPE_LIST_ITEM_RENDERED: frozenset[str] = frozenset( + { + "name", + "description", + "summary", + "source", + } +) +_FMT_RECIPE_LIST_ITEM_SUPPRESSED: frozenset[str] = frozenset() + + +def _fmt_open_kitchen(data: dict[str, Any], pipeline: bool) -> str: + """Format open_kitchen combined kitchen+recipe result.""" + version = data.get("version", "") + + error = data.get("error") + if error: + return f"## open_kitchen {_CROSS_MARK} v{version}\n\nKitchen open. Recipe error: {error}" + + valid = data.get("valid", True) + mark = _CHECK_MARK if valid else _CROSS_MARK + lines: list[str] = [f"## open_kitchen {mark} v{version}"] + lines.extend(_fmt_recipe_body(data)) + return "\n".join(lines) + + +def _fmt_open_kitchen_plain_text(text: str, _pipeline: bool) -> str: + """Format open_kitchen plain-text response (no recipe attached).""" + return f"## open_kitchen\n\n{text}" + + +def _fmt_list_recipes(data: ListRecipesResult, pipeline: bool) -> str: + """Format list_recipes result as Markdown-KV.""" + if not isinstance(data, dict): + return "## list_recipes\n\n_(unexpected response type)_" + lines: list[str] = ["## list_recipes"] + recipes = data.get("recipes") or [] + for recipe in recipes[:30]: + if isinstance(recipe, dict): + name = recipe.get("name", "?") + desc = recipe.get("description", "") + summary = recipe.get("summary", "") + source = recipe.get("source", "") + source_tag = f" [{source}]" if source else "" + lines.append(f" - {name}{source_tag}: {desc}" if desc else f" - {name}{source_tag}") + if summary: + lines.append(f" {summary}") + else: + lines.append(f" - {recipe}") + if len(recipes) > 30: + lines.append(f" ... and {len(recipes) - 30} more") + count = data.get("count", len(recipes)) + lines.append(f"\n{count} recipe(s) available") + errors = data.get("errors") or [] + if errors: + lines.append(f"\n{_WARN_MARK} {len(errors)} recipe file(s) had load errors") + return "\n".join(lines) diff --git a/src/autoskillit/hooks/_fmt_status.py b/src/autoskillit/hooks/_fmt_status.py new file mode 100644 index 0000000000..c3d5006676 --- /dev/null +++ b/src/autoskillit/hooks/_fmt_status.py @@ -0,0 +1,134 @@ +"""Status/summary tool formatters for the pretty_output split. + +Hosts the per-tool formatters for ``get_token_summary``, ``get_timing_summary``, +``kitchen_status``, and ``clone_repo``. Stdlib-only at runtime. +""" + +from __future__ import annotations + +from _fmt_primitives import ( # type: ignore[import-not-found] + _CHECK_MARK, + _CROSS_MARK, + _WARN_MARK, + _fmt_tokens, +) + + +def _fmt_get_token_summary(data: dict, _pipeline: bool) -> str: + """Format get_token_summary compact Markdown-KV output (JSON payload only).""" + lines = ["## token_summary", ""] + steps = data.get("steps", []) + for step in steps: + name = step.get("step_name", "?") + count = step.get("invocation_count", 1) + inp = _fmt_tokens(step.get("input_tokens", 0)) + out = _fmt_tokens(step.get("output_tokens", 0)) + cache_rd = _fmt_tokens(step.get("cache_read_input_tokens", 0)) + cache_wr = _fmt_tokens(step.get("cache_creation_input_tokens", 0)) + wc = step.get("wall_clock_seconds", step.get("elapsed_seconds", 0.0)) + lines.append( + f"{name} x{count} [uc:{inp} out:{out} cr:{cache_rd} cw:{cache_wr} t:{wc:.1f}s]" + ) + total = data.get("total", {}) + if total: + lines.append("") + lines.append(f"total_uncached: {_fmt_tokens(total.get('input_tokens', 0))}") + lines.append(f"total_out: {_fmt_tokens(total.get('output_tokens', 0))}") + lines.append(f"total_cache_read: {_fmt_tokens(total.get('cache_read_input_tokens', 0))}") + lines.append( + f"total_cache_write: {_fmt_tokens(total.get('cache_creation_input_tokens', 0))}" + ) + mcp = data.get("mcp_responses", {}) + mcp_total = mcp.get("total", {}) + if mcp_total: + lines.append("") + lines.append(f"mcp_invocations: {mcp_total.get('total_invocations', 0)}") + est_tokens = mcp_total.get("total_estimated_response_tokens", 0) + lines.append(f"mcp_response_tokens: ~{_fmt_tokens(est_tokens)}") + return "\n".join(lines) + + +def _fmt_get_timing_summary(data: dict, _pipeline: bool) -> str: + """Format get_timing_summary compact Markdown-KV output (JSON payload only). + + Each step becomes: name xN [dur:Xs] + """ + lines = ["## timing_summary", ""] + steps = data.get("steps", []) + for step in steps: + name = step.get("step_name", "?") + count = step.get("invocation_count", 1) + secs = step.get("total_seconds", 0.0) + if secs < 60: + dur = f"{secs:.0f}s" + elif secs < 3600: + m, s = divmod(int(secs), 60) + dur = f"{m}m {s}s" + else: + h, remainder = divmod(int(secs), 3600) + m = remainder // 60 + dur = f"{h}h {m}m" + lines.append(f"{name} x{count} [dur:{dur}]") + total = data.get("total", {}) + if total: + total_secs = total.get("total_seconds", 0.0) + if total_secs < 60: + total_dur = f"{total_secs:.0f}s" + elif total_secs < 3600: + m, s = divmod(int(total_secs), 60) + total_dur = f"{m}m {s}s" + else: + h, remainder = divmod(int(total_secs), 3600) + m = remainder // 60 + total_dur = f"{h}h {m}m" + lines.append("") + lines.append(f"total: {total_dur}") + return "\n".join(lines) + + +def _fmt_kitchen_status(data: dict, _pipeline: bool) -> str: + """Format kitchen_status as Markdown-KV.""" + success = not data.get("error") + mark = _CHECK_MARK if success else _CROSS_MARK + enabled = data.get("tools_enabled", False) + gate_str = "OPEN" if enabled else "CLOSED" + lines = [f"## kitchen_status {mark} {gate_str}", ""] + for key in ( + "package_version", + "plugin_json_version", + "versions_match", + "tools_enabled", + "token_usage_verbosity", + "quota_guard_enabled", + "github_token_configured", + "github_default_repo", + ): + if key in data: + lines.append(f"{key}: {data[key]}") + warning = data.get("warning") + if warning: + lines.extend(["", f"warning: {warning}"]) + return "\n".join(lines) + + +def _fmt_clone_repo(data: dict, _pipeline: bool) -> str: + """Format clone_repo result as Markdown-KV.""" + is_warning = "uncommitted_changes" in data or "unpublished_branch" in data + has_error = "error" in data + + if is_warning: + mark = _WARN_MARK + status = "WARNING" + elif has_error: + mark = _CROSS_MARK + status = "FAIL" + else: + mark = _CHECK_MARK + status = "OK" + + lines = [f"## clone_repo {mark} {status}", ""] + for key, val in data.items(): + if isinstance(val, (dict, list)): + continue + lines.append(f"{key}: {val}") + return "\n".join(lines) diff --git a/src/autoskillit/hooks/_hook_settings.py b/src/autoskillit/hooks/_hook_settings.py new file mode 100644 index 0000000000..4aa3ba28ac --- /dev/null +++ b/src/autoskillit/hooks/_hook_settings.py @@ -0,0 +1,118 @@ +"""Shared stdlib-only settings resolver for quota guard hooks. + +Resolves hook settings from a layered hierarchy that mirrors the +dynaconf-backed settings system without importing third-party packages: + + 1. Function parameter (``cache_path_override`` — for tests/DI) + 2. Environment variable (``AUTOSKILLIT_QUOTA_GUARD__``) — highest runtime priority + 3. Hook config snapshot (``.autoskillit/temp/.hook_config.json``) — bridge from + resolved settings + 4. Module default (matches ``config/defaults.yaml``) — lowest + +This module is stdlib-only: no third-party imports, no ``autoskillit.*`` +imports. It runs unchanged under the bare Python interpreter used by +Claude Code hook subprocesses. +""" + +import json +import os +from dataclasses import dataclass +from pathlib import Path + +# Keep in sync with _HOOK_CONFIG_PATH_COMPONENTS in hooks/_fmt_primitives.py +# (stdlib-only boundary prevents a shared import). +HOOK_CONFIG_FILENAME = ".hook_config.json" +HOOK_DIR_COMPONENTS = (".autoskillit", "temp") + +DEFAULT_CACHE_PATH = "~/.claude/autoskillit_quota_cache.json" +DEFAULT_CACHE_MAX_AGE = 300 +DEFAULT_BUFFER_SECONDS = 60 + +ENV_CACHE_PATH = "AUTOSKILLIT_QUOTA_GUARD__CACHE_PATH" +ENV_CACHE_MAX_AGE = "AUTOSKILLIT_QUOTA_GUARD__CACHE_MAX_AGE" +ENV_BUFFER_SECONDS = "AUTOSKILLIT_QUOTA_GUARD__BUFFER_SECONDS" +ENV_DISABLED = "AUTOSKILLIT_QUOTA_GUARD__DISABLED" + + +@dataclass(frozen=True, slots=True) +class QuotaHookSettings: + """Resolved settings for quota guard hooks.""" + + cache_path: str + cache_max_age: int + buffer_seconds: int + disabled: bool = False + + +def _read_hook_config() -> dict: + """Read the ``quota_guard`` section of ``/.autoskillit/temp/.hook_config.json``. + + Returns ``{}`` if the file is absent or unreadable. This file is written by + ``open_kitchen`` and removed by ``close_kitchen``. + """ + try: + config_path = Path.cwd().joinpath(*HOOK_DIR_COMPONENTS, HOOK_CONFIG_FILENAME) + return json.loads(config_path.read_text()).get("quota_guard", {}) + except (OSError, json.JSONDecodeError, AttributeError, TypeError): + return {} + + +def _resolve_int(env_var: str, hook_value: object, default: int) -> int: + """Resolve an integer setting: env var > hook config > default. + + Non-numeric env var values fall through to the next level. + """ + env_raw = os.environ.get(env_var) + if env_raw is not None: + try: + return int(env_raw) + except (ValueError, TypeError): + pass + if isinstance(hook_value, int) and not isinstance(hook_value, bool): + return hook_value + if isinstance(hook_value, float): + return int(hook_value) + return default + + +def resolve_quota_settings(*, cache_path_override: str | None = None) -> QuotaHookSettings: + """Resolve quota hook settings from the layered hierarchy. + + ``cache_path``: ``cache_path_override`` > env var > hook config > default. + ``cache_max_age`` / ``buffer_seconds``: env var > hook config > default. + """ + hook_config = _read_hook_config() + + cache_path = ( + cache_path_override + or os.environ.get(ENV_CACHE_PATH) + or hook_config.get("cache_path") + or DEFAULT_CACHE_PATH + ) + + cache_max_age = _resolve_int( + ENV_CACHE_MAX_AGE, + hook_config.get("cache_max_age"), + DEFAULT_CACHE_MAX_AGE, + ) + + buffer_seconds = _resolve_int( + ENV_BUFFER_SECONDS, + hook_config.get("buffer_seconds"), + DEFAULT_BUFFER_SECONDS, + ) + + env_disabled = os.environ.get(ENV_DISABLED, "").strip().lower() + if env_disabled in ("1", "true", "yes"): + disabled = True + elif env_disabled in ("0", "false", "no"): + disabled = False + else: + disabled = bool(hook_config.get("disabled", False)) + + return QuotaHookSettings( + cache_path=cache_path, + cache_max_age=cache_max_age, + buffer_seconds=buffer_seconds, + disabled=disabled, + ) diff --git a/src/autoskillit/hooks/ask_user_question_guard.py b/src/autoskillit/hooks/ask_user_question_guard.py new file mode 100644 index 0000000000..fc1b52ce87 --- /dev/null +++ b/src/autoskillit/hooks/ask_user_question_guard.py @@ -0,0 +1,92 @@ +#!/usr/bin/env python3 +"""PreToolUse hook — blocks AskUserQuestion before kitchen is open. + +Reads the kitchen-open session marker for the current session. If no fresh +marker exists, denies the call with a structured hookSpecificOutput envelope +containing the ToolSearch recovery hint. + +Stdlib-only — runs under any Python interpreter without the autoskillit package. +""" + +from __future__ import annotations + +import json +import os +import sys +from datetime import UTC +from pathlib import Path + + +def _get_marker_path(session_id: str) -> Path: + override = os.environ.get("AUTOSKILLIT_STATE_DIR") + if override: + return Path(override) / "kitchen_state" / f"{session_id}.json" + return Path.cwd() / ".autoskillit" / "temp" / "kitchen_state" / f"{session_id}.json" + + +def _read_marker(session_id: str) -> dict | None: + try: + path = _get_marker_path(session_id) + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return None + + +def _is_fresh(data: dict, ttl_hours: int = 24) -> bool: + try: + from datetime import datetime + + opened_at = datetime.fromisoformat(data["opened_at"]) + age = datetime.now(UTC) - opened_at + return age.total_seconds() < ttl_hours * 3600 + except (KeyError, ValueError, TypeError): + return False + + +def main() -> None: + try: + payload = json.loads(sys.stdin.read()) + except (json.JSONDecodeError, ValueError, OSError): + sys.exit(0) # fail-open on malformed input + + tool_name = payload.get("tool_name", "") + if tool_name != "AskUserQuestion": + sys.exit(0) # defensive; matcher should pre-filter + + # In interactive sessions, AskUserQuestion is always permitted -- + # the user is present at the terminal and can respond. + if os.environ.get("AUTOSKILLIT_HEADLESS") != "1": + sys.exit(0) # not headless -- pass through + + session_id = payload.get("session_id", "") + if not session_id: + sys.exit(0) # fail-open when session_id unavailable + + marker = _read_marker(session_id) + # NOTE: The in-hook freshness check below is the SOLE source of correctness. + # The session_start_hook TTL sweep is disk hygiene only — it has race windows. + # A future maintainer MUST NOT remove this check on the grounds that "the sweep + # handles stale markers": the sweep does not. + if marker is not None and _is_fresh(marker): + sys.exit(0) # kitchen is open — permit AskUserQuestion + + deny_payload = json.dumps( + { + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "deny", + "permissionDecisionReason": ( + "AskUserQuestion is not available in headless sessions without " + "an open kitchen. If this is a pipeline worker, proceed without " + "user confirmation or use a default/fallback behavior. " + "If an orchestrator session, call open_kitchen first." + ), + } + } + ) + sys.stdout.write(deny_payload + "\n") + sys.exit(0) + + +if __name__ == "__main__": + main() diff --git a/src/autoskillit/hooks/generated_file_write_guard.py b/src/autoskillit/hooks/generated_file_write_guard.py new file mode 100644 index 0000000000..a38d508d1a --- /dev/null +++ b/src/autoskillit/hooks/generated_file_write_guard.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +""" +PreToolUse hook — denies Write and Edit calls targeting generated files +(hooks.json and .claude/settings.json). These files are machine-local +generated artifacts managed by 'autoskillit install'. Direct edits bypass +hook_registry.py and create ghost entries that cause ENOENT fatal denials. +""" + +import json +import os +import sys + +_GENERATED_FILE_SUFFIXES = ("/hooks/hooks.json", ".claude/settings.json") + + +def main() -> None: + try: + data = json.loads(sys.stdin.read()) + except (json.JSONDecodeError, ValueError, OSError): + sys.exit(0) + + tool_name = data.get("tool_name", "") + if tool_name not in ("Write", "Edit"): + sys.exit(0) + + file_path = data.get("tool_input", {}).get("file_path", "") + if not isinstance(file_path, str) or not file_path: + sys.exit(0) + + # Normalize to forward slashes for cross-platform suffix matching + normalized = file_path.replace(os.sep, "/") + if not any(normalized.endswith(suffix) for suffix in _GENERATED_FILE_SUFFIXES): + sys.exit(0) + + payload = json.dumps( + { + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": "deny", + "permissionDecisionReason": ( + f"'{file_path}' is a generated file with machine-local absolute paths. " + f"Direct edits bypass hook_registry.py and create ghost hook entries " + f"that block all tool calls with ENOENT. " + f"Use 'autoskillit install' to regenerate, or " + f"'autoskillit init' to sync settings.json." + ), + } + } + ) + sys.stdout.write(payload + "\n") + sys.exit(0) + + +if __name__ == "__main__": + main() diff --git a/src/autoskillit/hooks/open_kitchen_guard.py b/src/autoskillit/hooks/open_kitchen_guard.py index 928f969254..1021693f25 100644 --- a/src/autoskillit/hooks/open_kitchen_guard.py +++ b/src/autoskillit/hooks/open_kitchen_guard.py @@ -1,19 +1,57 @@ #!/usr/bin/env python3 -"""PreToolUse hook — blocks open_kitchen from headless sessions. +"""PreToolUse hook — blocks open_kitchen from headless sessions and writes kitchen marker. Headless sessions launched by run_skill have AUTOSKILLIT_HEADLESS=1 in their environment. This hook denies open_kitchen calls from those sessions, enforcing that only humans (via /autoskillit:open-kitchen) can open the kitchen. + +On the permit path (non-headless), writes a kitchen-open session marker so that +ask_user_question_guard can verify the kitchen is open before allowing AskUserQuestion. """ import json import os import sys +from datetime import UTC + + +def _write_kitchen_marker(session_id: str, recipe_name: str | None) -> None: + """Write the kitchen-open session marker (stdlib-only, inline implementation).""" + import tempfile + from datetime import datetime + from pathlib import Path as _Path + + state_override = os.environ.get("AUTOSKILLIT_STATE_DIR") + if state_override: + state_dir = _Path(state_override) / "kitchen_state" + else: + state_dir = _Path.cwd() / ".autoskillit" / "temp" / "kitchen_state" + state_dir.mkdir(parents=True, exist_ok=True) + marker_path = state_dir / f"{session_id}.json" + payload = json.dumps( + { + "session_id": session_id, + "opened_at": datetime.now(UTC).isoformat(), + "recipe_name": recipe_name, + "marker_version": 1, + } + ) + fd, tmp = tempfile.mkstemp(dir=state_dir, suffix=".tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.write(payload) + os.replace(tmp, marker_path) + except Exception: + try: + os.unlink(tmp) + except OSError: + pass + raise def main() -> None: try: - json.loads(sys.stdin.read()) + data = json.loads(sys.stdin.read()) except (json.JSONDecodeError, ValueError, OSError): sys.exit(0) # fail-open on malformed input or broken pipe @@ -31,6 +69,38 @@ def main() -> None: } ) sys.stdout.write(payload + "\n") + sys.exit(0) + + # Permit path: write a kitchen-open session marker so ask_user_question_guard + # can verify the kitchen is open before allowing AskUserQuestion. + # The marker is written here (from the PreToolUse hook) rather than from the + # MCP server tool because the hook receives the Claude Code session_id on stdin; + # the FastMCP Context does not expose it. + try: + session_id = data.get("session_id", "") + recipe_name: str | None = None + tool_input = data.get("tool_input") or {} + if isinstance(tool_input, dict): + recipe_name = tool_input.get("name") or None + if session_id: + _write_kitchen_marker(session_id, recipe_name) + except Exception as e: + print(f"[open_kitchen_guard] marker write failed: {e}", file=sys.stderr) + # Surface the failure so the user knows AskUserQuestion will be blocked + # in headless sub-sessions (ask_user_question_guard relies on the marker). + payload = json.dumps( + { + "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "message": ( + f"Warning: kitchen marker write failed ({e}). " + "AskUserQuestion may be blocked in headless sub-sessions." + ), + } + } + ) + sys.stdout.write(payload + "\n") + sys.exit(0) diff --git a/src/autoskillit/hooks/pretty_output.py b/src/autoskillit/hooks/pretty_output.py deleted file mode 100644 index c1ba13e2fc..0000000000 --- a/src/autoskillit/hooks/pretty_output.py +++ /dev/null @@ -1,776 +0,0 @@ -#!/usr/bin/env python3 -"""PostToolUse hook: prettify MCP tool output as Markdown-KV. - -Intercepts MCP tool responses and reformats them from raw JSON to Markdown-KV -before Claude consumes them. Reduces token overhead 30-77% and improves -LLM field-extraction accuracy. - -Stdlib-only — runs under any Python interpreter without the autoskillit package. -""" - -from __future__ import annotations - -import json -import sys -from collections.abc import Callable, Mapping -from dataclasses import dataclass -from pathlib import Path -from typing import TYPE_CHECKING, Any - -if TYPE_CHECKING: - from autoskillit.recipe import ListRecipesResult, LoadRecipeResult - -_HOOK_CONFIG_PATH_COMPONENTS = (".autoskillit", "temp", ".autoskillit_hook_config.json") - - -@dataclass(frozen=True) -class _DictPayload: - data: dict[str, Any] - - -@dataclass(frozen=True) -class _PlainTextPayload: - text: str - - -_Payload = _DictPayload | _PlainTextPayload -_CHECK_MARK = "\u2713" # ✓ -_CROSS_MARK = "\u2717" # ✗ -_WARN_MARK = "\u26a0" # ⚠ - - -def _is_pipeline_mode() -> bool: - """Check if kitchen is open (pipeline mode) by hook config file presence.""" - config_path = Path.cwd().joinpath(*_HOOK_CONFIG_PATH_COMPONENTS) - return config_path.is_file() - - -def _fmt_tokens(n: int | None) -> str: - """Format a token count as compact string (45.2k, 1.2M, etc.).""" - if n is None or n == 0: - return "0" - if not isinstance(n, (int, float)): - return "0" - if n >= 1_000_000: - return f"{n / 1_000_000:.1f}M" - if n >= 1_000: - return f"{n / 1_000:.1f}k" - return str(n) - - -def _extract_tool_short_name(tool_name: str) -> str: - """Extract short tool name from full MCP tool name. - - "mcp__plugin_autoskillit_autoskillit__run_skill" -> "run_skill" - Falls back to the full tool_name if no __ separator found. - """ - return tool_name.rsplit("__", 1)[-1] if "__" in tool_name else tool_name - - -def _fmt_run_skill(data: dict, pipeline: bool) -> str: - """Format run_skill result as Markdown-KV.""" - success = data.get("success", False) - subtype = data.get("subtype", "") - mark = _CHECK_MARK if success else _CROSS_MARK - status = subtype if subtype else ("OK" if success else "FAIL") - - if pipeline: - # Compact format for pipeline mode - header = f"run_skill: {'OK' if success else 'FAIL'} [{status}]" - lines = [header] - session_id = data.get("session_id", "") - if session_id: - lines.append(f"session_id: {session_id}") - lines.append(f"exit_code: {data.get('exit_code', '')}") - lines.append(f"needs_retry: {data.get('needs_retry', False)}") - if data.get("retry_reason") and data["retry_reason"] != "none": - lines.append(f"retry_reason: {data['retry_reason']}") - worktree = data.get("worktree_path", "") - if worktree: - lines.append(f"worktree_path: {worktree}") - result = data.get("result", "") - if result: - lines.append(f"\nresult:\n{result}") - stderr = (data.get("stderr") or "").strip() - if stderr: - lines.extend(["", "### stderr", stderr]) - return "\n".join(lines) - - # Interactive mode - lines = [f"## run_skill {mark} {status}", ""] - lines.append(f"success: {success}") - session_id = data.get("session_id", "") - if session_id: - lines.append(f"session_id: {session_id}") - lines.append(f"subtype: {subtype}") - lines.append(f"exit_code: {data.get('exit_code', '')}") - lines.append(f"needs_retry: {data.get('needs_retry', False)}") - retry_reason = data.get("retry_reason", "none") - if retry_reason and retry_reason != "none": - lines.append(f"retry_reason: {retry_reason}") - worktree = data.get("worktree_path", "") - if worktree: - lines.append(f"worktree_path: {worktree}") - token_usage = data.get("token_usage") - if isinstance(token_usage, dict): - lines.append("") - lines.append(f"tokens_in: {_fmt_tokens(token_usage.get('input_tokens'))}") - lines.append(f"tokens_out: {_fmt_tokens(token_usage.get('output_tokens'))}") - cr = token_usage.get("cache_read_input_tokens", 0) - if cr: - lines.append(f"tokens_cached: {_fmt_tokens(cr)}") - result = data.get("result", "") - if result: - lines.extend(["", "### Result", result]) - stderr = data.get("stderr", "") - if stderr: - lines.extend(["", "### stderr", stderr]) - return "\n".join(lines) - - -def _fmt_run_cmd(data: dict, pipeline: bool) -> str: - """Format run_cmd result as Markdown-KV.""" - success = data.get("success", False) - exit_code = data.get("exit_code", "") - mark = _CHECK_MARK if success else _CROSS_MARK - - if pipeline: - lines = [ - f"run_cmd: {'OK' if success else 'FAIL'} [{exit_code}]", - f"success: {success}", - f"exit_code: {exit_code}", - ] - stdout = (data.get("stdout") or "").strip() - if stdout: - lines.extend(["", "### stdout", stdout]) - stderr = (data.get("stderr") or "").strip() - if stderr: - lines.extend(["", "### stderr", stderr]) - return "\n".join(lines) - - lines = [ - f"## run_cmd {mark} {'OK' if success else 'FAIL'}", - "", - f"success: {success}", - f"exit_code: {exit_code}", - ] - stdout = (data.get("stdout") or "").strip() - if stdout: - lines.extend(["", "### stdout", stdout]) - stderr = (data.get("stderr") or "").strip() - if stderr: - lines.extend(["", "### stderr", stderr]) - return "\n".join(lines) - - -def _filter_pytest_output(raw: str) -> str: - """Filter pytest boilerplate, keeping only failure-relevant lines.""" - boilerplate_prefixes = ( - "platform ", - "rootdir:", - "configfile:", - "plugins:", - "collecting ", - "collected ", - "cacheprovider", - ) - boilerplate_exact = {"", " "} - lines = raw.splitlines() - filtered = [] - for line in lines: - stripped = line.strip() - if stripped in boilerplate_exact: - continue - if any(stripped.startswith(p) for p in boilerplate_prefixes): - continue - filtered.append(line) - return "\n".join(filtered) - - -def _fmt_test_check(data: dict, _pipeline: bool) -> str: - """Format test_check result as Markdown-KV.""" - passed = data.get("passed", False) - mark = _CHECK_MARK if passed else _CROSS_MARK - status = "PASS" if passed else "FAIL" - lines = [f"## test_check {mark} {status}", "", f"passed: {passed}"] - raw_output = data.get("output", "") - if raw_output: - filtered = _filter_pytest_output(raw_output) - lines.extend(["", "### Output", filtered]) - error = data.get("error", "") - if error: - lines.extend(["", f"error: {error}"]) - return "\n".join(lines) - - -def _fmt_merge_worktree(data: dict, _pipeline: bool) -> str: - """Format merge_worktree result as Markdown-KV.""" - succeeded = data.get("merge_succeeded") - has_error = "error" in data - - if succeeded: - mark = _CHECK_MARK - status = "OK" - elif has_error: - mark = _CROSS_MARK - status = "FAIL" - else: - mark = _CROSS_MARK - status = "UNKNOWN" - - lines = [f"## merge_worktree {mark} {status}", ""] - for key, val in data.items(): - if isinstance(val, list): - lines.append(f"{key}:") - for item in val: - lines.append(f" - {item}") - elif isinstance(val, dict): - continue - elif key == "stderr": - continue - else: - lines.append(f"{key}: {val}") - stderr = (data.get("stderr") or "").strip() - if stderr: - lines.extend(["", "### stderr", stderr]) - return "\n".join(lines) - - -def _fmt_get_token_summary(data: dict, _pipeline: bool) -> str: - """Format get_token_summary compact Markdown-KV output. - - This formatter receives only the JSON dict payload (format="json"). - When format="table" is used, the tool returns a pre-formatted markdown - string. _resolve_payload() detects this as a _PlainTextPayload and routes - it through _PLAIN_TEXT_FORMATTERS (pass-through), so this function is - never called for the table format. - """ - lines = ["## token_summary", ""] - steps = data.get("steps", []) - for step in steps: - name = step.get("step_name", "?") - count = step.get("invocation_count", 1) - inp = _fmt_tokens(step.get("input_tokens", 0)) - out = _fmt_tokens(step.get("output_tokens", 0)) - cached = _fmt_tokens( - step.get("cache_read_input_tokens", 0) + step.get("cache_creation_input_tokens", 0) - ) - wc = step.get("wall_clock_seconds", step.get("elapsed_seconds", 0.0)) - lines.append(f"{name} x{count} [in:{inp} out:{out} cached:{cached} t:{wc:.1f}s]") - total = data.get("total", {}) - if total: - lines.append("") - lines.append(f"total_in: {_fmt_tokens(total.get('input_tokens', 0))}") - lines.append(f"total_out: {_fmt_tokens(total.get('output_tokens', 0))}") - cache_tokens = total.get("cache_read_input_tokens", 0) + total.get( - "cache_creation_input_tokens", 0 - ) - lines.append(f"total_cached: {_fmt_tokens(cache_tokens)}") - mcp = data.get("mcp_responses", {}) - mcp_total = mcp.get("total", {}) - if mcp_total: - lines.append("") - lines.append(f"mcp_invocations: {mcp_total.get('total_invocations', 0)}") - est_tokens = mcp_total.get("total_estimated_response_tokens", 0) - lines.append(f"mcp_response_tokens: ~{_fmt_tokens(est_tokens)}") - return "\n".join(lines) - - -def _fmt_get_timing_summary(data: dict, _pipeline: bool) -> str: - """Format get_timing_summary compact Markdown-KV output. - - This formatter receives only the JSON dict payload (format="json"). - When format="table" is used, the tool returns a pre-formatted markdown - string. _resolve_payload() detects this as a _PlainTextPayload and routes - it through _PLAIN_TEXT_FORMATTERS (pass-through), so this function is - never called for the table format. - - Each step becomes: name xN [dur:Xs] - """ - lines = ["## timing_summary", ""] - steps = data.get("steps", []) - for step in steps: - name = step.get("step_name", "?") - count = step.get("invocation_count", 1) - secs = step.get("total_seconds", 0.0) - if secs < 60: - dur = f"{secs:.0f}s" - elif secs < 3600: - m, s = divmod(int(secs), 60) - dur = f"{m}m {s}s" - else: - h, remainder = divmod(int(secs), 3600) - m = remainder // 60 - dur = f"{h}h {m}m" - lines.append(f"{name} x{count} [dur:{dur}]") - total = data.get("total", {}) - if total: - total_secs = total.get("total_seconds", 0.0) - if total_secs < 60: - total_dur = f"{total_secs:.0f}s" - elif total_secs < 3600: - m, s = divmod(int(total_secs), 60) - total_dur = f"{m}m {s}s" - else: - h, remainder = divmod(int(total_secs), 3600) - m = remainder // 60 - total_dur = f"{h}h {m}m" - lines.append("") - lines.append(f"total: {total_dur}") - return "\n".join(lines) - - -def _fmt_kitchen_status(data: dict, _pipeline: bool) -> str: - """Format kitchen_status as Markdown-KV.""" - success = not data.get("error") - mark = _CHECK_MARK if success else _CROSS_MARK - enabled = data.get("tools_enabled", False) - gate_str = "OPEN" if enabled else "CLOSED" - lines = [f"## kitchen_status {mark} {gate_str}", ""] - for key in ( - "package_version", - "plugin_json_version", - "versions_match", - "tools_enabled", - "token_usage_verbosity", - "quota_guard_enabled", - "github_token_configured", - "github_default_repo", - ): - if key in data: - lines.append(f"{key}: {data[key]}") - warning = data.get("warning") - if warning: - lines.extend(["", f"warning: {warning}"]) - return "\n".join(lines) - - -def _fmt_clone_repo(data: dict, _pipeline: bool) -> str: - """Format clone_repo result as Markdown-KV.""" - is_warning = "uncommitted_changes" in data or "unpublished_branch" in data - has_error = "error" in data - - if is_warning: - mark = "\u26a0" - status = "WARNING" - elif has_error: - mark = _CROSS_MARK - status = "FAIL" - else: - mark = _CHECK_MARK - status = "OK" - - lines = [f"## clone_repo {mark} {status}", ""] - for key, val in data.items(): - if isinstance(val, (dict, list)): - continue - lines.append(f"{key}: {val}") - return "\n".join(lines) - - -# Field coverage contract for _fmt_load_recipe ↔ LoadRecipeResult -_FMT_LOAD_RECIPE_RENDERED: frozenset[str] = frozenset( - { - "valid", - "suggestions", - "error", - "content", - "ingredients_table", - } -) -_FMT_LOAD_RECIPE_SUPPRESSED: frozenset[str] = frozenset( - { - "greeting", # delivered via positional CLI arg, not MCP response - "diagram", # user sees it in terminal preview; agent doesn't need it - "kitchen_rules", # already in the YAML content - } -) - -# Maps derived-display field name → source field name in LoadRecipeResult. -# When a derived field is present in a response, the formatter strips its -# corresponding source block from the source field to prevent duplicate display. -# All entries must map to "content" — only content-derived fields require -# ingredients-block stripping. Non-content source fields are not supported here. -# -# HOW TO USE: When adding a new field to _FMT_LOAD_RECIPE_RENDERED, ask: -# "Is this field a re-rendering of content already in another RENDERED field?" -# If yes, add an entry here: {new_derived_field: "content"}. -# The augmented field coverage test will enforce this declaration. -_LOAD_RECIPE_CONTENT_DERIVED_FROM: dict[str, str] = { - "ingredients_table": "content", # GFM table derived from the ingredients: block in content -} - - -def _strip_yaml_ingredients_block(yaml_text: str) -> str: - """Remove the top-level `ingredients:` block from YAML text. - - Called by _fmt_recipe_body() when ingredients_table is present, so the - RECIPE block does not repeat the TABLE block. Operates line-by-line: - drops the `ingredients:` key and all its indented children until a - non-indented line signals the next top-level key. Preserves all other - top-level keys (steps, kitchen_rules, description, etc.) unchanged. - """ - lines = yaml_text.splitlines(keepends=True) - result: list[str] = [] - in_ingredients = False - for line in lines: - if line.startswith("ingredients:"): - in_ingredients = True - continue - if in_ingredients: - if line and not line[0].isspace(): - # First non-indented non-empty line = next top-level key - in_ingredients = False - result.append(line) - # else: still inside the ingredients block — skip - else: - result.append(line) - return "".join(result) - - -def _fmt_recipe_body(data: Mapping[str, Any]) -> list[str]: - """Shared recipe content rendering for load_recipe and open_kitchen+recipe.""" - lines: list[str] = [] - content = data.get("content") - if content: - # When a derived field is present, strip its source block from content - # to prevent duplicate display. The derivation map drives this automatically. - display_content = content - for derived_field in _LOAD_RECIPE_CONTENT_DERIVED_FROM: - if data.get(derived_field): - display_content = _strip_yaml_ingredients_block(display_content) - lines.append("\n--- RECIPE ---") - lines.append(display_content) - lines.append("--- END RECIPE ---") - ing_table = data.get("ingredients_table") - if ing_table: - lines.append("\n--- INGREDIENTS TABLE (display this verbatim to the user) ---") - lines.append(ing_table) - lines.append("--- END TABLE ---") - suggestions = data.get("suggestions") or [] - errors = [ - f for f in suggestions if isinstance(f, dict) and f.get("severity") in ("error", "warning") - ] - if errors: - lines.append(f"\n{len(errors)} finding(s)") - return lines - - -def _fmt_load_recipe(data: LoadRecipeResult, pipeline: bool) -> str: - """Format load_recipe result as Markdown-KV.""" - if not isinstance(data, dict): - return "## load_recipe\n\n_(unexpected response type)_" - - error = data.get("error") - if error: - return f"## load_recipe {_CROSS_MARK}\n\n**Error:** {error}" - - valid = data.get("valid", True) - mark = _CHECK_MARK if valid else _CROSS_MARK - lines: list[str] = [f"## load_recipe {mark}"] - lines.extend(_fmt_recipe_body(data)) - return "\n".join(lines) - - -# Field coverage contract for _fmt_list_recipes ↔ ListRecipesResult -_FMT_LIST_RECIPES_RENDERED: frozenset[str] = frozenset( - { - "recipes", - "count", - "errors", - } -) -_FMT_LIST_RECIPES_SUPPRESSED: frozenset[str] = frozenset() - -# Field coverage contract for per-item recipe entries ↔ RecipeListItem -_FMT_RECIPE_LIST_ITEM_RENDERED: frozenset[str] = frozenset( - { - "name", - "description", - "summary", - "source", - } -) -_FMT_RECIPE_LIST_ITEM_SUPPRESSED: frozenset[str] = frozenset() - - -def _fmt_open_kitchen(data: dict, pipeline: bool) -> str: - """Format open_kitchen combined kitchen+recipe result.""" - version = data.get("version", "") - - error = data.get("error") - if error: - return f"## open_kitchen {_CROSS_MARK} v{version}\n\nKitchen open. Recipe error: {error}" - - valid = data.get("valid", True) - mark = _CHECK_MARK if valid else _CROSS_MARK - lines: list[str] = [f"## open_kitchen {mark} v{version}"] - lines.extend(_fmt_recipe_body(data)) - return "\n".join(lines) - - -def _fmt_open_kitchen_plain_text(text: str, _pipeline: bool) -> str: - """Format open_kitchen plain-text response (no recipe attached).""" - return f"## open_kitchen\n\n{text}" - - -def _fmt_list_recipes(data: ListRecipesResult, pipeline: bool) -> str: - """Format list_recipes result as Markdown-KV.""" - if not isinstance(data, dict): - return "## list_recipes\n\n_(unexpected response type)_" - lines: list[str] = ["## list_recipes"] - recipes = data.get("recipes") or [] - for recipe in recipes[:30]: - if isinstance(recipe, dict): - name = recipe.get("name", "?") - desc = recipe.get("description", "") - summary = recipe.get("summary", "") - source = recipe.get("source", "") - source_tag = f" [{source}]" if source else "" - lines.append(f" - {name}{source_tag}: {desc}" if desc else f" - {name}{source_tag}") - if summary: - lines.append(f" {summary}") - else: - lines.append(f" - {recipe}") - if len(recipes) > 30: - lines.append(f" ... and {len(recipes) - 30} more") - count = data.get("count", len(recipes)) - lines.append(f"\n{count} recipe(s) available") - errors = data.get("errors") or [] - if errors: - lines.append(f"\n{_WARN_MARK} {len(errors)} recipe file(s) had load errors") - return "\n".join(lines) - - -def _fmt_tool_exception(data: dict, pipeline: bool) -> str: - """Format a tool_exception response with full diagnostics.""" - error = data.get("error", "unknown error") - exit_code = data.get("exit_code", -1) - if pipeline: - return f"TOOL EXCEPTION [{exit_code}]: {error}" - return f"## {_CROSS_MARK} Tool Exception\n\nerror: {error}\nexit_code: {exit_code}" - - -def _fmt_gate_error(data: dict, _pipeline: bool) -> str: - """Format a gate_error response.""" - result = data.get("result", data.get("message", "Kitchen is closed.")) - lines = [f"## {_CROSS_MARK} Gate Error", "", f"message: {result}", "subtype: gate_error"] - return "\n".join(lines) - - -def _fmt_generic(short_name: str, data: dict, _pipeline: bool) -> str: - """Generic key-value formatter for tools without dedicated formatters.""" - lines = [f"## {short_name}", ""] - for key, val in data.items(): - if isinstance(val, list): - val = list(val) - if not val: - lines.append(f"{key}: []") - elif all(isinstance(item, str) for item in val): - lines.append(f"{key}:") - for item in val[:20]: - lines.append(f" - {item}") - if len(val) > 20: - lines.append(f" ... and {len(val) - 20} more") - else: - # Non-string list (list-of-dicts or mixed): render per-item up to 20-item cap - lines.append(f"{key}:") - for item in val[:20]: - if isinstance(item, dict): - # Render first two key-value pairs inline for readability - parts = [f"{k}: {v}" for k, v in list(item.items())[:2]] - lines.append(f" - {', '.join(parts)}") - else: - compact = json.dumps(item, separators=(",", ":")) - lines.append(f" - {compact[:200]}") - if len(val) > 20: - lines.append(f" ... and {len(val) - 20} more") - elif isinstance(val, dict): - if not val: - lines.append(f"{key}: {{}}") - else: - lines.append(f"{key}:") - for k, v in val.items(): - if isinstance(v, (dict, list)): - compact = json.dumps(v, separators=(",", ":")) - if len(compact) > 200: - compact = compact[:200] + "..." - lines.append(f" {k}: {compact}") - else: - lines.append(f" {k}: {v}") - else: - lines.append(f"{key}: {val}") - return "\n".join(lines) - - -# Dispatch table: short tool name → formatter function -_FORMATTERS: dict[str, Callable[..., str]] = { - "run_skill": _fmt_run_skill, - "run_cmd": _fmt_run_cmd, - "test_check": _fmt_test_check, - "merge_worktree": _fmt_merge_worktree, - "get_token_summary": _fmt_get_token_summary, - "get_timing_summary": _fmt_get_timing_summary, - "kitchen_status": _fmt_kitchen_status, - "clone_repo": _fmt_clone_repo, - "load_recipe": _fmt_load_recipe, - "open_kitchen": _fmt_open_kitchen, - "list_recipes": _fmt_list_recipes, -} - -# Tools explicitly opted out of dedicated formatters. -# The generic formatter is sufficient for these tools' response shapes. -# When adding a new tool, it MUST appear either in _FORMATTERS or here. -_UNFORMATTED_TOOLS: frozenset[str] = frozenset( - { - "run_python", # structured result dict, generic renders correctly - "read_db", # tabular rows, generic renders correctly - "reset_test_dir", # simple ack - "classify_fix", # simple classification result - "reset_workspace", # simple ack - "migrate_recipe", # simple migration result - "remove_clone", # simple ack - "push_to_remote", # simple ack - "report_bug", # simple result - "prepare_issue", # simple result - "enrich_issues", # simple result - "claim_issue", # simple result - "release_issue", # simple result - "wait_for_ci", # ci status dict, generic renders correctly - "wait_for_merge_queue", # merge queue result dict, generic renders correctly - "toggle_auto_merge", # simple success/error result dict, generic renders correctly - "create_unique_branch", # simple result - "write_telemetry_files", # simple path results - "get_pr_reviews", # list of reviews - "bulk_close_issues", # bulk result - "check_pr_mergeable", # simple bool result - "set_commit_status", # simple ack - "get_pipeline_report", # list-of-dicts, now renders correctly via hardened _fmt_generic - "validate_recipe", # suggestions list, now renders correctly via hardened _fmt_generic - "fetch_github_issue", # issue data dict - "get_issue_title", # simple string - "get_ci_status", # ci status dict - "get_quota_events", # list of quota events, generic renders correctly - "close_kitchen", # simple ack - "register_clone_status", # simple registered/error result - "batch_cleanup_clones", # bulk delete summary dict - } -) - -# Plain-text dispatch: called when _resolve_payload() returns _PlainTextPayload. -_PLAIN_TEXT_FORMATTERS: dict[str, Callable[[str, bool], str]] = { - # open_kitchen returns a plain orchestrator-notice string when no recipe is loaded. - # All other plain-text responses pass through unchanged (pre-formatted markdown). - "open_kitchen": _fmt_open_kitchen_plain_text, -} - - -def _resolve_payload(tool_name: str, tool_response: str) -> _Payload | None: - """Resolve a raw Claude Code PostToolUse event into a typed payload. - - Returns: - _DictPayload — tool returned a JSON dict (envelope successfully unwrapped, - or outer response was already a bare dict). - _PlainTextPayload — tool returned a pre-formatted string (non-JSON inner content). - None — response cannot be parsed or is not a dict at the outer level; - hook should pass through. - """ - try: - data = json.loads(tool_response) - except (json.JSONDecodeError, ValueError): - return None - - if not isinstance(data, dict): - return None - - if ( - tool_name.startswith("mcp__") - and list(data.keys()) == ["result"] - and isinstance(data["result"], str) - ): - try: - inner = json.loads(data["result"]) - if isinstance(inner, dict): - return _DictPayload(data=inner) - # Inner parsed but is not a dict (e.g. list, int) — pass through unformatted - return None - except (json.JSONDecodeError, ValueError): - pass - # Inner content is plain text (not valid JSON) - return _PlainTextPayload(text=data["result"]) - - return _DictPayload(data=data) - - -def _format_response(tool_name: str, tool_response: str, pipeline: bool) -> str | None: - """Parse tool_response JSON and dispatch to the appropriate formatter. - - Returns formatted string or None if formatting should be skipped. - """ - payload = _resolve_payload(tool_name, tool_response) - if payload is None: - return None - - short_name = _extract_tool_short_name(tool_name) - - if isinstance(payload, _PlainTextPayload): - # Tool returned pre-formatted content. Named dict-formatters must not - # receive this shape. Route through the plain-text dispatch table or - # pass through unchanged. - handler = _PLAIN_TEXT_FORMATTERS.get(short_name) - return handler(payload.text, pipeline) if handler is not None else payload.text - - # DictPayload path — envelope was successfully unwrapped (or was never an envelope). - data = payload.data - - if data.get("subtype") == "gate_error": - return _fmt_gate_error(data, pipeline) - if data.get("subtype") == "tool_exception": - return _fmt_tool_exception(data, pipeline) - - if short_name in _UNFORMATTED_TOOLS: - return _fmt_generic(short_name, data, pipeline) - - formatter = _FORMATTERS.get(short_name) - if formatter is not None: - return formatter(data, pipeline) - - return _fmt_generic(short_name, data, pipeline) - - -def main() -> None: - try: - raw = sys.stdin.read() - event = json.loads(raw) - except (json.JSONDecodeError, ValueError, OSError): - sys.exit(0) # fail-open - - tool_name = event.get("tool_name", "") - tool_response = event.get("tool_response", "") - - if not tool_name or not tool_response: - sys.exit(0) # no data to format - - try: - pipeline = _is_pipeline_mode() - formatted = _format_response(tool_name, tool_response, pipeline) - except Exception: - sys.exit(0) # fail-open — never block on hook bug - - if formatted is None: - sys.exit(0) # pass-through - - output = json.dumps( - { - "hookSpecificOutput": { - "hookEventName": "PostToolUse", - "updatedMCPToolOutput": formatted, - } - } - ) - print(output) - sys.exit(0) - - -if __name__ == "__main__": - main() diff --git a/src/autoskillit/hooks/pretty_output_hook.py b/src/autoskillit/hooks/pretty_output_hook.py new file mode 100644 index 0000000000..6a88b2675c --- /dev/null +++ b/src/autoskillit/hooks/pretty_output_hook.py @@ -0,0 +1,314 @@ +#!/usr/bin/env python3 +"""PostToolUse hook: prettify MCP tool output as Markdown-KV. + +Intercepts MCP tool responses and reformats them from raw JSON to Markdown-KV +before Claude consumes them. Reduces token overhead 30-77% and improves +LLM field-extraction accuracy. + +This module is the dispatch entrypoint. The per-tool formatters live in four +private helper modules to keep this file under its line budget: + + * ``_fmt_primitives`` — payload dataclasses, token formatter, pipeline-mode + detector, and short-name extractor. + * ``_fmt_execution`` — ``run_skill``, ``run_cmd``, ``test_check``, + ``merge_worktree``. + * ``_fmt_status`` — ``get_token_summary``, ``get_timing_summary``, + ``kitchen_status``, ``clone_repo``. + * ``_fmt_recipe`` — ``load_recipe``, ``open_kitchen``, ``list_recipes`` + plus the recipe field-coverage contracts. + +Stdlib-only — runs under any Python interpreter without the autoskillit package. +""" + +from __future__ import annotations + +import json +import sys +from collections.abc import Callable +from pathlib import Path # re-exported for tests that patch ``pretty_output.Path.cwd`` +from typing import Any + +# Hooks run as ``python3 /path/to/pretty_output.py`` subprocesses outside the +# autoskillit venv (test_hooks_are_stdlib_only). To split the formatter without +# breaking that constraint, sibling helpers are imported by bare name with the +# script's directory placed first on sys.path. The same bootstrap makes +# package-mode loading (``from autoskillit.hooks.pretty_output import ...``) +# resolve the helpers to the same top-level modules so identity stays +# consistent across both invocation modes. +_HOOKS_DIR = str(Path(__file__).resolve().parent) +if _HOOKS_DIR not in sys.path: + sys.path.insert(0, _HOOKS_DIR) + +from _fmt_execution import ( # type: ignore[import-not-found] # noqa: E402 + _fmt_merge_worktree, + _fmt_run_cmd, + _fmt_run_skill, + _fmt_test_check, +) +from _fmt_primitives import ( # type: ignore[import-not-found] # noqa: E402, F401 + _CHECK_MARK, + _CROSS_MARK, + _HOOK_CONFIG_PATH_COMPONENTS, + _DictPayload, + _extract_tool_short_name, + _is_pipeline_mode, + _Payload, + _PlainTextPayload, +) +from _fmt_recipe import ( # type: ignore[import-not-found] # noqa: E402, F401 + _FMT_LIST_RECIPES_RENDERED, + _FMT_LIST_RECIPES_SUPPRESSED, + _FMT_LOAD_RECIPE_RENDERED, + _FMT_LOAD_RECIPE_SUPPRESSED, + _FMT_RECIPE_LIST_ITEM_RENDERED, + _FMT_RECIPE_LIST_ITEM_SUPPRESSED, + _LOAD_RECIPE_CONTENT_DERIVED_FROM, + _fmt_list_recipes, + _fmt_load_recipe, + _fmt_open_kitchen, + _fmt_open_kitchen_plain_text, + _fmt_recipe_body, + _strip_yaml_ingredients_block, +) +from _fmt_status import ( # type: ignore[import-not-found] # noqa: E402 + _fmt_clone_repo, + _fmt_get_timing_summary, + _fmt_get_token_summary, + _fmt_kitchen_status, +) + + +def _fmt_tool_exception(data: dict, pipeline: bool) -> str: + """Format a tool_exception response with full diagnostics.""" + error = data.get("error", "unknown error") + exit_code = data.get("exit_code", -1) + if pipeline: + return f"TOOL EXCEPTION [{exit_code}]: {error}" + return f"## {_CROSS_MARK} Tool Exception\n\nerror: {error}\nexit_code: {exit_code}" + + +def _fmt_gate_error(data: dict, _pipeline: bool) -> str: + """Format a gate_error response.""" + result = data.get("result", data.get("message", "Kitchen is closed.")) + lines = [f"## {_CROSS_MARK} Gate Error", "", f"message: {result}", "subtype: gate_error"] + return "\n".join(lines) + + +def _fmt_generic(short_name: str, data: dict, _pipeline: bool) -> str: + """Generic key-value formatter for tools without dedicated formatters.""" + lines = [f"## {short_name}", ""] + for key, val in data.items(): + if isinstance(val, list): + val = list(val) + if not val: + lines.append(f"{key}: []") + elif all(isinstance(item, str) for item in val): + lines.append(f"{key}:") + for item in val[:20]: + lines.append(f" - {item}") + if len(val) > 20: + lines.append(f" ... and {len(val) - 20} more") + else: + # Non-string list (list-of-dicts or mixed): render per-item up to 20-item cap + lines.append(f"{key}:") + for item in val[:20]: + if isinstance(item, dict): + # Render first two key-value pairs inline for readability + parts = [f"{k}: {v}" for k, v in list(item.items())[:2]] + lines.append(f" - {', '.join(parts)}") + else: + compact = json.dumps(item, separators=(",", ":")) + lines.append(f" - {compact[:200]}") + if len(val) > 20: + lines.append(f" ... and {len(val) - 20} more") + elif isinstance(val, dict): + if not val: + lines.append(f"{key}: {{}}") + else: + lines.append(f"{key}:") + for k, v in val.items(): + if isinstance(v, (dict, list)): + compact = json.dumps(v, separators=(",", ":")) + if len(compact) > 200: + compact = compact[:200] + "..." + lines.append(f" {k}: {compact}") + else: + lines.append(f" {k}: {v}") + else: + lines.append(f"{key}: {val}") + return "\n".join(lines) + + +# Dispatch table: short tool name → formatter function +_FORMATTERS: dict[str, Callable[..., str]] = { + "run_skill": _fmt_run_skill, + "run_cmd": _fmt_run_cmd, + "test_check": _fmt_test_check, + "merge_worktree": _fmt_merge_worktree, + "get_token_summary": _fmt_get_token_summary, + "get_timing_summary": _fmt_get_timing_summary, + "kitchen_status": _fmt_kitchen_status, + "clone_repo": _fmt_clone_repo, + "load_recipe": _fmt_load_recipe, + "open_kitchen": _fmt_open_kitchen, + "list_recipes": _fmt_list_recipes, +} + +# Tools explicitly opted out of dedicated formatters. +# The generic formatter is sufficient for these tools' response shapes. +# When adding a new tool, it MUST appear either in _FORMATTERS or here. +_UNFORMATTED_TOOLS: frozenset[str] = frozenset( + { + "run_python", # structured result dict, generic renders correctly + "read_db", # tabular rows, generic renders correctly + "reset_test_dir", # simple ack + "classify_fix", # simple classification result + "reset_workspace", # simple ack + "migrate_recipe", # simple migration result + "remove_clone", # simple ack + "push_to_remote", # simple ack + "report_bug", # simple result + "prepare_issue", # simple result + "enrich_issues", # simple result + "claim_issue", # simple result + "release_issue", # simple result + "wait_for_ci", # ci status dict, generic renders correctly + "wait_for_merge_queue", # merge queue result dict, generic renders correctly + "check_repo_merge_state", # simple JSON boolean bundle, generic renders correctly + "toggle_auto_merge", # simple success/error result dict, generic renders correctly + "create_unique_branch", # simple result + "write_telemetry_files", # simple path results + "get_pr_reviews", # list of reviews + "bulk_close_issues", # bulk result + "check_pr_mergeable", # simple bool result + "set_commit_status", # simple ack + "get_pipeline_report", # list-of-dicts, now renders correctly via hardened _fmt_generic + "validate_recipe", # suggestions list, now renders correctly via hardened _fmt_generic + "fetch_github_issue", # issue data dict + "get_issue_title", # simple string + "get_ci_status", # ci status dict + "get_quota_events", # list of quota events, generic renders correctly + "close_kitchen", # simple ack + "disable_quota_guard", # simple success/error result + "register_clone_status", # simple registered/error result + "batch_cleanup_clones", # bulk delete summary dict + } +) + +# Plain-text dispatch: called when _resolve_payload() returns _PlainTextPayload. +_PLAIN_TEXT_FORMATTERS: dict[str, Callable[[str, bool], str]] = { + # open_kitchen returns a plain orchestrator-notice string when no recipe is loaded. + # All other plain-text responses pass through unchanged (pre-formatted markdown). + "open_kitchen": _fmt_open_kitchen_plain_text, +} + + +def _resolve_payload(tool_name: str, tool_response: str) -> _Payload | None: + """Resolve a raw Claude Code PostToolUse event into a typed payload. + + Returns: + _DictPayload — tool returned a JSON dict (envelope successfully unwrapped, + or outer response was already a bare dict). + _PlainTextPayload — tool returned a pre-formatted string (non-JSON inner content). + None — response cannot be parsed or is not a dict at the outer level; + hook should pass through. + """ + try: + data: Any = json.loads(tool_response) + except (json.JSONDecodeError, ValueError): + return None + + if not isinstance(data, dict): + return None + + if ( + tool_name.startswith("mcp__") + and list(data.keys()) == ["result"] + and isinstance(data["result"], str) + ): + try: + inner = json.loads(data["result"]) + if isinstance(inner, dict): + return _DictPayload(data=inner) + # Inner parsed but is not a dict (e.g. list, int) — pass through unformatted + return None + except (json.JSONDecodeError, ValueError): + pass + # Inner content is plain text (not valid JSON) + return _PlainTextPayload(text=data["result"]) + + return _DictPayload(data=data) + + +def _format_response(tool_name: str, tool_response: str, pipeline: bool) -> str | None: + """Parse tool_response JSON and dispatch to the appropriate formatter. + + Returns formatted string or None if formatting should be skipped. + """ + payload = _resolve_payload(tool_name, tool_response) + if payload is None: + return None + + short_name = _extract_tool_short_name(tool_name) + + if isinstance(payload, _PlainTextPayload): + # Tool returned pre-formatted content. Named dict-formatters must not + # receive this shape. Route through the plain-text dispatch table or + # pass through unchanged. + handler = _PLAIN_TEXT_FORMATTERS.get(short_name) + return handler(payload.text, pipeline) if handler is not None else payload.text + + # DictPayload path — envelope was successfully unwrapped (or was never an envelope). + data = payload.data + + if data.get("subtype") == "gate_error": + return _fmt_gate_error(data, pipeline) + if data.get("subtype") == "tool_exception": + return _fmt_tool_exception(data, pipeline) + + if short_name in _UNFORMATTED_TOOLS: + return _fmt_generic(short_name, data, pipeline) + + formatter = _FORMATTERS.get(short_name) + if formatter is not None: + return formatter(data, pipeline) + + return _fmt_generic(short_name, data, pipeline) + + +def main() -> None: + try: + raw = sys.stdin.read() + event = json.loads(raw) + except (json.JSONDecodeError, ValueError, OSError): + sys.exit(0) # fail-open + + tool_name = event.get("tool_name", "") + tool_response = event.get("tool_response", "") + + if not tool_name or not tool_response: + sys.exit(0) # no data to format + + try: + pipeline = _is_pipeline_mode() + formatted = _format_response(tool_name, tool_response, pipeline) + except Exception: + sys.exit(0) # fail-open — never block on hook bug + + if formatted is None: + sys.exit(0) # pass-through + + output = json.dumps( + { + "hookSpecificOutput": { + "hookEventName": "PostToolUse", + "updatedMCPToolOutput": formatted, + } + } + ) + print(output) + sys.exit(0) + + +if __name__ == "__main__": + main() diff --git a/src/autoskillit/hooks/quota_check.py b/src/autoskillit/hooks/quota_guard.py similarity index 61% rename from src/autoskillit/hooks/quota_check.py rename to src/autoskillit/hooks/quota_guard.py index 6b7debf4b8..cbe64349da 100644 --- a/src/autoskillit/hooks/quota_check.py +++ b/src/autoskillit/hooks/quota_guard.py @@ -2,8 +2,10 @@ """PreToolUse hook: quota check before run_skill. Reads the local quota cache file (written by autoskillit's quota module) and -denies run_skill when utilization exceeds the threshold. Fails open when the -cache is missing, expired, or unreadable — the next run_skill call will discover +denies run_skill when the cached binding marks ``should_block=True``. The +threshold classification is computed once on the cache write side, so this +hook contains no threshold logic of its own. Fails open when the cache is +missing, expired, or unreadable — the next run_skill call will discover quota exhaustion on its own. This script is stdlib-only so it can run under any Python interpreter without @@ -16,29 +18,20 @@ from datetime import UTC, datetime from pathlib import Path -_DEFAULT_CACHE_PATH = "~/.claude/autoskillit_quota_cache.json" -_DEFAULT_THRESHOLD = 90.0 -_DEFAULT_CACHE_MAX_AGE = 300 # seconds +# Sibling-import bootstrap: hooks run as ``python3 /path/to/quota_check.py`` +# subprocesses outside the autoskillit venv (test_hooks_are_stdlib_only). +# Placing the script's directory first on sys.path lets the bare-name import +# below resolve to the shared stdlib-only settings module in both subprocess +# and package-mode invocations. +_HOOKS_DIR = str(Path(__file__).resolve().parent) +if _HOOKS_DIR not in sys.path: + sys.path.insert(0, _HOOKS_DIR) -HOOK_CONFIG_FILENAME = ".autoskillit_hook_config.json" -HOOK_DIR_COMPONENTS = (".autoskillit", "temp") +from _hook_settings import resolve_quota_settings # type: ignore[import-not-found] # noqa: E402 _AUTOSKILLIT_LOG_DIR_ENV = "AUTOSKILLIT_LOG_DIR" -def _read_hook_config() -> dict: - """Read server-written config from .autoskillit/temp/.autoskillit_hook_config.json. - - Returns the quota_guard section, or {} if the file is absent or unreadable. - This file is written by open_kitchen and removed by close_kitchen. - """ - try: - config_path = Path.cwd().joinpath(*HOOK_DIR_COMPONENTS, HOOK_CONFIG_FILENAME) - return json.loads(config_path.read_text()).get("quota_guard", {}) - except (OSError, json.JSONDecodeError, AttributeError, TypeError): - return {} - - def _read_quota_cache(cache_path_str: str, max_age: int) -> dict | None: """Read quota cache file. Returns parsed data or None if missing/stale/corrupt.""" cache_path = Path(cache_path_str).expanduser() @@ -79,7 +72,8 @@ def _write_quota_log_event(event: dict, log_dir: Path | None) -> None: """Append a quota guard event to quota_events.jsonl at the log root. Silently no-ops on any error — hook observability must never block run_skill. - Event schema: {ts, event, threshold, utilization?, sleep_seconds?, resets_at?, cache_path?} + Event schema: {ts, event, effective_threshold?, window_name?, utilization?, + sleep_seconds?, resets_at?, cache_path?} """ if log_dir is None: return @@ -100,21 +94,16 @@ def main(*, cache_path_override: str | None = None) -> None: sys.exit(0) # malformed event — approve except Exception as e: print( - f"quota_check: unexpected error reading stdin: {type(e).__name__}: {e}", + f"quota_guard: unexpected error reading stdin: {type(e).__name__}: {e}", file=sys.stderr, ) sys.exit(0) # log but approve — don't block run_skill on hook bugs - hook_config = _read_hook_config() - threshold = hook_config.get("threshold", _DEFAULT_THRESHOLD) - cache_max_age = hook_config.get("cache_max_age", _DEFAULT_CACHE_MAX_AGE) - # Function parameter > env var > hook config > module default - cache_path_str = ( - cache_path_override - or os.environ.get("AUTOSKILLIT_QUOTA_CACHE") - or hook_config.get("cache_path") - or _DEFAULT_CACHE_PATH - ) + settings = resolve_quota_settings(cache_path_override=cache_path_override) + if settings.disabled: + sys.exit(0) # quota guard disabled for this session + cache_path_str = settings.cache_path + cache_max_age = settings.cache_max_age log_dir = _resolve_quota_log_dir() ts = datetime.now(UTC).isoformat() @@ -124,7 +113,6 @@ def main(*, cache_path_override: str | None = None) -> None: { "ts": ts, "event": "cache_miss", - "threshold": threshold, "cache_path": cache_path_str, }, log_dir, @@ -132,37 +120,45 @@ def main(*, cache_path_override: str | None = None) -> None: sys.exit(0) # no fresh cache — fail open try: - utilization = float(cache["five_hour"]["utilization"]) + binding = cache.get("binding") + if not binding or not isinstance(binding, dict): + raise KeyError("binding") + utilization = float(binding["utilization"]) + should_block = bool(binding.get("should_block", False)) + effective_threshold = float(binding.get("effective_threshold", 0.0)) + window_name = str(binding.get("window_name", "unknown")) except (KeyError, ValueError, TypeError): _write_quota_log_event( { "ts": ts, "event": "parse_error", - "threshold": threshold, "cache_path": cache_path_str, }, log_dir, ) sys.exit(0) # malformed cache — fail open - if utilization >= threshold: - resets_at_str = cache.get("five_hour", {}).get("resets_at") + if should_block: + resets_at_str = binding.get("resets_at") if resets_at_str: try: resets_at = datetime.fromisoformat(resets_at_str) - buffer_seconds = 60 now = datetime.now(UTC) - n = max(0, int((resets_at - now).total_seconds()) + buffer_seconds) + n = max( + 0, + int((resets_at - now).total_seconds()) + settings.buffer_seconds, + ) except (ValueError, TypeError): - n = 60 + n = settings.buffer_seconds else: - n = 60 + n = settings.buffer_seconds _write_quota_log_event( { "ts": ts, "event": "blocked", - "threshold": threshold, + "effective_threshold": effective_threshold, + "window_name": window_name, "utilization": utilization, "sleep_seconds": n, "resets_at": resets_at_str, @@ -176,9 +172,15 @@ def main(*, cache_path_override: str | None = None) -> None: "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": ( - f"Quota threshold exceeded. Sleep {n} seconds then retry. " - f'Call run_cmd with: python3 -c "import time; time.sleep({n})" ' - f"timeout={n + 30}" + f"QUOTA WAIT REQUIRED (temporary — NOT a permanent error). " + f"Utilization: {utilization:.0f}% on window '{window_name}' " + f"(threshold: {effective_threshold:.0f}%). " + f"MANDATORY ACTION: Call run_cmd with: " + f'python3 -c "import time; time.sleep({n})" timeout={n + 30} — ' + f"then retry the SAME run_skill call with identical arguments. " + f"Before executing, state aloud: " + f"'Quota exceeded at {utilization:.0f}%. " + f"Sleeping {n}s, then retrying.'" ), } } @@ -189,7 +191,8 @@ def main(*, cache_path_override: str | None = None) -> None: { "ts": ts, "event": "approved", - "threshold": threshold, + "effective_threshold": effective_threshold, + "window_name": window_name, "utilization": utilization, }, log_dir, diff --git a/src/autoskillit/hooks/quota_post_hook.py b/src/autoskillit/hooks/quota_post_hook.py new file mode 100644 index 0000000000..90a1a40af5 --- /dev/null +++ b/src/autoskillit/hooks/quota_post_hook.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +"""PostToolUse hook: quota warning after run_skill execution. + +Fires after run_skill completes and checks whether the cached binding marks +``should_block=True``. When set, replaces the tool output with a compact +result summary + quota warning + sleep instruction via updatedMCPToolOutput. + +This script is stdlib-only so it can run under any Python interpreter without +requiring the autoskillit package to be importable. +""" + +import json +import os +import sys +from datetime import UTC, datetime +from pathlib import Path + +# Sibling-import bootstrap: hooks run as ``python3 /path/to/quota_post_check.py`` +# subprocesses outside the autoskillit venv (test_hooks_are_stdlib_only). +# Placing the script's directory first on sys.path lets the bare-name import +# below resolve to the shared stdlib-only settings module in both subprocess +# and package-mode invocations. +_HOOKS_DIR = str(Path(__file__).resolve().parent) +if _HOOKS_DIR not in sys.path: + sys.path.insert(0, _HOOKS_DIR) + +from _hook_settings import resolve_quota_settings # type: ignore[import-not-found] # noqa: E402 + +_AUTOSKILLIT_LOG_DIR_ENV = "AUTOSKILLIT_LOG_DIR" + + +def _read_quota_cache(cache_path_str: str, max_age: int) -> dict | None: + """Read quota cache file. Returns parsed data or None if missing/stale/corrupt.""" + cache_path = Path(cache_path_str).expanduser() + if not cache_path.is_file(): + return None + try: + data = json.loads(cache_path.read_text()) + fetched = datetime.fromisoformat(data["fetched_at"]) + age = (datetime.now(UTC) - fetched).total_seconds() + if age > max_age: + return None # stale + return data + except (json.JSONDecodeError, KeyError, ValueError, OSError, TypeError): + return None + + +def _resolve_quota_log_dir() -> Path | None: + """Resolve the autoskillit log root directory. Returns None on any error.""" + try: + override = os.environ.get(_AUTOSKILLIT_LOG_DIR_ENV) + if override: + return Path(override) + if sys.platform == "darwin": + return Path.home() / "Library" / "Application Support" / "autoskillit" / "logs" + xdg = os.environ.get("XDG_DATA_HOME") + if xdg: + return Path(xdg) / "autoskillit" / "logs" + return Path.home() / ".local" / "share" / "autoskillit" / "logs" + except Exception: + return None + + +def _write_quota_log_event(event: dict, log_dir: Path | None) -> None: + """Append a quota guard event to quota_events.jsonl at the log root.""" + if log_dir is None: + return + try: + log_dir.mkdir(parents=True, exist_ok=True) + line = json.dumps(event) + "\n" + with open(log_dir / "quota_events.jsonl", "a", encoding="utf-8") as f: + f.write(line) + except Exception: + pass + + +def _extract_run_skill_result(tool_response: str | dict) -> str: + """Extract a compact summary from the run_skill double-wrapped JSON response.""" + try: + outer = json.loads(tool_response) if isinstance(tool_response, str) else tool_response + if isinstance(outer, dict) and "result" in outer: + inner_str = outer["result"] + if isinstance(inner_str, str): + try: + inner = json.loads(inner_str) + if isinstance(inner, dict): + success = inner.get("success", "unknown") + result_text = inner.get("result", "") + if isinstance(result_text, str) and len(result_text) > 500: + result_text = result_text[:500] + "..." + return f"success: {success}\nresult: {result_text}" + except (json.JSONDecodeError, ValueError): + pass + return inner_str[:500] if len(inner_str) > 500 else inner_str + return str(outer)[:500] + except (json.JSONDecodeError, ValueError, TypeError): + return str(tool_response)[:500] + + +def main(*, cache_path_override: str | None = None) -> None: + try: + raw = sys.stdin.read() + event = json.loads(raw) + except Exception: + sys.exit(0) + + if not isinstance(event, dict): + sys.exit(0) + + tool_name = event.get("tool_name", "") + tool_response = event.get("tool_response") or "" + + settings = resolve_quota_settings(cache_path_override=cache_path_override) + if settings.disabled: + sys.exit(0) # quota guard disabled for this session + cache_path_str = settings.cache_path + cache_max_age = settings.cache_max_age + log_dir = _resolve_quota_log_dir() + ts = datetime.now(UTC).isoformat() + + cache = _read_quota_cache(cache_path_str, cache_max_age) + if cache is None: + sys.exit(0) + + try: + binding = cache.get("binding") + if not binding or not isinstance(binding, dict): + raise KeyError("binding") + utilization = float(binding["utilization"]) + should_block = bool(binding.get("should_block", False)) + effective_threshold = float(binding.get("effective_threshold", 0.0)) + window_name = str(binding.get("window_name", "unknown")) + except (KeyError, ValueError, TypeError): + sys.exit(0) + + if not should_block: + _write_quota_log_event( + { + "ts": ts, + "event": "post_check_pass", + "effective_threshold": effective_threshold, + "window_name": window_name, + "utilization": utilization, + "tool_name": tool_name, + }, + log_dir, + ) + sys.exit(0) + + resets_at_str = binding.get("resets_at") + if resets_at_str: + try: + resets_at = datetime.fromisoformat(resets_at_str) + now = datetime.now(UTC) + n = max( + 0, + int((resets_at - now).total_seconds()) + settings.buffer_seconds, + ) + except (ValueError, TypeError): + n = settings.buffer_seconds + else: + n = settings.buffer_seconds + + result_summary = _extract_run_skill_result(tool_response) + + warning_text = ( + f"{result_summary}\n\n" + f"--- QUOTA WARNING ---\n" + f"Post-execution utilization: {utilization:.0f}% on window '{window_name}' " + f"(threshold: {effective_threshold:.0f}%)\n" + f"MANDATORY ACTION before next run_skill: Call run_cmd with: " + f'python3 -c "import time; time.sleep({n})" timeout={n + 30}\n' + f"Before executing, state aloud: " + f"'Quota at {utilization:.0f}%. Sleeping {n}s before next step.'" + ) + + _write_quota_log_event( + { + "ts": ts, + "event": "post_check_warning", + "effective_threshold": effective_threshold, + "window_name": window_name, + "utilization": utilization, + "sleep_seconds": n, + "resets_at": resets_at_str, + "tool_name": tool_name, + }, + log_dir, + ) + + print( + json.dumps( + { + "hookSpecificOutput": { + "hookEventName": "PostToolUse", + "updatedMCPToolOutput": warning_text, + } + } + ) + ) + sys.exit(0) + + +if __name__ == "__main__": + main() diff --git a/src/autoskillit/hooks/registry.sha256 b/src/autoskillit/hooks/registry.sha256 new file mode 100644 index 0000000000..6bb952b83f --- /dev/null +++ b/src/autoskillit/hooks/registry.sha256 @@ -0,0 +1 @@ +70827d7991056f6b4737f014b33fcdbb56681b2087dee455859d1e96fc5755a3 diff --git a/src/autoskillit/hooks/session_start_reminder.py b/src/autoskillit/hooks/session_start_hook.py similarity index 58% rename from src/autoskillit/hooks/session_start_reminder.py rename to src/autoskillit/hooks/session_start_hook.py index 2347c25c65..1651c1a2e9 100644 --- a/src/autoskillit/hooks/session_start_reminder.py +++ b/src/autoskillit/hooks/session_start_hook.py @@ -11,7 +11,9 @@ from __future__ import annotations import json +import os import sys +from datetime import UTC, datetime from pathlib import Path @@ -21,6 +23,30 @@ def main() -> None: except (json.JSONDecodeError, ValueError, OSError): sys.exit(0) # fail-open on malformed input + # Best-effort TTL sweep of stale kitchen markers. Fail-open — must not raise. + try: + _state_override = os.environ.get("AUTOSKILLIT_STATE_DIR") + if _state_override: + _state_dir = Path(_state_override) / "kitchen_state" + else: + _state_dir = Path.cwd() / ".autoskillit" / "temp" / "kitchen_state" + if _state_dir.is_dir(): + _ttl_hours = 24 + for _p in _state_dir.glob("*.json"): + try: + _d = json.loads(_p.read_text(encoding="utf-8")) + _opened_at = datetime.fromisoformat(_d["opened_at"]) + _age = datetime.now(UTC) - _opened_at + if _age.total_seconds() >= _ttl_hours * 3600: + _p.unlink() + except Exception: + try: + _p.unlink() + except OSError: + pass + except Exception: + pass # SessionStart hooks that raise break session start for the user + transcript_path = data.get("transcript_path", "") if not transcript_path: sys.exit(0) diff --git a/src/autoskillit/hooks/skill_cmd_check.py b/src/autoskillit/hooks/skill_cmd_guard.py similarity index 80% rename from src/autoskillit/hooks/skill_cmd_check.py rename to src/autoskillit/hooks/skill_cmd_guard.py index bca5b79a41..bdeade69aa 100644 --- a/src/autoskillit/hooks/skill_cmd_check.py +++ b/src/autoskillit/hooks/skill_cmd_guard.py @@ -16,10 +16,10 @@ - If the first token is already path-like → allow (correct format). Output format follows the Claude Code hookSpecificOutput spec, matching -the pattern established by quota_check.py in the same hooks/ package. +the pattern established by quota_guard.py in the same hooks/ package. Exit strategy: uses exit 0 + JSON permissionDecision "deny" (same as -quota_check.py). If the deny is found to be ignored in practice (see +quota_guard.py). If the deny is found to be ignored in practice (see GitHub Issue #4669 — closed as "not planned"), switch to exit 2 + stderr message. The two-pronged design (hook + SKILL.md path-detection instructions) provides defence in depth: even if the hook deny is occasionally ignored, @@ -113,14 +113,25 @@ def main() -> None: sys.exit(0) # Anti-pattern: path exists but is not the first token. - correct_cmd = f"/autoskillit:{skill_name} {path_token}" + # Reconstruct corrected command: all path tokens first, then non-path tokens. + # When args_str is multiline, separate prose from paths with a blank line. + has_newlines = "\n" in args_str + path_tokens = [t for t in tokens if _looks_like_path(t)] + non_path_tokens = [t for t in tokens if not _looks_like_path(t)] + path_part = " ".join(path_tokens) + if has_newlines and non_path_tokens: + prose_block = " ".join(non_path_tokens) + correct_cmd = f"/autoskillit:{skill_name} {path_part}\n\n{prose_block}" + else: + tail = (" " + " ".join(non_path_tokens)) if non_path_tokens else "" + correct_cmd = f"/autoskillit:{skill_name} {path_part}{tail}" _deny( f"skill_command format error for '{skill_name}': " f"found extra descriptive text '{first}...' before the path argument " f"'{path_token}'. Path-argument skills require the path as the first " - f"argument after the skill name. " - f'Fix: set skill_command to "{correct_cmd}" ' - f"(append any remaining positional args after the path if needed)." + f"argument after the skill name. Relocate any additional context or " + f"instructions to after all path arguments. " + f'Fix: set skill_command to "{correct_cmd}".' ) sys.exit(0) diff --git a/src/autoskillit/hooks/token_summary_appender.py b/src/autoskillit/hooks/token_summary_hook.py similarity index 86% rename from src/autoskillit/hooks/token_summary_appender.py rename to src/autoskillit/hooks/token_summary_hook.py index dff046b4bd..e452cadecb 100644 --- a/src/autoskillit/hooks/token_summary_appender.py +++ b/src/autoskillit/hooks/token_summary_hook.py @@ -20,6 +20,16 @@ import sys from typing import Any +# stdlib-only subprocess hook: import _fmt_primitives by bare name via sys.path +# (test_hooks_are_stdlib_only). Venv tests use the autoskillit.hooks package path. +_HOOKS_DIR = str(pathlib.Path(__file__).resolve().parent) +if _HOOKS_DIR not in sys.path: + sys.path.insert(0, _HOOKS_DIR) + +from _fmt_primitives import ( # type: ignore[import-not-found] # noqa: E402 + _HOOK_CONFIG_PATH_COMPONENTS, +) + _SUFFIX_RE = re.compile(r"-\d+$") _PR_PARTS_RE = re.compile(r"https://github\.com/([^/\s]+)/([^/\s]+)/pull/(\d+)") @@ -116,7 +126,7 @@ def _read_kitchen_id(base: pathlib.Path | None = None) -> str: Falls back to 'pipeline_id' key for configs written before the rename. """ root = base if base is not None else pathlib.Path.cwd() - path = root / ".autoskillit" / "temp" / ".autoskillit_hook_config.json" + path = root.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS) try: data = json.loads(path.read_text(encoding="utf-8")) if not isinstance(data, dict): @@ -231,7 +241,8 @@ def _load_sessions( entry["output_tokens"] += data.get("output_tokens", 0) entry["cache_creation_input_tokens"] += data.get("cache_creation_input_tokens", 0) entry["cache_read_input_tokens"] += data.get("cache_read_input_tokens", 0) - entry["elapsed_seconds"] += float(data.get("timing_seconds", 0.0)) + _raw_timing = data.get("timing_seconds") + entry["elapsed_seconds"] += float(_raw_timing) if _raw_timing is not None else 0.0 entry["invocation_count"] += 1 return aggregated @@ -242,36 +253,40 @@ def _format_table(aggregated: dict[str, dict[str, Any]]) -> str: lines = [ "## Token Usage Summary", "", - "| Step | input | output | cached | count | time |", - "|------|-------|--------|--------|-------|------|", + "| Step | uncached | output | cache_read | cache_write | count | time |", + "|------|----------|--------|------------|-------------|-------|------|", ] total_input = 0 total_output = 0 - total_cached = 0 + total_cache_rd = 0 + total_cache_wr = 0 total_time = 0.0 for entry in aggregated.values(): name = entry["step_name"] inp = entry["input_tokens"] out = entry["output_tokens"] - cached = entry["cache_read_input_tokens"] + entry["cache_creation_input_tokens"] + cache_rd = entry["cache_read_input_tokens"] + cache_wr = entry["cache_creation_input_tokens"] count = entry["invocation_count"] elapsed = entry["elapsed_seconds"] lines.append( - f"| {name} | {_humanize(inp)} | {_humanize(out)} | {_humanize(cached)}" - f" | {count} | {_fmt_duration(elapsed)} |" + f"| {name} | {_humanize(inp)} | {_humanize(out)} | {_humanize(cache_rd)}" + f" | {_humanize(cache_wr)} | {count} | {_fmt_duration(elapsed)} |" ) total_input += inp total_output += out - total_cached += cached + total_cache_rd += cache_rd + total_cache_wr += cache_wr total_time += elapsed lines.append( f"| **Total** | {_humanize(total_input)} | {_humanize(total_output)}" - f" | {_humanize(total_cached)} | | {_fmt_duration(total_time)} |" + f" | {_humanize(total_cache_rd)} | {_humanize(total_cache_wr)}" + f" | | {_fmt_duration(total_time)} |" ) return "\n".join(lines) @@ -306,10 +321,11 @@ def main() -> None: ["gh", "api", f"repos/{owner}/{repo}/pulls/{pr_number}", "--jq", ".body"], capture_output=True, text=True, + timeout=30, ) if view_proc.returncode != 0: sys.stderr.write( - f"token_summary_appender: gh api read failed (rc={view_proc.returncode}): " + f"token_summary_hook: gh api read failed (rc={view_proc.returncode}): " f"{view_proc.stderr.strip() if view_proc.stderr else 'no stderr'}\n" ) sys.exit(0) @@ -318,9 +334,7 @@ def main() -> None: current_body = view_proc.stdout.rstrip() if not current_body.strip(): - sys.stderr.write( - "token_summary_appender: empty PR body from gh api — aborting update\n" - ) + sys.stderr.write("token_summary_hook: empty PR body from gh api — aborting update\n") sys.exit(0) token_table = _format_table(aggregated) @@ -340,19 +354,19 @@ def main() -> None: check=True, capture_output=True, text=True, + timeout=30, ) except subprocess.CalledProcessError as cpe: sys.stderr.write( - f"token_summary_appender: gh api update failed" - f" (rc={cpe.returncode}): {cpe.stderr}\n" + f"token_summary_hook: gh api update failed (rc={cpe.returncode}): {cpe.stderr}\n" ) - sys.exit(1) + sys.exit(0) except SystemExit: raise except Exception as exc: # noqa: BLE001 - sys.stderr.write(f"token_summary_appender: unexpected error: {exc}\n") - sys.exit(1) + sys.stderr.write(f"token_summary_hook: unexpected error: {exc}\n") + sys.exit(0) if __name__ == "__main__": diff --git a/src/autoskillit/migration/_api.py b/src/autoskillit/migration/_api.py index 8e035a5045..2842ab540d 100644 --- a/src/autoskillit/migration/_api.py +++ b/src/autoskillit/migration/_api.py @@ -13,7 +13,7 @@ from pathlib import Path from typing import Any -from autoskillit.core import RetryReason, SkillResult +from autoskillit.core import RetryReason, SkillResult, resolve_temp_dir from autoskillit.migration.engine import MigrationFile, default_migration_engine from autoskillit.migration.loader import applicable_migrations @@ -22,6 +22,7 @@ async def check_and_migrate( name: str, project_dir: Path, installed_version: str, + temp_dir: Path | None = None, ) -> dict[str, Any]: """Check and apply pending migrations for a named recipe. @@ -50,7 +51,8 @@ async def check_and_migrate( if not migrations: return {"status": "up_to_date", "name": name} - temp_dir = _pdir / ".autoskillit" / "temp" + if temp_dir is None: + temp_dir = resolve_temp_dir(_pdir, None) engine = default_migration_engine() file = MigrationFile( name=name, diff --git a/src/autoskillit/migration/engine.py b/src/autoskillit/migration/engine.py index 79dd76a252..40860643fe 100644 --- a/src/autoskillit/migration/engine.py +++ b/src/autoskillit/migration/engine.py @@ -17,6 +17,7 @@ dump_yaml_str, get_logger, load_yaml, + resolve_temp_dir, ) from autoskillit.migration.loader import applicable_migrations @@ -366,9 +367,11 @@ def __init__( engine: MigrationEngine, *, run_headless: Callable[..., Awaitable[SkillResult]] | None = None, + temp_dir: Path | None = None, ) -> None: self._engine = engine self._run_headless = run_headless + self._temp_dir_override = temp_dir async def migrate(self, recipe_path: Path) -> dict[str, Any]: """Apply pending migration notes to the recipe file at recipe_path. @@ -394,7 +397,10 @@ async def migrate(self, recipe_path: Path) -> dict[str, Any]: # Derive project_dir: recipe_path → recipes_dir → .autoskillit/ → project_dir recipes_dir = recipe_path.parent project_dir = recipes_dir.parent.parent - temp_dir = project_dir / ".autoskillit" / "temp" + if self._temp_dir_override is not None: + temp_dir = self._temp_dir_override + else: + temp_dir = resolve_temp_dir(project_dir, None) if self._run_headless is not None: run_headless: Callable[..., Awaitable[SkillResult]] = self._run_headless @@ -430,7 +436,7 @@ async def run_headless(*args: Any, **kwargs: Any) -> SkillResult: # type: ignor file, run_headless=run_headless, temp_dir=temp_dir ) - failure_store = FailureStore(default_store_path(project_dir)) + failure_store = FailureStore(default_store_path(project_dir, temp_dir=temp_dir)) if migration_result.success: failure_store.clear(name) diff --git a/src/autoskillit/migration/store.py b/src/autoskillit/migration/store.py index a6269af99c..91d2abd0e1 100644 --- a/src/autoskillit/migration/store.py +++ b/src/autoskillit/migration/store.py @@ -5,7 +5,7 @@ from datetime import UTC, datetime from pathlib import Path -from autoskillit.core import atomic_write +from autoskillit.core import atomic_write, resolve_temp_dir @dataclass @@ -71,8 +71,9 @@ def has_failure(self, name: str) -> bool: return name in self._state -def default_store_path(project_dir: Path) -> Path: - return project_dir / ".autoskillit" / "temp" / "migrations" / "failures.json" +def default_store_path(project_dir: Path, temp_dir: Path | None = None) -> Path: + base = temp_dir if temp_dir is not None else resolve_temp_dir(project_dir, None) + return base / "migrations" / "failures.json" def record_from_skill( diff --git a/src/autoskillit/migrations/0.7.77-to-0.8.0.yaml b/src/autoskillit/migrations/0.7.77-to-0.8.0.yaml new file mode 100644 index 0000000000..9490c4f84c --- /dev/null +++ b/src/autoskillit/migrations/0.7.77-to-0.8.0.yaml @@ -0,0 +1,125 @@ +from_version: "0.7.77" +to_version: "0.8.0" +description: > + Research recipe: write-report renamed to generate-report, output_mode ingredient added + (default 'local'), bundle lifecycle refactored, plan-visualization step and vis-lens + pack requirement added. +changes: + - id: research-rename-write-report + description: "write-report skill and steps renamed to generate-report" + instruction: | + In any research.yaml recipe: + 1. Rename step 'write_report' → 'generate_report'. + 2. Rename step 'write_report_inconclusive' → 'generate_report_inconclusive'. + 3. Rename step 're_write_report' → 're_generate_report'. + 4. In each step's skill_command, replace '/autoskillit:write-report' with + '/autoskillit:generate-report'. + 5. Update all on_success, on_failure, on_result routes that reference the old names. + example_before: | + write_report: + tool: run_skill + with: + skill_command: "/autoskillit:write-report ${{ context.worktree_path }} ..." + on_success: test + retest: + on_failure: re_write_report + example_after: | + generate_report: + tool: run_skill + with: + skill_command: "/autoskillit:generate-report ${{ context.worktree_path }} ..." + on_success: test + retest: + on_failure: re_generate_report + + - id: research-add-output-mode-ingredient + description: "Add output_mode ingredient (default 'local') — BREAKING: old default was implicit pr" + instruction: | + In any research.yaml recipe, add to the ingredients block (after audit_claims): + + output_mode: + required: false + default: "local" + description: > + Where research outputs land. 'local' (default) produces a self-contained + report.html bundle under {source_dir}/research-bundles/{date-slug}/ with + no GitHub interaction. 'pr' opens a GitHub PR alongside the HTML bundle + and runs the full review/archival flow. + + BREAKING CHANGE: Prior to 0.8.0 the recipe always opened a GitHub PR. The new + default is 'local'. To restore previous behavior, set output_mode: "pr" in your + recipe or pass it as an override to open_kitchen. + example_before: | + ingredients: + audit_claims: + required: false + default: "false" + example_after: | + ingredients: + audit_claims: + required: false + default: "false" + output_mode: + required: false + default: "local" + description: "..." + + - id: research-replace-commit-with-stage-and-finalize + description: "commit_research_artifacts replaced by stage_bundle + finalize_bundle lifecycle" + instruction: | + In any research.yaml recipe: + 1. Remove the 'commit_research_artifacts' step. + 2. Add 'stage_bundle' after run_experiment_lenses (idempotent cp, no commit). + 3. Add 're_stage_bundle' after 're_generate_report'. + 4. Add 'finalize_bundle' in the archival phase (after re_push_research.on_success). + finalize_bundle conditionally renames/commits in pr mode and keeps browsable files + intact in local mode. + 5. Update all route edges that referenced commit_research_artifacts. + example_before: | + run_experiment_lenses: + on_success: commit_research_artifacts + commit_research_artifacts: + tool: run_cmd + with: + cmd: "... git commit ..." + on_success: push_branch + example_after: | + run_experiment_lenses: + on_success: stage_bundle + stage_bundle: + tool: run_cmd + with: + cmd: "... cp (no commit) ..." + on_success: route_pr_or_local + + - id: research-add-plan-visualization-step + description: "Add plan_visualization step after design review GO verdict" + instruction: | + In any research.yaml recipe, wire a 'plan_visualization' step between the design + review GO verdict and create_worktree. The step invokes + '/autoskillit:plan-visualization' and captures visualization_plan_path and + report_plan_path. + example_before: | + revise_design: + on_result: + - when: "${{ result.verdict }} == GO" + route: create_worktree + example_after: | + revise_design: + on_result: + - when: "${{ result.verdict }} == GO" + route: plan_visualization + plan_visualization: + tool: run_skill + with: + skill_command: "/autoskillit:plan-visualization ..." + on_success: create_worktree + + - id: research-add-vis-lens-pack-requirement + description: "Add vis-lens to requires_packs" + instruction: | + In any research.yaml recipe, ensure 'vis-lens' appears in the requires_packs list. + example_before: | + requires_packs: [research, exp-lens] + example_after: | + requires_packs: [research, exp-lens, vis-lens] diff --git a/src/autoskillit/migrations/0.8.38-to-0.8.39.yaml b/src/autoskillit/migrations/0.8.38-to-0.8.39.yaml new file mode 100644 index 0000000000..9da3195876 --- /dev/null +++ b/src/autoskillit/migrations/0.8.38-to-0.8.39.yaml @@ -0,0 +1,32 @@ +from_version: "0.8.38" +to_version: "0.8.39" +description: > + Quota guard configuration migrated from single threshold to dual-window + thresholds (short and long window). +changes: + - id: quota-guard-dual-window-thresholds + description: > + QuotaGuardConfig.threshold (single float) replaced by two separate + fields: short_window_threshold and long_window_threshold, enabling + independent control of short-burst and sustained-usage quota limits. + instruction: | + In your project's .autoskillit/config.yaml, replace: + quota_guard: + threshold: 90.0 + with: + quota_guard: + short_window_threshold: 85.0 + long_window_threshold: 98.0 + Adjust values to taste. The old 'threshold' key is no longer recognized + and will raise a ConfigSchemaError at startup. + detect: + key: quota_guard.threshold + example_before: | + quota_guard: + threshold: 90.0 + enabled: true + example_after: | + quota_guard: + short_window_threshold: 85.0 + long_window_threshold: 98.0 + enabled: true diff --git a/src/autoskillit/migrations/0.8.9-to-0.9.0.yaml b/src/autoskillit/migrations/0.8.9-to-0.9.0.yaml new file mode 100644 index 0000000000..99734d4750 --- /dev/null +++ b/src/autoskillit/migrations/0.8.9-to-0.9.0.yaml @@ -0,0 +1,143 @@ +from_version: "0.8.9" +to_version: "0.9.0" +description: > + Verdict-gated CI recovery: auto-fix skills declare a typed verdict output, + recipes route via on_result instead of unconditional on_success, diagnose-ci + emits failure_subtype, and a new semantic rule prevents ungated push paths. +changes: + - id: verdict-output-on-auto-fix-skills + description: > + resolve-failures, resolve-review, resolve-claims-review, and + resolve-research-review now declare a 'verdict' output + (allowed_values: real_fix, already_green, flake_suspected, ci_only_failure) + and 'fixes_applied' as typed outputs. write_expected_when migrated from + fixes_applied pattern to verdict=real_fix. + instruction: | + In skill_contracts.yaml, for each of the four auto-fix skills, replace: + outputs: [] + with: + outputs: + - name: verdict + type: string + allowed_values: [real_fix, already_green, flake_suspected, ci_only_failure] + - name: fixes_applied + type: integer + And update write_expected_when to: + write_expected_when: + - "verdict\\s*=\\s*real_fix" + example_before: | + resolve-failures: + outputs: [] + write_behavior: conditional + write_expected_when: + - "fixes_applied\\s*=\\s*[1-9][0-9]*" + example_after: | + resolve-failures: + outputs: + - name: verdict + type: string + allowed_values: [real_fix, already_green, flake_suspected, ci_only_failure] + - name: fixes_applied + type: integer + write_behavior: conditional + write_expected_when: + - "verdict\\s*=\\s*real_fix" + + - id: diagnose-ci-failure-subtype-output + description: > + diagnose-ci now declares failure_subtype as a typed output with + allowed_values: flaky, timing_race, deterministic, fixture, import, env, unknown. + instruction: | + In skill_contracts.yaml under diagnose-ci, add to outputs: + - name: failure_subtype + type: string + allowed_values: [flaky, timing_race, deterministic, fixture, import, env, unknown] + example_before: | + diagnose-ci: + outputs: + - name: diagnosis_path + type: file_path + - name: failure_type + type: string + - name: is_fixable + type: boolean + example_after: | + diagnose-ci: + outputs: + - name: diagnosis_path + type: file_path + - name: failure_type + type: string + allowed_values: [test, lint, build, type_check, env, unknown] + - name: failure_subtype + type: string + allowed_values: [flaky, timing_race, deterministic, fixture, import, env, unknown] + - name: is_fixable + type: boolean + + - id: recipe-verdict-gated-routing + description: > + resolve_ci and resolve_review steps in implementation.yaml, + implementation-groups.yaml, and remediation.yaml now use on_result: + with verdict dispatch instead of unconditional on_success: re_push. + A new pre_resolve_rebase step handles the already_green re-entry path. + instruction: | + In each pipeline recipe, replace: + resolve_ci: + ... + on_success: re_push + with: + resolve_ci: + ... + on_result: + - when: "${{ result.verdict }} == 'real_fix'" + route: re_push + - when: "${{ result.verdict }} == 'already_green'" + route: pre_resolve_rebase + - when: "${{ result.verdict }} == 'flake_suspected'" + route: release_issue_failure + - when: "${{ result.verdict }} == 'ci_only_failure'" + route: release_issue_failure + And add: + pre_resolve_rebase: + tool: run_cmd + with: + cmd: "git fetch origin && git rebase origin/${{ inputs.base_branch }}" + cwd: "${{ context.work_dir }}" + step_name: "pre_resolve_rebase" + retries: 1 + on_success: diagnose_ci + on_failure: release_issue_failure + Apply the same pattern to resolve_review steps. + example_before: | + resolve_ci: + tool: run_skill + with: + skill_command: "/autoskillit:resolve-failures ..." + on_success: re_push + on_failure: release_issue_failure + example_after: | + resolve_ci: + tool: run_skill + with: + skill_command: "/autoskillit:resolve-failures ..." + on_result: + - when: "${{ result.verdict }} == 'real_fix'" + route: re_push + - when: "${{ result.verdict }} == 'already_green'" + route: pre_resolve_rebase + - when: "${{ result.verdict }} == 'flake_suspected'" + route: release_issue_failure + - when: "${{ result.verdict }} == 'ci_only_failure'" + route: release_issue_failure + on_failure: release_issue_failure + + - id: conditional-skill-ungated-push-rule + description: > + New semantic rule 'conditional-skill-ungated-push' (ERROR severity) in + rules_fixing.py. Rejects any recipe where a write_behavior=conditional skill + step reaches push_to_remote without an on_result: gate on a declared output. + instruction: | + No user action required. The rule fires automatically during recipe validation. + If custom recipes route a conditional-write skill unconditionally to push, + add on_result: verdict dispatch before the push step. diff --git a/src/autoskillit/pipeline/__init__.py b/src/autoskillit/pipeline/__init__.py index eafb970a6d..fbc5e1e49e 100644 --- a/src/autoskillit/pipeline/__init__.py +++ b/src/autoskillit/pipeline/__init__.py @@ -11,7 +11,11 @@ STDERR_MAX_LEN, DefaultAuditLog, ) -from autoskillit.pipeline.background import DefaultBackgroundSupervisor, write_status +from autoskillit.pipeline.background import ( + DefaultBackgroundSupervisor, + create_background_task, + write_status, +) from autoskillit.pipeline.context import ToolContext from autoskillit.pipeline.gate import ( GATED_TOOLS, @@ -57,6 +61,7 @@ "TelemetryFormatter", # background "DefaultBackgroundSupervisor", + "create_background_task", "write_status", # context "ToolContext", diff --git a/src/autoskillit/pipeline/background.py b/src/autoskillit/pipeline/background.py index 4e08dd6c46..32c339462b 100644 --- a/src/autoskillit/pipeline/background.py +++ b/src/autoskillit/pipeline/background.py @@ -105,6 +105,19 @@ async def drain(self) -> None: await asyncio.gather(*self._tasks, return_exceptions=True) +def create_background_task( + coro: Coroutine[Any, Any, Any], *, label: str = "" +) -> asyncio.Task[Any]: + """Create an asyncio.Task for a long-running background coroutine. + + Unlike DefaultBackgroundSupervisor.submit(), this does NOT wrap the coroutine + in _supervise_task — the caller owns the task handle and is responsible for + cancellation. Used for kitchen-scoped lifecycle tasks (quota_refresh_loop) that + must be cancelled explicitly when the kitchen closes. + """ + return asyncio.create_task(coro, name=label) + + def write_status(path: Path | None, status: str, *, error: str | None = None) -> None: """Write a status.json file atomically. Never raises.""" try: diff --git a/src/autoskillit/pipeline/context.py b/src/autoskillit/pipeline/context.py index 3f139ffc05..e8526c732b 100644 --- a/src/autoskillit/pipeline/context.py +++ b/src/autoskillit/pipeline/context.py @@ -8,29 +8,32 @@ from __future__ import annotations from dataclasses import dataclass, field +from pathlib import Path from autoskillit.config import AutomationConfig from autoskillit.core import ( - AuditStore, + AuditLog, BackgroundSupervisor, CIRunScope, CIWatcher, CloneManager, DatabaseReader, - GatePolicy, + GateState, GitHubFetcher, HeadlessExecutor, - McpResponseStore, + McpResponseLog, MergeQueueWatcher, MigrationService, OutputPatternResolver, + QuotaRefreshTask, RecipeRepository, SessionSkillManager, + SkillResolver, SubprocessRunner, - TargetSkillResolver, TestRunner, - TimingStore, - TokenStore, + TimingLog, + TokenFactory, + TokenLog, WorkspaceManager, WriteExpectedResolver, ) @@ -49,12 +52,13 @@ class ToolContext: Fields ------ config: AutomationConfig loaded from .autoskillit/config.yaml - audit: AuditStore — records pipeline failures - token_log: TokenStore — per-step token tracking - timing_log: TimingStore — per-step wall-clock duration tracking - response_log: McpResponseStore — per-tool MCP response size tracking - gate: GatePolicy — enables/disables gated tools - plugin_dir: Absolute path string to the autoskillit package directory + audit: AuditLog — records pipeline failures + token_log: TokenLog — per-step token tracking + timing_log: TimingLog — per-step wall-clock duration tracking + response_log: McpResponseLog — per-tool MCP response size tracking + gate: GateState — enables/disables gated tools + plugin_dir: Absolute path string to the autoskillit package directory, or None if + the marketplace plugin is installed and `--plugin-dir` should be omitted. runner: SubprocessRunner implementation (DefaultSubprocessRunner in production, MockSubprocessRunner in tests) executor: HeadlessExecutor — runs headless Claude Code sessions @@ -68,21 +72,36 @@ class ToolContext: ci_watcher: CIWatcher — watches GitHub Actions CI runs merge_queue_watcher: MergeQueueWatcher — polls GitHub merge queue for a PR session_skill_manager: SessionSkillManager — manages per-session ephemeral skill dirs - skill_resolver: TargetSkillResolver — resolves skill names to source tier + skill_resolver: SkillResolver — resolves skill names to source tier kitchen_id: UUID string assigned when open_kitchen fires; scopes token telemetry to the current kitchen session lifetime. active_recipe_packs: frozenset[str] | None — pack names declared by the loaded recipe (frozenset() when kitchen open but no recipe loaded; None when closed) + temp_dir: Resolved temp directory for this project. MUST be supplied explicitly + by callers outside make_context(). The default_factory falls back to + Path.cwd() / ".autoskillit" / "temp", which is cwd-dependent and + ignores the configured workspace.temp_dir. + token_factory: Optional callable that resolves a GitHub token via the + config → GITHUB_TOKEN env → gh CLI fallback chain. + Set by make_context(); None in test ToolContext instances + unless explicitly provided. """ config: AutomationConfig - audit: AuditStore - token_log: TokenStore - timing_log: TimingStore - gate: GatePolicy - plugin_dir: str + audit: AuditLog + token_log: TokenLog + timing_log: TimingLog + gate: GateState + plugin_dir: str | None runner: SubprocessRunner | None - response_log: McpResponseStore = field(default_factory=DefaultMcpResponseLog) + # Always supply temp_dir explicitly when constructing ToolContext directly. + # The default captures Path.cwd() at field-instantiation time, which is + # cwd-dependent and will differ from the configured workspace.temp_dir. + # Production callers must use make_context() (server/_factory.py), which + # resolves temp_dir from config via resolve_temp_dir(). Direct construction + # (e.g. in tests) must override this field before any file I/O that uses it. + temp_dir: Path = field(default_factory=lambda: Path.cwd() / ".autoskillit" / "temp") + response_log: McpResponseLog = field(default_factory=DefaultMcpResponseLog) executor: HeadlessExecutor | None = field(default=None) tester: TestRunner | None = field(default=None) recipes: RecipeRepository | None = field(default=None) @@ -97,9 +116,11 @@ class ToolContext: output_pattern_resolver: OutputPatternResolver | None = field(default=None) write_expected_resolver: WriteExpectedResolver | None = field(default=None) session_skill_manager: SessionSkillManager | None = field(default=None) - skill_resolver: TargetSkillResolver | None = field(default=None) + skill_resolver: SkillResolver | None = field(default=None) kitchen_id: str = field(default="") active_recipe_packs: frozenset[str] | None = field(default_factory=lambda: None) + quota_refresh_task: QuotaRefreshTask | None = field(default=None) + token_factory: TokenFactory | None = field(default=None) def __post_init__(self) -> None: if self.background is None: @@ -109,4 +130,4 @@ def __post_init__(self) -> None: def default_ci_scope(self) -> CIRunScope: """Build the default CI scope from config. Used by handlers as fallback when the caller does not supply a workflow argument.""" - return CIRunScope(workflow=self.config.ci.workflow) + return CIRunScope(workflow=self.config.ci.workflow, event=self.config.ci.event) diff --git a/src/autoskillit/pipeline/gate.py b/src/autoskillit/pipeline/gate.py index 91696d7778..61a7deb4ec 100644 --- a/src/autoskillit/pipeline/gate.py +++ b/src/autoskillit/pipeline/gate.py @@ -13,7 +13,7 @@ import json from dataclasses import dataclass -from autoskillit.core import GATED_TOOLS, UNGATED_TOOLS # noqa: F401 +from autoskillit.core import GATED_TOOLS, UNGATED_TOOLS, KillReason # noqa: F401 @dataclass(slots=True) @@ -56,6 +56,7 @@ def gate_error_result(message: str | None = None) -> str: "cli_subtype": "", "is_error": True, "exit_code": -1, + "kill_reason": KillReason.NOT_APPLICABLE, "needs_retry": False, "retry_reason": "none", "stderr": "", @@ -89,6 +90,7 @@ def headless_error_result(message: str | None = None) -> str: "cli_subtype": "", "is_error": True, "exit_code": -1, + "kill_reason": KillReason.NOT_APPLICABLE, "needs_retry": False, "retry_reason": "none", "stderr": "", diff --git a/src/autoskillit/pipeline/telemetry_fmt.py b/src/autoskillit/pipeline/telemetry_fmt.py index f75236342a..fc4392f671 100644 --- a/src/autoskillit/pipeline/telemetry_fmt.py +++ b/src/autoskillit/pipeline/telemetry_fmt.py @@ -12,9 +12,10 @@ _TOKEN_COLUMNS = ( TerminalColumn("STEP", max_width=40, align="<"), - TerminalColumn("INPUT", max_width=10, align=">"), + TerminalColumn("UNCACHED", max_width=10, align=">"), TerminalColumn("OUTPUT", max_width=10, align=">"), - TerminalColumn("CACHED", max_width=10, align=">"), + TerminalColumn("CACHE_RD", max_width=10, align=">"), + TerminalColumn("CACHE_WR", max_width=10, align=">"), TerminalColumn("COUNT", max_width=7, align=">"), TerminalColumn("TIME", max_width=8, align=">"), ) @@ -64,28 +65,29 @@ def format_token_table(steps: list[dict], total: dict) -> str: lines = [ "## Token Usage Summary", "", - "| Step | input | output | cached | count | time |", - "|------|-------|--------|--------|-------|------|", + "| Step | uncached | output | cache_read | cache_write | count | time |", + "|------|----------|--------|------------|-------------|-------|------|", ] for step in steps: name = step.get("step_name", "?") inp = h(step.get("input_tokens", 0)) out = h(step.get("output_tokens", 0)) - cached = h( - step.get("cache_read_input_tokens", 0) + step.get("cache_creation_input_tokens", 0) - ) + cache_rd = h(step.get("cache_read_input_tokens", 0)) + cache_wr = h(step.get("cache_creation_input_tokens", 0)) count = step.get("invocation_count", 1) wc = step.get("wall_clock_seconds", step.get("elapsed_seconds", 0.0)) - lines.append(f"| {name} | {inp} | {out} | {cached} | {count} | {fmt_dur(wc)} |") + lines.append( + f"| {name} | {inp} | {out} | {cache_rd} | {cache_wr} | {count} | {fmt_dur(wc)} |" + ) total_in = h(total.get("input_tokens", 0)) total_out = h(total.get("output_tokens", 0)) - total_cached = h( - total.get("cache_read_input_tokens", 0) + total.get("cache_creation_input_tokens", 0) - ) + total_cache_rd = h(total.get("cache_read_input_tokens", 0)) + total_cache_wr = h(total.get("cache_creation_input_tokens", 0)) total_time = total.get("total_elapsed_seconds", 0.0) lines.append( - f"| **Total** | {total_in} | {total_out} | {total_cached} | | {fmt_dur(total_time)} |" + f"| **Total** | {total_in} | {total_out} | {total_cache_rd}" + f" | {total_cache_wr} | | {fmt_dur(total_time)} |" ) return "\n".join(lines) @@ -116,17 +118,15 @@ def format_token_table_terminal(steps: list[dict], total: dict) -> str: h = TelemetryFormatter._humanize fmt_dur = TelemetryFormatter._fmt_duration - rows: list[tuple[str, str, str, str, str, str]] = [] + rows: list[tuple[str, str, str, str, str, str, str]] = [] for step in steps: rows.append( ( step.get("step_name", "?"), h(step.get("input_tokens", 0)), h(step.get("output_tokens", 0)), - h( - step.get("cache_read_input_tokens", 0) - + step.get("cache_creation_input_tokens", 0) - ), + h(step.get("cache_read_input_tokens", 0)), + h(step.get("cache_creation_input_tokens", 0)), str(step.get("invocation_count", 1)), fmt_dur(step.get("wall_clock_seconds", step.get("elapsed_seconds", 0.0))), ) @@ -136,10 +136,8 @@ def format_token_table_terminal(steps: list[dict], total: dict) -> str: "Total", h(total.get("input_tokens", 0)), h(total.get("output_tokens", 0)), - h( - total.get("cache_read_input_tokens", 0) - + total.get("cache_creation_input_tokens", 0) - ), + h(total.get("cache_read_input_tokens", 0)), + h(total.get("cache_creation_input_tokens", 0)), "", fmt_dur(total.get("total_elapsed_seconds", 0.0)), ) @@ -177,19 +175,18 @@ def format_compact_kv( count = step.get("invocation_count", 1) inp = h(step.get("input_tokens", 0)) out = h(step.get("output_tokens", 0)) - cached = h( - step.get("cache_read_input_tokens", 0) + step.get("cache_creation_input_tokens", 0) - ) + cache_rd = h(step.get("cache_read_input_tokens", 0)) + cache_wr = h(step.get("cache_creation_input_tokens", 0)) wc = step.get("wall_clock_seconds", step.get("elapsed_seconds", 0.0)) - lines.append(f"{name} x{count} [in:{inp} out:{out} cached:{cached} t:{wc:.1f}s]") + lines.append( + f"{name} x{count} [uc:{inp} out:{out} cr:{cache_rd} cw:{cache_wr} t:{wc:.1f}s]" + ) if total: lines.append("") - lines.append(f"total_in: {h(total.get('input_tokens', 0))}") + lines.append(f"total_uncached: {h(total.get('input_tokens', 0))}") lines.append(f"total_out: {h(total.get('output_tokens', 0))}") - cache_tokens = total.get("cache_read_input_tokens", 0) + total.get( - "cache_creation_input_tokens", 0 - ) - lines.append(f"total_cached: {h(cache_tokens)}") + lines.append(f"total_cache_read: {h(total.get('cache_read_input_tokens', 0))}") + lines.append(f"total_cache_write: {h(total.get('cache_creation_input_tokens', 0))}") if mcp_responses: mcp_total = mcp_responses.get("total", {}) if mcp_total: diff --git a/src/autoskillit/pipeline/timings.py b/src/autoskillit/pipeline/timings.py index 1e51efafb5..fc95054a51 100644 --- a/src/autoskillit/pipeline/timings.py +++ b/src/autoskillit/pipeline/timings.py @@ -140,7 +140,8 @@ def load_from_log_dir( if key not in self._entries: self._entries[key] = TimingEntry(step_name=step_name) e = self._entries[key] - e.total_seconds += max(0.0, float(data.get("total_seconds", 0.0))) + _raw_total = data.get("total_seconds") + e.total_seconds += max(0.0, float(_raw_total) if _raw_total is not None else 0.0) e.invocation_count += 1 count += 1 diff --git a/src/autoskillit/pipeline/tokens.py b/src/autoskillit/pipeline/tokens.py index 92db5f40c4..1a19da9976 100644 --- a/src/autoskillit/pipeline/tokens.py +++ b/src/autoskillit/pipeline/tokens.py @@ -216,7 +216,8 @@ def load_from_log_dir( e.cache_read_input_tokens += data.get("cache_read_input_tokens", 0) # timing_seconds is the on-disk key name written by session_log.py; # elapsed_seconds is the in-memory field name on TokenEntry. - e.elapsed_seconds += float(data.get("timing_seconds", 0.0)) + _raw_timing = data.get("timing_seconds") + e.elapsed_seconds += float(_raw_timing) if _raw_timing is not None else 0.0 # Each token_usage.json file represents a single run_skill invocation # (one file = one invocation). Incrementing here reconstructs the # invocation count that was accumulated live via record(). diff --git a/src/autoskillit/recipe/__init__.py b/src/autoskillit/recipe/__init__.py index fdd0986612..48dd98f856 100644 --- a/src/autoskillit/recipe/__init__.py +++ b/src/autoskillit/recipe/__init__.py @@ -7,14 +7,20 @@ _logger = get_logger(__name__) # Rule registration — import triggers @semantic_rule registration. +from autoskillit.recipe import rules_blocks as _rules_blocks # noqa: E402 F401 from autoskillit.recipe import rules_bypass as _rules_bypass # noqa: E402 F401 from autoskillit.recipe import rules_ci as _rules_ci # noqa: E402 F401 from autoskillit.recipe import rules_clone as _rules_clone # noqa: E402 F401 +from autoskillit.recipe import rules_cmd as _rules_cmd # noqa: E402 F401 from autoskillit.recipe import rules_contracts as _rules_contracts # noqa: E402 F401 from autoskillit.recipe import rules_dataflow as _rules_dataflow # noqa: E402 F401 +from autoskillit.recipe import rules_fixing as _rules_fixing # noqa: E402 F401 from autoskillit.recipe import rules_graph as _rules_graph # noqa: E402 F401 from autoskillit.recipe import rules_inputs as _rules_inputs # noqa: E402 F401 +from autoskillit.recipe import rules_isolation as _rules_isolation # noqa: E402 F401 from autoskillit.recipe import rules_merge as _rules_merge # noqa: E402 F401 +from autoskillit.recipe import rules_packs as _rules_packs # noqa: E402 F401 +from autoskillit.recipe import rules_reachability as _rules_reachability # noqa: E402 F401 from autoskillit.recipe import rules_recipe as _rules_recipe # noqa: E402 F401 from autoskillit.recipe import rules_skill_content as _rules_skill_content # noqa: E402 F401 from autoskillit.recipe import rules_skills as _rules_skills # noqa: E402 F401 @@ -47,6 +53,10 @@ diagram_stale_to_suggestions, load_recipe_diagram, ) +from autoskillit.recipe.experiment_type_registry import ( # noqa: E402 + ExperimentTypeSpec, + load_all_experiment_types, +) from autoskillit.recipe.io import ( # noqa: E402 builtin_sub_recipes_dir, find_recipe_by_name, @@ -61,6 +71,7 @@ AUTOSKILLIT_VERSION_KEY, DataFlowReport, Recipe, + RecipeBlock, RecipeInfo, RecipeIngredient, RecipeStep, @@ -87,6 +98,7 @@ "RecipeListItem", "build_ingredient_rows", "Recipe", + "RecipeBlock", "RecipeInfo", "RecipeIngredient", "RecipeStep", @@ -127,4 +139,6 @@ "diagram_stale_to_suggestions", "builtin_sub_recipes_dir", "find_sub_recipe_by_name", + "ExperimentTypeSpec", + "load_all_experiment_types", ] diff --git a/src/autoskillit/recipe/_analysis.py b/src/autoskillit/recipe/_analysis.py index b980d1cea1..4fc6f82e47 100644 --- a/src/autoskillit/recipe/_analysis.py +++ b/src/autoskillit/recipe/_analysis.py @@ -10,19 +10,22 @@ from __future__ import annotations +import re +from collections import deque from dataclasses import dataclass, field from pathlib import Path import igraph from autoskillit.core import SKILL_TOOLS, get_logger -from autoskillit.recipe.contracts import _CONTEXT_REF_RE, _RESULT_CAPTURE_RE +from autoskillit.recipe.contracts import _CONTEXT_REF_RE, RESULT_CAPTURE_RE from autoskillit.recipe.io import iter_steps_with_context # noqa: F401 — re-exported for rules from autoskillit.recipe.schema import ( _TERMINAL_TARGETS, DataFlowReport, DataFlowWarning, Recipe, + RecipeBlock, RecipeStep, ) @@ -218,6 +221,8 @@ class ValidationContext: disabled_subsets: frozenset[str] = field(default_factory=frozenset) skill_category_map: dict[str, frozenset[str]] | None = None overridden_skills: frozenset[str] | None = None + blocks: tuple[RecipeBlock, ...] = field(default_factory=tuple) + predecessors: dict[str, set[str]] = field(default_factory=dict) # --------------------------------------------------------------------------- @@ -287,6 +292,101 @@ def _build_step_graph(recipe: Recipe) -> dict[str, set[str]]: return graph +# --------------------------------------------------------------------------- +# Block extraction helpers +# --------------------------------------------------------------------------- + + +def _count_by_tool(members: list[RecipeStep]) -> dict[str, int]: + """Count tool occurrences across a list of steps.""" + counts: dict[str, int] = {} + for step in members: + key = step.tool or "" + if key: + counts[key] = counts.get(key, 0) + 1 + return counts + + +def _count_gh_api(step: RecipeStep) -> int: + """Count occurrences of 'gh api' in a run_cmd step's cmd argument.""" + if step.tool != "run_cmd": + return 0 + cmd = (step.with_args or {}).get("cmd", "") or "" + return cmd.count("gh api") + + +def extract_blocks( + recipe: Recipe, + step_graph: dict[str, set[str]], + *, + predecessors: dict[str, set[str]] | None = None, +) -> tuple[RecipeBlock, ...]: + """Extract named block regions from a recipe's routing graph. + + Groups steps that share the same ``step.block`` value, then computes the + entry step (no in-block predecessor) and exit step (no in-block successor) + for each group. The step_graph is the forward adjacency dict produced by + ``_build_step_graph``; a local inverse is built here to find predecessors. + + Steps without a ``block`` annotation are ignored. Recipes with no block + annotations return an empty tuple. + """ + if predecessors is None: + # Build predecessor map by inverting the forward step_graph edges. + predecessors = {} + for src, successors in step_graph.items(): + for dst in successors: + predecessors.setdefault(dst, set()).add(src) + + by_name: dict[str, list[RecipeStep]] = {} + for step in recipe.steps.values(): + if step.block is not None: + by_name.setdefault(step.block, []).append(step) + + blocks: list[RecipeBlock] = [] + for name, members in by_name.items(): + member_names = {s.name for s in members} + # Entry: no in-block predecessor (predecessor set ∩ member_names is empty) + entry_candidates = [ + s for s in members if not (predecessors.get(s.name, set()) & member_names) + ] + # Exit: no in-block successor (successor set ∩ member_names is empty) + exit_candidates = [ + s for s in members if not (step_graph.get(s.name, set()) & member_names) + ] + entry_name: str + if entry_candidates: + entry_name = entry_candidates[0].name + else: + logger.warning( + "block %r has no graph-reachable entry step; falling back to first member", + name, + ) + entry_name = members[0].name + + exit_name: str + if exit_candidates: + exit_name = exit_candidates[0].name + else: + logger.warning( + "block %r has no graph-reachable exit step; falling back to last member", + name, + ) + exit_name = members[-1].name + + blocks.append( + RecipeBlock( + name=name, + entry=entry_name, + exit=exit_name, + members=tuple(members), + tool_counts=_count_by_tool(members), + gh_api_occurrences=sum(_count_gh_api(s) for s in members), + ) + ) + return tuple(blocks) + + # --------------------------------------------------------------------------- # BFS helpers # --------------------------------------------------------------------------- @@ -317,7 +417,7 @@ def _build_capture_origin_map(recipe: Recipe) -> dict[str, str]: for step in recipe.steps.values(): for cap_var, cap_expr in (step.capture or {}).items(): if isinstance(cap_expr, str): - keys = _RESULT_CAPTURE_RE.findall(cap_expr) + keys = RESULT_CAPTURE_RE.findall(cap_expr) if len(keys) == 1: origin[cap_var] = keys[0] return origin @@ -356,6 +456,101 @@ def _bfs_capped( return visited +# --------------------------------------------------------------------------- +# Symbolic reachability: BFS with fact propagation +# --------------------------------------------------------------------------- + +# A FactSet is a frozen set of (variable, value) pairs established by +# conditional on_result.when edges. Each frozenset represents the facts +# that are known-to-be-true on one particular path through the routing graph. +_FactSet = frozenset[tuple[str, str]] + +# Matches simple equality conditions of the form: +# context.X == 'v' or ${{ context.X }} == "v" +# Capture groups: 1 = variable name, 2 = value. +# Non-equality expressions (inequalities, conjunctions) produce no match — +# conservative assumption (no fact is established). +_SIMPLE_WHEN_RE = re.compile( + r"(?:\$\{\{\s*)?context\.(\w+)(?:\s*\}\})?\s*==\s*" + r"(?:\"(\w+)\"|'(\w+)'|(\w+))" +) + + +def _parse_when_expr(expr: str) -> tuple[str, str] | None: + """Parse a simple equality when-expression into a (variable, value) fact. + + Returns ``None`` for conjunctions, inequalities, or non-context refs. + Conservative: only establishes facts for provably-simple equality conditions. + """ + m = _SIMPLE_WHEN_RE.fullmatch(expr.strip()) + if not m: + return None + # Groups 2/3/4 are mutually exclusive (double-quoted, single-quoted, unquoted) + value = m.group(2) or m.group(3) or m.group(4) + return (m.group(1), value) + + +def _edge_fact(recipe: Recipe, source: str, target: str) -> tuple[str, str] | None: + """Return the (variable, value) fact established by the edge source→target, or None. + + Only ``on_result.conditions`` edges with a parseable simple equality ``when`` + expression contribute a fact. ``on_success``/``on_failure`` edges contribute no fact. + """ + step = recipe.steps.get(source) + if step is None or step.on_result is None: + return None + for cond in step.on_result.conditions: + if cond.route == target and cond.when is not None: + return _parse_when_expr(cond.when) + return None + + +def _intersect_facts(fs: set[_FactSet]) -> _FactSet: + """Intersect all fact sets — only facts that hold on every incoming path survive.""" + if not fs: + return frozenset() + return frozenset.intersection(*fs) + + +def _bfs_with_facts( + graph: dict[str, set[str]], + recipe: Recipe, + start: str, +) -> dict[str, set[_FactSet]]: + """BFS from *start* propagating conditional edge facts. + + Each ``on_result`` edge whose ``when`` expression parses as + ``'context.X == "v"'`` extends the current fact set with ``(X, v)`` on + the target; other edges carry facts unchanged. At join points, the + returned fact set is the intersection of all incoming fact sets — a fact + is only "known" at a node if it holds on every path reaching that node. + + Returns ``{step_name: {intersected_fact_set}}``. Each value is a + single-element set containing one :class:`frozenset` of ``(var, val)`` + pairs. + """ + # facts maps step_name → set of fact-sets that have been discovered for it. + # visited tracks (node, fact_set) pairs to avoid reprocessing. + facts: dict[str, set[_FactSet]] = {start: {frozenset()}} + work: deque[str] = deque([start]) + visited: set[tuple[str, _FactSet]] = set() + + while work: + node = work.popleft() + for succ in graph.get(node, ()): + edge_fact = _edge_fact(recipe, node, succ) + for f in facts.get(node, {frozenset()}): + new_f: _FactSet = f | {edge_fact} if edge_fact else f + state = (succ, new_f) + if state in visited: + continue + visited.add(state) + facts.setdefault(succ, set()).add(new_f) + work.append(succ) + + return {n: {_intersect_facts(fs)} for n, fs in facts.items()} + + # --------------------------------------------------------------------------- # Detection helpers # --------------------------------------------------------------------------- @@ -444,6 +639,51 @@ def _detect_ref_invalidations(recipe: Recipe, graph: dict[str, set[str]]) -> lis return warnings +# Observability captures: variables captured for human-readable logs, hook +# consumption, or note-driven orchestration rather than downstream recipe +# threading. Each entry is (cap_key, skill_command_fragment). A capture is +# exempt when cap_key matches AND skill_command_fragment appears in the +# step's skill_command (or tool/step_name for non-skill steps). +_OBSERVABILITY_CAPTURES: frozenset[tuple[str, str]] = frozenset( + { + ("diagnosis_path", "diagnose-ci"), + ("summary_path", "pipeline-summary"), + ("report_path", "generate-report"), + ("selected_lenses", "prepare-research-pr"), + ("selected_lenses", "prepare-pr"), + ("lens_context_paths", "prepare-research-pr"), + ("lens_context_paths", "prepare-pr"), + ("pr_url", "compose-pr"), + ("html_path", "bundle-local-report"), + ("resource_report", "stage-data"), + } +) + + +def _is_observability_capture(cap_key: str, step_name: str, step: RecipeStep) -> bool: + """Return True if *cap_key* is a known observability-only capture.""" + skill_cmd = step.with_args.get("skill_command", "") if step.with_args else "" + + # Skill-command-based exemptions (the common case). + for obs_key, fragment in _OBSERVABILITY_CAPTURES: + if cap_key == obs_key and fragment in skill_cmd: + return True + + # merge_worktree cleanup_succeeded: matched by tool name + capture value, + # not skill_command (merge_worktree is a direct tool, not a skill). + if step.tool == "merge_worktree" and "result.cleanup_succeeded" in str( + step.capture.get(cap_key, "") + ): + return True + + # export_local_bundle local_bundle_path: matched by step name (terminal + # step in the local-mode path that ends at a stop action). + if cap_key == "local_bundle_path" and step_name == "export_local_bundle": + return True + + return False + + def _detect_dead_outputs(recipe: Recipe, graph: dict[str, set[str]]) -> list[DataFlowWarning]: """Detect captured variables that are never consumed downstream.""" warnings: list[DataFlowWarning] = [] @@ -483,26 +723,7 @@ def _detect_dead_outputs(recipe: Recipe, graph: dict[str, set[str]]) -> list[Dat # Flag captured vars not consumed on any path for cap_key in step.capture: if cap_key not in consumed: - # Exempt merge_worktree diagnostic captures: cleanup_succeeded is captured - # for observability (to surface orphaned worktrees), not for data-passing. - # The merge-cleanup-uncaptured rule requires this capture; exempting it - # from dead-output prevents the two rules from conflicting. - cap_val = step.capture.get(cap_key, "") - if step.tool == "merge_worktree" and "result.cleanup_succeeded" in str(cap_val): - continue - # Exempt diagnose-ci diagnosis_path captures: in recipes without a resolve_ci - # step (e.g. merge-prs), diagnosis_path is captured for observability - # only — no downstream automated remediation consumes it. - if cap_key == "diagnosis_path" and "diagnose-ci" in step.with_args.get( - "skill_command", "" - ): - continue - # Exempt pipeline-summary summary_path captures: pipeline-summary is a - # terminal reporting skill that writes to disk for human use; summary_path - # is captured for observability only — no downstream step consumes it. - if cap_key == "summary_path" and "pipeline-summary" in step.with_args.get( - "skill_command", "" - ): + if _is_observability_capture(cap_key, step_name, step): continue warnings.append( DataFlowWarning( @@ -594,6 +815,12 @@ def make_validation_context( """ step_graph = _build_step_graph(recipe) dataflow = analyze_dataflow(recipe, step_graph=step_graph) + # Build predecessor map once; also passed to extract_blocks to avoid + # recomputing the same inversion inside that function. + predecessors: dict[str, set[str]] = {} + for src, successors in step_graph.items(): + for dst in successors: + predecessors.setdefault(dst, set()).add(src) return ValidationContext( recipe=recipe, step_graph=step_graph, @@ -603,4 +830,6 @@ def make_validation_context( available_sub_recipes=available_sub_recipes, project_dir=project_dir, disabled_subsets=disabled_subsets, + blocks=extract_blocks(recipe, step_graph, predecessors=predecessors), + predecessors=predecessors, ) diff --git a/src/autoskillit/recipe/_api.py b/src/autoskillit/recipe/_api.py index 4c50e1b627..82c5772032 100644 --- a/src/autoskillit/recipe/_api.py +++ b/src/autoskillit/recipe/_api.py @@ -14,12 +14,14 @@ from autoskillit.core import ( LoadResult, RecipeSource, + SkillLister, TerminalColumn, YAMLError, _render_gfm_table, get_logger, load_yaml, pkg_root, + resolve_temp_dir, ) from autoskillit.recipe._analysis import make_validation_context from autoskillit.recipe.contracts import ( @@ -41,6 +43,7 @@ find_recipe_by_name, find_sub_recipe_by_name, list_recipes, + substitute_temp_placeholder, ) from autoskillit.recipe.io import ( load_recipe as _load_recipe_from_path, @@ -112,10 +115,10 @@ def build_ingredient_rows( sort_key = _ingredient_sort_key(name, required, default) if default is None and required: default_str, name_str = "(required)", f"{name} *" + elif res := resolved.get(name): + default_str, name_str = res, name elif default == "": - res = resolved.get(name) - default_str = res if res else "auto-detect" - name_str = name + default_str, name_str = "auto-detect", name elif default == "true": default_str, name_str = "on", name elif default == "false": @@ -157,6 +160,7 @@ class LoadRecipeResult(TypedDict, total=False): suggestions: list[dict[str, Any]] valid: bool kitchen_rules: list[str] + requires_packs: list[str] error: str greeting: str ingredients_table: str @@ -366,11 +370,20 @@ def _fix_result_route(route: Any) -> Any: merged_rules.append(rule) seen_rules.add(rule) + # Merge requires_packs: union (parent first, then sub-recipe additions) + seen_packs: set[str] = set(parent.requires_packs) + merged_packs = list(parent.requires_packs) + for pack in sub.requires_packs: + if pack not in seen_packs: + merged_packs.append(pack) + seen_packs.add(pack) + return dataclasses.replace( parent, steps=new_steps, ingredients=merged_ingredients, kitchen_rules=merged_rules, + requires_packs=merged_packs, ) @@ -378,6 +391,7 @@ def _build_active_recipe( recipe: Any, ingredient_overrides: dict[str, str] | None, project_dir: Path, + temp_dir_relpath: str = ".autoskillit/temp", ) -> tuple[Any, Any | None]: """Return (active_recipe, combined_recipe | None). @@ -418,7 +432,7 @@ def _build_active_recipe( f"Expected in recipes/sub-recipes/{current_step.sub_recipe}.yaml" ) try: - sub_recipe = _load_recipe_from_path(sr_path) + sub_recipe = _load_recipe_from_path(sr_path, temp_dir_relpath) except (YAMLError, ValueError, OSError) as exc: raise ValueError( f"Failed to load sub-recipe '{current_step.sub_recipe}' " @@ -432,9 +446,20 @@ def _build_active_recipe( return working, combined -def validate_from_path(path: Path) -> dict[str, Any]: +def validate_from_path( + path: Path, + temp_dir_relpath: str = ".autoskillit/temp", + *, + lister: SkillLister | None = None, +) -> dict[str, Any]: """Validate a recipe YAML file at the given path. + Args: + path: Path to the recipe YAML file. + temp_dir_relpath: Relative path to the temp directory used for + ``{{AUTOSKILLIT_TEMP}}`` substitution. Defaults to + ``.autoskillit/temp``. + Returns: {"valid": bool, "errors": list, "quality": dict, "semantic": list, "contracts": list} On file/parse error: {"error": str} @@ -446,7 +471,9 @@ def validate_from_path(path: Path) -> dict[str, Any]: } try: - data = load_yaml(path) + raw_text = path.read_text(encoding="utf-8") + substituted = substitute_temp_placeholder(raw_text, temp_dir_relpath) + data = load_yaml(substituted) except YAMLError as exc: return { "valid": False, @@ -459,11 +486,14 @@ def validate_from_path(path: Path) -> dict[str, Any]: "findings": [{"error": "File must contain a YAML mapping"}], } - from autoskillit.workspace import SkillResolver # noqa: PLC0415 + if lister is None: + from autoskillit.workspace import DefaultSkillResolver # noqa: PLC0415 + + lister = DefaultSkillResolver() recipe = _parse_recipe(data) errors = validate_recipe(recipe) - known_skills = frozenset(s.name for s in SkillResolver().list_all()) + known_skills = frozenset(s.name for s in lister.list_all()) ctx = make_validation_context(recipe, available_skills=known_skills) report = ctx.dataflow semantic_findings = run_semantic_rules(ctx) @@ -497,6 +527,9 @@ def load_and_validate( recipe_info: RecipeInfo | None = None, resolved_defaults: dict[str, str] | None = None, ingredient_overrides: dict[str, str] | None = None, + temp_dir: Path | None = None, + temp_dir_relpath: str | None = None, + lister: SkillLister | None = None, ) -> LoadRecipeResult: """Load a recipe by name and run full validation. @@ -554,6 +587,8 @@ def load_and_validate( return {"error": f"No recipe named '{name}' found"} raw = match.content if match.content is not None else match.path.read_text() + _temp_relpath = temp_dir_relpath or ".autoskillit/temp" + raw = substitute_temp_placeholder(raw, _temp_relpath) suggestions: list[dict[str, Any]] = [] valid = True recipe = None @@ -575,7 +610,7 @@ def load_and_validate( # Stage: sub-recipe composition (lazy-loaded prefixes) active_recipe, combined_recipe = _build_active_recipe( - recipe, ingredient_overrides, _pdir + recipe, ingredient_overrides, _pdir, _temp_relpath ) # Stage: structural validation on active recipe @@ -587,10 +622,13 @@ def load_and_validate( t0 = _t("validate_recipe", t0, name) # Stage: semantic rules (builds ValidationContext once — shared computation) - from autoskillit.workspace import SkillResolver # noqa: PLC0415 + if lister is None: + from autoskillit.workspace import DefaultSkillResolver # noqa: PLC0415 + + lister = DefaultSkillResolver() known = frozenset(r.name for r in list_recipes(_pdir).items) - known_skills = frozenset(s.name for s in SkillResolver().list_all()) + known_skills = frozenset(s.name for s in lister.list_all()) sub_recipes_dir = builtin_sub_recipes_dir() known_sub_recipes: frozenset[str] = ( frozenset(p.stem for p in sub_recipes_dir.glob("*.yaml")) @@ -626,9 +664,8 @@ def load_and_validate( # Stage: staleness check if contract: - staleness_cache_path = ( - _pdir / ".autoskillit" / "temp" / "recipe_staleness_cache.json" - ) + resolved_temp = temp_dir if temp_dir is not None else resolve_temp_dir(_pdir, None) + staleness_cache_path = resolved_temp / "recipe_staleness_cache.json" stale = check_contract_staleness( contract, recipe_path=match.path, cache_path=staleness_cache_path ) @@ -697,6 +734,8 @@ def load_and_validate( } if _serving_recipe is not None and _serving_recipe.kitchen_rules: result["kitchen_rules"] = _serving_recipe.kitchen_rules + if _serving_recipe is not None and _serving_recipe.requires_packs: + result["requires_packs"] = _serving_recipe.requires_packs if ing_table: result["ingredients_table"] = ing_table diff --git a/src/autoskillit/recipe/block_budgets.yaml b/src/autoskillit/recipe/block_budgets.yaml new file mode 100644 index 0000000000..3be4da956f --- /dev/null +++ b/src/autoskillit/recipe/block_budgets.yaml @@ -0,0 +1,20 @@ +# Block-level budget configuration for recipe semantic validation. +# +# Each top-level key is a block name (matching RecipeStep.block declarations). +# The special DEFAULT key provides fallback budgets for blocks not listed here. +# +# Fields per block: +# run_cmd: maximum number of run_cmd steps allowed in the block +# mcp_tools: maximum number of non-run_cmd MCP tool calls allowed +# forbid_gh_api: if true, any "gh api" shell pattern in a run_cmd inside this block is an error +# +# version: enables future staleness detection via _llm_triage.py +version: 1 + +DEFAULT: + run_cmd: 1 # fallback budget for blocks not explicitly listed + +pre_queue_gate: + run_cmd: 0 # MCP-only block — shell gh api calls are prohibited + mcp_tools: 1 # exactly one consolidated tool call for all three captures + forbid_gh_api: true diff --git a/src/autoskillit/recipe/contracts.py b/src/autoskillit/recipe/contracts.py index b114034d18..f26c0042f0 100644 --- a/src/autoskillit/recipe/contracts.py +++ b/src/autoskillit/recipe/contracts.py @@ -11,7 +11,7 @@ from typing import TYPE_CHECKING, Any if TYPE_CHECKING: - from autoskillit.workspace import SkillResolver + from autoskillit.core import SkillResolver from autoskillit.core import ( SKILL_TOOLS, @@ -23,6 +23,7 @@ pkg_root, ) from autoskillit.recipe.io import _parse_recipe +from autoskillit.recipe.schema import Recipe, RecipeBlock from autoskillit.recipe.staleness_cache import ( StalenessEntry, compute_recipe_hash, @@ -43,6 +44,7 @@ class SkillInput: name: str type: str required: bool + recommended: bool = False @dataclasses.dataclass @@ -77,6 +79,24 @@ class DataFlowEntry: produced: list[str] +@dataclasses.dataclass(frozen=True) +class BlockFingerprint: + """Structural fingerprint for a named recipe block. + + Used by ``check_contract_staleness`` to detect silent composition drift: + any change to a block's member count, tool usage, gh api call count, or + capture names produces a fingerprint mismatch (reason='block_composition_drift'). + """ + + name: str + member_count: int + tool_counts_sorted: tuple[tuple[str, int], ...] # sorted by tool name for stable comparison + gh_api_occurrences: int + capture_names_hash: str # sha256hex of sorted capture key names across all members + entry_step: str + exit_step: str + + @dataclasses.dataclass class RecipeCard: generated_at: str @@ -84,6 +104,9 @@ class RecipeCard: skill_hashes: dict[str, str] skills: dict[str, SkillContract] dataflow: list[DataFlowEntry] + block_fingerprints: tuple[BlockFingerprint, ...] = dataclasses.field( + default_factory=tuple # type: ignore[arg-type] + ) # --------------------------------------------------------------------------- @@ -92,9 +115,9 @@ class RecipeCard: _SKILL_NAME_RE = re.compile(r"/autoskillit:([\w-]+)") _CONTEXT_REF_RE = re.compile(r"\$\{\{\s*context\.(\w+)\s*\}\}") -_INPUT_REF_RE = re.compile(r"\$\{\{\s*inputs\.(\w+)\s*\}\}") +INPUT_REF_RE = re.compile(r"\$\{\{\s*inputs\.(\w+)\s*\}\}") _TEMPLATE_REF_RE = re.compile(r"\$\{\{[^}]+\}\}") -_RESULT_CAPTURE_RE = re.compile(r"\$\{\{\s*result\.([\w-]+)\s*\}\}") +RESULT_CAPTURE_RE = re.compile(r"\$\{\{\s*result\.([\w-]+)\s*\}\}") # --------------------------------------------------------------------------- @@ -122,6 +145,11 @@ def resolve_skill_name(skill_command: str) -> str | None: # Reject dynamic names containing template expressions if "${{" in name: return None + # Reject names truncated by a bash-style {placeholder} token immediately + # following the match (e.g. "/autoskillit:exp-lens-{slug}" extracts + # "exp-lens-" but is dynamic — the true name is resolved at runtime). + if match.end() < len(skill_command) and skill_command[match.end()] == "{": + return None return name @@ -136,6 +164,7 @@ def get_skill_contract(skill_name: str, manifest: dict[str, Any]) -> SkillContra name=inp["name"], type=inp["type"], required=inp.get("required", False), + recommended=inp.get("recommended", False), ) for inp in skill_data.get("inputs", []) ] @@ -177,7 +206,7 @@ def extract_input_refs(step: Any) -> set[str]: """Extract ${{ inputs.X }} references from a step's with_args.""" refs: set[str] = set() for val in step.with_args.values(): - refs.update(_INPUT_REF_RE.findall(str(val))) + refs.update(INPUT_REF_RE.findall(str(val))) return refs @@ -189,7 +218,7 @@ def extract_skill_cmd_refs(skill_command: str) -> set[str]: invocations where template ref names don't match named contract inputs. """ ctx = set(_CONTEXT_REF_RE.findall(skill_command)) - inp = set(_INPUT_REF_RE.findall(skill_command)) + inp = set(INPUT_REF_RE.findall(skill_command)) return ctx | inp @@ -214,17 +243,77 @@ def count_positional_args(skill_command: str) -> int: return len(without_templates.split()) +# --------------------------------------------------------------------------- +# Block fingerprint helpers +# --------------------------------------------------------------------------- + + +def _compute_block_fingerprint(block: RecipeBlock) -> BlockFingerprint: + """Compute a structural fingerprint for a RecipeBlock. + + The fingerprint captures: + - ``member_count``: total number of member steps + - ``tool_counts_sorted``: per-tool counts sorted by tool name (stable comparison) + - ``gh_api_occurrences``: total 'gh api' shell substring occurrences + - ``capture_names_hash``: sha256 of the sorted set of capture key names across members + - ``entry_step`` / ``exit_step``: the block's entry and exit step names + """ + all_capture_names: list[str] = [] + for step in block.members: + all_capture_names.extend(sorted((step.capture or {}).keys())) + sorted_capture_names = sorted(all_capture_names) + capture_names_hash = ( + f"sha256:{hashlib.sha256(' '.join(sorted_capture_names).encode()).hexdigest()}" + ) + tool_counts_sorted = tuple(sorted(block.tool_counts.items())) + return BlockFingerprint( + name=block.name, + member_count=len(block.members), + tool_counts_sorted=tool_counts_sorted, + gh_api_occurrences=block.gh_api_occurrences, + capture_names_hash=capture_names_hash, + entry_step=block.entry, + exit_step=block.exit, + ) + + +def _generate_recipe_card_for_recipe(recipe: Recipe) -> RecipeCard: + """Generate a RecipeCard from a Recipe object (no disk write). + + Used by the block fingerprint drift detection path in ``check_contract_staleness`` + and by tests that want a ``RecipeCard`` with populated ``block_fingerprints``. + Uses a deferred import of ``_build_step_graph`` and ``extract_blocks`` to avoid + a circular import (``_analysis.py`` imports from ``contracts.py``). + """ + # Deferred import to avoid circular dependency: + # contracts.py → _analysis.py (already safe via _analysis.py → contracts.py) + from autoskillit.recipe._analysis import _build_step_graph, extract_blocks # noqa: PLC0415 + + step_graph = _build_step_graph(recipe) + blocks = extract_blocks(recipe, step_graph) + fingerprints = tuple(_compute_block_fingerprint(b) for b in blocks) + manifest = load_bundled_manifest() + return RecipeCard( + generated_at=datetime.now(UTC).isoformat(), + bundled_manifest_version=manifest.get("version", ""), + skill_hashes={}, + skills={}, + dataflow=[], + block_fingerprints=fingerprints, + ) + + # --------------------------------------------------------------------------- # Pipeline contract generation, loading, and validation # --------------------------------------------------------------------------- def generate_recipe_card( - pipeline_path: Path | str, - recipes_dir: Path | str, + pipeline_path: Path | str | Recipe, + recipes_dir: Path | str | None = None, *, skills_dir: Path | None = None, -) -> dict: +) -> dict | RecipeCard: """Generate a recipe card file for a recipe. Walks each step, resolves skill names, looks up contracts in the manifest, @@ -234,8 +323,15 @@ def generate_recipe_card( When ``skills_dir`` is None, skill hashes are not computed and ``skill_hashes`` in the generated card will be empty. - Returns the contract data dict directly (no disk re-read required by callers). + When ``pipeline_path`` is a ``Recipe`` object, returns a ``RecipeCard`` with + populated ``block_fingerprints`` (no disk write). The path-based form returns + the contract data dict directly (no disk re-read required by callers). """ + if isinstance(pipeline_path, Recipe): + return _generate_recipe_card_for_recipe(pipeline_path) + + if recipes_dir is None: + raise ValueError("recipes_dir required when pipeline_path is a file path") pipeline_path = Path(pipeline_path) recipes_dir = Path(recipes_dir) @@ -266,7 +362,12 @@ def generate_recipe_card( if contract: skill_entry: dict[str, Any] = { "inputs": [ - {"name": i.name, "type": i.type, "required": i.required} + { + "name": i.name, + "type": i.type, + "required": i.required, + "recommended": i.recommended, + } for i in contract.inputs ], "outputs": [{"name": o.name, "type": o.type} for o in contract.outputs], @@ -375,15 +476,22 @@ def validate_recipe_cards(recipe: Any, contract: dict[str, Any]) -> list[dict[st def check_contract_staleness( - contract: dict[str, Any], + contract: dict[str, Any] | Recipe, *, recipe_path: Path | None = None, cache_path: Path | None = None, skills_dir: Path | None = None, resolver: SkillResolver | None = None, + stored_card: RecipeCard | None = None, ) -> list[StaleItem]: """Check a pipeline contract for staleness against the current manifest. + When ``stored_card`` is provided and ``contract`` is a ``Recipe``, compares + block fingerprints from the stored card against the current recipe's blocks. + Returns ``StaleItem`` entries with ``reason='block_composition_drift'`` for + any block whose fingerprint has changed. This path does not perform manifest + or skill-hash checks — it is a pure structural comparison. + When ``recipe_path`` and ``cache_path`` are both provided, a disk-backed cache keyed by recipe content hash + manifest version is consulted first. A cache hit with ``is_stale=False`` returns [] immediately without reading @@ -393,8 +501,43 @@ def check_contract_staleness( When ``skills_dir`` is None, the bundled skills directory is used for hash comparison. + When ``contract`` is a ``Recipe`` but ``stored_card`` is ``None``, no + comparison baseline is available and [] is returned immediately. This is + expected during initial card generation before a stored card exists. + Returns a list of StaleItem entries indicating what changed. """ + if stored_card is not None: + recipe_obj = contract if isinstance(contract, Recipe) else None + if recipe_obj is not None: + current_card = _generate_recipe_card_for_recipe(recipe_obj) + current_fps = {fp.name: fp for fp in current_card.block_fingerprints} + stale_items: list[StaleItem] = [] + for stored_fp in stored_card.block_fingerprints: + current_fp = current_fps.get(stored_fp.name) + if current_fp is None: + stale_items.append( + StaleItem( + skill=stored_fp.name, + reason="block_composition_drift", + stored_value=repr(stored_fp), + current_value="(block removed)", + ) + ) + elif current_fp != stored_fp: + stale_items.append( + StaleItem( + skill=stored_fp.name, + reason="block_composition_drift", + stored_value=repr(stored_fp), + current_value=repr(current_fp), + ) + ) + return stale_items + + if isinstance(contract, Recipe): + return [] + manifest = load_bundled_manifest() current_version = manifest["version"] cached: StalenessEntry | None = None @@ -426,9 +569,9 @@ def check_contract_staleness( effective_skills_dir: Path | None = skills_dir else: if resolver is None: - from autoskillit.workspace import SkillResolver # noqa: PLC0415 + from autoskillit.workspace import DefaultSkillResolver # noqa: PLC0415 - resolver = SkillResolver() + resolver = DefaultSkillResolver() _resolver = resolver effective_skills_dir = None for skill_name, stored_hash in contract.get("skill_hashes", {}).items(): diff --git a/src/autoskillit/recipe/experiment_type_registry.py b/src/autoskillit/recipe/experiment_type_registry.py new file mode 100644 index 0000000000..f94f9c884f --- /dev/null +++ b/src/autoskillit/recipe/experiment_type_registry.py @@ -0,0 +1,86 @@ +"""Experiment type registry — load bundled and user-defined experiment type specs.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +from autoskillit.core import get_logger, load_yaml, pkg_root + +_log = get_logger(__name__) + +BUNDLED_EXPERIMENT_TYPES_DIR: Path = pkg_root() / "recipes" / "experiment-types" + + +@dataclass +class ExperimentTypeSpec: + """Specification for a single experiment type.""" + + name: str + classification_triggers: list[str] + dimension_weights: dict[str, str] + applicable_lenses: dict[str, str | None] + red_team_focus: dict[str, str] + l1_severity: dict[str, str] + + +def _parse_experiment_type(data: dict, source_path: Path) -> ExperimentTypeSpec: + if "name" not in data: + raise ValueError(f"Experiment type YAML missing 'name' field: {source_path}") + for field in ("dimension_weights", "applicable_lenses", "red_team_focus", "l1_severity"): + val = data.get(field) + if val is not None and not isinstance(val, dict): + raise TypeError( + f"Experiment type '{data['name']}' field '{field}' must be a dict, " + f"got {type(val).__name__}: {source_path}" + ) + return ExperimentTypeSpec( + name=data["name"], + classification_triggers=list(data.get("classification_triggers", [])), + dimension_weights=dict(data.get("dimension_weights", {})), + applicable_lenses=dict(data.get("applicable_lenses", {})), + red_team_focus=dict(data.get("red_team_focus", {})), + l1_severity=dict(data.get("l1_severity", {})), + ) + + +def _load_types_from_dir(directory: Path) -> dict[str, ExperimentTypeSpec]: + if not directory.exists(): + return {} + result: dict[str, ExperimentTypeSpec] = {} + for path in sorted(directory.glob("*.yaml")): + try: + data = load_yaml(path) + if isinstance(data, dict): + spec = _parse_experiment_type(data, path) + result[spec.name] = spec + except Exception: + _log.warning("Skipping malformed experiment type file: %s", path, exc_info=True) + return result + + +def load_all_experiment_types( + project_dir: Path | None = None, +) -> dict[str, ExperimentTypeSpec]: + """Load experiment types: bundled types merged with user-defined overrides. + + User-defined types with the same name as a bundled type replace the bundled + type entirely — no field merging. User-defined types with a new name are added + alongside bundled types. + + Args: + project_dir: Project root containing optional user-defined overrides at + ``.autoskillit/experiment-types/``. When ``None``, only bundled types + are returned. + + Returns: + Mapping of experiment type name to ``ExperimentTypeSpec``. + """ + types = _load_types_from_dir(BUNDLED_EXPERIMENT_TYPES_DIR) + + if project_dir is not None: + user_dir = Path(project_dir) / ".autoskillit" / "experiment-types" + user_types = _load_types_from_dir(user_dir) + types.update(user_types) + + return types diff --git a/src/autoskillit/recipe/io.py b/src/autoskillit/recipe/io.py index 3f5d82a0f7..0b3cc349d4 100644 --- a/src/autoskillit/recipe/io.py +++ b/src/autoskillit/recipe/io.py @@ -20,12 +20,45 @@ logger = get_logger(__name__) -def load_recipe(path: Path) -> Recipe: - """Parse a YAML recipe file into a Recipe dataclass.""" - data = load_yaml(path) +_TEMP_PLACEHOLDER = "{{AUTOSKILLIT_TEMP}}" + + +def substitute_temp_placeholder(text: str, temp_dir_relpath: str) -> str: + """Replace ``{{AUTOSKILLIT_TEMP}}`` in raw recipe/skill text. + + Validates that ``temp_dir_relpath`` is YAML-safe (no newlines or + ``": "`` sequences); raises ``ValueError`` otherwise. Filesystem paths + should never contain these characters, but the guard makes the failure + loud and free. + """ + if "\n" in temp_dir_relpath or ": " in temp_dir_relpath: + raise ValueError(f"temp_dir_relpath is YAML-unsafe: {temp_dir_relpath!r}") + return text.replace(_TEMP_PLACEHOLDER, temp_dir_relpath) + + +def load_recipe(path: Path, temp_dir_relpath: str = ".autoskillit/temp") -> Recipe: + """Parse a YAML recipe file into a Recipe dataclass. + + Substitutes ``{{AUTOSKILLIT_TEMP}}`` in the raw text with + ``temp_dir_relpath`` *before* YAML parsing so the resulting Recipe + dataclass observes the resolved value uniformly. + + After parsing, ``recipe.blocks`` is populated via ``extract_blocks`` from + ``_analysis.py``. The import is deferred to break the circular dependency: + ``_analysis.py`` imports ``iter_steps_with_context`` from this module, so a + top-level import here would create a cycle. + """ + raw_text = path.read_text(encoding="utf-8") + substituted = substitute_temp_placeholder(raw_text, temp_dir_relpath) + data = load_yaml(substituted) if not isinstance(data, dict): raise ValueError(f"Recipe file must contain a YAML mapping: {path}") - return _parse_recipe(data) + recipe = _parse_recipe(data) + # Deferred import breaks the circular dependency with _analysis.py. + from autoskillit.recipe._analysis import _build_step_graph, extract_blocks # noqa: PLC0415 + + recipe.blocks = extract_blocks(recipe, _build_step_graph(recipe)) + return recipe def list_recipes(project_dir: Path) -> LoadResult[RecipeInfo]: @@ -102,6 +135,7 @@ def find_recipe_by_name(name: str, project_dir: Path) -> RecipeInfo | None: # field name here — the assertion below will fail at import time otherwise. _PARSE_STEP_HANDLED_FIELDS: frozenset[str] = frozenset( { + "name", # Set from YAML dict key in _parse_recipe, not from step data "tool", "action", "python", @@ -123,6 +157,10 @@ def find_recipe_by_name(name: str, project_dir: Path) -> RecipeInfo | None: "description", "sub_recipe", "gate", + "optional_context_refs", + "stale_threshold", + "idle_output_timeout", + "block", # Named block anchor; maps to step's block: key in YAML } ) if _PARSE_STEP_HANDLED_FIELDS != frozenset(RecipeStep.__dataclass_fields__): @@ -153,12 +191,20 @@ def _parse_recipe(data: dict[str, Any]) -> Recipe: steps: dict[str, RecipeStep] = {} for step_name, step_data in (data.get("steps") or {}).items(): if isinstance(step_data, dict): - steps[step_name] = _parse_step(step_data) + step = _parse_step(step_data) + step.name = step_name + steps[step_name] = step kitchen_rules = data.get("kitchen_rules", []) if not isinstance(kitchen_rules, list): raise ValueError(f"'kitchen_rules' must be a list, got {type(kitchen_rules).__name__!r}") + requires_packs_raw = data.get("requires_packs") or [] + if not isinstance(requires_packs_raw, list): + raise ValueError( + f"'requires_packs' must be a list, got {type(requires_packs_raw).__name__!r}" + ) + return Recipe( name=name, description=description, @@ -168,6 +214,7 @@ def _parse_recipe(data: dict[str, Any]) -> Recipe: kitchen_rules=kitchen_rules, version=data.get(AUTOSKILLIT_VERSION_KEY), experimental=bool(data.get("experimental", False)), + requires_packs=requires_packs_raw, ) @@ -220,6 +267,10 @@ def _parse_step(data: dict[str, Any]) -> RecipeStep: description=data.get("description", ""), sub_recipe=data.get("sub_recipe"), gate=data.get("gate"), + optional_context_refs=data.get("optional_context_refs", []), + stale_threshold=data.get("stale_threshold"), + idle_output_timeout=data.get("idle_output_timeout"), + block=data.get("block"), ) diff --git a/src/autoskillit/recipe/registry.py b/src/autoskillit/recipe/registry.py index 8a7142c0ed..e1b273e62b 100644 --- a/src/autoskillit/recipe/registry.py +++ b/src/autoskillit/recipe/registry.py @@ -16,7 +16,7 @@ # not import registry.py). The runtime isinstance() check in run_semantic_rules also # requires this to be available as a concrete class, not just a TYPE_CHECKING stub. from autoskillit.recipe._analysis import ValidationContext # noqa: E402 -from autoskillit.recipe.schema import DataFlowReport, Recipe +from autoskillit.recipe.schema import DataFlowReport, Recipe, RecipeBlock @dataclass @@ -50,6 +50,32 @@ class RuleSpec: _RULE_REGISTRY: list[RuleSpec] = [] +@dataclass(frozen=True) +class BlockContext: + """Per-block dispatch context for block-level semantic rules. + + Block rules receive a ``BlockContext`` rather than a full ``ValidationContext`` + to enforce the constraint that rules operate on exactly one block at a time. + ``parent`` is available read-only for cross-block lookups if ever needed. + """ + + block: RecipeBlock + parent: ValidationContext + + +@dataclass +class BlockRuleSpec: + """Internal: metadata for one registered block-level rule.""" + + name: str + description: str + severity: Severity + check: Callable[[BlockContext], list[RuleFinding]] + + +_BLOCK_RULE_REGISTRY: list[BlockRuleSpec] = [] + + def semantic_rule( name: str, description: str, @@ -68,6 +94,29 @@ def decorator( return decorator +def block_rule( + name: str, + description: str, + severity: Severity = Severity.WARNING, +) -> Callable: + """Decorator that registers a block-level semantic validation rule. + + The decorated function receives a ``BlockContext`` (one block at a time) and + returns a list of ``RuleFinding`` objects. Registered rules are dispatched + by ``run_semantic_rules`` for every block in ``ctx.blocks``. + """ + + def decorator( + fn: Callable[[BlockContext], list[RuleFinding]], + ) -> Callable[[BlockContext], list[RuleFinding]]: + _BLOCK_RULE_REGISTRY.append( + BlockRuleSpec(name=name, description=description, severity=severity, check=fn) + ) + return fn + + return decorator + + def run_semantic_rules(wf: Recipe | ValidationContext) -> list[RuleFinding]: """Execute all registered semantic rules against a workflow. @@ -81,6 +130,11 @@ def run_semantic_rules(wf: Recipe | ValidationContext) -> list[RuleFinding]: findings: list[RuleFinding] = [] for spec in _RULE_REGISTRY: findings.extend(spec.check(ctx)) + # Dispatch block-level rules for every declared block in the recipe. + for block in ctx.blocks: + bctx = BlockContext(block=block, parent=ctx) + for bspec in _BLOCK_RULE_REGISTRY: + findings.extend(bspec.check(bctx)) return findings diff --git a/src/autoskillit/recipe/repository.py b/src/autoskillit/recipe/repository.py index e777cb3062..a72fa3d9f0 100644 --- a/src/autoskillit/recipe/repository.py +++ b/src/autoskillit/recipe/repository.py @@ -59,6 +59,8 @@ def load_and_validate( suppressed: Sequence[str] | None = None, resolved_defaults: dict[str, str] | None = None, ingredient_overrides: dict[str, str] | None = None, + temp_dir: Path | None = None, + temp_dir_relpath: str | None = None, ) -> dict[str, Any]: recipe_info = self.find(name, project_dir) return cast( @@ -70,11 +72,15 @@ def load_and_validate( recipe_info=recipe_info, resolved_defaults=resolved_defaults, ingredient_overrides=ingredient_overrides, + temp_dir=temp_dir, + temp_dir_relpath=temp_dir_relpath, ), ) - def validate_from_path(self, script_path: Any) -> dict[str, Any]: - return _api.validate_from_path(script_path) + def validate_from_path( + self, script_path: Any, temp_dir_relpath: str = ".autoskillit/temp" + ) -> dict[str, Any]: + return _api.validate_from_path(script_path, temp_dir_relpath=temp_dir_relpath) def list_all(self, project_dir: Any | None = None) -> dict[str, Any]: return _api.list_all(project_dir=project_dir) diff --git a/src/autoskillit/recipe/rules_blocks.py b/src/autoskillit/recipe/rules_blocks.py new file mode 100644 index 0000000000..c60725b6ab --- /dev/null +++ b/src/autoskillit/recipe/rules_blocks.py @@ -0,0 +1,202 @@ +"""Block-level semantic validation rules for recipe pipelines. + +Each rule is registered via @block_rule and dispatched by run_semantic_rules +for every RecipeBlock in a recipe. Block rules operate on one block at a time +via BlockContext — they must not access ctx.recipe.steps directly to express +cross-block constraints; use bctx.parent for read-only access when needed. + +Budget values are loaded from block_budgets.yaml at import time (lru_cache). +""" + +from __future__ import annotations + +from collections.abc import Mapping +from functools import lru_cache +from typing import Any + +from autoskillit.core import Severity, load_yaml, pkg_root +from autoskillit.recipe.registry import BlockContext, RuleFinding, block_rule + + +@lru_cache(maxsize=1) +def _block_budgets() -> Mapping[str, Mapping[str, Any]]: + """Load block_budgets.yaml, cached for the lifetime of the process.""" + path = pkg_root() / "recipe" / "block_budgets.yaml" + try: + data = load_yaml(path) + except FileNotFoundError: + return {} + if not isinstance(data, dict): + return {} + return data # type: ignore[return-value] + + +def _budget_for(block_name: str) -> dict[str, Any]: + """Return the budget dict for a named block, falling back to DEFAULT.""" + budgets = _block_budgets() + return dict(budgets.get(block_name, budgets.get("DEFAULT", {}))) + + +@block_rule( + name="block-run-cmd-budget", + description="Block members contain at most the declared number of run_cmd steps.", + severity=Severity.ERROR, +) +def _check_block_run_cmd_budget(bctx: BlockContext) -> list[RuleFinding]: + budget_entry = _budget_for(bctx.block.name) + if "run_cmd" not in budget_entry: + return [] # No run_cmd budget declared for this block — skip check + budget = int(budget_entry["run_cmd"]) + actual = bctx.block.tool_counts.get("run_cmd", 0) + if actual <= budget: + return [] + return [ + RuleFinding( + rule="block-run-cmd-budget", + severity=Severity.ERROR, + step_name=bctx.block.entry, + message=( + f"Block {bctx.block.name!r} contains {actual} run_cmd step" + f"{'s' if actual != 1 else ''} (budget: {budget}). " + f"Consolidate into an MCP tool." + ), + ) + ] + + +@block_rule( + name="block-mcp-tool-budget", + description="Block members contain at most the declared number of non-run_cmd MCP tool calls.", + severity=Severity.ERROR, +) +def _check_block_mcp_tool_budget(bctx: BlockContext) -> list[RuleFinding]: + budget_entry = _budget_for(bctx.block.name) + if "mcp_tools" not in budget_entry: + return [] # No mcp_tools budget declared for this block — skip check + budget = int(budget_entry["mcp_tools"]) + # MCP tool calls: any tool step that is not run_cmd + actual = sum(count for tool, count in bctx.block.tool_counts.items() if tool != "run_cmd") + if actual <= budget: + return [] + return [ + RuleFinding( + rule="block-mcp-tool-budget", + severity=Severity.ERROR, + step_name=bctx.block.entry, + message=( + f"Block {bctx.block.name!r} contains {actual} MCP tool call" + f"{'s' if actual != 1 else ''} (budget: {budget}). " + f"Reduce to a single consolidated tool call." + ), + ) + ] + + +@block_rule( + name="block-gh-api-forbidden", + description=( + "Blocks with forbid_gh_api: true must not contain 'gh api' shell patterns " + "in any run_cmd step." + ), + severity=Severity.ERROR, +) +def _check_block_gh_api_forbidden(bctx: BlockContext) -> list[RuleFinding]: + if not _budget_for(bctx.block.name).get("forbid_gh_api", False): + return [] # This block does not prohibit gh api shell patterns + if bctx.block.gh_api_occurrences == 0: + return [] + return [ + RuleFinding( + rule="block-gh-api-forbidden", + severity=Severity.ERROR, + step_name=bctx.block.entry, + message=( + f"Block {bctx.block.name!r} has {bctx.block.gh_api_occurrences} " + f"'gh api' shell invocation" + f"{'s' if bctx.block.gh_api_occurrences != 1 else ''}. " + f"MCP tools must own all GitHub API calls in declared blocks; " + f"consolidate into a single MCP tool call." + ), + ) + ] + + +@block_rule( + name="block-single-producer", + description="Each capture key produced within a block must originate from exactly one step.", + severity=Severity.WARNING, +) +def _check_block_single_producer(bctx: BlockContext) -> list[RuleFinding]: + # Build a map: capture_key → list of step names that produce it + producers: dict[str, list[str]] = {} + for step in bctx.block.members: + for cap_key in step.capture or {}: + producers.setdefault(cap_key, []).append(step.name) + findings = [] + for cap_key, producer_names in producers.items(): + if len(producer_names) > 1: + findings.append( + RuleFinding( + rule="block-single-producer", + severity=Severity.WARNING, + step_name=bctx.block.entry, + message=( + f"Block {bctx.block.name!r}: capture key {cap_key!r} is produced by " + f"{len(producer_names)} steps ({', '.join(producer_names)}); " + f"expected exactly one producer." + ), + ) + ) + return findings + + +@block_rule( + name="block-entry-exit-reachable", + description=( + "Block members must form a single connected region with exactly one " + "entry step and one exit step." + ), + severity=Severity.WARNING, +) +def _check_block_entry_exit_reachable(bctx: BlockContext) -> list[RuleFinding]: + step_graph = bctx.parent.step_graph + # Use the pre-computed predecessor map from ValidationContext (built once per pass). + predecessors = bctx.parent.predecessors + + member_names = {s.name for s in bctx.block.members} + entry_candidates = [ + s for s in bctx.block.members if not (predecessors.get(s.name, set()) & member_names) + ] + exit_candidates = [ + s for s in bctx.block.members if not (step_graph.get(s.name, set()) & member_names) + ] + findings = [] + if len(entry_candidates) != 1: + findings.append( + RuleFinding( + rule="block-entry-exit-reachable", + severity=Severity.WARNING, + step_name=bctx.block.entry, + message=( + f"Block {bctx.block.name!r} has {len(entry_candidates)} entry candidates " + f"(expected 1): " + f"{[s.name for s in entry_candidates]}. " + f"Block members must form a single connected region." + ), + ) + ) + if len(exit_candidates) != 1: + findings.append( + RuleFinding( + rule="block-entry-exit-reachable", + severity=Severity.WARNING, + step_name=bctx.block.exit, + message=( + f"Block {bctx.block.name!r} has {len(exit_candidates)} exit candidates " + f"(expected 1): " + f"{[s.name for s in exit_candidates]}. " + f"Block members must form a single connected region." + ), + ) + ) + return findings diff --git a/src/autoskillit/recipe/rules_ci.py b/src/autoskillit/recipe/rules_ci.py index dbdfd4b432..d5d12e82dd 100644 --- a/src/autoskillit/recipe/rules_ci.py +++ b/src/autoskillit/recipe/rules_ci.py @@ -2,7 +2,9 @@ from __future__ import annotations -from autoskillit.core import Severity +import re + +from autoskillit.core import PRState, Severity from autoskillit.recipe._analysis import ValidationContext from autoskillit.recipe.registry import RuleFinding, semantic_rule @@ -141,3 +143,183 @@ def _check_ci_failure_conflict_gate(ctx: ValidationContext) -> list[RuleFinding] ) ) return findings + + +_CI_EVENT_SCOPE_TOOLS = {"wait_for_ci", "get_ci_status"} + + +@semantic_rule( + name="ci-missing-event-scope", + description="CI tool step without event parameter risks cross-event confusion", + severity=Severity.WARNING, +) +def _check_ci_missing_event_scope(ctx: ValidationContext) -> list[RuleFinding]: + findings: list[RuleFinding] = [] + for step_name, step in ctx.recipe.steps.items(): + if step.tool not in _CI_EVENT_SCOPE_TOOLS: + continue + if "event" not in (step.with_args or {}): + findings.append( + RuleFinding( + rule="ci-missing-event-scope", + severity=Severity.WARNING, + step_name=step_name, + message=( + f"Step '{step_name}' calls {step.tool} without an 'event' parameter. " + f"Without event filtering, a passing pull_request run can mask a " + f"failing push run. Add event: 'push' (or the appropriate trigger " + f"event) to the step's with_args, or set ci.event in project config." + ), + ) + ) + return findings + + +@semantic_rule( + name="ci-hardcoded-workflow", + description="wait_for_ci step with hardcoded workflow bypasses config fallback", + severity=Severity.WARNING, +) +def _check_ci_hardcoded_workflow(ctx: ValidationContext) -> list[RuleFinding]: + findings: list[RuleFinding] = [] + for step_name, step in ctx.recipe.steps.items(): + if step.tool != "wait_for_ci": + continue + workflow = (step.with_args or {}).get("workflow") + if isinstance(workflow, str) and not workflow.startswith("${{"): + findings.append( + RuleFinding( + rule="ci-hardcoded-workflow", + severity=Severity.WARNING, + step_name=step_name, + message=( + f"Step '{step_name}' hardcodes workflow: '{workflow}'. " + f"Remove the workflow parameter to use the project-level " + f"ci.workflow config default, or use '${{{{ inputs.workflow }}}}' " + f"to parameterize it via recipe ingredients." + ), + ) + ) + return findings + + +# --------------------------------------------------------------------------- +# wait_for_merge_queue routing rules (I7 + I8) +# --------------------------------------------------------------------------- + +_REQUIRED_MQ_PR_STATES: frozenset[str] = frozenset(s.value for s in PRState if s != PRState.ERROR) +_PR_STATE_WHEN_RE = re.compile(r"\$\{\{\s*result\.pr_state\s*\}\}\s*==\s*(\w+)") +_MQ_EXPECTED_FALLBACK = "release_issue_timeout" + + +def _extract_mq_when_values(on_result: object) -> set[str]: + """Return the set of pr_state values covered by explicit when conditions.""" + values: set[str] = set() + for cond in getattr(on_result, "conditions", []): + if getattr(cond, "when", None) is None: + continue + m = _PR_STATE_WHEN_RE.search(cond.when) + if m: + values.add(m.group(1)) + return values + + +def _recipe_uses_release_issue_timeout(ctx: ValidationContext) -> bool: + """Return True if this recipe family uses release_issue_timeout as its error escalation step. + + The two new wait_for_merge_queue rules only apply to implementation/remediation-family + recipes that define release_issue_timeout. merge-prs.yaml and other recipe families + route queue timeouts/errors differently (e.g. register_clone_failure) and are exempt. + """ + return _MQ_EXPECTED_FALLBACK in ctx.recipe.steps + + +@semantic_rule( + name="wait-for-merge-queue-routing-covers-all-pr-states", + description=( + "Every non-error PRState value must have an explicit when arm in " + "wait_for_merge_queue on_result; prevents silent routing of new states to fallback" + ), + severity=Severity.ERROR, +) +def _check_wait_for_merge_queue_routing_covers_all_pr_states( + ctx: ValidationContext, +) -> list[RuleFinding]: + if not _recipe_uses_release_issue_timeout(ctx): + return [] + findings: list[RuleFinding] = [] + for step_name, step in ctx.recipe.steps.items(): + if step.tool != "wait_for_merge_queue": + continue + if step.on_result is None or not step.on_result.conditions: + continue + covered = _extract_mq_when_values(step.on_result) + missing = _REQUIRED_MQ_PR_STATES - covered + if missing: + findings.append( + RuleFinding( + rule="wait-for-merge-queue-routing-covers-all-pr-states", + severity=Severity.ERROR, + step_name=step_name, + message=( + f"Step {step_name!r} is missing explicit routing arms for " + f"PRState values: {sorted(missing)}. Every non-error PRState " + f"must have an explicit when condition in on_result." + ), + ) + ) + return findings + + +@semantic_rule( + name="wait-for-merge-queue-routing-conforms-to-expected-targets", + description=( + "wait_for_merge_queue fallback and on_failure must both target " + "release_issue_timeout; prevents silent success routing on timeout/unknown states" + ), + severity=Severity.ERROR, +) +def _check_wait_for_merge_queue_routing_conforms_to_expected_targets( + ctx: ValidationContext, +) -> list[RuleFinding]: + if not _recipe_uses_release_issue_timeout(ctx): + return [] + findings: list[RuleFinding] = [] + for step_name, step in ctx.recipe.steps.items(): + if step.tool != "wait_for_merge_queue": + continue + # Check fallback condition (when=None) + if step.on_result is not None and step.on_result.conditions: + fallback_routes = [ + c.route for c in step.on_result.conditions if getattr(c, "when", None) is None + ] + for route in fallback_routes: + if route != _MQ_EXPECTED_FALLBACK: + findings.append( + RuleFinding( + rule="wait-for-merge-queue-routing-conforms-to-expected-targets", + severity=Severity.ERROR, + step_name=step_name, + message=( + f"Step {step_name!r} has fallback route {route!r} but " + f"expected {_MQ_EXPECTED_FALLBACK!r}. The fallback must " + f"route to release_issue_timeout so unrecognised states " + f"are escalated, not silently treated as success." + ), + ) + ) + # Check on_failure + if step.on_failure is not None and step.on_failure != _MQ_EXPECTED_FALLBACK: + findings.append( + RuleFinding( + rule="wait-for-merge-queue-routing-conforms-to-expected-targets", + severity=Severity.ERROR, + step_name=step_name, + message=( + f"Step {step_name!r} has on_failure={step.on_failure!r} but " + f"expected {_MQ_EXPECTED_FALLBACK!r}. Tool errors must route " + f"to release_issue_timeout, not a success-path step." + ), + ) + ) + return findings diff --git a/src/autoskillit/recipe/rules_clone.py b/src/autoskillit/recipe/rules_clone.py index 7b8c82a821..50e8228fc8 100644 --- a/src/autoskillit/recipe/rules_clone.py +++ b/src/autoskillit/recipe/rules_clone.py @@ -1,7 +1,20 @@ -"""Semantic validation rules for clone, push, and multipart-plan capture.""" +"""Semantic validation rules for clone, push, and multipart-plan capture. + +clone-step dataflow rules +-------------------------- +- push-missing-explicit-remote-url: push_to_remote step is missing an explicit + remote_url argument; implicit lookup fails for non-bare repos. +- clone-local-strategy-with-remote-url-capture: a run_python clone_repo step + uses strategy="clone_local" and captures remote_url from the result. Under + local transport, remote_url is always empty, so any downstream consumer of + context.remote_url will receive "". The rule fires at recipe-validation time + (open_kitchen / load_recipe) before any runtime call. +""" from __future__ import annotations +import re + from autoskillit.core import ( SKILL_COMMAND_PREFIX, SKILL_TOOLS, @@ -91,3 +104,102 @@ def _check_push_missing_explicit_remote_url(ctx: ValidationContext) -> list[Rule for n, step in recipe.steps.items() if step.tool == "push_to_remote" and "remote_url" not in (step.with_args or {}) ] + + +_CLONE_REPO_PYTHON = "autoskillit.workspace.clone.clone_repo" +_TEMPLATE_RE = re.compile(r"\$\{\{.*?\}\}", re.DOTALL) +_SAFE_STRATEGIES = {"", "proceed"} + + +def _captures_result_remote_url(capture: dict[str, str]) -> bool: + """Return True if any capture entry reads result.remote_url from the step result.""" + for tmpl in capture.values(): + # Only flag entries whose template expression references result.remote_url. + # An entry like `other_key: "${{ result.remote_url }}"` still captures the + # empty value, so it is equally dangerous. + if "result.remote_url" in tmpl: + return True + return False + + +@semantic_rule( + name="clone-local-strategy-with-remote-url-capture", + description=( + "clone_repo step using strategy='clone_local' must not capture remote_url; " + "under local transport remote_url is always empty" + ), + severity=Severity.ERROR, +) +def _check_clone_local_remote_url_capture(ctx: ValidationContext) -> list[RuleFinding]: + """Reject recipes that combine clone_repo(strategy='clone_local') with remote_url capture. + + Under the clone_local strategy, clone_repo always sets remote_url to "". Any + downstream step that reads context.remote_url therefore receives an empty string, + silently corrupting push, CI-wait, or run_cmd steps. + + Strategy classification + ----------------------- + - absent / "" / "proceed" → safe; Part A guarantees non-empty on success + - "clone_local" (literal) → ERROR (always empty) + - template "${{ ... }}" → WARNING (cannot determine statically) + - any other unknown literal → WARNING (conservative default) + + The rule inspects template *expressions* (capture values), not just capture key + names, so aliasing (e.g. ``alt_url: "${{ result.remote_url }}"``) is caught. + """ + recipe = ctx.recipe + findings: list[RuleFinding] = [] + + for step_name, step in recipe.steps.items(): + if step.tool != "run_python": + continue + if step.python != _CLONE_REPO_PYTHON: + continue + + capture = step.capture or {} + if not _captures_result_remote_url(capture): + continue + + strategy: str = (step.with_args or {}).get("strategy", "") + + if strategy in _SAFE_STRATEGIES: + # proceed / absent: Part A guarantees a non-empty remote_url on success. + continue + + if strategy == "clone_local": + severity = Severity.ERROR + explanation = ( + f'clone step "{step_name}" uses strategy="clone_local" and captures ' + f"remote_url from result. Under clone_local, remote_url is always " + f'empty, so downstream consumers of context.remote_url will receive "". ' + f'Remove the remote_url capture, or use strategy="proceed" if a ' + f"network clone is intended." + ) + elif _TEMPLATE_RE.search(strategy): + severity = Severity.WARNING + explanation = ( + f'clone step "{step_name}" uses a templated strategy ({strategy!r}) ' + f"that cannot be statically determined. If the strategy resolves to " + f'"clone_local" at runtime, remote_url will be empty and downstream ' + f"consumers of context.remote_url will receive an empty string." + ) + else: + severity = Severity.WARNING + explanation = ( + f'clone step "{step_name}" uses an unrecognised strategy ({strategy!r}) ' + f"and captures remote_url. If this strategy produces an empty remote_url, " + f'downstream consumers of context.remote_url will receive "". ' + f"Verify that {strategy!r} always produces a non-empty remote_url, " + f"or remove the remote_url capture." + ) + + findings.append( + RuleFinding( + rule="clone-local-strategy-with-remote-url-capture", + severity=severity, + step_name=step_name, + message=explanation, + ) + ) + + return findings diff --git a/src/autoskillit/recipe/rules_cmd.py b/src/autoskillit/recipe/rules_cmd.py new file mode 100644 index 0000000000..fd58645fba --- /dev/null +++ b/src/autoskillit/recipe/rules_cmd.py @@ -0,0 +1,94 @@ +"""Semantic rules for run_cmd echo-capture alignment in recipe steps.""" + +from __future__ import annotations + +import re + +from autoskillit.core import Severity +from autoskillit.recipe._analysis import ValidationContext +from autoskillit.recipe.contracts import RESULT_CAPTURE_RE +from autoskillit.recipe.registry import RuleFinding, semantic_rule + +# Raw tool output fields — these are populated directly from the tool JSON response, +# no echo statement in the cmd is required to capture them. +_RAW_RESULT_FIELDS = {"stdout", "stderr", "exit_code"} + +# Matches find ... | sort ... | (tail|head) patterns that indicate a step is +# re-discovering a path that should have been captured by an upstream step. +_FIND_HEURISTIC_RE = re.compile(r"\bfind\b.+\|\s*sort\b.+\|\s*(tail|head)\b") + + +@semantic_rule( + name="run-cmd-emit-alignment", + description=( + "For every run_cmd step, each non-raw capture key K must have a matching " + 'echo "K=..." in the cmd. A missing echo causes a silent empty-string capture.' + ), + severity=Severity.ERROR, +) +def _check_run_cmd_emit_alignment(ctx: ValidationContext) -> list[RuleFinding]: + findings: list[RuleFinding] = [] + for name, step in ctx.recipe.steps.items(): + if step.tool != "run_cmd": + continue + cmd = (step.with_args or {}).get("cmd", "") + if not isinstance(cmd, str): + continue + for cap_key, cap_val in step.capture.items(): + m = RESULT_CAPTURE_RE.search(cap_val) + if m is None: + # Cannot determine the result field — skip (e.g. pipe-filtered values). + continue + result_key = m.group(1) + if result_key in _RAW_RESULT_FIELDS: + continue + # Check that the cmd emits `echo "result_key=..."`. + echo_pattern = re.compile(rf'\becho\s+"?{re.escape(result_key)}=') + if not echo_pattern.search(cmd): + findings.append( + RuleFinding( + rule="run-cmd-emit-alignment", + severity=Severity.ERROR, + step_name=name, + message=( + f"Step '{name}' captures '{cap_key}' from result.{result_key} " + f'but cmd contains no `echo "{result_key}=..."` statement. ' + f'Add `echo "{result_key}=${{...}}"` to the cmd or the ' + "captured value will always be empty." + ), + ) + ) + return findings + + +@semantic_rule( + name="run-cmd-find-rediscovery", + description=( + "Flags run_cmd steps using find|sort|tail/head to select a path — this pattern " + "indicates an upstream step computed the path but did not echo it into context." + ), + severity=Severity.WARNING, +) +def _check_run_cmd_find_rediscovery(ctx: ValidationContext) -> list[RuleFinding]: + findings: list[RuleFinding] = [] + for name, step in ctx.recipe.steps.items(): + if step.tool != "run_cmd": + continue + cmd = (step.with_args or {}).get("cmd", "") + if not isinstance(cmd, str): + continue + if _FIND_HEURISTIC_RE.search(cmd): + findings.append( + RuleFinding( + rule="run-cmd-find-rediscovery", + severity=Severity.WARNING, + step_name=name, + message=( + f"Step '{name}' uses a `find | sort | tail` heuristic to select " + "a directory. This pattern indicates an upstream step computed " + "the path but did not echo it into context. Capture the path via " + "echo+capture in the originating step instead." + ), + ) + ) + return findings diff --git a/src/autoskillit/recipe/rules_contracts.py b/src/autoskillit/recipe/rules_contracts.py index 2fc165416b..d1eb8c9aa8 100644 --- a/src/autoskillit/recipe/rules_contracts.py +++ b/src/autoskillit/recipe/rules_contracts.py @@ -4,7 +4,7 @@ import re as _re -from autoskillit.core import Severity +from autoskillit.core import Severity, get_logger, pkg_root from autoskillit.recipe._analysis import ValidationContext from autoskillit.recipe.contracts import ( get_skill_contract, @@ -13,6 +13,8 @@ ) from autoskillit.recipe.registry import RuleFinding, semantic_rule +logger = get_logger(__name__) + @semantic_rule( name="missing-output-patterns", @@ -229,3 +231,96 @@ def _check_write_behavior_consistency(ctx: ValidationContext) -> list[RuleFindin ) return findings + + +# --------------------------------------------------------------------------- +# always-has-no-write-exit: detect annotation mismatches +# --------------------------------------------------------------------------- + +# Phrases in SKILL.md text that indicate a documented no-write success exit. +# Any skill with write_behavior='always' whose SKILL.md contains one of these +# phrases likely has a mismatched annotation and should use 'conditional' instead. +_ALWAYS_WITH_NO_WRITE_EXIT_PHRASES: frozenset[str] = frozenset( + { + "may be 0", # resolve-failures: "may be 0 if tests were already passing" + "nothing to do", + "no changes needed", + "already green", + "graceful degradation", # resolve-review: "graceful degradation — do not fail" + r"\bskip\b.{0,30}\bstep\b", # conditional path language + "exit 0", # graceful early exit + r"\bif no\b.{0,30}\bfound\b", + r"if.*unavailable", + "already complete", + "all phases", + } +) + + +@semantic_rule( + name="always-has-no-write-exit", + description=( + "Flag write_behavior='always' on skills whose SKILL.md documents a " + "legitimate no-write success path" + ), + severity=Severity.ERROR, +) +def _check_always_has_no_write_exit(ctx: ValidationContext) -> list[RuleFinding]: + """Detect contract annotation mismatches: 'always' on skills with documented no-write exits. + + Reads each 'always' skill's SKILL.md and searches for phrases indicating + the skill can legitimately succeed with zero writes. If found, the skill + must use 'conditional' write_behavior instead. + """ + findings: list[RuleFinding] = [] + manifest = load_bundled_manifest() + + for step_name, step in ctx.recipe.steps.items(): + if step.tool != "run_skill": + continue + + skill_cmd = step.with_args.get("skill_command", "") + if "${{" in skill_cmd: + continue + + name = resolve_skill_name(skill_cmd) + if not name: + continue + + contract = get_skill_contract(name, manifest) + if contract is None or contract.write_behavior != "always": + continue + + # Locate the skill's SKILL.md + for skills_dir in ("skills", "skills_extended"): + skill_md = pkg_root() / skills_dir / name / "SKILL.md" + if skill_md.exists(): + try: + content = skill_md.read_text(encoding="utf-8").lower() + except (OSError, UnicodeDecodeError): + logger.warning( + "could not read %s; skipping always-has-no-write-exit check", + skill_md, + ) + break + for phrase in _ALWAYS_WITH_NO_WRITE_EXIT_PHRASES: + if _re.search(phrase, content): + findings.append( + RuleFinding( + rule="always-has-no-write-exit", + severity=Severity.ERROR, + step_name=step_name, + message=( + f"Skill '{name}' declares write_behavior='always' " + f"but its SKILL.md contains phrase matching '{phrase}', " + f"suggesting a legitimate no-write success path. " + f"Change to write_behavior='conditional' with a " + f"write_expected_when pattern tied to a structured " + f"completion token." + ), + ) + ) + break # one finding per step is enough + break + + return findings diff --git a/src/autoskillit/recipe/rules_dataflow.py b/src/autoskillit/recipe/rules_dataflow.py index a13a5c033a..af7a6dcc1b 100644 --- a/src/autoskillit/recipe/rules_dataflow.py +++ b/src/autoskillit/recipe/rules_dataflow.py @@ -10,7 +10,7 @@ ) from autoskillit.recipe._analysis import ValidationContext from autoskillit.recipe.contracts import ( - _RESULT_CAPTURE_RE, + RESULT_CAPTURE_RE, get_skill_contract, load_bundled_manifest, resolve_skill_name, @@ -90,7 +90,7 @@ def _check_capture_output_coverage(ctx: ValidationContext) -> list[RuleFinding]: declared_keys = {out.name for out in contract.outputs} for _capture_var, capture_expr in step.capture.items(): - for ref_key in _RESULT_CAPTURE_RE.findall(capture_expr): + for ref_key in RESULT_CAPTURE_RE.findall(capture_expr): if ref_key not in declared_keys: findings.append( RuleFinding( @@ -106,7 +106,7 @@ def _check_capture_output_coverage(ctx: ValidationContext) -> list[RuleFinding]: ) for _capture_var, capture_expr in step.capture_list.items(): - for ref_key in _RESULT_CAPTURE_RE.findall(capture_expr): + for ref_key in RESULT_CAPTURE_RE.findall(capture_expr): if ref_key not in declared_keys: findings.append( RuleFinding( diff --git a/src/autoskillit/recipe/rules_fixing.py b/src/autoskillit/recipe/rules_fixing.py new file mode 100644 index 0000000000..b6beb0cc21 --- /dev/null +++ b/src/autoskillit/recipe/rules_fixing.py @@ -0,0 +1,179 @@ +"""Semantic rule: conditional-write skill steps must gate on a declared verdict output. + +A step invoking a write_behavior='conditional' skill must not reach a push_to_remote +tool step without passing through an on_result: edge that dispatches on a declared +output field from the skill contract. + +This rule closes the no-op loop: if a fix skill emits zero writes (no real fix) its +on_result: must dispatch on a typed verdict, preventing an unconditional re-push from +looping CI indefinitely. + +Modelled on the rebase-then-push-requires-force rule in rules_tools.py. +""" + +from __future__ import annotations + +import re +from collections import deque + +from autoskillit.core import SKILL_TOOLS, Severity, get_logger +from autoskillit.recipe._analysis import ValidationContext +from autoskillit.recipe.contracts import load_bundled_manifest, resolve_skill_name +from autoskillit.recipe.registry import RuleFinding, semantic_rule + +logger = get_logger(__name__) + +# Maximum hops to walk forward from a conditional-write step when looking for push. +_MAX_HOPS = 6 + +# Regex to find result. references in a when: expression. +_RESULT_REF_RE = re.compile(r"result\.([\w-]+)") + + +def _get_skill_outputs(skill_data: dict) -> list[dict]: + """Return the outputs list from raw skill YAML data.""" + return skill_data.get("outputs", []) + + +def _declared_output_names(skill_data: dict) -> frozenset[str]: + """Return the set of declared output field names for a skill.""" + return frozenset(o["name"] for o in _get_skill_outputs(skill_data) if "name" in o) + + +def _step_gated_on_declared_output(step, declared_outputs: frozenset[str]) -> bool: + """Return True if this step uses on_result: with a condition referencing a declared output. + + A condition counts as a real gate if: + - It has a non-None when: expression (not a catch-all) + - The when: expression references result. for some declared output name + """ + if step.on_result is None: + return False + conditions = step.on_result.conditions or [] + for cond in conditions: + if cond.when is None: + continue # catch-all — does not count as a gate + if cond.when.strip() == "true": + continue # explicit catch-all — does not count + # Check if any declared output is referenced in this condition + refs = _RESULT_REF_RE.findall(cond.when) + for ref in refs: + if ref in declared_outputs: + return True + return False + + +def _push_reachable( + graph: dict[str, set[str]], + start: str, + recipe, + max_hops: int = _MAX_HOPS, +) -> tuple[bool, str | None]: + """Return (reachable, push_step_name) if push_to_remote is reachable within max_hops. + + Returns (False, None) if no push_to_remote step is reachable. + """ + visited: set[str] = set() + queue: deque[tuple[str, int]] = deque([(start, 0)]) + while queue: + name, hops = queue.popleft() + if name in visited: + continue + if hops > max_hops: + continue + visited.add(name) + step = recipe.steps.get(name) + if step is not None and step.tool == "push_to_remote": + return True, name + for succ in graph.get(name, set()): + queue.append((succ, hops + 1)) + return False, None + + +@semantic_rule( + name="conditional-skill-ungated-push", + description=( + "A step invoking a write_behavior='conditional' skill must not reach a " + "push_to_remote tool step without an on_result: gate that dispatches on a " + "declared verdict output. Unconditional on_success: to push creates a " + "no-op loop: a zero-fix run silently re-pushes, causing infinite CI retries." + ), + severity=Severity.ERROR, +) +def _check_conditional_skill_ungated_push(ctx: ValidationContext) -> list[RuleFinding]: + """Fire when a conditional-write skill step can reach push_to_remote without a verdict gate.""" + try: + manifest = load_bundled_manifest() + except Exception: + logger.warning( + "conditional-skill-ungated-push: failed to load manifest; skipping", + exc_info=True, + ) + return [] + + skills = manifest.get("skills", {}) + findings: list[RuleFinding] = [] + + for step_name, step in ctx.recipe.steps.items(): + if step.tool not in SKILL_TOOLS: + continue + skill_cmd = (step.with_args or {}).get("skill_command", "") + skill = resolve_skill_name(skill_cmd) + if skill is None: + continue + skill_data = skills.get(skill) + if skill_data is None: + continue + if skill_data.get("write_behavior") != "conditional": + continue + + # Check that push_to_remote is reachable before firing any finding. + # Steps that don't lead to push (e.g. worktree-fix → merge_worktree) + # are not in scope for this rule. + push_reachable, push_step = _push_reachable(ctx.step_graph, step_name, ctx.recipe) + if not push_reachable: + continue + + declared = _declared_output_names(skill_data) + + # If the step is already gated on a declared output via on_result:, it passes. + # This allows skills like resolve-merge-conflicts that gate on their own + # declared outputs (e.g. escalation_required) without needing a 'verdict' field. + if _step_gated_on_declared_output(step, declared): + continue + + # The step is NOT properly gated — fire an error. + if not declared: + findings.append( + RuleFinding( + rule="conditional-skill-ungated-push", + step_name=step_name, + severity=Severity.ERROR, + message=( + f"Step '{step_name}' invokes skill '{skill}' " + f"(write_behavior=conditional) but the skill declares no " + f"outputs; add a typed output field (e.g. 'verdict') to the " + f"skill contract and gate this step with on_result: before " + f"reaching push step '{push_step}'." + ), + ) + ) + else: + findings.append( + RuleFinding( + rule="conditional-skill-ungated-push", + step_name=step_name, + severity=Severity.ERROR, + message=( + f"Step '{step_name}' (skill '{skill}', write_behavior=conditional) " + f"reaches push step '{push_step}' without an on_result: gate " + f"on a declared verdict output. " + f"Replace 'on_success:' with an 'on_result:' block that " + f"dispatches on one of: {sorted(declared)}. " + f"An unconditional push path allows a zero-fix run to " + f"re-push silently, looping CI indefinitely." + ), + ) + ) + + return findings diff --git a/src/autoskillit/recipe/rules_graph.py b/src/autoskillit/recipe/rules_graph.py index 77defd04a3..482ac84254 100644 --- a/src/autoskillit/recipe/rules_graph.py +++ b/src/autoskillit/recipe/rules_graph.py @@ -59,6 +59,65 @@ def dfs(node: str, path: list[str]) -> None: if s in recipe.steps ) if has_retry_exit: + # Check whether the success path of the retrying step stays inside + # the cycle. If it does, the retry exit only bounds individual visits + # but the outer loop can still iterate unboundedly. + retrying_steps = [ + s + for s in cycle_steps + if s in recipe.steps + and recipe.steps[s].retries > 0 + and recipe.steps[s].tool in SKILL_TOOLS + and recipe.steps[s].on_exhausted not in cycle_set + ] + success_stays_in_cycle = any( + recipe.steps[s].on_success in cycle_set + for s in retrying_steps + if recipe.steps[s].on_success is not None + ) + if not success_stays_in_cycle: + # Success path exits the cycle — but does it loop back? + # BFS from exit targets to check if they can reach any + # cycle member through the step graph. + exit_targets: set[str] = set() + for _rs in retrying_steps: + _os = recipe.steps[_rs].on_success + if _os is not None and _os not in cycle_set: + exit_targets.add(_os) + loops_back = False + visited_exit: set[str] = set() + frontier = exit_targets + while frontier: + if frontier & cycle_set: + loops_back = True + break + visited_exit |= frontier + nxt: set[str] = set() + for f in frontier: + nxt |= set(graph.get(f, set())) - visited_exit + frontier = nxt + if not loops_back: + # Truly exits — cycle is bounded + rec_stack.discard(node) + return + + # Success path re-enters the cycle — retry exit only bounds + # individual step visits, not the outer loop. Emit WARNING. + findings.append( + RuleFinding( + rule="unbounded-cycle", + severity=Severity.WARNING, + step_name=node, + message=( + f"Routing cycle detected: {' → '.join(cycle_steps)} → {neighbor}. " + f"Step(s) {', '.join(retrying_steps)} have retry exits, but their " + f"success paths re-enter the cycle. The inner retry budget resets " + f"on each loop iteration, so the outer loop is unbounded. " + "Add a global iteration counter or route success outside the " + "cycle." + ), + ) + ) rec_stack.discard(node) return diff --git a/src/autoskillit/recipe/rules_inputs.py b/src/autoskillit/recipe/rules_inputs.py index 3d6e21f3a1..9cda08dd2a 100644 --- a/src/autoskillit/recipe/rules_inputs.py +++ b/src/autoskillit/recipe/rules_inputs.py @@ -140,6 +140,50 @@ def _check_unsatisfied_skill_input(ctx: ValidationContext) -> list[RuleFinding]: return findings +@semantic_rule( + name="missing-recommended-input", + description="Skill steps should provide recommended inputs for full-quality output.", + severity=Severity.WARNING, +) +def _check_missing_recommended_input(ctx: ValidationContext) -> list[RuleFinding]: + wf = ctx.recipe + findings: list[RuleFinding] = [] + manifest = load_bundled_manifest() + + for step_name, step, _available_context in iter_steps_with_context(wf): + if step.tool not in SKILL_TOOLS: + continue + skill_cmd = step.with_args.get("skill_command", "") if step.with_args else "" + if not skill_cmd: + continue + skill_name = resolve_skill_name(skill_cmd) + if not skill_name: + continue + contract = get_skill_contract(skill_name, manifest) + if not contract: + continue + + for inp in contract.inputs: + if not inp.recommended or inp.required: + continue + if not re.search(rf"(?:^|\s){re.escape(inp.name)}=", skill_cmd): + findings.append( + RuleFinding( + rule="missing-recommended-input", + severity=Severity.WARNING, + step_name=step_name, + message=( + f"Step '{step_name}' invokes {skill_name} which recommends " + f"'{inp.name}' for full-quality output, but the step does not " + f"pass it. Add '{inp.name}=${{{{ context.{inp.name} }}}}' to " + f"the skill_command or add a pre-computation step." + ), + ) + ) + + return findings + + @semantic_rule( name="shadowed-required-input", description=( @@ -283,3 +327,68 @@ def _check_pipeline_internal_not_hidden( ) ) return findings + + +@semantic_rule( + name="required-ingredient-no-default", + severity=Severity.WARNING, + description=( + "Ingredient with required=True and no default may cause the orchestrator " + "to call AskUserQuestion before open_kitchen." + ), +) +def _check_required_without_default( + ctx: ValidationContext, +) -> list[RuleFinding]: + findings: list[RuleFinding] = [] + for name, ing in (ctx.recipe.ingredients or {}).items(): + if getattr(ing, "hidden", False): + continue + if getattr(ing, "required", False) and getattr(ing, "default", None) is None: + findings.append( + RuleFinding( + rule="required-ingredient-no-default", + severity=Severity.WARNING, + step_name=f"ingredient:{name}", + message=( + f"Ingredient '{name}' is required but has no default value. " + "This may cause the orchestrator to call AskUserQuestion " + "before open_kitchen. Consider adding a default value or " + "marking as hidden." + ), + ) + ) + return findings + + +@semantic_rule( + name="research-output-mode-enum", + severity=Severity.ERROR, + description=( + "The research recipe's output_mode ingredient default must be 'pr' or 'local'. " + "Any other value is rejected at validation time." + ), +) +def _check_research_output_mode_enum( + ctx: ValidationContext, +) -> list[RuleFinding]: + wf = ctx.recipe + if wf.name != "research": + return [] + ing = (wf.ingredients or {}).get("output_mode") + if ing is None: + return [] + default = getattr(ing, "default", None) + if default not in {"pr", "local"}: + return [ + RuleFinding( + rule="research-output-mode-enum", + severity=Severity.ERROR, + step_name="output_mode", + message=( + f"output_mode.default must be 'pr' or 'local', got {default!r}. " + "Only two modes are supported (issue body overrides gist §1)." + ), + ) + ] + return [] diff --git a/src/autoskillit/recipe/rules_isolation.py b/src/autoskillit/recipe/rules_isolation.py new file mode 100644 index 0000000000..2b1827ea97 --- /dev/null +++ b/src/autoskillit/recipe/rules_isolation.py @@ -0,0 +1,106 @@ +"""Semantic rules for workspace isolation — prevent recipes from operating on the source repo.""" + +from __future__ import annotations + +import re + +from autoskillit.core import Severity, get_logger +from autoskillit.recipe._analysis import ValidationContext +from autoskillit.recipe.contracts import INPUT_REF_RE +from autoskillit.recipe.registry import RuleFinding, semantic_rule + +logger = get_logger(__name__) + +# Git commands that mutate repository state +_GIT_MUTATION_RE = re.compile( + r"git\s+(checkout|worktree\s+add|branch\s+-[dD]|push|reset|merge|rebase|commit|cherry-pick)" +) + +# Tools that inherently mutate git state when given a cwd +_GIT_MUTATING_TOOLS = frozenset({"create_unique_branch"}) + + +@semantic_rule( + name="source-isolation-violation", + description=( + "Steps using git-mutating tools or run_skill must not operate on the source repo " + "via inputs.* as cwd. Use clone_repo and operate on context.work_dir instead." + ), + severity=Severity.ERROR, +) +def _check_source_isolation(ctx: ValidationContext) -> list[RuleFinding]: + wf = ctx.recipe + # NOTE: structural presence check — does not account for skip_when_false. + # A conditionally-skipped clone_repo step will suppress the WARNING below + # even for execution paths where the clone never runs. Full fix requires + # dataflow-aware conditional reachability analysis (out of scope). + has_clone = any(step.tool == "clone_repo" for step in wf.steps.values()) + findings: list[RuleFinding] = [] + for step_name, step in wf.steps.items(): + cwd = step.with_args.get("cwd", "") + if not INPUT_REF_RE.search(cwd): + continue + + # Rule 1: git-mutating tools with inputs.* cwd — always ERROR + if step.tool in _GIT_MUTATING_TOOLS: + findings.append( + RuleFinding( + rule="source-isolation-violation", + severity=Severity.ERROR, + step_name=step_name, + message=( + f"Step '{step_name}' uses '{step.tool}' with cwd pointing at the " + f"source repo ({cwd}). This tool mutates git state. " + f"Use clone_repo and operate on context.work_dir instead." + ), + ) + ) + + # Rule 1 extension: run_skill with inputs.* cwd and no clone — WARNING + if step.tool == "run_skill" and not has_clone: + findings.append( + RuleFinding( + rule="source-isolation-violation", + severity=Severity.WARNING, + step_name=step_name, + message=( + f"Step '{step_name}' runs a skill with cwd pointing at the source " + f"repo ({cwd}) and the recipe has no clone_repo step. " + f"Skills modify files — operating on the source repo without " + f"clone isolation is unsafe." + ), + ) + ) + return findings + + +@semantic_rule( + name="git-mutation-on-source", + description=("run_cmd steps with git-mutating commands must not use inputs.* as cwd."), + severity=Severity.WARNING, +) +def _check_git_mutation_on_source(ctx: ValidationContext) -> list[RuleFinding]: + wf = ctx.recipe + findings: list[RuleFinding] = [] + for step_name, step in wf.steps.items(): + if step.tool != "run_cmd": + continue + cmd = step.with_args.get("cmd", "") + cwd = step.with_args.get("cwd", "") + if not INPUT_REF_RE.search(cwd): + continue + if not _GIT_MUTATION_RE.search(cmd): + continue + findings.append( + RuleFinding( + rule="git-mutation-on-source", + severity=Severity.WARNING, + step_name=step_name, + message=( + f"Step '{step_name}' runs a git-mutating command with cwd pointing " + f"at the source repo ({cwd}). " + f"Use clone_repo and operate on context.work_dir instead." + ), + ) + ) + return findings diff --git a/src/autoskillit/recipe/rules_merge.py b/src/autoskillit/recipe/rules_merge.py index c372553a97..062457f1d4 100644 --- a/src/autoskillit/recipe/rules_merge.py +++ b/src/autoskillit/recipe/rules_merge.py @@ -10,6 +10,23 @@ logger = get_logger(__name__) + +def _is_commit_guard(step_name: str, ctx: ValidationContext) -> bool: + """Return True if step_name is a commit_guard predecessor for merge_worktree. + + A commit_guard step is one whose name starts with 'commit_guard' OR whose + tool is 'run_cmd' and whose cmd contains 'git commit'. + """ + if step_name.startswith("commit_guard"): + return True + step = ctx.recipe.steps.get(step_name) + if step and step.tool == "run_cmd": + cmd = step.with_args.get("cmd", "") + if "git commit" in cmd: + return True + return False + + _RECOVERABLE_FAILED_STEPS: frozenset[str] = frozenset( { MergeFailedStep.DIRTY_TREE, @@ -64,3 +81,54 @@ def _check_merge_routing_completeness(ctx: ValidationContext) -> list[RuleFindin ) ) return findings + + +def _has_commit_guard_ancestor( + step_name: str, ctx: ValidationContext, *, max_depth: int = 5 +) -> bool: + """BFS over predecessors to find a commit_guard within *max_depth* hops.""" + visited: set[str] = set() + frontier = ctx.predecessors.get(step_name, set()) + for _ in range(max_depth): + if not frontier: + break + for p in frontier: + if _is_commit_guard(p, ctx): + return True + visited |= frontier + next_frontier: set[str] = set() + for p in frontier: + next_frontier |= ctx.predecessors.get(p, set()) - visited + frontier = next_frontier + return False + + +@semantic_rule( + name="merge-without-commit-guard", + description=( + "A merge_worktree step has no commit_guard predecessor. Any path reaching " + "merge with uncommitted changes will fail at the dirty-tree gate, burning " + "an expensive recovery cycle. Add a commit_guard run_cmd step before merge." + ), + severity=Severity.ERROR, +) +def _check_merge_without_commit_guard(ctx: ValidationContext) -> list[RuleFinding]: + findings: list[RuleFinding] = [] + for step_name, step in ctx.recipe.steps.items(): + if step.tool != "merge_worktree": + continue + if not _has_commit_guard_ancestor(step_name, ctx): + findings.append( + RuleFinding( + rule="merge-without-commit-guard", + severity=Severity.ERROR, + step_name=step_name, + message=( + f"merge_worktree step '{step_name}' has no commit_guard predecessor. " + f"Uncommitted changes from context-exhausted skills will trigger " + f"the dirty-tree gate, causing an expensive recovery cycle. " + f"Add a commit_guard run_cmd step immediately before this step." + ), + ) + ) + return findings diff --git a/src/autoskillit/recipe/rules_packs.py b/src/autoskillit/recipe/rules_packs.py new file mode 100644 index 0000000000..3f151cd0e5 --- /dev/null +++ b/src/autoskillit/recipe/rules_packs.py @@ -0,0 +1,32 @@ +"""Semantic rules for pack validation in recipe pipelines.""" + +from __future__ import annotations + +from autoskillit.core import PACK_REGISTRY, Severity +from autoskillit.recipe._analysis import ValidationContext +from autoskillit.recipe.registry import RuleFinding, semantic_rule + + +@semantic_rule( + name="unknown-required-pack", + description="Pack name in requires_packs is not in PACK_REGISTRY", + severity=Severity.WARNING, +) +def _check_unknown_required_pack(ctx: ValidationContext) -> list[RuleFinding]: + findings = [] + seen_reported: set[str] = set() + for pack_name in ctx.recipe.requires_packs: + if pack_name not in PACK_REGISTRY and pack_name not in seen_reported: + seen_reported.add(pack_name) + findings.append( + RuleFinding( + rule="unknown-required-pack", + severity=Severity.WARNING, + step_name="(top-level)", + message=( + f"Pack {pack_name!r} in requires_packs is not in PACK_REGISTRY. " + f"Known packs: {sorted(PACK_REGISTRY)}" + ), + ) + ) + return findings diff --git a/src/autoskillit/recipe/rules_reachability.py b/src/autoskillit/recipe/rules_reachability.py new file mode 100644 index 0000000000..f2db3f82f8 --- /dev/null +++ b/src/autoskillit/recipe/rules_reachability.py @@ -0,0 +1,207 @@ +"""Symbolic reachability semantic rules for recipe pipelines. + +Provides two rules: + +``capture-inversion-detection`` + Flags steps that read ``context.X`` via ``${{ context.X }}`` when X is + established by a conditional edge (``on_result.when``) that does not cover + every path reaching that step. Uses ``_bfs_with_facts`` to propagate + conditional edge facts and intersect them at join points. + +``event-scope-requires-upstream-capture`` + Flags ``wait_for_ci`` steps that hardcode a literal ``event`` value + (e.g. ``event: "push"``) without a step that captures ``merge_group_trigger`` + upstream of them on every path. When the repo only triggers CI on + ``merge_group``, a hardcoded ``push`` event produces a ``no_runs`` timeout. + +Both rules fire at severity ERROR and are registered via ``@semantic_rule``. +""" + +from __future__ import annotations + +import re + +from autoskillit.core import Severity +from autoskillit.recipe._analysis import ( + ValidationContext, + _bfs_reachable, + _bfs_with_facts, +) +from autoskillit.recipe.registry import RuleFinding, semantic_rule + +# Regex to find ${{ context.X }} references anywhere in a string value. +_CTX_REF_RE = re.compile(r"\$\{\{\s*context\.(\w+)\s*\}\}") + + +def _find_context_refs_in_step(step_name: str, ctx: ValidationContext) -> list[str]: + """Return context variable names referenced in step's with_args or skill_command. + + Scans ``step.with_args`` values and the ``skill_command`` arg for + ``${{ context.X }}`` patterns. + """ + step = ctx.recipe.steps.get(step_name) + if step is None: + return [] + refs: list[str] = [] + for key, val in (step.with_args or {}).items(): + if key == "skill_command": + continue # handled below to avoid double-scan via values() + if isinstance(val, str): + refs.extend(_CTX_REF_RE.findall(val)) + skill_cmd = (step.with_args or {}).get("skill_command", "") + if skill_cmd: + refs.extend(_CTX_REF_RE.findall(skill_cmd)) + return refs + + +def _find_capture_producers(ctx: ValidationContext, var: str) -> list[str]: + """Return all step names whose ``capture`` dict contains ``var``.""" + return [step.name for step in ctx.recipe.steps.values() if var in (step.capture or {})] + + +def _ancestors(ctx: ValidationContext, step_name: str) -> set[str]: + """Return all steps reachable via backward BFS from step_name (i.e. ancestors).""" + return _bfs_reachable(ctx.predecessors, step_name) + + +@semantic_rule( + name="capture-inversion-detection", + description=( + "Flags steps that read context.X via conditional-edge facts when X's " + "conditional producer is downstream on some path." + ), + severity=Severity.ERROR, +) +def _check_capture_inversion(ctx: ValidationContext) -> list[RuleFinding]: + """Flag context variable reads where the var is conditionally established but + not known on every path to the reading step. + + This fires when: + - Step S reads ``${{ context.X }}`` + - X is established only by a conditional ``on_result.when`` edge (not by + an unconditional capture) + - X is not present in the intersected fact set at S (i.e. not known on + every path from the recipe entry to S) + + Note: variables captured unconditionally by tool steps are NOT flagged here + because they do not appear in the ``_bfs_with_facts`` conditional fact domain. + """ + # Find the recipe entry: the step with no in-edges in the step graph. + all_targets = {t for targets in ctx.step_graph.values() for t in targets} + entry = next( + (name for name in ctx.recipe.steps if name not in all_targets), + next(iter(ctx.recipe.steps), None), + ) + if entry is None: + return [] + + facts = _bfs_with_facts(ctx.step_graph, ctx.recipe, start=entry) + + # Pre-compute the full conditional fact domain once — not inside the inner loop. + all_facts_in_recipe: set[tuple[str, str]] = set() + for node_facts in facts.values(): + for fs in node_facts: + all_facts_in_recipe.update(fs) + recipe_fact_vars = {v for v, _ in all_facts_in_recipe} + + findings: list[RuleFinding] = [] + for step_name, step in ctx.recipe.steps.items(): + context_refs = _find_context_refs_in_step(step_name, ctx) + if not context_refs: + continue + step_facts_set = facts.get(step_name, {frozenset()}) + # Intersected fact set at this step (single element after _bfs_with_facts return) + intersected = next(iter(step_facts_set), frozenset()) + known_vars = {var for var, _ in intersected} + + for var in context_refs: + # Only flag vars that appear in the conditional fact domain of the recipe. + # If no step establishes (var, value) via a conditional edge, the var is + # captured unconditionally — not an inversion. + + if var not in recipe_fact_vars: + continue # var is not conditionally established anywhere — skip + + if var in known_vars: + continue # fact is known on every path to this step — OK + + producers = _find_capture_producers(ctx, var) + if not producers: + continue # no producer anywhere — not an inversion, different bug + + findings.append( + RuleFinding( + rule="capture-inversion-detection", + severity=Severity.ERROR, + step_name=step_name, + message=( + f"Step {step_name!r} reads context.{var} but the producer " + f"{producers[0]!r} does not establish {var!r} on every path. " + f"Move producer upstream or gate the reader on producer's capture." + ), + ) + ) + + return findings + + +@semantic_rule( + name="event-scope-requires-upstream-capture", + description=( + "wait_for_ci steps must not hardcode a literal event value without " + "an upstream step that captures merge_group_trigger on every path." + ), + severity=Severity.ERROR, +) +def _check_event_scope_requires_upstream_capture(ctx: ValidationContext) -> list[RuleFinding]: + """Flag wait_for_ci steps that hardcode a literal event without upstream capture. + + A hardcoded ``event: "push"`` on a ``wait_for_ci`` step produces a + ``no_runs`` timeout on repos that only trigger CI on ``merge_group``. + The correct pattern is to capture ``merge_group_trigger`` (or ``ci_event``) + from ``check_repo_merge_state`` upstream and bind it dynamically. + + Skips steps where ``event`` is absent (matches any trigger) or is a + template reference starting with ``${{`` (already dynamic). + """ + findings: list[RuleFinding] = [] + + for step_name, step in ctx.recipe.steps.items(): + if step.tool != "wait_for_ci": + continue + + event = (step.with_args or {}).get("event") + if event is None: + continue # absent is fine — matches any event + if isinstance(event, str) and event.startswith("${{"): + continue # dynamic reference — correct pattern + + # Literal event value: check whether at least one merge_group_trigger + # producer is upstream of this step (i.e. it's an ancestor in the graph). + mg_producers = _find_capture_producers(ctx, "merge_group_trigger") + ancestor_set = _ancestors(ctx, step_name) + + if any(p in ancestor_set for p in mg_producers): + continue # at least one producer is upstream — context is known + + producer_desc = ( + f"producer steps {mg_producers!r}" + if mg_producers + else "no producer for merge_group_trigger" + ) + findings.append( + RuleFinding( + rule="event-scope-requires-upstream-capture", + severity=Severity.ERROR, + step_name=step_name, + message=( + f"wait_for_ci step {step_name!r} hardcodes event={event!r} without " + f"an upstream merge_group_trigger capture ({producer_desc} " + f"is not an ancestor). On a repo that only triggers on merge_group, " + f'this produces a no_runs timeout. Use event: "${{{{ context.ci_event }}}}" ' + f"and capture ci_event from check_repo_merge_state upstream." + ), + ) + ) + + return findings diff --git a/src/autoskillit/recipe/rules_recipe.py b/src/autoskillit/recipe/rules_recipe.py index 4b24ae8df0..44e265577c 100644 --- a/src/autoskillit/recipe/rules_recipe.py +++ b/src/autoskillit/recipe/rules_recipe.py @@ -20,7 +20,7 @@ description="sub_recipe step must reference a known sub-recipe name", severity=Severity.ERROR, ) -def _unknown_sub_recipe(ctx: ValidationContext) -> list[RuleFinding]: +def _check_unknown_sub_recipe(ctx: ValidationContext) -> list[RuleFinding]: if not ctx.available_sub_recipes: return [] # fail open when registry is unavailable findings: list[RuleFinding] = [] @@ -46,7 +46,7 @@ def _unknown_sub_recipe(ctx: ValidationContext) -> list[RuleFinding]: description="sub_recipe references must not form a cycle", severity=Severity.ERROR, ) -def _circular_sub_recipe(ctx: ValidationContext) -> list[RuleFinding]: +def _check_circular_sub_recipe(ctx: ValidationContext) -> list[RuleFinding]: """Detect circular sub-recipe references using DFS.""" findings: list[RuleFinding] = [] _detect_cycles(ctx.recipe, [], findings, project_dir=ctx.project_dir) diff --git a/src/autoskillit/recipe/rules_skill_content.py b/src/autoskillit/recipe/rules_skill_content.py index 21081e24da..6f9fc7ed05 100644 --- a/src/autoskillit/recipe/rules_skill_content.py +++ b/src/autoskillit/recipe/rules_skill_content.py @@ -9,8 +9,12 @@ import re from pathlib import Path +from typing import TYPE_CHECKING from autoskillit.core import Severity + +if TYPE_CHECKING: + from autoskillit.core import SkillResolver from autoskillit.recipe._analysis import ValidationContext from autoskillit.recipe._skill_placeholder_parser import ( extract_bash_blocks, @@ -30,11 +34,17 @@ ("implement-worktree", "test_command"), ("implement-worktree-no-merge", "test_command"), ("resolve-failures", "test_command"), + # ── research experiment skills: slug is the experiment directory name ───────── + # Derived at runtime from the `name:` field of the experiment's environment.yml. + # The prose in both skills explicitly describes how to derive it before the + # bash blocks that reference it. + ("implement-experiment", "slug"), + ("generate-report", "slug"), } ) -def _resolve_skill_md(skill_name: str) -> Path | None: +def _resolve_skill_md(skill_name: str, *, resolver: SkillResolver | None = None) -> Path | None: """Resolve a skill name to its SKILL.md path. When SKILL_SEARCH_DIRS is set (e.g., in tests), searches those directories. @@ -46,9 +56,11 @@ def _resolve_skill_md(skill_name: str) -> Path | None: if skill_md.is_file(): return skill_md return None - from autoskillit.workspace import SkillResolver # noqa: PLC0415 + if resolver is None: + from autoskillit.workspace import DefaultSkillResolver # noqa: PLC0415 - skill_info = SkillResolver().resolve(skill_name) + resolver = DefaultSkillResolver() + skill_info = resolver.resolve(skill_name) if skill_info is None: return None return skill_info.path # skill_info.path IS the SKILL.md file diff --git a/src/autoskillit/recipe/rules_skills.py b/src/autoskillit/recipe/rules_skills.py index 00cadf4d13..0be72cbbc9 100644 --- a/src/autoskillit/recipe/rules_skills.py +++ b/src/autoskillit/recipe/rules_skills.py @@ -4,37 +4,45 @@ import re -from autoskillit.core import AUTOSKILLIT_SKILL_PREFIX, SKILL_TOOLS, Severity +from autoskillit.core import AUTOSKILLIT_SKILL_PREFIX, SKILL_TOOLS, Severity, SkillLister from autoskillit.recipe._analysis import ValidationContext from autoskillit.recipe.contracts import resolve_skill_name from autoskillit.recipe.registry import RuleFinding, semantic_rule -def _get_bundled_skill_names() -> frozenset[str]: - from autoskillit.workspace import SkillResolver # noqa: PLC0415 +def _get_bundled_skill_names(lister: SkillLister | None = None) -> frozenset[str]: + if lister is None: + from autoskillit.workspace import DefaultSkillResolver # noqa: PLC0415 - return frozenset(s.name for s in SkillResolver().list_all()) + lister = DefaultSkillResolver() + return frozenset(s.name for s in lister.list_all()) -def _get_skill_category_map() -> dict[str, frozenset[str]]: +def _get_skill_category_map(lister: SkillLister | None = None) -> dict[str, frozenset[str]]: """Return {skill_name: categories} for all bundled skills.""" - from autoskillit.workspace import SkillResolver # noqa: PLC0415 + if lister is None: + from autoskillit.workspace import DefaultSkillResolver # noqa: PLC0415 - return {s.name: s.categories for s in SkillResolver().list_all()} + lister = DefaultSkillResolver() + return {s.name: s.categories for s in lister.list_all()} _SKILL_TOKEN_RE = re.compile(r"/autoskillit:(\S+)") def _has_dynamic_skill_name(skill_cmd: str) -> bool: - """Return True if the skill name portion contains template expressions.""" + """Return True if the skill name portion contains template expressions. + + Handles both ``${{ }}`` Jinja-style expressions and bare ``{placeholder}`` + orchestrator-level template tokens (e.g. ``exp-lens-{slug}``). + """ m = _SKILL_TOKEN_RE.search(skill_cmd) if not m: return False token = m.group(1) first_space = token.find(" ") name_part = token[:first_space] if first_space >= 0 else token - return "${{" in name_part + return "${{" in name_part or "{" in name_part @semantic_rule( diff --git a/src/autoskillit/recipe/rules_tools.py b/src/autoskillit/recipe/rules_tools.py index c56709f36f..a0eb096110 100644 --- a/src/autoskillit/recipe/rules_tools.py +++ b/src/autoskillit/recipe/rules_tools.py @@ -12,7 +12,17 @@ # Intentionally hardcoded — recipe validation runs without a live MCP server. _TOOL_PARAMS: dict[str, frozenset[str]] = { # --- Execution tools --- - "run_skill": frozenset({"skill_command", "cwd", "model", "step_name", "order_id"}), + "run_skill": frozenset( + { + "skill_command", + "cwd", + "model", + "step_name", + "order_id", + "stale_threshold", + "idle_output_timeout", + } + ), "run_cmd": frozenset({"cmd", "cwd", "timeout", "step_name"}), "run_python": frozenset({"callable", "args", "timeout"}), # --- Workspace tools --- @@ -59,6 +69,7 @@ "batch_cleanup_clones": frozenset( { "registry_path", + "all_owners", "step_name", } ), @@ -70,6 +81,7 @@ "remote_url", "head_sha", "workflow", + "event", "timeout_seconds", "cwd", "step_name", @@ -87,10 +99,11 @@ "stall_grace_period", "max_stall_retries", "not_in_queue_confirmation_cycles", + "max_inconclusive_retries", "step_name", } ), - "get_ci_status": frozenset({"branch", "run_id", "repo", "workflow", "cwd"}), + "get_ci_status": frozenset({"branch", "run_id", "repo", "workflow", "event", "cwd"}), "set_commit_status": frozenset( { "sha", diff --git a/src/autoskillit/recipe/rules_verdict.py b/src/autoskillit/recipe/rules_verdict.py index 97a37df1a4..5c3941980a 100644 --- a/src/autoskillit/recipe/rules_verdict.py +++ b/src/autoskillit/recipe/rules_verdict.py @@ -101,6 +101,12 @@ def _check_unrouted_verdict_values(ctx: ValidationContext) -> list[RuleFinding]: continue # No on_result — other rules handle missing routing conditions = step.on_result.conditions or [] + # Only check outputs that are actually used as routing discriminators. + # Context-forwarding captures (e.g. experiment_type) have allowed_values + # for schema validation, not for routing — skip them here. + if not any(c.when and f"result.{output_name}" in c.when for c in conditions): + continue + unrouted = [ value for value in allowed_values diff --git a/src/autoskillit/recipe/rules_worktree.py b/src/autoskillit/recipe/rules_worktree.py index c24940e1af..a3d9c28f39 100644 --- a/src/autoskillit/recipe/rules_worktree.py +++ b/src/autoskillit/recipe/rules_worktree.py @@ -8,15 +8,16 @@ get_logger, ) from autoskillit.recipe._analysis import ValidationContext -from autoskillit.recipe.contracts import resolve_skill_name +from autoskillit.recipe.contracts import load_bundled_manifest, resolve_skill_name from autoskillit.recipe.registry import RuleFinding, semantic_rule logger = get_logger(__name__) -_WORKTREE_CREATING_SKILLS = frozenset( +_WORKTREE_MODIFYING_SKILLS = frozenset( { "implement-worktree", "implement-worktree-no-merge", + "implement-experiment", } ) @@ -47,11 +48,11 @@ def _check_model_on_non_skill(ctx: ValidationContext) -> list[RuleFinding]: @semantic_rule( - name="retries-on-worktree-creating-skill", - description="Worktree-creating skills must not have retries > 0.", + name="retries-on-worktree-modifying-skill", + description="Worktree-modifying skills must not have retries > 0.", severity=Severity.ERROR, ) -def _check_retries_on_worktree_creating_skill(ctx: ValidationContext) -> list[RuleFinding]: +def _check_retries_on_worktree_modifying_skill(ctx: ValidationContext) -> list[RuleFinding]: wf = ctx.recipe findings: list[RuleFinding] = [] for step_name, step in wf.steps.items(): @@ -61,10 +62,10 @@ def _check_retries_on_worktree_creating_skill(ctx: ValidationContext) -> list[Ru continue skill_cmd = step.with_args.get("skill_command", "") skill_name = resolve_skill_name(skill_cmd) - if skill_name and skill_name in _WORKTREE_CREATING_SKILLS: + if skill_name and skill_name in _WORKTREE_MODIFYING_SKILLS: findings.append( RuleFinding( - rule="retries-on-worktree-creating-skill", + rule="retries-on-worktree-modifying-skill", severity=Severity.ERROR, step_name=step_name, message=( @@ -81,7 +82,7 @@ def _check_retries_on_worktree_creating_skill(ctx: ValidationContext) -> list[Ru @semantic_rule( name="missing-context-limit-on-worktree", description=( - "A step invoking a worktree-creating skill with retries:0 has no on_context_limit " + "A step invoking a worktree-modifying skill with retries:0 has no on_context_limit " "route. If the session hits a context limit, the worktree partial progress is " "unreachable: the step falls through to on_failure instead of routing to retry_worktree. " "Add on_context_limit pointing to a retry_worktree step to preserve partial progress." @@ -96,7 +97,7 @@ def _check_missing_context_limit_on_worktree(ctx: ValidationContext) -> list[Rul continue skill_cmd = step.with_args.get("skill_command", "") skill = resolve_skill_name(skill_cmd) - if not skill or skill not in _WORKTREE_CREATING_SKILLS: + if not skill or skill not in _WORKTREE_MODIFYING_SKILLS: continue if step.retries <= 0 and step.on_context_limit is None: findings.append( @@ -139,3 +140,58 @@ def _check_retry_worktree_cwd(ctx: ValidationContext) -> list[RuleFinding]: ) ) return findings + + +@semantic_rule( + name="file-writing-skill-missing-context-limit", + description=( + "A step invoking a write_behavior='always' skill has no on_context_limit route. " + "If the session hits a context limit mid-edit, uncommitted changes strand on disk " + "and the step falls through to on_failure, losing progress." + ), + severity=Severity.WARNING, +) +def _check_file_writing_skill_missing_context_limit( + ctx: ValidationContext, +) -> list[RuleFinding]: + wf = ctx.recipe + findings: list[RuleFinding] = [] + + manifest = load_bundled_manifest() + if manifest is None: + logger.warning( + "file-writing-skill-missing-context-limit: failed to load manifest; skipping" + ) + return findings + + skills = manifest.get("skills", {}) + + for step_name, step in wf.steps.items(): + if step.tool not in SKILL_TOOLS: + continue + # Advisory steps (skip_when_false) are covered by advisory-step-missing-context-limit. + if step.skip_when_false: + continue + if step.on_context_limit is not None: + continue + skill_cmd = step.with_args.get("skill_command", "") + skill = resolve_skill_name(skill_cmd) + if not skill: + continue + skill_data = skills.get(skill, {}) + if skill_data.get("write_behavior") != "always": + continue + findings.append( + RuleFinding( + rule="file-writing-skill-missing-context-limit", + severity=Severity.WARNING, + step_name=step_name, + message=( + f"Step '{step_name}' invokes '{skill}' (write_behavior=always) " + f"but has no on_context_limit route. Context exhaustion mid-edit " + f"will strand uncommitted changes on disk and fall through to " + f"on_failure, losing progress. Add on_context_limit routing." + ), + ) + ) + return findings diff --git a/src/autoskillit/recipe/schema.py b/src/autoskillit/recipe/schema.py index f44cf9013d..259b137a7b 100644 --- a/src/autoskillit/recipe/schema.py +++ b/src/autoskillit/recipe/schema.py @@ -3,6 +3,7 @@ from __future__ import annotations import dataclasses +from collections.abc import Mapping from dataclasses import dataclass, field from pathlib import Path from typing import Final @@ -64,6 +65,7 @@ class StepResultRoute: @dataclass class RecipeStep: + name: str = "" # Set from the YAML dict key after parsing; enables block member lookup tool: str | None = None action: str | None = None # Built-in action: "route", "stop", "confirm" python: str | None = None @@ -85,6 +87,30 @@ class RecipeStep: description: str = "" sub_recipe: str | None = None # Name of sub-recipe file (no extension) gate: str | None = None # Ingredient name whose value controls lazy loading + optional_context_refs: list[str] = field( + default_factory=list + ) # Context variable names that may be referenced before they are captured (cyclic routes) + stale_threshold: int | None = None # None means use global RunSkillConfig.stale_threshold + idle_output_timeout: int | None = None # None = use global cfg; 0 = disabled for this step + block: str | None = None # Named block anchor this step belongs to (e.g. "pre_queue_gate") + + +@dataclass(frozen=True) +class RecipeBlock: + """A named contiguous region of the step routing graph with budget constraints. + + Populated by ``extract_blocks`` in ``recipe/_analysis.py`` during validation. + Steps declare membership via ``step.block = ``. The block primitive + enables per-block semantic rules (budget guards, single-producer checks, etc.) + that individual-step rules cannot express. + """ + + name: str # e.g. "pre_queue_gate" + entry: str # name of the step at the block entry point (no in-block predecessor) + exit: str # name of the step at the block exit point (no in-block successor) + members: tuple[RecipeStep, ...] # ordered member steps (by YAML declaration order) + tool_counts: Mapping[str, int] # {"run_cmd": 1, "check_repo_merge_state": 1, …} + gh_api_occurrences: int # total count of "gh api" substrings across all run_cmd cmds @dataclass @@ -97,6 +123,9 @@ class Recipe: kitchen_rules: list[str] = field(default_factory=list) version: str | None = None experimental: bool = False + requires_packs: list[str] = field(default_factory=list) + # Populated by extract_blocks() during load; empty tuple for recipes with no block: anchors. + blocks: tuple[RecipeBlock, ...] = field(default_factory=tuple) def __post_init__(self) -> None: self.name = self.name.strip() diff --git a/src/autoskillit/recipe/skill_contracts.yaml b/src/autoskillit/recipe/skill_contracts.yaml index c971cc4c09..f530854a01 100644 --- a/src/autoskillit/recipe/skill_contracts.yaml +++ b/src/autoskillit/recipe/skill_contracts.yaml @@ -1,5 +1,25 @@ version: 0.1.0 skills: + troubleshoot-experiment: + inputs: + - name: worktree_path + type: string + required: true + - name: step_name + type: string + required: true + outputs: + - name: diagnosis_path + type: file_path + - name: failure_type + type: string + - name: is_fixable + type: string + expected_output_patterns: + - "is_fixable\\s*=\\s*(true|false)" + pattern_examples: + - "diagnosis_path = /tmp/diagnosis.md\nfailure_type = stale_timeout\nis_fixable = true\n%%ORDER_UP%%" + write_behavior: always diagnose-ci: inputs: - name: branch @@ -16,12 +36,39 @@ skills: type: file_path - name: failure_type type: string + allowed_values: [test, lint, build, type_check, env, unknown] + - name: failure_subtype + type: string + allowed_values: [flaky, timing_race, deterministic, fixture, import, env, unknown] - name: is_fixable type: string expected_output_patterns: - "diagnosis_path\\s*=\\s*/.+" + - "failure_subtype\\s*=\\s*(flaky|timing_race|deterministic|fixture|import|env|unknown)" + pattern_examples: + - "diagnosis_path = /tmp/diagnosis.md\nfailure_type = test\nfailure_subtype = deterministic\nis_fixable = true\n%%ORDER_UP%%" + - "diagnosis_path = /tmp/diagnosis.md\nfailure_type = test\nfailure_subtype = flaky\nis_fixable = false\n%%ORDER_UP%%" + write_behavior: always + resolve-design-review: + inputs: + - name: evaluation_dashboard + type: file_path + required: true + - name: experiment_plan + type: file_path + required: true + outputs: + - name: resolution + type: string + allowed_values: [revised, failed] + - name: revision_guidance + type: file_path + expected_output_patterns: + - "resolution\\s*=\\s*(revised|failed)" + - "resolution\\s*=\\s*revised[\\s\\S]*?revision_guidance\\s*=\\s*/.+" pattern_examples: - - "diagnosis_path = /tmp/diagnosis.md\n%%ORDER_UP%%" + - "resolution = revised\nrevision_guidance = /tmp/guidance.md\n%%ORDER_UP%%" + - "resolution = failed\n%%ORDER_UP%%" write_behavior: always resolve-failures: inputs: @@ -34,8 +81,22 @@ skills: - name: base_branch type: string required: true - outputs: [] - write_behavior: always + - name: diagnosis_path + type: file_path + required: false + outputs: + - name: verdict + type: string + allowed_values: + - real_fix + - already_green + - flake_suspected + - ci_only_failure + - name: fixes_applied + type: integer + write_behavior: conditional + write_expected_when: + - "verdict\\s*=\\s*real_fix" resolve-merge-conflicts: inputs: - name: worktree_path @@ -73,8 +134,19 @@ skills: - name: base_branch type: string required: true - outputs: [] - write_behavior: always + outputs: + - name: verdict + type: string + allowed_values: + - real_fix + - already_green + - flake_suspected + - ci_only_failure + - name: fixes_applied + type: integer + write_behavior: conditional + write_expected_when: + - "verdict\\s*=\\s*real_fix" dry-walkthrough: inputs: - name: plan_path @@ -213,11 +285,15 @@ skills: type: directory_path - name: branch_name type: string + - name: phases_implemented + type: integer expected_output_patterns: - "worktree_path\\s*=\\s*/.+" pattern_examples: - - "worktree_path = /tmp/worktrees/impl-foo-20260316\n%%ORDER_UP%%" - write_behavior: always + - "worktree_path = /tmp/worktrees/impl-foo-20260316\nbranch_name = feature/123\nphases_implemented = 2\n%%ORDER_UP%%" + write_behavior: conditional + write_expected_when: + - "phases_implemented\\s*=\\s*[1-9][0-9]*" review-approach: inputs: - name: plan_path @@ -335,6 +411,65 @@ skills: pattern_examples: - "https://github.com/owner/repo/pull/42\n%%ORDER_UP%%" + prepare-pr: + inputs: + - name: plan_paths + type: string + required: true + - name: run_name + type: string + required: true + - name: base_branch + type: string + required: true + - name: closing_issue + type: string + required: false + - name: conflict_report_path + type: file_path + required: false + outputs: + - name: prep_path + type: file_path + - name: selected_lenses + type: string + - name: lens_context_paths + type: string + expected_output_patterns: + - "prep_path\\s*=\\s*/.+" + - "selected_lenses\\s*=\\s*\\S+" + - "lens_context_paths\\s*=\\s*/.+" + pattern_examples: + - "prep_path = /abs/path/pr_prep_2026-04-07_120000.md\nselected_lenses = module-dependency,process-flow\nlens_context_paths = /abs/ctx1.md,/abs/ctx2.md\n%%ORDER_UP%%" + write_behavior: always + + compose-pr: + inputs: + - name: prep_path + type: file_path + required: true + - name: all_diagram_paths + type: string + required: true + - name: work_dir + type: directory_path + required: true + - name: base_branch + type: string + required: true + - name: closing_issue + type: string + required: false + outputs: + - name: pr_url + type: string + expected_output_patterns: + - "pr_url\\s*=\\s*(https://github\\.com/.*/pull/\\d+)?" + pattern_examples: + - "pr_url = https://github.com/owner/repo/pull/42\n%%ORDER_UP%%" + - "pr_url = \n%%ORDER_UP%%" + write_behavior: always + open-integration-pr: inputs: - name: integration_branch @@ -389,9 +524,11 @@ skills: - name: annotated_diff_path type: string required: false + recommended: true - name: hunk_ranges_path type: string required: false + recommended: true outputs: - name: verdict type: string @@ -408,6 +545,12 @@ skills: arch-lens-c4-container: inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false - name: project_context type: string required: false @@ -421,6 +564,12 @@ skills: arch-lens-concurrency: inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false - name: project_context type: string required: false @@ -434,6 +583,12 @@ skills: arch-lens-data-lineage: inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false - name: project_context type: string required: false @@ -447,6 +602,12 @@ skills: arch-lens-deployment: inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false - name: project_context type: string required: false @@ -460,6 +621,12 @@ skills: arch-lens-development: inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false - name: project_context type: string required: false @@ -473,6 +640,12 @@ skills: arch-lens-error-resilience: inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false - name: project_context type: string required: false @@ -486,6 +659,12 @@ skills: arch-lens-module-dependency: inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false - name: project_context type: string required: false @@ -499,6 +678,12 @@ skills: arch-lens-operational: inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false - name: project_context type: string required: false @@ -512,6 +697,12 @@ skills: arch-lens-process-flow: inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false - name: project_context type: string required: false @@ -525,6 +716,12 @@ skills: arch-lens-repository-access: inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false - name: project_context type: string required: false @@ -538,6 +735,12 @@ skills: arch-lens-scenarios: inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false - name: project_context type: string required: false @@ -551,6 +754,12 @@ skills: arch-lens-security: inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false - name: project_context type: string required: false @@ -564,6 +773,12 @@ skills: arch-lens-state-lifecycle: inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false - name: project_context type: string required: false @@ -575,59 +790,947 @@ skills: pattern_examples: - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" - prepare-issue: - inputs: [] - outputs: [] + exp-lens-estimand-clarity: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path expected_output_patterns: - - "---prepare-issue-result---" + - "diagram_path\\s*=\\s*/.+" pattern_examples: - - "---prepare-issue-result---" + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" - enrich-issues: - inputs: [] - outputs: [] + exp-lens-causal-assumptions: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path expected_output_patterns: - - "---enrich-issues-result---" + - "diagram_path\\s*=\\s*/.+" pattern_examples: - - "---enrich-issues-result---" + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" - report-bug: - inputs: [] - outputs: [] + exp-lens-comparator-construction: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path expected_output_patterns: - - "---bug-fingerprint---" + - "diagram_path\\s*=\\s*/.+" pattern_examples: - - "---bug-fingerprint---" - write_behavior: always + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" - collapse-issues: - inputs: [] - outputs: [] + exp-lens-pipeline-integrity: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path expected_output_patterns: - - "---collapse-issues-result---" + - "diagram_path\\s*=\\s*/.+" pattern_examples: - - "---collapse-issues-result---" + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" - issue-splitter: - inputs: [] - outputs: [] + exp-lens-variance-stability: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path expected_output_patterns: - - "---issue-splitter-result---" + - "diagram_path\\s*=\\s*/.+" pattern_examples: - - "---issue-splitter-result---" + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" - process-issues: - inputs: [] - outputs: [] + exp-lens-fair-comparison: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path expected_output_patterns: - - "---process-issues-result---" + - "diagram_path\\s*=\\s*/.+" pattern_examples: - - "---process-issues-result---" + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" - design-guards: + exp-lens-reproducibility-artifacts: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + exp-lens-measurement-validity: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + exp-lens-sensitivity-robustness: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + exp-lens-benchmark-representativeness: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + exp-lens-unit-interference: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + exp-lens-error-budget: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + exp-lens-severity-testing: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + exp-lens-randomization-blocking: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + exp-lens-validity-threats: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + exp-lens-iterative-learning: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + exp-lens-exploratory-confirmatory: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + exp-lens-governance-risk: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + prepare-issue: + inputs: [] + outputs: [] + expected_output_patterns: + - "---prepare-issue-result---" + pattern_examples: + - "---prepare-issue-result---" + + enrich-issues: + inputs: [] + outputs: [] + expected_output_patterns: + - "---enrich-issues-result---" + pattern_examples: + - "---enrich-issues-result---" + + report-bug: + inputs: [] + outputs: [] + expected_output_patterns: + - "---bug-fingerprint---" + pattern_examples: + - "---bug-fingerprint---" + write_behavior: always + + collapse-issues: + inputs: [] + outputs: [] + expected_output_patterns: + - "---collapse-issues-result---" + pattern_examples: + - "---collapse-issues-result---" + + issue-splitter: + inputs: [] + outputs: [] + expected_output_patterns: + - "---issue-splitter-result---" + pattern_examples: + - "---issue-splitter-result---" + + process-issues: + inputs: [] + outputs: [] + expected_output_patterns: + - "---process-issues-result---" + pattern_examples: + - "---process-issues-result---" + + design-guards: inputs: - name: report_path type: file_path required: true outputs: [] write_behavior: always + + scope: + inputs: + - name: research_question + type: string + required: true + outputs: + - name: scope_report + type: file_path + expected_output_patterns: + - "scope_report\\s*=\\s*/.+" + pattern_examples: + - "scope_report = /tmp/scope_report.md\n%%ORDER_UP%%" + write_behavior: always + + plan-experiment: + inputs: + - name: scope_report_path + type: file_path + required: true + - name: revision_guidance + type: file_path + required: false + outputs: + - name: experiment_plan + type: file_path + expected_output_patterns: + - "experiment_plan\\s*=\\s*/.+" + pattern_examples: + - "experiment_plan = /tmp/experiment_plan.md\n%%ORDER_UP%%" + write_behavior: always + + plan-visualization: + inputs: + - name: source_dir + type: directory_path + required: true + - name: experiment_plan_path + type: file_path + required: true + - name: scope_report_path + type: string + required: false + outputs: + - name: visualization_plan_path + type: file_path + - name: report_plan_path + type: file_path + expected_output_patterns: + - "visualization_plan_path\\s*=\\s*/.+" + - "report_plan_path\\s*=\\s*/.+" + pattern_examples: + - "visualization_plan_path = /tmp/plan-visualization/visualization-plan.md\nreport_plan_path = /tmp/plan-visualization/report-plan.md\n%%ORDER_UP%%" + write_behavior: always + + stage-data: + inputs: + - name: experiment_plan + type: file_path + required: true + outputs: + - name: verdict + type: string + - name: resource_report + type: file_path + expected_output_patterns: + - "verdict\\s*=\\s*(PASS|WARN|FAIL)" + - "resource_report\\s*=\\s*/.+" + pattern_examples: + - "verdict = PASS\nresource_report = /tmp/stage-data/resource_feasibility_2026-04-13_120000.md\n%%ORDER_UP%%" + write_behavior: always + + implement-experiment: + inputs: + - name: plan_path + type: file_path + required: true + outputs: + - name: worktree_path + type: directory_path + - name: branch_name + type: string + expected_output_patterns: + - "worktree_path\\s*=\\s*/.+" + pattern_examples: + - "worktree_path = /tmp/worktrees/research-20260101-120000\n%%ORDER_UP%%" + write_behavior: always + + run-experiment: + inputs: + - name: worktree_path + type: directory_path + required: true + outputs: + - name: results_path + type: file_path + expected_output_patterns: + - "results_path\\s*=\\s*/.+" + pattern_examples: + - "results_path = /tmp/run-experiment/results.md\n%%ORDER_UP%%" + write_behavior: always + + generate-report: + inputs: + - name: worktree_path + type: directory_path + required: true + - name: results_path + type: file_path + required: true + outputs: + - name: report_path + type: file_path + expected_output_patterns: + - "report_path\\s*=\\s*/.+" + pattern_examples: + - "report_path = /tmp/research/report.md\n%%ORDER_UP%%" + write_behavior: always + + prepare-research-pr: + inputs: + - name: report_path + type: file_path + required: true + - name: experiment_plan_path + type: file_path + required: true + - name: worktree_path + type: directory_path + required: true + - name: base_branch + type: string + required: true + outputs: + - name: prep_path + type: file_path + - name: selected_lenses + type: string + - name: lens_context_paths + type: string + expected_output_patterns: + - "prep_path\\s*=\\s*/.+" + - "selected_lenses\\s*=\\s*\\S+" + - "lens_context_paths\\s*=\\s*/.+" + pattern_examples: + - "prep_path = /abs/path/pr_prep_2026-04-07_101349.md\nselected_lenses = fair-comparison,estimand-clarity\nlens_context_paths = /abs/ctx1.md,/abs/ctx2.md\n%%ORDER_UP%%" + write_behavior: always + + compose-research-pr: + inputs: + - name: prep_path + type: file_path + required: true + - name: all_diagram_paths + type: string + required: true + - name: worktree_path + type: directory_path + required: true + - name: base_branch + type: string + required: true + - name: closing_issue + type: string + required: false + outputs: + - name: pr_url + type: string + expected_output_patterns: + - "pr_url\\s*=\\s*(https://github\\.com/.*/pull/\\d+)?" + pattern_examples: + - "pr_url = https://github.com/owner/repo/pull/42\n%%ORDER_UP%%" + - "pr_url = \n%%ORDER_UP%%" + write_behavior: always + + review-design: + inputs: + - name: experiment_plan + type: file_path + required: true + outputs: + - name: verdict + type: string + allowed_values: [GO, REVISE, STOP] + - name: experiment_type + type: string + allowed_values: [benchmark, configuration_study, causal_inference, robustness_audit, exploratory] + - name: evaluation_dashboard + type: file_path + - name: revision_guidance + type: file_path + expected_output_patterns: + - "verdict\\s*=\\s*(GO|REVISE|STOP)" + - "experiment_type\\s*=\\s*\\S+" + pattern_examples: + - "verdict = GO\nexperiment_type = benchmark\nevaluation_dashboard = /tmp/eval.md\nrevision_guidance = /tmp/guidance.md\n%%ORDER_UP%%" + write_behavior: always + + review-research-pr: + inputs: + - name: worktree_path + type: directory_path + required: true + - name: base_branch + type: string + required: true + - name: pr_url + type: string + required: true + outputs: + - name: verdict + type: string + allowed_values: [approved, changes_requested, needs_human] + expected_output_patterns: + - "verdict\\s*=\\s*(approved|changes_requested|needs_human)" + pattern_examples: + - "verdict = approved\n%%ORDER_UP%%" + - "verdict = changes_requested\n%%ORDER_UP%%" + - "verdict = needs_human\n%%ORDER_UP%%" + + audit-claims: + inputs: + - name: worktree_path + type: directory_path + required: true + - name: base_branch + type: string + required: true + - name: pr_url + type: string + required: true + outputs: + - name: verdict + type: string + allowed_values: [approved, changes_requested, needs_human] + expected_output_patterns: + - "verdict\\s*=\\s*(approved|changes_requested|needs_human)" + pattern_examples: + - "verdict = approved\n%%ORDER_UP%%" + - "verdict = changes_requested\n%%ORDER_UP%%" + - "verdict = needs_human\n%%ORDER_UP%%" + + resolve-claims-review: + inputs: + - name: worktree_path + type: directory_path + required: true + - name: base_branch + type: string + required: true + outputs: + - name: needs_rerun + type: string + - name: verdict + type: string + allowed_values: + - real_fix + - already_green + - flake_suspected + - ci_only_failure + - name: fixes_applied + type: integer + expected_output_patterns: + - "needs_rerun\\s*=\\s*(true|false)" + pattern_examples: + - "needs_rerun = true\nverdict = real_fix\nfixes_applied = 2\n%%ORDER_UP%%" + - "needs_rerun = false\nverdict = already_green\nfixes_applied = 0\n%%ORDER_UP%%" + write_behavior: conditional + write_expected_when: + - "verdict\\s*=\\s*real_fix" + + resolve-research-review: + inputs: + - name: worktree_path + type: directory_path + required: true + - name: base_branch + type: string + required: true + outputs: + - name: needs_rerun + type: string + - name: verdict + type: string + allowed_values: + - real_fix + - already_green + - flake_suspected + - ci_only_failure + - name: fixes_applied + type: integer + expected_output_patterns: + - "needs_rerun\\s*=\\s*(true|false)" + pattern_examples: + - "needs_rerun = true\nverdict = real_fix\nfixes_applied = 2\n%%ORDER_UP%%" + - "needs_rerun = false\nverdict = already_green\nfixes_applied = 0\n%%ORDER_UP%%" + write_behavior: conditional + write_expected_when: + - "verdict\\s*=\\s*real_fix" + + vis-lens-always-on: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + vis-lens-antipattern: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + vis-lens-chart-select: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + vis-lens-domain-norms: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + vis-lens-uncertainty: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + vis-lens-multi-compare: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + vis-lens-temporal: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + vis-lens-color-access: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + + vis-lens-figure-table: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + vis-lens-caption-annot: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + vis-lens-story-arc: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + vis-lens-reproducibility: + inputs: + - name: context_path + type: file_path + required: false + - name: experiment_plan_path + type: file_path + required: false + - name: project_context + type: string + required: false + outputs: + - name: diagram_path + type: file_path + expected_output_patterns: + - "diagram_path\\s*=\\s*/.+" + pattern_examples: + - "diagram_path = /tmp/diagram.md\n%%ORDER_UP%%" + bundle-local-report: + inputs: + - name: research_dir + type: directory_path + required: true + - name: report_path + type: file_path + required: true + - name: all_diagram_paths + type: string + required: false + - name: visualization_plan_path + type: file_path + required: false + outputs: + - name: html_path + type: file_path + expected_output_patterns: + - "html_path\\s*=\\s*\\S+" + pattern_examples: + - "html_path = /tmp/research/report.html\n%%ORDER_UP%%" + write_behavior: always diff --git a/src/autoskillit/recipe/validator.py b/src/autoskillit/recipe/validator.py index ffcb8ac3df..e84ecf19b4 100644 --- a/src/autoskillit/recipe/validator.py +++ b/src/autoskillit/recipe/validator.py @@ -17,8 +17,8 @@ ) from autoskillit.recipe.contracts import ( _CONTEXT_REF_RE, - _INPUT_REF_RE, _TEMPLATE_REF_RE, + INPUT_REF_RE, ) from autoskillit.recipe.io import iter_steps_with_context from autoskillit.recipe.registry import ( @@ -153,6 +153,22 @@ def validate_recipe(recipe: Recipe) -> list[str]: f"Step '{step_name}'.retries must be a non-negative integer, got {step.retries!r}." ) + if step.stale_threshold is not None and ( + not isinstance(step.stale_threshold, int) or step.stale_threshold <= 0 + ): + errors.append( + f"Step {step_name!r}: 'stale_threshold' must be a positive integer " + f"when set, got {step.stale_threshold!r}" + ) + + if step.idle_output_timeout is not None and ( + not isinstance(step.idle_output_timeout, int) or step.idle_output_timeout < 0 + ): + errors.append( + f"Step {step_name!r}: 'idle_output_timeout' must be a non-negative integer " + f"when set (0 = disabled), got {step.idle_output_timeout!r}" + ) + if step.on_result is not None: if step.on_success is not None: errors.append( @@ -215,13 +231,13 @@ def validate_recipe(recipe: Recipe) -> list[str]: for arg_key, arg_val in step.with_args.items(): if not isinstance(arg_val, str): continue - for ref in _INPUT_REF_RE.findall(arg_val): + for ref in INPUT_REF_RE.findall(arg_val): if ref not in ingredient_names: errors.append( f"Step '{step_name}'.with.{arg_key} references undeclared input '{ref}'." ) for ref in _CONTEXT_REF_RE.findall(arg_val): - if ref not in available_context: + if ref not in available_context and ref not in step.optional_context_refs: errors.append( f"Step '{step_name}'.with.{arg_key} references " f"context variable '{ref}' which has not been " @@ -239,4 +255,4 @@ def validate_recipe(recipe: Recipe) -> list[str]: # Re-export test-access symbols from their new locations. from autoskillit.recipe.rules_inputs import _check_outdated_version # noqa: E402 F401 -from autoskillit.recipe.rules_worktree import _WORKTREE_CREATING_SKILLS # noqa: E402 F401 +from autoskillit.recipe.rules_worktree import _WORKTREE_MODIFYING_SKILLS # noqa: E402 F401 diff --git a/src/autoskillit/recipes/contracts/implementation-groups.yaml b/src/autoskillit/recipes/contracts/implementation-groups.yaml new file mode 100644 index 0000000000..591e8b55f1 --- /dev/null +++ b/src/autoskillit/recipes/contracts/implementation-groups.yaml @@ -0,0 +1,2217 @@ +generated_at: '2026-04-05T02:19:56.037706+00:00' +bundled_manifest_version: 0.1.0 +skill_hashes: {} +skills: + make-groups: + inputs: + - name: source_doc + type: file_path + required: true + outputs: + - name: groups_path + type: file_path + - name: manifest_path + type: file_path + - name: group_files + type: file_path_list + expected_output_patterns: + - groups_path\s*=\s*/.+ + pattern_examples: + - 'groups_path = /tmp/groups.json' + make-plan: + inputs: + - name: task + type: string + required: true + outputs: + - name: plan_path + type: file_path + - name: plan_parts + type: file_path_list + expected_output_patterns: + - plan_path\s*=\s*/.+ + pattern_examples: + - 'plan_path = /tmp/plan.md' + write_behavior: always + review-approach: + inputs: + - name: plan_path + type: file_path + required: false + outputs: + - name: review_path + type: file_path + expected_output_patterns: + - review_path\s*=\s*/.+ + pattern_examples: + - 'review_path = /tmp/review.md' + dry-walkthrough: + inputs: + - name: plan_path + type: file_path + required: true + outputs: [] + expected_output_patterns: [] + pattern_examples: [] + write_behavior: always + implement-worktree-no-merge: + inputs: + - name: plan_path + type: file_path + required: true + outputs: + - name: worktree_path + type: directory_path + - name: branch_name + type: string + expected_output_patterns: + - worktree_path\s*=\s*/.+ + pattern_examples: + - 'worktree_path = /tmp/worktrees/impl-foo-20260316' + write_behavior: always + retry-worktree: + inputs: + - name: plan_path + type: file_path + required: true + - name: worktree_path + type: directory_path + required: true + outputs: + - name: worktree_path + type: directory_path + - name: branch_name + type: string + expected_output_patterns: + - worktree_path\s*=\s*/.+ + pattern_examples: + - 'worktree_path = /tmp/worktrees/impl-foo-20260316' + write_behavior: always + resolve-failures: + inputs: + - name: worktree_path + type: directory_path + required: true + - name: plan_path + type: file_path + required: true + - name: base_branch + type: string + required: true + outputs: [] + expected_output_patterns: [] + pattern_examples: [] + write_behavior: always + audit-impl: + inputs: + - name: plan_path + type: file_path + required: true + - name: branch_name + type: string + required: false + - name: base_branch + type: string + required: false + outputs: + - name: verdict + type: string + - name: remediation_path + type: file_path + expected_output_patterns: + - verdict\s*=\s*(GO|NO GO) + pattern_examples: + - 'verdict = GO' + - 'verdict = NO GO + + remediation_path = /tmp/remediation.md' + open-pr: + inputs: + - name: plan_paths + type: string + required: true + - name: feature_branch + type: string + required: true + - name: base_branch + type: string + required: true + - name: closing_issue + type: string + required: false + outputs: [] + expected_output_patterns: + - https://github\.com/.*/pull/\d+ + pattern_examples: + - 'https://github.com/owner/repo/pull/42' + review-pr: + inputs: + - name: feature_branch + type: string + required: true + - name: base_branch + type: string + required: true + - name: annotated_diff_path + type: string + required: false + - name: hunk_ranges_path + type: string + required: false + outputs: + - name: verdict + type: string + expected_output_patterns: + - verdict\s*=\s*(approved|changes_requested|needs_human) + pattern_examples: + - 'verdict = approved' + - 'verdict = changes_requested' + - 'verdict = needs_human' + resolve-review: + inputs: + - name: feature_branch + type: string + required: true + - name: base_branch + type: string + required: true + outputs: [] + expected_output_patterns: [] + pattern_examples: [] + write_behavior: always + diagnose-ci: + inputs: + - name: branch + type: string + required: true + - name: run_id + type: string + required: false + - name: ci_failed_jobs + type: string + required: false + outputs: + - name: diagnosis_path + type: file_path + - name: failure_type + type: string + - name: is_fixable + type: string + expected_output_patterns: + - diagnosis_path\s*=\s*/.+ + pattern_examples: + - 'diagnosis_path = /tmp/diagnosis.md' + write_behavior: always + resolve-merge-conflicts: + inputs: + - name: worktree_path + type: directory_path + required: true + - name: plan_path + type: file_path + required: true + - name: base_branch + type: string + required: true + outputs: + - name: worktree_path + type: directory_path + - name: branch_name + type: string + - name: conflict_report_path + type: file_path + - name: escalation_required + type: string + - name: escalation_reason + type: string + expected_output_patterns: + - worktree_path\s*=\s*/.+ + pattern_examples: + - 'worktree_path = /tmp/worktrees/impl-foo-20260316' + write_behavior: conditional + write_expected_when: + - conflict_report_path\s*=\s*/.+ +dataflow: +- step: clone + available: + - audit + - auto_merge + - base_branch + - issue_url + - open_pr + - review_approach + - run_name + - source_dir + - source_doc + - upfront_claimed + required: [] + produced: + - work_dir + - remote_url +- step: capture_base_sha + available: + - audit + - auto_merge + - base_branch + - issue_url + - open_pr + - remote_url + - review_approach + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + required: [] + produced: + - base_sha +- step: set_merge_target + available: + - audit + - auto_merge + - base_branch + - base_sha + - issue_url + - open_pr + - remote_url + - review_approach + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + required: [] + produced: + - merge_target +- step: get_issue_title + available: + - audit + - auto_merge + - base_branch + - base_sha + - issue_url + - merge_target + - open_pr + - remote_url + - review_approach + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + required: [] + produced: + - issue_number + - issue_title + - issue_slug +- step: claim_issue + available: + - audit + - auto_merge + - base_branch + - base_sha + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - remote_url + - review_approach + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + required: [] + produced: + - claimed +- step: compute_branch + available: + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - remote_url + - review_approach + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + required: [] + produced: + - proposed_branch +- step: create_branch + available: + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - proposed_branch + - remote_url + - review_approach + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + required: [] + produced: + - merge_target +- step: push_merge_target + available: + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - proposed_branch + - remote_url + - review_approach + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + required: [] + produced: [] +- step: group + available: + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - proposed_branch + - remote_url + - review_approach + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + required: [] + produced: + - group_files +- step: plan + available: + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - proposed_branch + - remote_url + - review_approach + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + required: [] + produced: + - plan_path + - all_plan_paths +- step: review + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remote_url + - review_approach + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + required: [] + produced: + - review_path +- step: verify + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + required: [] + produced: [] +- step: implement + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + required: [] + produced: + - worktree_path +- step: retry_worktree + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + - worktree_path + required: [] + produced: + - worktree_path +- step: test + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + - worktree_path + required: [] + produced: [] +- step: merge + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + - worktree_path + required: [] + produced: + - cleanup_succeeded + - worktree_path +- step: push + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + - worktree_path + required: [] + produced: [] +- step: fix + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + - worktree_path + required: [] + produced: [] +- step: next_or_done + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + - worktree_path + required: [] + produced: [] +- step: audit_impl + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + - worktree_path + required: [] + produced: + - remediation_path +- step: remediate + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + - worktree_path + required: [] + produced: [] +- step: compose_pr + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + - worktree_path + required: + - plan_paths + - feature_branch + produced: [] +- step: extract_pr_number + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + - worktree_path + required: [] + produced: + - pr_number +- step: review_pr + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - work_dir + - worktree_path + required: + - feature_branch + produced: + - verdict +- step: resolve_review + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - feature_branch + produced: [] +- step: re_push_review + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: ci_watch + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - ci_conclusion + - ci_failed_jobs +- step: diagnose_ci + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - diagnosis_path +- step: resolve_ci + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - worktree_path + produced: [] +- step: re_push + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: check_merge_queue + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - queue_available +- step: check_merge_group_trigger + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - merge_group_trigger +- step: check_auto_merge + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - auto_merge_available +- step: route_queue_mode + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: enable_auto_merge + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: wait_for_queue + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - queue_pr_state +- step: reenroll_stalled_pr + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: queue_ejected_fix + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - worktree_path + produced: + - conflict_escalation_required +- step: re_push_queue_fix + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: reenter_merge_queue + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: direct_merge + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: wait_for_direct_merge + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: direct_merge_conflict_fix + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - worktree_path + produced: + - conflict_escalation_required +- step: re_push_direct_fix + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: redirect_merge + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: immediate_merge + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: wait_for_immediate_merge + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: immediate_merge_conflict_fix + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - worktree_path + produced: + - conflict_escalation_required +- step: re_push_immediate_fix + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: remerge_immediate + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: release_issue_timeout + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: detect_ci_conflict + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: ci_conflict_fix + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - worktree_path + produced: + - conflict_escalation_required +- step: release_issue_success + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: release_issue_failure + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: register_clone_success + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: register_clone_failure + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: done + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: escalate_stop + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - group_files + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_name + - source_dir + - source_doc + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] diff --git a/src/autoskillit/recipes/contracts/implementation.yaml b/src/autoskillit/recipes/contracts/implementation.yaml index 0471f76408..02f4ac03ea 100644 --- a/src/autoskillit/recipes/contracts/implementation.yaml +++ b/src/autoskillit/recipes/contracts/implementation.yaml @@ -1,19 +1,7 @@ -generated_at: '2026-03-03T23:35:18.371293+00:00' +generated_at: '2026-04-05T02:19:55.954339+00:00' bundled_manifest_version: 0.1.0 skill_hashes: {} skills: - make-groups: - inputs: - - name: source_doc - type: file_path - required: true - outputs: - - name: groups_path - type: file_path - - name: manifest_path - type: file_path - - name: group_files - type: file_path_list make-plan: inputs: - name: task @@ -24,6 +12,11 @@ skills: type: file_path - name: plan_parts type: file_path_list + expected_output_patterns: + - plan_path\s*=\s*/.+ + pattern_examples: + - 'plan_path = /tmp/plan.md' + write_behavior: always review-approach: inputs: - name: plan_path @@ -32,12 +25,19 @@ skills: outputs: - name: review_path type: file_path + expected_output_patterns: + - review_path\s*=\s*/.+ + pattern_examples: + - 'review_path = /tmp/review.md' dry-walkthrough: inputs: - name: plan_path type: file_path required: true outputs: [] + expected_output_patterns: [] + pattern_examples: [] + write_behavior: always implement-worktree-no-merge: inputs: - name: plan_path @@ -48,6 +48,11 @@ skills: type: directory_path - name: branch_name type: string + expected_output_patterns: + - worktree_path\s*=\s*/.+ + pattern_examples: + - 'worktree_path = /tmp/worktrees/impl-foo-20260316' + write_behavior: always retry-worktree: inputs: - name: plan_path @@ -61,6 +66,11 @@ skills: type: directory_path - name: branch_name type: string + expected_output_patterns: + - worktree_path\s*=\s*/.+ + pattern_examples: + - 'worktree_path = /tmp/worktrees/impl-foo-20260316' + write_behavior: always resolve-failures: inputs: - name: worktree_path @@ -73,6 +83,9 @@ skills: type: string required: true outputs: [] + expected_output_patterns: [] + pattern_examples: [] + write_behavior: always audit-impl: inputs: - name: plan_path @@ -89,18 +102,150 @@ skills: type: string - name: remediation_path type: file_path + expected_output_patterns: + - verdict\s*=\s*(GO|NO GO) + pattern_examples: + - 'verdict = GO' + - 'verdict = NO GO + + remediation_path = /tmp/remediation.md' + open-pr: + inputs: + - name: plan_paths + type: string + required: true + - name: feature_branch + type: string + required: true + - name: base_branch + type: string + required: true + - name: closing_issue + type: string + required: false + outputs: [] + expected_output_patterns: + - https://github\.com/.*/pull/\d+ + pattern_examples: + - 'https://github.com/owner/repo/pull/42' + review-pr: + inputs: + - name: feature_branch + type: string + required: true + - name: base_branch + type: string + required: true + - name: annotated_diff_path + type: string + required: false + - name: hunk_ranges_path + type: string + required: false + outputs: + - name: verdict + type: string + expected_output_patterns: + - verdict\s*=\s*(approved|changes_requested|needs_human) + pattern_examples: + - 'verdict = approved' + - 'verdict = changes_requested' + - 'verdict = needs_human' + resolve-review: + inputs: + - name: feature_branch + type: string + required: true + - name: base_branch + type: string + required: true + outputs: [] + expected_output_patterns: [] + pattern_examples: [] + write_behavior: always + resolve-merge-conflicts: + inputs: + - name: worktree_path + type: directory_path + required: true + - name: plan_path + type: file_path + required: true + - name: base_branch + type: string + required: true + outputs: + - name: worktree_path + type: directory_path + - name: branch_name + type: string + - name: conflict_report_path + type: file_path + - name: escalation_required + type: string + - name: escalation_reason + type: string + expected_output_patterns: + - worktree_path\s*=\s*/.+ + pattern_examples: + - 'worktree_path = /tmp/worktrees/impl-foo-20260316' + write_behavior: conditional + write_expected_when: + - conflict_report_path\s*=\s*/.+ + diagnose-ci: + inputs: + - name: branch + type: string + required: true + - name: run_id + type: string + required: false + - name: ci_failed_jobs + type: string + required: false + outputs: + - name: diagnosis_path + type: file_path + - name: failure_type + type: string + - name: is_fixable + type: string + expected_output_patterns: + - diagnosis_path\s*=\s*/.+ + pattern_examples: + - 'diagnosis_path = /tmp/diagnosis.md' + write_behavior: always dataflow: +- step: sprint_entry + available: + - audit + - auto_merge + - base_branch + - issue_url + - open_pr + - review_approach + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + required: [] + produced: [] - step: clone available: - audit + - auto_merge - base_branch - - make_groups + - issue_url - open_pr - review_approach + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed required: [] produced: - work_dir @@ -108,15 +253,18 @@ dataflow: - step: capture_base_sha available: - audit + - auto_merge - base_branch - - make_groups + - issue_url - open_pr - remote_url - review_approach + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: @@ -124,170 +272,283 @@ dataflow: - step: set_merge_target available: - audit + - auto_merge - base_branch - base_sha - - make_groups + - issue_url - open_pr - remote_url - review_approach + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: - merge_target -- step: create_branch +- step: get_issue_title available: - audit + - auto_merge - base_branch - base_sha - - make_groups + - issue_url - merge_target - open_pr - remote_url - review_approach + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: + - issue_number + - issue_title + - issue_slug +- step: claim_issue + available: + - audit + - auto_merge + - base_branch + - base_sha + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target -- step: push_merge_target + - open_pr + - remote_url + - review_approach + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - work_dir + required: [] + produced: + - claimed +- step: compute_branch available: - audit + - auto_merge - base_branch - base_sha - - make_groups + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - remote_url - review_approach + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir required: [] - produced: [] -- step: group + produced: + - proposed_branch +- step: create_branch available: - audit + - auto_merge - base_branch - base_sha - - make_groups + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr + - proposed_branch - remote_url - review_approach + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: - - group_files + - merge_target +- step: push_merge_target + available: + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - proposed_branch + - remote_url + - review_approach + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - work_dir + required: [] + produced: [] - step: plan available: - audit + - auto_merge - base_branch - base_sha - - group_files - - make_groups + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr + - proposed_branch - remote_url - review_approach + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: - plan_path + - all_plan_paths - step: review available: + - all_plan_paths - audit + - auto_merge - base_branch - base_sha - - group_files - - make_groups + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: - review_path - step: verify available: + - all_plan_paths - audit + - auto_merge - base_branch - base_sha - - group_files - - make_groups + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: [] - step: implement available: + - all_plan_paths - audit + - auto_merge - base_branch - base_sha - - group_files - - make_groups + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: - worktree_path - step: retry_worktree available: + - all_plan_paths - audit + - auto_merge - base_branch - base_sha - - group_files - - make_groups + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir - worktree_path required: [] @@ -295,42 +556,58 @@ dataflow: - worktree_path - step: test available: + - all_plan_paths - audit + - auto_merge - base_branch - base_sha - - group_files - - make_groups + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir - worktree_path required: [] produced: [] - step: merge available: + - all_plan_paths - audit + - auto_merge - base_branch - base_sha - - group_files - - make_groups + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir - worktree_path required: [] @@ -339,88 +616,120 @@ dataflow: - worktree_path - step: push available: + - all_plan_paths - audit + - auto_merge - base_branch - base_sha + - claimed - cleanup_succeeded - - group_files - - make_groups + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir - worktree_path required: [] produced: [] - step: fix available: + - all_plan_paths - audit + - auto_merge - base_branch - base_sha + - claimed - cleanup_succeeded - - group_files - - make_groups + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir - worktree_path required: [] produced: [] - step: next_or_done available: + - all_plan_paths - audit + - auto_merge - base_branch - base_sha + - claimed - cleanup_succeeded - - group_files - - make_groups + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir - worktree_path required: [] produced: [] - step: audit_impl available: + - all_plan_paths - audit + - auto_merge - base_branch - base_sha + - claimed - cleanup_succeeded - - group_files - - make_groups + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed - work_dir - worktree_path required: [] @@ -428,138 +737,1517 @@ dataflow: - remediation_path - step: remediate available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - work_dir + - worktree_path + required: [] + produced: [] +- step: compose_pr + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - work_dir + - worktree_path + required: + - plan_paths + - feature_branch + produced: [] +- step: extract_pr_number + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - work_dir + - worktree_path + required: [] + produced: + - pr_number +- step: review_pr + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - work_dir + - worktree_path + required: + - feature_branch + produced: + - verdict +- step: resolve_review + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - feature_branch + produced: [] +- step: re_push_review + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: ci_watch + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - claimed + - cleanup_succeeded + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - ci_conclusion + - ci_failed_jobs +- step: check_merge_queue + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - queue_available +- step: check_merge_group_trigger + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - merge_group_trigger +- step: check_auto_merge + available: + - all_plan_paths + - audit + - auto_merge + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - auto_merge_available +- step: route_queue_mode + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: enable_auto_merge + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: wait_for_queue + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - queue_pr_state +- step: reenroll_stalled_pr + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: queue_ejected_fix + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - worktree_path + produced: + - conflict_escalation_required +- step: re_push_queue_fix + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: reenter_merge_queue + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: direct_merge + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: wait_for_direct_merge + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: direct_merge_conflict_fix + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - worktree_path + produced: + - conflict_escalation_required +- step: re_push_direct_fix + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: redirect_merge + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: immediate_merge + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: wait_for_immediate_merge + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: immediate_merge_conflict_fix + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - worktree_path + produced: + - conflict_escalation_required +- step: re_push_immediate_fix + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: remerge_immediate + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: diagnose_ci + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - diagnosis_path +- step: resolve_ci + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - worktree_path + produced: [] +- step: re_push + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: detect_ci_conflict + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: ci_conflict_fix + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - worktree_path + produced: + - conflict_escalation_required +- step: release_issue_success + available: + - all_plan_paths + - audit + - auto_merge + - auto_merge_available + - base_branch + - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: release_issue_timeout + available: + - all_plan_paths - audit + - auto_merge + - auto_merge_available - base_branch - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed - cleanup_succeeded - - group_files - - make_groups + - conflict_escalation_required + - diagnosis_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger - merge_target - open_pr - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state - remediation_path - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed + - verdict - work_dir - worktree_path required: [] produced: [] -- step: open_pr_step +- step: release_issue_failure available: + - all_plan_paths - audit + - auto_merge + - auto_merge_available - base_branch - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed - cleanup_succeeded - - group_files - - make_groups + - conflict_escalation_required + - diagnosis_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger - merge_target - open_pr - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state - remediation_path - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed + - verdict - work_dir - worktree_path required: [] produced: [] -- step: cleanup_success +- step: register_clone_success available: + - all_plan_paths - audit + - auto_merge + - auto_merge_available - base_branch - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed - cleanup_succeeded - - group_files - - make_groups + - conflict_escalation_required + - diagnosis_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger - merge_target - open_pr - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state - remediation_path - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed + - verdict - work_dir - worktree_path required: [] produced: [] -- step: cleanup_failure +- step: register_clone_failure available: + - all_plan_paths - audit + - auto_merge + - auto_merge_available - base_branch - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed - cleanup_succeeded - - group_files - - make_groups + - conflict_escalation_required + - diagnosis_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger - merge_target - open_pr - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state - remediation_path - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed + - verdict - work_dir - worktree_path required: [] produced: [] - step: done available: + - all_plan_paths - audit + - auto_merge + - auto_merge_available - base_branch - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed - cleanup_succeeded - - group_files - - make_groups + - conflict_escalation_required + - diagnosis_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger - merge_target - open_pr - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state - remediation_path - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed + - verdict - work_dir - worktree_path required: [] produced: [] - step: escalate_stop available: + - all_plan_paths - audit + - auto_merge + - auto_merge_available - base_branch - base_sha + - ci_conclusion + - ci_failed_jobs + - claimed - cleanup_succeeded - - group_files - - make_groups + - conflict_escalation_required + - diagnosis_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger - merge_target - open_pr - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state - remediation_path - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - source_doc + - sprint_mode - task + - upfront_claimed + - verdict - work_dir - worktree_path required: [] diff --git a/src/autoskillit/recipes/contracts/merge-prs.yaml b/src/autoskillit/recipes/contracts/merge-prs.yaml index f69f644bd3..479d954d9e 100644 --- a/src/autoskillit/recipes/contracts/merge-prs.yaml +++ b/src/autoskillit/recipes/contracts/merge-prs.yaml @@ -1,13 +1,93 @@ -generated_at: '2026-03-02T02:12:42.454223+00:00' +generated_at: '2026-04-05T02:19:56.074977+00:00' bundled_manifest_version: 0.1.0 -skill_hashes: - make-plan: sha256:4d33f1e86f9ffb91d29924a65b968d056887c271a73249f4472b874126291e0c - dry-walkthrough: sha256:a479c92bcf9afe200fb84fdbe8cd46b7b376e63d9e3b134a1caab2fe5611e095 - implement-worktree-no-merge: sha256:86515d79175468eb205e964d033ad48598812e7997014f7c0e6b52d80a7c002d - retry-worktree: sha256:c66703245d49df7f94a71456a4f76da62c3527652f03bec62b71cc344d5028b9 - resolve-failures: sha256:81ee708f6c8f1e75edb27a5f68dde6d1eac7db229fd5e18690f4c74185de8b45 - audit-impl: sha256:d8fca36db95f0de3ca32c1d1201d6b913f0dbcd541dfa12c7f868f04c8f4c411 +skill_hashes: {} skills: + analyze-prs: + inputs: + - name: base_branch + type: string + required: true + - name: merge_queue_data_path + type: file_path + required: false + outputs: + - name: pr_order_file + type: file_path + - name: analysis_file + type: file_path + - name: integration_branch + type: string + - name: pr_count + type: string + - name: simple_count + type: string + - name: needs_check_count + type: string + - name: queue_mode + type: string + expected_output_patterns: + - pr_order_file\s*=\s*.+ + pattern_examples: + - 'pr_order_file = /tmp/pr_order.json' + resolve-merge-conflicts: + inputs: + - name: worktree_path + type: directory_path + required: true + - name: plan_path + type: file_path + required: true + - name: base_branch + type: string + required: true + outputs: + - name: worktree_path + type: directory_path + - name: branch_name + type: string + - name: conflict_report_path + type: file_path + - name: escalation_required + type: string + - name: escalation_reason + type: string + expected_output_patterns: + - worktree_path\s*=\s*/.+ + pattern_examples: + - 'worktree_path = /tmp/worktrees/impl-foo-20260316' + write_behavior: conditional + write_expected_when: + - conflict_report_path\s*=\s*/.+ + merge-pr: + inputs: + - name: pr_number + type: string + required: true + - name: complexity + type: string + required: true + outputs: + - name: merged + type: string + - name: needs_plan + type: string + - name: escalation_required + type: string + - name: escalation_reason + type: string + - name: pr_number + type: string + - name: pr_branch + type: string + - name: pr_title + type: string + - name: conflict_report_path + type: file_path + expected_output_patterns: + - merged\s*=\s*(true|false) + pattern_examples: + - 'merged = true' + - 'merged = false' make-plan: inputs: - name: task @@ -18,12 +98,20 @@ skills: type: file_path - name: plan_parts type: file_path_list + expected_output_patterns: + - plan_path\s*=\s*/.+ + pattern_examples: + - 'plan_path = /tmp/plan.md' + write_behavior: always dry-walkthrough: inputs: - name: plan_path type: file_path required: true outputs: [] + expected_output_patterns: [] + pattern_examples: [] + write_behavior: always implement-worktree-no-merge: inputs: - name: plan_path @@ -34,6 +122,11 @@ skills: type: directory_path - name: branch_name type: string + expected_output_patterns: + - worktree_path\s*=\s*/.+ + pattern_examples: + - 'worktree_path = /tmp/worktrees/impl-foo-20260316' + write_behavior: always retry-worktree: inputs: - name: plan_path @@ -47,6 +140,11 @@ skills: type: directory_path - name: branch_name type: string + expected_output_patterns: + - worktree_path\s*=\s*/.+ + pattern_examples: + - 'worktree_path = /tmp/worktrees/impl-foo-20260316' + write_behavior: always resolve-failures: inputs: - name: worktree_path @@ -59,6 +157,9 @@ skills: type: string required: true outputs: [] + expected_output_patterns: [] + pattern_examples: [] + write_behavior: always audit-impl: inputs: - name: plan_path @@ -75,46 +176,386 @@ skills: type: string - name: remediation_path type: file_path + expected_output_patterns: + - verdict\s*=\s*(GO|NO GO) + pattern_examples: + - 'verdict = GO' + - 'verdict = NO GO + + remediation_path = /tmp/remediation.md' + open-integration-pr: + inputs: + - name: integration_branch + type: string + required: true + - name: base_branch + type: string + required: true + - name: pr_order_file + type: file_path + required: true + - name: audit_verdict + type: string + required: false + - name: domain_partitions_path + type: file_path + required: false + outputs: + - name: pr_url + type: string + expected_output_patterns: + - https://github\.com/.*/pull/\d+ + pattern_examples: + - 'https://github.com/owner/repo/pull/42' + review-pr: + inputs: + - name: feature_branch + type: string + required: true + - name: base_branch + type: string + required: true + - name: annotated_diff_path + type: string + required: false + - name: hunk_ranges_path + type: string + required: false + outputs: + - name: verdict + type: string + expected_output_patterns: + - verdict\s*=\s*(approved|changes_requested|needs_human) + pattern_examples: + - 'verdict = approved' + - 'verdict = changes_requested' + - 'verdict = needs_human' + resolve-review: + inputs: + - name: feature_branch + type: string + required: true + - name: base_branch + type: string + required: true + outputs: [] + expected_output_patterns: [] + pattern_examples: [] + write_behavior: always + diagnose-ci: + inputs: + - name: branch + type: string + required: true + - name: run_id + type: string + required: false + - name: ci_failed_jobs + type: string + required: false + outputs: + - name: diagnosis_path + type: file_path + - name: failure_type + type: string + - name: is_fixable + type: string + expected_output_patterns: + - diagnosis_path\s*=\s*/.+ + pattern_examples: + - 'diagnosis_path = /tmp/diagnosis.md' + write_behavior: always dataflow: - step: clone available: - audit - base_branch - - keep_clone_on_failure + - plans_dir - run_name - source_dir required: [] produced: - work_dir + - remote_url - step: setup_remote available: - audit - base_branch - - keep_clone_on_failure + - plans_dir + - remote_url - run_name - source_dir - work_dir required: [] produced: [] +- step: check_integration_exists + available: + - audit + - base_branch + - plans_dir + - remote_url + - run_name + - source_dir + - work_dir + required: [] + produced: [] +- step: confirm_create_integration + available: + - audit + - base_branch + - plans_dir + - remote_url + - run_name + - source_dir + - work_dir + required: [] + produced: [] +- step: create_persistent_integration + available: + - audit + - base_branch + - plans_dir + - remote_url + - run_name + - source_dir + - work_dir + required: [] + produced: [] +- step: fetch_merge_queue_data + available: + - audit + - base_branch + - plans_dir + - remote_url + - run_name + - source_dir + - work_dir + required: [] + produced: + - merge_queue_data_path - step: analyze_prs available: - audit - base_branch - - keep_clone_on_failure + - merge_queue_data_path + - plans_dir + - remote_url + - run_name + - source_dir + - work_dir + required: [] + produced: + - pr_order_file + - integration_branch + - queue_mode +- step: route_by_queue_mode + available: + - audit + - base_branch + - integration_branch + - merge_queue_data_path + - plans_dir + - pr_order_file + - queue_mode + - remote_url + - run_name + - source_dir + - work_dir + required: [] + produced: [] +- step: enqueue_all_prs + available: + - audit + - base_branch + - integration_branch + - merge_queue_data_path + - plans_dir + - pr_order_file + - queue_mode + - remote_url + - run_name + - source_dir + - work_dir + required: [] + produced: [] +- step: get_first_pr_number + available: + - audit + - base_branch + - integration_branch + - merge_queue_data_path + - plans_dir + - pr_order_file + - queue_mode + - remote_url + - run_name + - source_dir + - work_dir + required: [] + produced: + - current_pr_number +- step: wait_queue_pr + available: + - audit + - base_branch + - current_pr_number + - integration_branch + - merge_queue_data_path + - plans_dir + - pr_order_file + - queue_mode + - remote_url + - run_name + - source_dir + - work_dir + required: [] + produced: + - queue_pr_state +- step: get_ejected_pr_branch + available: + - audit + - base_branch + - current_pr_number + - integration_branch + - merge_queue_data_path + - plans_dir + - pr_order_file + - queue_mode + - queue_pr_state + - remote_url + - run_name + - source_dir + - work_dir + required: [] + produced: + - ejected_pr_branch +- step: checkout_ejected_pr + available: + - audit + - base_branch + - current_pr_number + - ejected_pr_branch + - integration_branch + - merge_queue_data_path + - plans_dir + - pr_order_file + - queue_mode + - queue_pr_state + - remote_url + - run_name + - source_dir + - work_dir + required: [] + produced: [] +- step: resolve_ejected_conflicts + available: + - audit + - base_branch + - current_pr_number + - ejected_pr_branch + - integration_branch + - merge_queue_data_path + - plans_dir + - pr_order_file + - queue_mode + - queue_pr_state + - remote_url - run_name - source_dir - work_dir required: [] produced: + - conflict_escalation_required +- step: push_ejected_fix + available: + - audit + - base_branch + - conflict_escalation_required + - current_pr_number + - ejected_pr_branch + - integration_branch + - merge_queue_data_path + - plans_dir + - pr_order_file + - queue_mode + - queue_pr_state + - remote_url + - run_name + - source_dir + - work_dir + required: [] + produced: [] +- step: reenter_queue + available: + - audit + - base_branch + - conflict_escalation_required + - current_pr_number + - ejected_pr_branch + - integration_branch + - merge_queue_data_path + - plans_dir - pr_order_file + - queue_mode + - queue_pr_state + - remote_url + - run_name + - source_dir + - work_dir + required: [] + produced: [] +- step: next_queue_pr_or_done + available: + - audit + - base_branch + - conflict_escalation_required + - current_pr_number + - ejected_pr_branch - integration_branch + - merge_queue_data_path + - plans_dir + - pr_order_file + - queue_mode + - queue_pr_state + - remote_url + - run_name + - source_dir + - work_dir + required: [] + produced: [] - step: create_integration_branch available: - audit - base_branch + - conflict_escalation_required + - current_pr_number + - ejected_pr_branch + - integration_branch + - merge_queue_data_path + - plans_dir + - pr_order_file + - queue_mode + - queue_pr_state + - remote_url + - run_name + - source_dir + - work_dir + required: [] + produced: [] +- step: publish_integration_branch + available: + - audit + - base_branch + - conflict_escalation_required + - current_pr_number + - ejected_pr_branch - integration_branch - - keep_clone_on_failure + - merge_queue_data_path + - plans_dir - pr_order_file + - queue_mode + - queue_pr_state + - remote_url - run_name - source_dir - work_dir @@ -124,143 +565,316 @@ dataflow: available: - audit - base_branch + - conflict_escalation_required + - current_pr_number + - ejected_pr_branch - integration_branch - - keep_clone_on_failure + - merge_queue_data_path + - plans_dir - pr_order_file + - queue_mode + - queue_pr_state + - remote_url - run_name - source_dir - work_dir required: [] produced: - needs_plan + - escalation_required + - escalation_reason - task + - current_pr_number - step: plan available: - audit - base_branch + - conflict_escalation_required + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan + - plans_dir - pr_order_file + - queue_mode + - queue_pr_state + - remote_url - run_name - source_dir - task - work_dir required: [] produced: - - plan_path + - pr_plan_path - step: verify available: - audit - base_branch + - conflict_escalation_required + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan - - plan_path + - plans_dir - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remote_url - run_name - source_dir - task - work_dir - required: [] + required: + - plan_path produced: [] - step: implement available: - audit - base_branch + - conflict_escalation_required + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan - - plan_path + - plans_dir - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remote_url - run_name - source_dir - task - work_dir - required: [] + required: + - plan_path produced: - worktree_path + - worktree_branch_name - step: retry_worktree available: - audit - base_branch + - conflict_escalation_required + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan - - plan_path + - plans_dir - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remote_url - run_name - source_dir - task - work_dir + - worktree_branch_name - worktree_path - required: [] + required: + - plan_path produced: - worktree_path + - worktree_branch_name - step: test available: - audit - base_branch + - conflict_escalation_required + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan - - plan_path + - plans_dir - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remote_url - run_name - source_dir - task - work_dir + - worktree_branch_name - worktree_path required: [] produced: [] -- step: merge_to_integration +- step: push_worktree_branch available: - audit - base_branch + - conflict_escalation_required + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan - - plan_path + - plans_dir - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remote_url - run_name - source_dir - task - work_dir + - worktree_branch_name + - worktree_path + required: [] + produced: [] +- step: create_conflict_pr + available: + - audit + - base_branch + - conflict_escalation_required + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remote_url + - run_name + - source_dir + - task + - work_dir + - worktree_branch_name - worktree_path required: [] produced: - - cleanup_succeeded -- step: fix + - conflict_pr_number +- step: wait_for_conflict_ci available: - audit - base_branch - - cleanup_succeeded + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan - - plan_path + - plans_dir - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remote_url - run_name - source_dir - task - work_dir + - worktree_branch_name - worktree_path required: [] produced: [] -- step: next_part_or_next_pr +- step: merge_conflict_pr + available: + - audit + - base_branch + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remote_url + - run_name + - source_dir + - task + - work_dir + - worktree_branch_name + - worktree_path + required: [] + produced: [] +- step: fix available: - audit - base_branch - - cleanup_succeeded + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remote_url + - run_name + - source_dir + - task + - work_dir + - worktree_branch_name + - worktree_path + required: - plan_path + produced: [] +- step: next_part_or_next_pr + available: + - audit + - base_branch + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remote_url - run_name - source_dir - task - work_dir + - worktree_branch_name - worktree_path required: [] produced: [] @@ -268,16 +882,26 @@ dataflow: available: - audit - base_branch - - cleanup_succeeded + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan - - plan_path + - plans_dir - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remote_url - run_name - source_dir - task - work_dir + - worktree_branch_name - worktree_path required: [] produced: [] @@ -285,16 +909,53 @@ dataflow: available: - audit - base_branch - - cleanup_succeeded + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan - - plan_path + - plans_dir - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remote_url - run_name - source_dir - task - work_dir + - worktree_branch_name + - worktree_path + required: [] + produced: [] +- step: check_impl_plans + available: + - audit + - base_branch + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remote_url + - run_name + - source_dir + - task + - work_dir + - worktree_branch_name - worktree_path required: [] produced: [] @@ -302,16 +963,26 @@ dataflow: available: - audit - base_branch - - cleanup_succeeded + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan - - plan_path + - plans_dir - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remote_url - run_name - source_dir - task - work_dir + - worktree_branch_name - worktree_path required: [] produced: @@ -321,113 +992,653 @@ dataflow: available: - audit - base_branch - - cleanup_succeeded + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan - - plan_path + - plans_dir - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state - remediation_path + - remote_url - run_name - source_dir - task - verdict - work_dir + - worktree_branch_name - worktree_path required: [] produced: [] +- step: compute_domain_partitions + available: + - audit + - base_branch + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - ejected_pr_branch + - escalation_reason + - escalation_required + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remediation_path + - remote_url + - run_name + - source_dir + - task + - verdict + - work_dir + - worktree_branch_name + - worktree_path + required: [] + produced: + - domain_partitions_path - step: open_integration_pr available: - audit - base_branch - - cleanup_succeeded + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan - - plan_path + - plans_dir + - pr_order_file + - pr_plan_path + - queue_mode + - queue_pr_state + - remediation_path + - remote_url + - run_name + - source_dir + - task + - verdict + - work_dir + - worktree_branch_name + - worktree_path + required: [] + produced: + - pr_url +- step: wait_for_review_pr_mergeability + available: + - audit + - base_branch + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state - remediation_path + - remote_url - run_name - source_dir - task - verdict - work_dir + - worktree_branch_name + - worktree_path + required: [] + produced: + - review_pr_number +- step: check_mergeability + available: + - audit + - base_branch + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state + - remediation_path + - remote_url + - review_pr_number + - run_name + - source_dir + - task + - verdict + - work_dir + - worktree_branch_name - worktree_path required: [] produced: [] -- step: cleanup_success +- step: resolve_integration_conflicts available: - audit - base_branch - - cleanup_succeeded + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state + - remediation_path + - remote_url + - review_pr_number + - run_name + - source_dir + - task + - verdict + - work_dir + - worktree_branch_name + - worktree_path + required: + - worktree_path - plan_path + produced: + - conflict_escalation_required + - conflict_escalation_reason +- step: force_push_after_rebase + available: + - audit + - base_branch + - conflict_escalation_reason + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state - remediation_path + - remote_url + - review_pr_number - run_name - source_dir - task - verdict - work_dir + - worktree_branch_name - worktree_path required: [] produced: [] -- step: cleanup_failure +- step: wait_for_post_rebase_mergeability available: - audit - base_branch - - cleanup_succeeded + - conflict_escalation_reason + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan - - plan_path + - plans_dir - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state - remediation_path + - remote_url + - review_pr_number - run_name - source_dir - task - verdict - work_dir + - worktree_branch_name + - worktree_path + required: [] + produced: [] +- step: check_mergeability_post_rebase + available: + - audit + - base_branch + - conflict_escalation_reason + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state + - remediation_path + - remote_url + - review_pr_number + - run_name + - source_dir + - task + - verdict + - work_dir + - worktree_branch_name + - worktree_path + required: [] + produced: [] +- step: annotate_pr_diff + available: + - audit + - base_branch + - conflict_escalation_reason + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state + - remediation_path + - remote_url + - review_pr_number + - run_name + - source_dir + - task + - verdict + - work_dir + - worktree_branch_name + - worktree_path + required: [] + produced: + - annotated_diff_path + - hunk_ranges_path +- step: review_pr_integration + available: + - annotated_diff_path + - audit + - base_branch + - conflict_escalation_reason + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required + - hunk_ranges_path + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state + - remediation_path + - remote_url + - review_pr_number + - run_name + - source_dir + - task + - verdict + - work_dir + - worktree_branch_name + - worktree_path + required: [] + produced: + - review_verdict +- step: resolve_review_integration + available: + - annotated_diff_path + - audit + - base_branch + - conflict_escalation_reason + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required + - hunk_ranges_path + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state + - remediation_path + - remote_url + - review_pr_number + - review_verdict + - run_name + - source_dir + - task + - verdict + - work_dir + - worktree_branch_name + - worktree_path + required: + - feature_branch + produced: [] +- step: re_push_review_integration + available: + - annotated_diff_path + - audit + - base_branch + - conflict_escalation_reason + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required + - hunk_ranges_path + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state + - remediation_path + - remote_url + - review_pr_number + - review_verdict + - run_name + - source_dir + - task + - verdict + - work_dir + - worktree_branch_name + - worktree_path + required: [] + produced: [] +- step: ci_watch_pr + available: + - annotated_diff_path + - audit + - base_branch + - conflict_escalation_reason + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required + - hunk_ranges_path + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state + - remediation_path + - remote_url + - review_pr_number + - review_verdict + - run_name + - source_dir + - task + - verdict + - work_dir + - worktree_branch_name + - worktree_path + required: [] + produced: [] +- step: diagnose_ci + available: + - annotated_diff_path + - audit + - base_branch + - conflict_escalation_reason + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required + - hunk_ranges_path + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state + - remediation_path + - remote_url + - review_pr_number + - review_verdict + - run_name + - source_dir + - task + - verdict + - work_dir + - worktree_branch_name + - worktree_path + required: [] + produced: + - diagnosis_path +- step: register_clone_success + available: + - annotated_diff_path + - audit + - base_branch + - conflict_escalation_reason + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - diagnosis_path + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required + - hunk_ranges_path + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state + - remediation_path + - remote_url + - review_pr_number + - review_verdict + - run_name + - source_dir + - task + - verdict + - work_dir + - worktree_branch_name + - worktree_path + required: [] + produced: [] +- step: register_clone_failure + available: + - annotated_diff_path + - audit + - base_branch + - conflict_escalation_reason + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - diagnosis_path + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required + - hunk_ranges_path + - integration_branch + - merge_queue_data_path + - needs_plan + - plans_dir + - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state + - remediation_path + - remote_url + - review_pr_number + - review_verdict + - run_name + - source_dir + - task + - verdict + - work_dir + - worktree_branch_name - worktree_path required: [] produced: [] - step: done available: + - annotated_diff_path - audit - base_branch - - cleanup_succeeded + - conflict_escalation_reason + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - diagnosis_path + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required + - hunk_ranges_path - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan - - plan_path + - plans_dir - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state - remediation_path + - remote_url + - review_pr_number + - review_verdict - run_name - source_dir - task - verdict - work_dir + - worktree_branch_name - worktree_path required: [] produced: [] - step: escalate_stop available: + - annotated_diff_path - audit - base_branch - - cleanup_succeeded + - conflict_escalation_reason + - conflict_escalation_required + - conflict_pr_number + - current_pr_number + - diagnosis_path + - domain_partitions_path + - ejected_pr_branch + - escalation_reason + - escalation_required + - hunk_ranges_path - integration_branch - - keep_clone_on_failure + - merge_queue_data_path - needs_plan - - plan_path + - plans_dir - pr_order_file + - pr_plan_path + - pr_url + - queue_mode + - queue_pr_state - remediation_path + - remote_url + - review_pr_number + - review_verdict - run_name - source_dir - task - verdict - work_dir + - worktree_branch_name - worktree_path required: [] produced: [] diff --git a/src/autoskillit/recipes/contracts/remediation.yaml b/src/autoskillit/recipes/contracts/remediation.yaml index 758adb7db3..f49193786e 100644 --- a/src/autoskillit/recipes/contracts/remediation.yaml +++ b/src/autoskillit/recipes/contracts/remediation.yaml @@ -1,23 +1,34 @@ -generated_at: '2026-03-03T23:39:44.033912+00:00' +generated_at: '2026-04-05T02:19:55.997695+00:00' bundled_manifest_version: 0.1.0 skill_hashes: {} skills: investigate: inputs: - - name: task + - name: topic type: string required: true - outputs: [] + outputs: + - name: investigation_path + type: file_path + expected_output_patterns: + - investigation_path\s*=\s*/.+ + pattern_examples: + - 'investigation_path = /tmp/investigation.md' rectify: inputs: - name: investigation_path type: file_path - required: false + required: true outputs: - name: plan_path type: file_path - name: plan_parts type: file_path_list + expected_output_patterns: + - plan_path\s*=\s*/.+ + pattern_examples: + - 'plan_path = /tmp/plan.md' + write_behavior: always review-approach: inputs: - name: plan_path @@ -26,12 +37,19 @@ skills: outputs: - name: review_path type: file_path + expected_output_patterns: + - review_path\s*=\s*/.+ + pattern_examples: + - 'review_path = /tmp/review.md' dry-walkthrough: inputs: - name: plan_path type: file_path required: true outputs: [] + expected_output_patterns: [] + pattern_examples: [] + write_behavior: always implement-worktree-no-merge: inputs: - name: plan_path @@ -42,6 +60,11 @@ skills: type: directory_path - name: branch_name type: string + expected_output_patterns: + - worktree_path\s*=\s*/.+ + pattern_examples: + - 'worktree_path = /tmp/worktrees/impl-foo-20260316' + write_behavior: always retry-worktree: inputs: - name: plan_path @@ -55,6 +78,11 @@ skills: type: directory_path - name: branch_name type: string + expected_output_patterns: + - worktree_path\s*=\s*/.+ + pattern_examples: + - 'worktree_path = /tmp/worktrees/impl-foo-20260316' + write_behavior: always resolve-failures: inputs: - name: worktree_path @@ -67,6 +95,9 @@ skills: type: string required: true outputs: [] + expected_output_patterns: [] + pattern_examples: [] + write_behavior: always audit-impl: inputs: - name: plan_path @@ -83,6 +114,13 @@ skills: type: string - name: remediation_path type: file_path + expected_output_patterns: + - verdict\s*=\s*(GO|NO GO) + pattern_examples: + - 'verdict = GO' + - 'verdict = NO GO + + remediation_path = /tmp/remediation.md' make-plan: inputs: - name: task @@ -93,65 +131,261 @@ skills: type: file_path - name: plan_parts type: file_path_list + expected_output_patterns: + - plan_path\s*=\s*/.+ + pattern_examples: + - 'plan_path = /tmp/plan.md' + write_behavior: always + open-pr: + inputs: + - name: plan_paths + type: string + required: true + - name: feature_branch + type: string + required: true + - name: base_branch + type: string + required: true + - name: closing_issue + type: string + required: false + outputs: [] + expected_output_patterns: + - https://github\.com/.*/pull/\d+ + pattern_examples: + - 'https://github.com/owner/repo/pull/42' + review-pr: + inputs: + - name: feature_branch + type: string + required: true + - name: base_branch + type: string + required: true + - name: annotated_diff_path + type: string + required: false + - name: hunk_ranges_path + type: string + required: false + outputs: + - name: verdict + type: string + expected_output_patterns: + - verdict\s*=\s*(approved|changes_requested|needs_human) + pattern_examples: + - 'verdict = approved' + - 'verdict = changes_requested' + - 'verdict = needs_human' + resolve-review: + inputs: + - name: feature_branch + type: string + required: true + - name: base_branch + type: string + required: true + outputs: [] + expected_output_patterns: [] + pattern_examples: [] + write_behavior: always + resolve-merge-conflicts: + inputs: + - name: worktree_path + type: directory_path + required: true + - name: plan_path + type: file_path + required: true + - name: base_branch + type: string + required: true + outputs: + - name: worktree_path + type: directory_path + - name: branch_name + type: string + - name: conflict_report_path + type: file_path + - name: escalation_required + type: string + - name: escalation_reason + type: string + expected_output_patterns: + - worktree_path\s*=\s*/.+ + pattern_examples: + - 'worktree_path = /tmp/worktrees/impl-foo-20260316' + write_behavior: conditional + write_expected_when: + - conflict_report_path\s*=\s*/.+ + diagnose-ci: + inputs: + - name: branch + type: string + required: true + - name: run_id + type: string + required: false + - name: ci_failed_jobs + type: string + required: false + outputs: + - name: diagnosis_path + type: file_path + - name: failure_type + type: string + - name: is_fixable + type: string + expected_output_patterns: + - diagnosis_path\s*=\s*/.+ + pattern_examples: + - 'diagnosis_path = /tmp/diagnosis.md' + write_behavior: always dataflow: +- step: sprint_entry + available: + - audit + - auto_merge + - base_branch + - issue_url + - open_pr + - review_approach + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + required: [] + produced: [] - step: clone available: - audit + - auto_merge - base_branch + - issue_url - open_pr - review_approach + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed required: [] produced: - work_dir - remote_url -- step: capture_base_sha +- step: set_merge_target available: - audit + - auto_merge - base_branch + - issue_url - open_pr - remote_url - review_approach + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: - - base_sha -- step: set_merge_target + - merge_target +- step: get_issue_title available: - audit + - auto_merge - base_branch - - base_sha + - issue_url + - merge_target + - open_pr + - remote_url + - review_approach + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - work_dir + required: [] + produced: + - issue_number + - issue_title + - issue_slug +- step: claim_issue + available: + - audit + - auto_merge + - base_branch + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target - open_pr - remote_url - review_approach + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: + - claimed +- step: compute_branch + available: + - audit + - auto_merge + - base_branch + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target + - open_pr + - remote_url + - review_approach + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - work_dir + required: [] + produced: + - proposed_branch - step: create_branch available: - audit + - auto_merge - base_branch - - base_sha + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr + - proposed_branch - remote_url - review_approach + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: @@ -159,48 +393,75 @@ dataflow: - step: push_merge_target available: - audit + - auto_merge - base_branch - - base_sha + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr + - proposed_branch - remote_url - review_approach + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: [] - step: investigate available: - audit + - auto_merge - base_branch - - base_sha + - claimed + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr + - proposed_branch - remote_url - review_approach + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir - required: [] - produced: [] + required: + - topic + produced: + - investigation_path - step: rectify available: - audit + - auto_merge - base_branch - - base_sha + - claimed + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr + - proposed_branch - remote_url - review_approach + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: @@ -208,17 +469,26 @@ dataflow: - step: review available: - audit + - auto_merge - base_branch - - base_sha + - claimed + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: @@ -226,79 +496,119 @@ dataflow: - step: dry_walkthrough available: - audit + - auto_merge - base_branch - - base_sha + - claimed + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: [] - step: implement available: - audit + - auto_merge - base_branch - - base_sha + - claimed + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir required: [] produced: - implementation_ref - worktree_path + - branch_name - step: retry_worktree available: - audit + - auto_merge - base_branch - - base_sha + - branch_name + - claimed - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir - worktree_path required: [] produced: - implementation_ref - worktree_path + - branch_name - step: test available: - audit + - auto_merge - base_branch - - base_sha + - branch_name + - claimed - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir - worktree_path required: [] @@ -306,19 +616,29 @@ dataflow: - step: assess available: - audit + - auto_merge - base_branch - - base_sha + - branch_name + - claimed - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir - worktree_path required: [] @@ -326,19 +646,29 @@ dataflow: - step: audit_impl available: - audit + - auto_merge - base_branch - - base_sha + - branch_name + - claimed - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir - worktree_path required: [] @@ -347,20 +677,30 @@ dataflow: - step: remediate available: - audit + - auto_merge - base_branch - - base_sha + - branch_name + - claimed - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remediation_path - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir - worktree_path required: [] @@ -368,20 +708,30 @@ dataflow: - step: make_plan available: - audit + - auto_merge - base_branch - - base_sha + - branch_name + - claimed - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remediation_path - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir - worktree_path required: [] @@ -390,20 +740,30 @@ dataflow: - step: merge available: - audit + - auto_merge - base_branch - - base_sha + - branch_name + - claimed - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url - merge_target - open_pr - plan_path + - proposed_branch - remediation_path - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed - work_dir - worktree_path required: [] @@ -413,87 +773,1471 @@ dataflow: - step: push available: - audit + - auto_merge + - base_branch + - branch_name + - claimed + - cleanup_succeeded + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - work_dir + - worktree_path + required: [] + produced: [] +- step: compose_pr + available: + - audit + - auto_merge + - base_branch + - branch_name + - claimed + - cleanup_succeeded + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - work_dir + - worktree_path + required: + - plan_paths + - feature_branch + produced: [] +- step: extract_pr_number + available: + - audit + - auto_merge + - base_branch + - branch_name + - claimed + - cleanup_succeeded + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - work_dir + - worktree_path + required: [] + produced: + - pr_number +- step: review_pr + available: + - audit + - auto_merge + - base_branch + - branch_name + - claimed + - cleanup_succeeded + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - work_dir + - worktree_path + required: + - feature_branch + produced: + - verdict +- step: resolve_review + available: + - audit + - auto_merge + - base_branch + - branch_name + - claimed + - cleanup_succeeded + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - feature_branch + produced: [] +- step: re_push_review + available: + - audit + - auto_merge + - base_branch + - branch_name + - claimed + - cleanup_succeeded + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: ci_watch + available: + - audit + - auto_merge + - base_branch + - branch_name + - claimed + - cleanup_succeeded + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - ci_conclusion + - ci_failed_jobs +- step: check_merge_queue + available: + - audit + - auto_merge + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - queue_available +- step: check_merge_group_trigger + available: + - audit + - auto_merge + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - merge_group_trigger +- step: check_auto_merge + available: + - audit + - auto_merge + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - auto_merge_available +- step: route_queue_mode + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: enable_auto_merge + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: wait_for_queue + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - queue_pr_state +- step: reenroll_stalled_pr + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: queue_ejected_fix + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - worktree_path + produced: + - conflict_escalation_required +- step: re_push_queue_fix + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: reenter_merge_queue + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: direct_merge + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: wait_for_direct_merge + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: direct_merge_conflict_fix + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - worktree_path + produced: + - conflict_escalation_required +- step: re_push_direct_fix + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: redirect_merge + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: immediate_merge + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: wait_for_immediate_merge + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: immediate_merge_conflict_fix + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - worktree_path + produced: + - conflict_escalation_required +- step: re_push_immediate_fix + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: remerge_immediate + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: diagnose_ci + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: + - diagnosis_path +- step: resolve_ci + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - worktree_path + produced: [] +- step: re_push + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: detect_ci_conflict + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: ci_conflict_fix + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: + - worktree_path + produced: + - conflict_escalation_required +- step: release_issue_timeout + available: + - audit + - auto_merge + - auto_merge_available + - base_branch + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed + - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path + - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger + - merge_target + - open_pr + - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state + - remediation_path + - remote_url + - review_approach + - review_path + - run_mode + - run_name + - source_dir + - sprint_mode + - task + - upfront_claimed + - verdict + - work_dir + - worktree_path + required: [] + produced: [] +- step: release_issue_success + available: + - audit + - auto_merge + - auto_merge_available - base_branch - - base_sha + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger - merge_target - open_pr - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state - remediation_path - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed + - verdict - work_dir - worktree_path required: [] produced: [] -- step: open_pr_step +- step: release_issue_failure available: - audit + - auto_merge + - auto_merge_available - base_branch - - base_sha + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger - merge_target - open_pr - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state - remediation_path - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed + - verdict - work_dir - worktree_path required: [] produced: [] -- step: cleanup_success +- step: register_clone_success available: - audit + - auto_merge + - auto_merge_available - base_branch - - base_sha + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger - merge_target - open_pr - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state - remediation_path - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed + - verdict - work_dir - worktree_path required: [] produced: [] -- step: cleanup_failure +- step: register_clone_failure available: - audit + - auto_merge + - auto_merge_available - base_branch - - base_sha + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger - merge_target - open_pr - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state - remediation_path - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed + - verdict - work_dir - worktree_path required: [] @@ -501,21 +2245,41 @@ dataflow: - step: done available: - audit + - auto_merge + - auto_merge_available - base_branch - - base_sha + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger - merge_target - open_pr - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state - remediation_path - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed + - verdict - work_dir - worktree_path required: [] @@ -523,21 +2287,41 @@ dataflow: - step: escalate_stop available: - audit + - auto_merge + - auto_merge_available - base_branch - - base_sha + - branch_name + - ci_conclusion + - ci_failed_jobs + - claimed - cleanup_succeeded + - conflict_escalation_required + - diagnosis_path - implementation_ref + - investigation_path + - issue_number + - issue_slug + - issue_title + - issue_url + - merge_group_trigger - merge_target - open_pr - plan_path + - pr_number + - proposed_branch + - queue_available + - queue_pr_state - remediation_path - remote_url - review_approach - review_path + - run_mode - run_name - source_dir - - target_dir + - sprint_mode - task + - upfront_claimed + - verdict - work_dir - worktree_path required: [] diff --git a/src/autoskillit/recipes/contracts/smoke-test.yaml b/src/autoskillit/recipes/contracts/smoke-test.yaml deleted file mode 100644 index 9e9f318772..0000000000 --- a/src/autoskillit/recipes/contracts/smoke-test.yaml +++ /dev/null @@ -1,161 +0,0 @@ -generated_at: '2026-02-25T05:37:09.868627+00:00' -bundled_manifest_version: 0.1.0 -skill_hashes: - pipeline-summary: sha256:08d8a65e195c48a4508e18682560a7d76cb9cabdc13ecc259a17ca895aadff1c -skills: - pipeline-summary: - inputs: - - name: bug_report_path - type: file_path - required: true - - name: feature_branch - type: string - required: true - - name: target_branch - type: string - required: true - - name: workspace - type: directory_path - required: true - outputs: - - name: summary_path - type: file_path - - name: issue_url - type: string - - name: pr_url - type: string -dataflow: -- step: setup - available: - - base_branch - - collect_on_branch - - original_base_branch - - workspace - required: [] - produced: [] -- step: seed_task - available: - - base_branch - - collect_on_branch - - original_base_branch - - workspace - required: [] - produced: [] -- step: create_branch - available: - - base_branch - - collect_on_branch - - original_base_branch - - workspace - required: [] - produced: [] -- step: investigate - available: - - base_branch - - collect_on_branch - - original_base_branch - - workspace - required: [] - produced: [] -- step: rectify - available: - - base_branch - - collect_on_branch - - original_base_branch - - workspace - required: [] - produced: - - plan_path -- step: implement - available: - - base_branch - - collect_on_branch - - original_base_branch - - plan_path - - workspace - required: [] - produced: - - worktree_path -- step: test - available: - - base_branch - - collect_on_branch - - original_base_branch - - plan_path - - workspace - - worktree_path - required: [] - produced: [] -- step: assess - available: - - base_branch - - collect_on_branch - - original_base_branch - - plan_path - - workspace - - worktree_path - required: [] - produced: [] -- step: classify - available: - - base_branch - - collect_on_branch - - original_base_branch - - plan_path - - workspace - - worktree_path - required: [] - produced: [] -- step: merge - available: - - base_branch - - collect_on_branch - - original_base_branch - - plan_path - - workspace - - worktree_path - required: [] - produced: [] -- step: check_summary - available: - - base_branch - - collect_on_branch - - original_base_branch - - plan_path - - workspace - - worktree_path - required: [] - produced: [] -- step: create_summary - available: - - base_branch - - collect_on_branch - - original_base_branch - - plan_path - - workspace - - worktree_path - required: [] - produced: - - summary_path -- step: done - available: - - base_branch - - collect_on_branch - - original_base_branch - - plan_path - - summary_path - - workspace - - worktree_path - required: [] - produced: [] -- step: escalate - available: - - base_branch - - collect_on_branch - - original_base_branch - - plan_path - - summary_path - - workspace - - worktree_path - required: [] - produced: [] diff --git a/src/autoskillit/recipes/diagrams/smoke-test.md b/src/autoskillit/recipes/diagrams/smoke-test.md deleted file mode 100644 index ee77e5f5ce..0000000000 --- a/src/autoskillit/recipes/diagrams/smoke-test.md +++ /dev/null @@ -1,17 +0,0 @@ -## smoke-test - -``` - investigate - | - rectify - | - implement - | - test <-> [x fail -> fix] - | | - | x exhaust -> classify - | full_restart [-> investigate] - | default [-> implement] - | - +-- [pipeline-summary] (optional) -``` diff --git a/src/autoskillit/recipes/experiment-types/benchmark.yaml b/src/autoskillit/recipes/experiment-types/benchmark.yaml new file mode 100644 index 0000000000..f82897ca46 --- /dev/null +++ b/src/autoskillit/recipes/experiment-types/benchmark.yaml @@ -0,0 +1,21 @@ +name: benchmark +classification_triggers: + - "IVs are system/method names, DVs are performance metrics, multiple comparators" +dimension_weights: + causal_structure: S + variance_protocol: H + statistical_corrections: M + ecological_validity: M + measurement_alignment: M + resource_proportionality: L + data_acquisition: M + agent_implementability: H +applicable_lenses: + primary: exp-lens-estimand-clarity + secondary: null +red_team_focus: + specific: asymmetric effort + severity_cap: warning +l1_severity: + estimand_clarity: warning + hypothesis_falsifiability: warning diff --git a/src/autoskillit/recipes/experiment-types/causal_inference.yaml b/src/autoskillit/recipes/experiment-types/causal_inference.yaml new file mode 100644 index 0000000000..0ff2da0e81 --- /dev/null +++ b/src/autoskillit/recipes/experiment-types/causal_inference.yaml @@ -0,0 +1,21 @@ +name: causal_inference +classification_triggers: + - "Causal language (\"causes\", \"effect of\"), confounders in threats" +dimension_weights: + causal_structure: H + variance_protocol: L + statistical_corrections: H + ecological_validity: L + measurement_alignment: M + resource_proportionality: L + data_acquisition: M + agent_implementability: M +applicable_lenses: + primary: exp-lens-estimand-clarity + secondary: null +red_team_focus: + specific: unblocked backdoor path + severity_cap: critical +l1_severity: + estimand_clarity: critical + hypothesis_falsifiability: critical diff --git a/src/autoskillit/recipes/experiment-types/configuration_study.yaml b/src/autoskillit/recipes/experiment-types/configuration_study.yaml new file mode 100644 index 0000000000..901bddab8b --- /dev/null +++ b/src/autoskillit/recipes/experiment-types/configuration_study.yaml @@ -0,0 +1,21 @@ +name: configuration_study +classification_triggers: + - "IVs are numeric parameters of one system, grid/sweep structure" +dimension_weights: + causal_structure: S + variance_protocol: H + statistical_corrections: H + ecological_validity: L + measurement_alignment: M + resource_proportionality: L + data_acquisition: M + agent_implementability: H +applicable_lenses: + primary: exp-lens-estimand-clarity + secondary: null +red_team_focus: + specific: overfitting to held-out set + severity_cap: warning +l1_severity: + estimand_clarity: warning + hypothesis_falsifiability: warning diff --git a/src/autoskillit/recipes/experiment-types/exploratory.yaml b/src/autoskillit/recipes/experiment-types/exploratory.yaml new file mode 100644 index 0000000000..a7dae8b654 --- /dev/null +++ b/src/autoskillit/recipes/experiment-types/exploratory.yaml @@ -0,0 +1,21 @@ +name: exploratory +classification_triggers: + - "Default — no prior rule fires, or hypothesis absent" +dimension_weights: + causal_structure: L + variance_protocol: L + statistical_corrections: S + ecological_validity: M + measurement_alignment: M + resource_proportionality: L + data_acquisition: M + agent_implementability: L +applicable_lenses: + primary: exp-lens-estimand-clarity + secondary: null +red_team_focus: + specific: HARKing vulnerability + severity_cap: info +l1_severity: + estimand_clarity: info + hypothesis_falsifiability: info diff --git a/src/autoskillit/recipes/experiment-types/robustness_audit.yaml b/src/autoskillit/recipes/experiment-types/robustness_audit.yaml new file mode 100644 index 0000000000..ab4fe78f8e --- /dev/null +++ b/src/autoskillit/recipes/experiment-types/robustness_audit.yaml @@ -0,0 +1,21 @@ +name: robustness_audit +classification_triggers: + - "Tests generalization/stability, deliberately varied conditions" +dimension_weights: + causal_structure: M + variance_protocol: M + statistical_corrections: S + ecological_validity: H + measurement_alignment: H + resource_proportionality: L + data_acquisition: H + agent_implementability: M +applicable_lenses: + primary: exp-lens-estimand-clarity + secondary: null +red_team_focus: + specific: unrealistic threat distribution + severity_cap: warning +l1_severity: + estimand_clarity: warning + hypothesis_falsifiability: warning diff --git a/src/autoskillit/recipes/implementation-groups.yaml b/src/autoskillit/recipes/implementation-groups.yaml index c117a34cac..a3f38c16b0 100644 --- a/src/autoskillit/recipes/implementation-groups.yaml +++ b/src/autoskillit/recipes/implementation-groups.yaml @@ -22,7 +22,7 @@ ingredients: default: "false" audit: description: Post-merge quality gate - default: "true" + default: "false" open_pr: description: PR instead of direct merge default: "true" @@ -38,22 +38,6 @@ ingredients: description: "Set to 'true' when process-issues has already claimed this issue upfront. Allows claim_issue defense step to pass through without aborting." default: "false" hidden: true - defer_cleanup: - description: >- - When 'true', skip per-pipeline interactive cleanup and register this clone - in the shared registry for batch deletion after all parallel pipelines - complete. Set to 'true' on every parallel instance; leave 'false' for - sequential single-pipeline runs. - default: "false" - hidden: true - registry_path: - description: >- - Absolute path to the shared clone cleanup registry file. Required when - defer_cleanup=true. Must be identical across all parallel pipeline runs in - the same batch (use a fixed path like - /path/to/project/.autoskillit/temp/clone-cleanup-registry.json). - default: "" - hidden: true kitchen_rules: - "NEVER use native Claude Code tools (Read, Grep, Glob, Edit, Write, @@ -66,9 +50,9 @@ kitchen_rules: derived from inputs.run_name and context.issue_number (e.g. impl/124) or a date suffix (e.g. impl/20260304) when no issue is available. All worktree merges target the feature branch (context.merge_target), not base_branch - directly. The push step publishes the feature branch, then open_pr_step + directly. The push step publishes the feature branch, then prepare_pr → run_arch_lenses → compose_pr opens a PR to base_branch. When open_pr=false, merges target base_branch - directly and open_pr_step is skipped." + directly and prepare_pr is skipped." - "SOURCE ISOLATION: After clone_repo returns, the source_dir is strictly off-limits. Never run any command in source_dir — no git checkout, git fetch, git reset, git pull, run_cmd, run_skill, or any other operation. @@ -141,7 +125,7 @@ steps: note: > Runs when inputs.issue_url is non-empty. Skipped otherwise. Fetches only the issue title and slug (no body, no comments). - issue_number is threaded to open_pr_step for "Closes #N" in the PR body. + issue_number is threaded to prepare_pr for "Closes #N" in the PR body. issue_slug provides a descriptive branch prefix. The make-plan skill running in a headless session can call fetch_github_issue directly if it needs full issue content — pass inputs.issue_url through. @@ -232,7 +216,7 @@ steps: on_failure: release_issue_failure note: > Always runs — groups are the primary workflow in this recipe. - Produces group files in .autoskillit/temp/make-groups/ containing sequenced groups (groupA, groupB, ...). + Produces group files in {{AUTOSKILLIT_TEMP}}/make-groups/ containing sequenced groups (groupA, groupB, ...). GROUPS MODE: Pass the file paths (group_files) directly to the plan step via context.group_files — do NOT read the files. The current group's file path becomes the task passed to the plan step. ITERATION: The agent maintains a group queue. For each group, run the full cycle @@ -255,7 +239,7 @@ steps: on_success: review on_failure: release_issue_failure note: > - Produces plan in .autoskillit/temp/make-plan/. Glob plan_dir for *_part_*.md or single plan file. + Produces plan in {{AUTOSKILLIT_TEMP}}/make-plan/. Glob plan_dir for *_part_*.md or single plan file. plan_parts context key contains the full ordered list of part files (sorted alphabetically). For a single-part plan, plan_parts has one entry equal to plan_path. GROUPS MODE: Replace the skill_command task with the current group's file path from @@ -300,6 +284,7 @@ steps: implement: tool: run_skill + stale_threshold: 2400 with: skill_command: "/autoskillit:implement-worktree-no-merge ${{ context.plan_path }}" cwd: "${{ context.work_dir }}" @@ -314,23 +299,41 @@ steps: retry_worktree: tool: run_skill + stale_threshold: 2400 with: skill_command: "/autoskillit:retry-worktree ${{ context.plan_path }} ${{ context.worktree_path }}" cwd: "${{ context.worktree_path }}" step_name: "retry_worktree" capture: worktree_path: "${{ result.worktree_path }}" + phases_implemented: "${{ result.phases_implemented }}" + on_result: + - when: "${{ result.phases_implemented }} > 0" + route: test + - route: test on_exhausted: release_issue_failure - on_success: test on_failure: release_issue_failure test: tool: test_check with: worktree_path: "${{ context.worktree_path }}" - on_success: merge + on_success: commit_guard on_failure: fix + commit_guard: + tool: run_cmd + with: + cmd: "cd ${{ context.worktree_path }} && if [ -n \"$(git status --porcelain)\" ]; then git add -A && git commit -m 'chore: commit pending session changes'; fi" + cwd: "${{ context.worktree_path }}" + step_name: commit_guard + on_success: merge + on_failure: merge + note: > + Belt-and-suspenders guard: auto-commits any uncommitted changes before merge. + Catches dirty state from context-exhausted skills, cascading pre-commit auto-fixes, + or any other source. on_failure routes to merge (dirty-tree gate will catch real issues). + merge: tool: merge_worktree with: @@ -360,7 +363,7 @@ steps: By default (open_pr=true), merge_target is the feature branch named from run_name. When open_pr=false, merge_target equals base_branch — merges go directly to base. test_gate failures route to fix (resolve-failures) for recovery; - all other failures route to cleanup_failure. + all other failures route to release_issue_failure. push: tool: push_to_remote @@ -368,15 +371,15 @@ steps: clone_path: "${{ context.work_dir }}" remote_url: "${{ context.remote_url }}" branch: "${{ context.merge_target }}" - on_success: open_pr_step + on_success: prepare_pr on_failure: release_issue_failure note: > Runs once at the end, after audit_impl passes. Pushes merge_target branch from the clone to the upstream remote. By default (open_pr=true), this pushes the feature branch; when open_pr=false, pushes base_branch. Uses the pre-resolved remote_url captured at clone time, preserving clone isolation. - On success, routes to open_pr_step (which opens the PR by default; skipped when open_pr=false). - On failure, cleanup_failure still removes the clone. + On success, routes to prepare_pr (which opens the PR by default; skipped when open_pr=false). + On failure, release_issue_failure registers the clone and escalates. fix: tool: run_skill @@ -384,7 +387,19 @@ steps: skill_command: "/autoskillit:resolve-failures ${{ context.worktree_path }} ${{ context.plan_path }} ${{ inputs.base_branch }}" cwd: "${{ context.worktree_path }}" step_name: "fix" - on_success: test + capture: + verdict: "${{ result.verdict }}" + fixes_applied: "${{ result.fixes_applied }}" + on_result: + - when: "${{ result.verdict }} == 'real_fix'" + route: test + - when: "${{ result.verdict }} == 'already_green'" + route: test + - when: "${{ result.verdict }} == 'flake_suspected'" + route: test + - when: "${{ result.verdict }} == 'ci_only_failure'" + route: release_issue_failure + - route: release_issue_failure on_failure: release_issue_failure on_context_limit: test note: "Fixes test failures without merging. Routes back to test for re-validation before merge_worktree. on_context_limit routes needs_retry=True to test (worktree may already be green) instead of re-running fix blindly." @@ -437,29 +452,73 @@ steps: remediation_path: "${{ context.remediation_path }}" on_success: plan - open_pr_step: + prepare_pr: tool: run_skill with: - skill_command: "/autoskillit:open-pr ${{ context.all_plan_paths }} ${{ inputs.run_name }} ${{ inputs.base_branch }}" + skill_command: "/autoskillit:prepare-pr ${{ context.all_plan_paths }} ${{ inputs.run_name }} ${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" - step_name: "open_pr" + step_name: "prepare_pr" issue_number: "${{ context.issue_number }}" - on_success: extract_pr_number + capture: + prep_path: "${{ result.prep_path }}" + selected_lenses: "${{ result.selected_lenses }}" + lens_context_paths: "${{ result.lens_context_paths }}" + on_success: run_arch_lenses on_failure: release_issue_failure on_context_limit: release_issue_failure optional: true skip_when_false: "inputs.open_pr" note: > - Runs by default (open_pr=true). Skipped when open_pr=false. - The feature branch is already published by the push step that precedes this step. - Invokes the open-pr skill which selects arch-lens diagrams, composes a PR body, - and runs gh pr create. The skill gracefully degrades if gh is unavailable. + Reads plan(s), runs git diff, classifies changed files, selects 1–3 arch-lens slugs, + writes one PR context file per lens, and writes a PR prep file. Does NOT invoke + arch-lens skills. If context.issue_number is a non-empty string, append it as the + 4th positional argument so prepare-pr fetches requirements from the closing issue. MULTI-GROUP: context.all_plan_paths may contain comma-separated plan paths - accumulated across group iterations. The open-pr skill splits and synthesizes - PR content from all plans. - If context.issue_number is a non-empty string (set by fetch_issue), append it - as a 4th positional argument to the skill_command. The open-pr skill will insert - "Closes #{issue_number}" into the PR body to auto-close the issue on merge. + accumulated across group iterations. + + run_arch_lenses: + tool: run_skill + with: + skill_command: "/autoskillit:arch-lens-{slug} {context_path}" + cwd: "${{ context.work_dir }}" + step_name: "run_arch_lenses" + capture_list: + all_diagram_paths: "${{ result.diagram_path }}" + on_success: compose_pr + on_failure: compose_pr + on_context_limit: compose_pr + optional: true + skip_when_false: "inputs.open_pr" + note: > + LENS ITERATION: context.selected_lenses contains comma-separated arch-lens slugs + (e.g. "module-dependency,process-flow"). context.lens_context_paths contains the + corresponding comma-separated context file paths (same order as slugs). For each + lens slug, run: + /autoskillit:arch-lens-{slug} {matching_context_path} + Run all selected lenses in parallel (all run_skill calls in a single message). + Accumulate each diagram_path value into context.all_diagram_paths via capture_list. + If a lens fails, continue with remaining lenses — compose_pr handles empty lists + gracefully by omitting the Architecture Impact section. + + compose_pr: + tool: run_skill + with: + skill_command: "/autoskillit:compose-pr ${{ context.prep_path }} \"${{ context.all_diagram_paths }}\" ${{ context.work_dir }} ${{ inputs.base_branch }}" + cwd: "${{ context.work_dir }}" + step_name: "compose_pr" + issue_number: "${{ context.issue_number }}" + capture: + pr_url: "${{ result.pr_url }}" + on_success: extract_pr_number + on_failure: release_issue_failure + on_context_limit: release_issue_failure + optional: true + skip_when_false: "inputs.open_pr" + note: > + Reads the PR prep file, validates arch-lens diagrams (must contain ★ or ●), + composes the PR body, and runs gh pr create. Degrades gracefully if gh is + unavailable (emits pr_url=). If context.issue_number is set, append it as the + 5th positional argument for Closes #N injection in the PR body. extract_pr_number: tool: run_cmd @@ -469,18 +528,36 @@ steps: step_name: "extract_pr_number" capture: pr_number: "${{ result.stdout | trim }}" - on_success: review_pr + on_success: annotate_pr_diff on_failure: release_issue_failure optional: true skip_when_false: "inputs.open_pr" note: > - Extracts the integer PR number from the feature branch opened by open_pr_step. + Extracts the integer PR number from the feature branch opened by compose_pr. pr_number is required by the queue finale steps (enable_auto_merge, wait_for_queue). + annotate_pr_diff: + tool: run_python + with: + callable: "autoskillit.smoke_utils.annotate_pr_diff" + pr_number: "${{ context.pr_number }}" + cwd: "${{ context.work_dir }}" + output_dir: "${{ context.work_dir }}/{{AUTOSKILLIT_TEMP}}/review-pr" + capture: + annotated_diff_path: "${{ result.annotated_diff_path }}" + hunk_ranges_path: "${{ result.hunk_ranges_path }}" + on_success: review_pr + on_failure: review_pr + optional: true + skip_when_false: "inputs.open_pr" + note: > + Pre-computes annotated diff with [LNNN] markers and hunk ranges JSON for + review-pr. On failure, falls through to review_pr which uses empty fallback. + review_pr: tool: run_skill with: - skill_command: "/autoskillit:review-pr ${{ context.merge_target }} ${{ inputs.base_branch }}" + skill_command: "/autoskillit:review-pr ${{ context.merge_target }} ${{ inputs.base_branch }} annotated_diff_path=${{ context.annotated_diff_path }} hunk_ranges_path=${{ context.hunk_ranges_path }}" cwd: "${{ context.work_dir }}" step_name: "review_pr" capture: @@ -497,7 +574,7 @@ steps: optional: true skip_when_false: "inputs.open_pr" note: > - Runs after open_pr_step creates the PR. Invokes the review-pr skill as a + Runs after compose_pr creates the PR. Invokes the review-pr skill as a headless session to leave inline review comments on the PR. The skill finds the open PR by feature branch name (context.merge_target). Captures verdict and routes via on_result: changes_requested → resolve_review, @@ -510,16 +587,27 @@ steps: skill_command: "/autoskillit:resolve-review ${{ context.merge_target }} ${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" step_name: "resolve_review" + capture: + verdict: "${{ result.verdict }}" retries: 2 on_exhausted: release_issue_failure - on_success: re_push_review + on_result: + - when: "${{ result.verdict }} == 'real_fix'" + route: re_push_review + - when: "${{ result.verdict }} == 'already_green'" + route: re_push_review + - when: "${{ result.verdict }} == 'flake_suspected'" + route: release_issue_failure + - when: "${{ result.verdict }} == 'ci_only_failure'" + route: release_issue_failure on_failure: release_issue_failure note: > Runs when review_pr reports issues (verdict=changes_requested). The clone (context.work_dir) has the feature branch (context.merge_target) checked out. resolve-review fetches inline and summary review comments via the GitHub API, applies fixes for each actionable finding (critical + warning severity), and - commits each fix. Orchestrator re-pushes via re_push_review after success. + commits each fix. Routes via on_result: verdict dispatch — real_fix/already_green + both route to re_push_review; flake_suspected/ci_only_failure escalate. Retries up to 2 times (3 total attempts) before exhausting to release_issue_failure. re_push_review: @@ -539,14 +627,13 @@ steps: tool: wait_for_ci with: branch: "${{ context.merge_target }}" - workflow: "tests.yml" timeout_seconds: 300 cwd: "${{ context.work_dir }}" remote_url: "${{ context.remote_url }}" capture: ci_conclusion: "${{ result.conclusion }}" ci_failed_jobs: "${{ result.failed_jobs }}" - on_success: check_merge_queue + on_success: check_repo_merge_state on_failure: detect_ci_conflict optional: true skip_when_false: "inputs.open_pr" @@ -555,14 +642,14 @@ steps: using the wait_for_ci MCP tool (timeout: 300 s). Captures structured output (conclusion + failed job names) for downstream resolve_ci. Skipped when open_pr=false — no remote feature branch is opened in that mode. - On success, routes to check_merge_queue to determine if the PR should enter + On success, routes to check_repo_merge_state to determine if the PR should enter the merge queue. On failure, routes to detect_ci_conflict which checks whether the failure is caused by a stale base before falling through to diagnose_ci. diagnose_ci: tool: run_skill with: - skill_command: "/autoskillit:diagnose-ci ${{ context.merge_target }} - - tests.yml" + skill_command: "/autoskillit:diagnose-ci ${{ context.merge_target }} - - - ${{ context.ci_event }}" cwd: "${{ context.work_dir }}" step_name: "diagnose_ci" ci_failed_jobs: "${{ context.ci_failed_jobs }}" @@ -572,10 +659,11 @@ steps: on_failure: resolve_ci on_context_limit: resolve_ci optional: true + optional_context_refs: [ci_event] skip_when_false: "inputs.open_pr" note: > Runs when ci_watch reports a CI failure. Fetches CI logs via gh API and writes - a structured diagnosis to .autoskillit/temp/diagnose-ci/. Routes to resolve_ci on success + a structured diagnosis to {{AUTOSKILLIT_TEMP}}/diagnose-ci/. Routes to resolve_ci on success OR failure (best-effort: resolve-failures proceeds even without a diagnosis). diagnosis_path is passed to resolve_ci for targeted remediation context. @@ -585,17 +673,41 @@ steps: skill_command: "/autoskillit:resolve-failures ${{ context.work_dir }} ${{ context.plan_path }} ${{ inputs.base_branch }} ${{ context.ci_conclusion }} ${{ context.ci_failed_jobs }} ${{ context.diagnosis_path }}" cwd: "${{ context.work_dir }}" step_name: "resolve_ci" + capture: + verdict: "${{ result.verdict }}" retries: 2 on_exhausted: release_issue_failure - on_success: re_push + on_context_limit: re_push + on_result: + - when: "${{ result.verdict }} == 'real_fix'" + route: re_push + - when: "${{ result.verdict }} == 'already_green'" + route: pre_resolve_rebase + - when: "${{ result.verdict }} == 'flake_suspected'" + route: release_issue_failure + - when: "${{ result.verdict }} == 'ci_only_failure'" + route: release_issue_failure on_failure: release_issue_failure note: > Runs when ci_watch reports a CI failure. Receives ci_failed_jobs from wait_for_ci - structured output to avoid redundant CI failure re-investigation. The clone - (context.work_dir) has the feature branch (context.merge_target) checked out. - The skill commits fixes and exits without merging; the orchestrator re-pushes - via re_push. Retries up to 2 times (3 total attempts) before exhausting - to cleanup_failure. + structured output to avoid redundant CI failure re-investigation. Routes via + on_result: verdict dispatch — real_fix pushes, already_green rebases and re-diagnoses + (sibling fix may have landed), flake_suspected/ci_only_failure escalate to human. + Retries up to 2 times (3 total attempts) before exhausting to release_issue_failure. + + pre_resolve_rebase: + tool: run_cmd + with: + cmd: "git -C ${{ context.work_dir }} fetch origin && git -C ${{ context.work_dir }} rebase origin/${{ inputs.base_branch }}" + step_name: "pre_resolve_rebase" + retries: 1 + on_success: diagnose_ci + on_failure: release_issue_failure + note: > + Rebases the feature branch against integration head when resolve_ci emits + already_green — the worktree was already clean because a sibling pipeline's + fix already landed on integration. Pulling it in before re-running diagnose_ci + gives the pipeline a real chance at emitting real_fix and reaching re_push. re_push: tool: push_to_remote @@ -609,100 +721,42 @@ steps: note: > Pushes the CI-fixed feature branch back to the remote after resolve_ci succeeds. Routes back to ci_watch to verify the fix resolves CI. On push failure, escalates - via cleanup_failure. + via release_issue_failure. - check_merge_queue: - tool: run_cmd + check_repo_merge_state: + tool: check_repo_merge_state + block: pre_queue_gate with: - cmd: > - REPO=$( { git remote get-url upstream 2>/dev/null || git remote get-url origin; } | sed 's|.*github\.com[:/]||; s|\.git$||') && - OWNER=${REPO%%/*} && REPO_NAME=${REPO##*/} && - BRANCH="${{ inputs.base_branch }}" && - gh api graphql -f query="query { - repository(owner:\"$OWNER\", name:\"$REPO_NAME\") { - mergeQueue(branch:\"$BRANCH\") { id } - } - }" | jq -r 'if .data.repository.mergeQueue != null then "true" else "false" end' - cwd: "${{ context.work_dir }}" - step_name: "check_merge_queue" - capture: - queue_available: "${{ result.stdout | trim }}" - on_success: check_merge_group_trigger - on_failure: release_issue_success - skip_when_false: "inputs.open_pr" - note: > - Detects whether the target branch has an active merge queue via GraphQL. - Captures "true" or "false" into context.queue_available. - On failure (gh error, parse error), degrades gracefully to release_issue_success - (non-queue path). On success, routes to check_merge_group_trigger to validate - that a CI workflow includes the merge_group trigger before proceeding. - Skipped when open_pr=false — no PR was opened. - - check_merge_group_trigger: - tool: run_cmd - with: - cmd: > - REPO=$( { git remote get-url upstream 2>/dev/null || git remote get-url origin; } | sed 's|.*github\.com[:/]||; s|\.git$||') && - OWNER=${REPO%%/*} && REPO_NAME=${REPO##*/} && - [ -n "$OWNER" ] && [ -n "$REPO_NAME" ] && - FOUND="" && - while IFS= read -r wf; do - content=$(gh api "repos/$OWNER/$REPO_NAME/contents/.github/workflows/$wf" -q '.content') - [ -n "$content" ] && echo "$content" | base64 -d 2>/dev/null | grep -q 'merge_group' && FOUND=true && break - done < <(gh api "repos/$OWNER/$REPO_NAME/contents/.github/workflows" 2>/dev/null | jq -r '.[] | select(.type == "file") | .name'); - if [ "$FOUND" = "true" ]; then echo "true"; else - echo "WARNING: Merge queue detected on ${{ inputs.base_branch }} but no CI workflow includes merge_group trigger -- degrading to non-queue merge path" >&2 - echo "false" - fi - cwd: "${{ context.work_dir }}" - step_name: "check_merge_group_trigger" - capture: - merge_group_trigger: "${{ result.stdout | trim }}" - on_success: check_auto_merge - on_failure: check_auto_merge - skip_when_false: "inputs.open_pr" - note: > - Validates that at least one CI workflow in .github/workflows/ includes the - merge_group event trigger; emits WARNING to stderr when absent. - Lists workflow files via GitHub API, decodes base64 content, and greps for - 'merge_group'; captures merge_group_trigger as "true" (found) or "false" - (absent). - - check_auto_merge: - tool: run_cmd - with: - cmd: > - REPO=$( { git remote get-url upstream 2>/dev/null || git remote get-url origin; } | sed 's|.*github\.com[:/]||; s|\.git$||') && - OWNER=${REPO%%/*} && REPO_NAME=${REPO##*/} && - gh api graphql -f query="query { - repository(owner:\"$OWNER\", name:\"$REPO_NAME\") { - autoMergeAllowed - } - }" | jq -r '.data.repository.autoMergeAllowed // false' + branch: "${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" - step_name: "check_auto_merge" + remote_url: "${{ context.remote_url }}" + step_name: "check_repo_merge_state" capture: - auto_merge_available: "${{ result.stdout | trim }}" + queue_available: "${{ result.queue_available }}" + merge_group_trigger: "${{ result.merge_group_trigger }}" + auto_merge_available: "${{ result.auto_merge_available }}" + ci_event: "${{ result.ci_event }}" on_success: route_queue_mode - on_failure: route_queue_mode + on_failure: immediate_merge skip_when_false: "inputs.open_pr" note: > - Detects whether the target repository has autoMergeAllowed enabled via GraphQL. - Captures "true" or "false" into context.auto_merge_available. - On failure (gh error, network error), falls through to route_queue_mode with - auto_merge_available unset — route_queue_mode defaults to immediate_merge (safe - non-auto path). GraphQL-level errors (rate-limit, missing auth scope) also return - exit 0 with an errors array and no .data field; the jq // false fallback outputs - false safely, so auto_merge_available defaults to false on any error path. + Single GraphQL round-trip that captures queue_available, merge_group_trigger, + auto_merge_available, and ci_event for the target branch. Consolidates the former three + sequential run_cmd steps (check_merge_queue, check_merge_group_trigger, + check_auto_merge) into one MCP tool call. On failure (network error, auth failure), + falls through to immediate_merge (non-queue direct merge path). Skipped when open_pr=false — no PR was opened. route_queue_mode: + block: pre_queue_gate action: route on_result: - when: "${{ inputs.auto_merge }} != 'true'" - route: confirm_cleanup - - when: "${{ context.queue_available }} == true and ${{ context.merge_group_trigger }} == true" + route: register_clone_success + - when: "${{ context.queue_available }} == true and ${{ context.merge_group_trigger }} == true and ${{ context.auto_merge_available }} == true" route: enable_auto_merge + - when: "${{ context.queue_available }} == true and ${{ context.merge_group_trigger }} == true and ${{ context.auto_merge_available }} == false" + route: queue_enqueue_no_auto - when: "${{ context.auto_merge_available }} == true" route: direct_merge - route: immediate_merge @@ -715,11 +769,29 @@ steps: cwd: "${{ context.work_dir }}" step_name: "enable_auto_merge" on_success: wait_for_queue - on_failure: confirm_cleanup + on_failure: register_clone_success skip_when_false: "inputs.open_pr" note: > Submits the PR to the merge queue. On failure (PR not mergeable, already merged), - degrades to confirm_cleanup. + degrades to register_clone_success. + + queue_enqueue_no_auto: + tool: run_cmd + with: + cmd: "gh pr merge '${{ context.pr_number }}' --squash" + cwd: "${{ context.work_dir }}" + step_name: "queue_enqueue_no_auto" + on_success: wait_for_queue + on_failure: register_clone_success + skip_when_false: "inputs.open_pr" + note: > + Submits the PR to the merge queue when the target branch has a configured + merge queue but the repository disallows auto-merge (autoMergeAllowed=false). + Uses plain `gh pr merge --squash` (no --auto, which would be rejected by + GitHub's API auto-merge gate). GitHub intercepts the call and enqueues + the PR because the branch has a queue. Routes to wait_for_queue (the + shared queue waiter) — never to wait_for_immediate_merge, whose 5-minute + poll is too short for queue serialization. wait_for_queue: tool: wait_for_merge_queue @@ -734,6 +806,10 @@ steps: on_result: - when: "${{ result.pr_state }} == merged" route: release_issue_success + - when: "${{ result.pr_state }} == ejected_ci_failure" + route: diagnose_ci + - when: "${{ result.pr_state }} == dropped_healthy" + route: reenter_merge_queue_cheap - when: "${{ result.pr_state }} == ejected" route: queue_ejected_fix - when: "${{ result.pr_state }} == stalled" @@ -745,7 +821,8 @@ steps: skip_when_false: "inputs.open_pr" note: > Waits up to 15 minutes for the PR to merge through the queue. - merged → release_issue_success to transition issue state then confirm_cleanup. + merged → release_issue_success to transition issue state then register_clone_success. + ejected_ci_failure → diagnose_ci (CI failure; conflict resolution cannot fix this). ejected → conflict fix cycle then re-enter. stalled → lightweight re-enrollment (disable then re-enable auto-merge). timeout → release_issue_timeout (release claim without staged label; merge unconfirmed). @@ -761,11 +838,33 @@ steps: skip_when_false: "inputs.open_pr" queue_ejected_fix: + tool: run_cmd + with: + cmd: > + if git fetch origin ${{ inputs.base_branch }} && git rebase origin/${{ inputs.base_branch }}; + then echo 'clean'; + else git rebase --abort 2>/dev/null || true; echo 'conflicts'; + fi + cwd: "${{ context.work_dir }}" + step_name: "queue_ejected_fix" + on_result: + - when: "${{ result.stdout | trim }} == clean" + route: re_push_queue_fix + - route: resolve_queue_merge_conflicts + on_failure: resolve_queue_merge_conflicts + skip_when_false: "inputs.open_pr" + note: > + Attempts a cheap rebase before invoking the full conflict-resolution skill. + On a clean rebase (stdout "clean"), skips the skill and proceeds directly to + re_push_queue_fix. On conflict, aborts the rebase and routes to + resolve_queue_merge_conflicts for goal-aware resolution. + + resolve_queue_merge_conflicts: tool: run_skill with: skill_command: "/autoskillit:resolve-merge-conflicts ${{ context.work_dir }} ${{ context.plan_path }} ${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" - step_name: "queue_ejected_fix" + step_name: "resolve_queue_merge_conflicts" capture: conflict_escalation_required: "${{ result.escalation_required }}" on_result: @@ -779,8 +878,7 @@ steps: skip_when_false: "inputs.open_pr" note: > Resolves rebase conflicts on the feature branch after queue ejection. - Uses the clone working directory (context.work_dir) with the feature branch - (context.merge_target) checked out. context.plan_path provides resolution guidance. + Only reached when the cheap rebase in queue_ejected_fix encountered conflicts. escalation_required=true → release_issue_failure for human review. re_push_queue_fix: @@ -790,10 +888,29 @@ steps: remote_url: "${{ context.remote_url }}" branch: "${{ context.merge_target }}" force: "true" - on_success: reenter_merge_queue + on_success: ci_watch_post_queue_fix on_failure: release_issue_failure skip_when_false: "inputs.open_pr" + ci_watch_post_queue_fix: + tool: wait_for_ci + with: + branch: "${{ context.merge_target }}" + event: "${{ context.ci_event }}" + timeout_seconds: 300 + cwd: "${{ context.work_dir }}" + remote_url: "${{ context.remote_url }}" + capture: + ci_conclusion: "${{ result.conclusion }}" + ci_failed_jobs: "${{ result.failed_jobs }}" + on_success: reenter_merge_queue + on_failure: detect_ci_conflict + skip_when_false: "inputs.open_pr" + note: > + Validates CI on the rebased feature branch after queue ejection fix and re-push. + Mirrors ci_watch: routes to reenter_merge_queue on CI pass, to detect_ci_conflict + on CI failure. Prevents re-entering the merge queue with a broken manifest or code. + reenter_merge_queue: tool: run_cmd with: @@ -807,6 +924,20 @@ steps: Re-submits the PR after conflict resolution. Routes back to wait_for_queue. If re-entry fails, release_issue_failure preserves the clone for debugging. + reenter_merge_queue_cheap: + tool: run_cmd + with: + cmd: "gh pr merge '${{ context.pr_number }}' --squash --auto" + cwd: "${{ context.work_dir }}" + step_name: "reenter_merge_queue_cheap" + on_success: wait_for_queue + on_failure: release_issue_failure + skip_when_false: "inputs.open_pr" + note: > + Re-submits a healthy PR into the merge queue after auto_merge was cleared + externally (DROPPED_HEALTHY state). No conflict-resolution CI wait needed. + Routes back to wait_for_queue on success. + direct_merge: tool: run_cmd with: @@ -814,12 +945,12 @@ steps: cwd: "${{ context.work_dir }}" step_name: "direct_merge" on_success: wait_for_direct_merge - on_failure: confirm_cleanup + on_failure: register_clone_success skip_when_false: "inputs.open_pr" note: > Enables GitHub native auto-merge for direct merge (no merge queue). GitHub merges automatically once all required checks pass. On failure (PR already - merged, not mergeable), degrades gracefully to confirm_cleanup. + merged, not mergeable), degrades gracefully to register_clone_success. wait_for_direct_merge: tool: run_cmd @@ -848,11 +979,32 @@ steps: timeout / unexpected → release_issue_timeout. direct_merge_conflict_fix: + tool: run_cmd + with: + cmd: > + if git fetch origin ${{ inputs.base_branch }} && git rebase origin/${{ inputs.base_branch }}; + then echo 'clean'; + else git rebase --abort 2>/dev/null || true; echo 'conflicts'; + fi + cwd: "${{ context.work_dir }}" + step_name: "direct_merge_conflict_fix" + on_result: + - when: "${{ result.stdout | trim }} == clean" + route: re_push_direct_fix + - route: resolve_direct_merge_conflicts + on_failure: resolve_direct_merge_conflicts + skip_when_false: "inputs.open_pr" + note: > + Attempts a cheap rebase before invoking the full conflict-resolution skill. + On clean rebase, proceeds to re_push_direct_fix. On conflict, routes to + resolve_direct_merge_conflicts for goal-aware resolution. + + resolve_direct_merge_conflicts: tool: run_skill with: skill_command: "/autoskillit:resolve-merge-conflicts ${{ context.work_dir }} ${{ context.plan_path }} ${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" - step_name: "direct_merge_conflict_fix" + step_name: "resolve_direct_merge_conflicts" capture: conflict_escalation_required: "${{ result.escalation_required }}" on_result: @@ -865,7 +1017,8 @@ steps: on_exhausted: release_issue_failure skip_when_false: "inputs.open_pr" note: > - Resolves rebase conflicts on the feature branch after direct-merge rejection. + Resolves rebase conflicts after direct-merge rejection. + Only reached when the cheap rebase in direct_merge_conflict_fix encountered conflicts. escalation_required=true → release_issue_failure for human review. re_push_direct_fix: @@ -900,13 +1053,13 @@ steps: cwd: "${{ context.work_dir }}" step_name: "immediate_merge" on_success: wait_for_immediate_merge - on_failure: confirm_cleanup + on_failure: register_clone_success skip_when_false: "inputs.open_pr" note: > Merges the PR immediately using plain --squash when autoMergeAllowed=false. Unlike direct_merge, no --auto flag is used — GitHub executes the merge synchronously rather than queueing it for when checks pass. On failure - (conflict or not-mergeable error from GitHub), degrades to confirm_cleanup. + (conflict or not-mergeable error from GitHub), degrades to register_clone_success. wait_for_immediate_merge: tool: run_cmd @@ -937,11 +1090,32 @@ steps: timeout → release_issue_timeout. immediate_merge_conflict_fix: + tool: run_cmd + with: + cmd: > + if git fetch origin ${{ inputs.base_branch }} && git rebase origin/${{ inputs.base_branch }}; + then echo 'clean'; + else git rebase --abort 2>/dev/null || true; echo 'conflicts'; + fi + cwd: "${{ context.work_dir }}" + step_name: "immediate_merge_conflict_fix" + on_result: + - when: "${{ result.stdout | trim }} == clean" + route: re_push_immediate_fix + - route: resolve_immediate_merge_conflicts + on_failure: resolve_immediate_merge_conflicts + skip_when_false: "inputs.open_pr" + note: > + Attempts a cheap rebase before invoking the full conflict-resolution skill. + On clean rebase, proceeds to re_push_immediate_fix. On conflict, routes to + resolve_immediate_merge_conflicts for goal-aware resolution. + + resolve_immediate_merge_conflicts: tool: run_skill with: skill_command: "/autoskillit:resolve-merge-conflicts ${{ context.work_dir }} ${{ context.plan_path }} ${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" - step_name: "immediate_merge_conflict_fix" + step_name: "resolve_immediate_merge_conflicts" capture: conflict_escalation_required: "${{ result.escalation_required }}" on_result: @@ -954,8 +1128,8 @@ steps: on_exhausted: release_issue_failure skip_when_false: "inputs.open_pr" note: > - Resolves rebase conflicts on the feature branch after immediate-merge rejection. - Analogous to direct_merge_conflict_fix. + Resolves rebase conflicts after immediate-merge rejection. + Only reached when the cheap rebase in immediate_merge_conflict_fix encountered conflicts. escalation_required=true → release_issue_failure for human review. re_push_immediate_fix: @@ -990,13 +1164,13 @@ steps: skip_when_false: inputs.issue_url with: issue_url: ${{ inputs.issue_url }} - on_success: check_defer_cleanup - on_failure: check_defer_cleanup + on_success: register_clone_success + on_failure: register_clone_success note: > Called when wait_for_merge_queue times out or errors. Releases the in-progress claim without passing target_branch, so the staged label is not applied. The merge is unconfirmed; a human must verify queue state independently. - Routes to confirm_cleanup so the pipeline completes cleanly. + Routes to register_clone_success so the pipeline completes cleanly. detect_ci_conflict: tool: run_cmd @@ -1047,13 +1221,13 @@ steps: with: issue_url: ${{ inputs.issue_url }} target_branch: ${{ inputs.base_branch }} - on_success: check_defer_cleanup - on_failure: check_defer_cleanup + on_success: register_clone_success + on_failure: register_clone_success note: > Called on the success path after PR merge is confirmed. Passes target_branch so release_issue can determine whether to apply the staged label (non-default target) or just remove in-progress (default target). - optional=true ensures pipeline still reaches confirm_cleanup if this step errors. + optional=true ensures pipeline still reaches register_clone_success if this step errors. release_issue_failure: description: "Release the in-progress claim after pipeline failure" @@ -1062,91 +1236,29 @@ steps: skip_when_false: inputs.issue_url with: issue_url: ${{ inputs.issue_url }} - on_success: check_defer_on_failure - on_failure: check_defer_on_failure - - check_defer_cleanup: - description: "Route to deferred or immediate cleanup on success path" - tool: run_python - with: - callable: "autoskillit.smoke_utils.check_cleanup_mode" - defer_cleanup: "${{ inputs.defer_cleanup }}" - on_result: - - when: "result.deferred == 'true'" - route: register_success_deferred - - route: confirm_cleanup - on_failure: confirm_cleanup + on_success: register_clone_failure + on_failure: register_clone_failure - register_success_deferred: - description: "Register clone as cleanup candidate (deferred batch cleanup mode)" + register_clone_success: + description: "Register clone as cleanup candidate for batch deletion" tool: register_clone_status with: clone_path: "${{ context.work_dir }}" status: "success" - registry_path: "${{ inputs.registry_path }}" - step_name: register_success_deferred + step_name: register_clone_success on_success: done on_failure: done - check_defer_on_failure: - description: "Route to deferred or immediate cleanup on failure path" - tool: run_python - with: - callable: "autoskillit.smoke_utils.check_cleanup_mode" - defer_cleanup: "${{ inputs.defer_cleanup }}" - on_result: - - when: "result.deferred == 'true'" - route: register_error_deferred - - route: cleanup_failure - on_failure: cleanup_failure - - register_error_deferred: - description: "Register clone as preserved (error pipeline — deferred mode)" + register_clone_failure: + description: "Register clone as preserved (error pipeline)" tool: register_clone_status with: clone_path: "${{ context.work_dir }}" status: "error" - registry_path: "${{ inputs.registry_path }}" - step_name: register_error_deferred + step_name: register_clone_failure on_success: escalate_stop on_failure: escalate_stop - confirm_cleanup: - action: confirm - message: >- - Implementation-groups pipeline succeeded! The clone at ${{ context.work_dir }} is preserved. - Delete it now? Keeping it lets you resume any session from this pipeline run. - Type yes to delete or no to keep. - on_success: delete_clone - on_failure: done - note: >- - User confirmation gate — preserves clone by default. On yes: delete_clone removes it. - On no: done is reached immediately, clone stays on disk. - - delete_clone: - tool: remove_clone - with: - clone_path: "${{ context.work_dir }}" - keep: "false" - step_name: delete_clone - on_success: done - on_failure: done - note: >- - Reached only after user explicitly confirms cleanup. Sync-check hook gates deletion — - removal approved only when branch is pushed. - - cleanup_failure: - tool: remove_clone - with: - clone_path: "${{ context.work_dir }}" - keep: "true" - on_success: escalate_stop - on_failure: escalate_stop - note: > - Clone preservation step — keep=true means the clone is never - auto-removed on failure. Remove manually: rm -rf {clone_path}. - Always routes to escalate_stop. - done: action: stop message: "Implementation pipeline complete. All groups/tasks have been planned, implemented, tested, and merged." @@ -1155,24 +1267,3 @@ steps: action: stop message: "Pipeline failed — human intervention needed. Check the worktree and plan for details." - batch_confirm_cleanup: - action: confirm - message: >- - All parallel pipelines complete. Delete all registered successful clones? - Error pipeline clones will be preserved for investigation. - Type yes to delete or no to keep all. - note: >- - ORCHESTRATOR: Run this step ONCE after ALL parallel pipeline instances have - reached 'done' or 'escalate_stop'. Do NOT run per-pipeline instance. - Only applicable when run_mode=parallel and defer_cleanup=true. - on_success: batch_delete_clones - on_failure: done - - batch_delete_clones: - description: "Delete all registered successful clones in one batch operation" - tool: batch_cleanup_clones - with: - registry_path: "${{ inputs.registry_path }}" - step_name: batch_delete_clones - on_success: done - on_failure: done diff --git a/src/autoskillit/recipes/implementation.yaml b/src/autoskillit/recipes/implementation.yaml index 34772b9204..54fcc2df78 100644 --- a/src/autoskillit/recipes/implementation.yaml +++ b/src/autoskillit/recipes/implementation.yaml @@ -22,7 +22,7 @@ ingredients: default: "false" audit: description: Post-merge quality gate - default: "true" + default: "false" open_pr: description: PR instead of direct merge default: "true" @@ -49,22 +49,6 @@ ingredients: step scheduling — fast steps for all pipelines before any slow step). default: "sequential" hidden: true - defer_cleanup: - description: >- - When 'true', skip per-pipeline interactive cleanup and register this clone - in the shared registry for batch deletion after all parallel pipelines - complete. Set to 'true' on every parallel instance; leave 'false' for - sequential single-pipeline runs. - default: "false" - hidden: true - registry_path: - description: >- - Absolute path to the shared clone cleanup registry file. Required when - defer_cleanup=true. Must be identical across all parallel pipeline runs in - the same batch (use a fixed path like - /path/to/project/.autoskillit/temp/clone-cleanup-registry.json). - default: "" - hidden: true kitchen_rules: - "NEVER use native Claude Code tools (Read, Grep, Glob, Edit, Write, @@ -76,26 +60,23 @@ kitchen_rules: derived from inputs.run_name and context.issue_number (e.g. impl/124) or a date suffix (e.g. impl/20260304) when no issue is available. All worktree merges target the feature branch (context.merge_target), not base_branch - directly. The push step publishes the feature branch, then open_pr_step + directly. The push step publishes the feature branch, then prepare_pr → run_arch_lenses → compose_pr opens a PR to base_branch. When open_pr=false, merges target base_branch - directly and open_pr_step is skipped." + directly and prepare_pr is skipped." - "SOURCE ISOLATION: After clone_repo returns, the source_dir is strictly off-limits. Never run any command in source_dir — no git checkout, git fetch, git reset, git pull, run_cmd, run_skill, or any other operation. All work — skill invocations, git operations, file reads — happens exclusively in the clone (work_dir). source_dir is used ONLY to read the remote URL inside push_to_remote." - - "MERGE ROUTING: check_merge_queue detects whether the target branch has an active - merge queue (GraphQL). check_merge_group_trigger (new) validates that at least - one CI workflow includes the merge_group trigger — skipped when queue_available=false, - falls through gracefully on API failure. check_auto_merge detects whether - autoMergeAllowed is enabled. route_queue_mode then routes to: enable_auto_merge - → wait_for_queue ONLY when queue_available=true AND merge_group_trigger=true; - direct_merge → wait_for_direct_merge (no queue or trigger missing, - autoMergeAllowed=true); or immediate_merge → wait_for_immediate_merge (no queue, - autoMergeAllowed=false). Never call gh pr merge directly via run_cmd — all merges - go through these named recipe steps so CI enforcement and conflict routing are - preserved." + - "MERGE ROUTING: check_repo_merge_state performs a single GraphQL round-trip to detect + queue_available, merge_group_trigger, and auto_merge_available for the target branch. + route_queue_mode then routes to: enable_auto_merge → wait_for_queue ONLY when + queue_available=true AND merge_group_trigger=true; direct_merge → wait_for_direct_merge + (no queue or trigger missing, autoMergeAllowed=true); or immediate_merge → + wait_for_immediate_merge (no queue, autoMergeAllowed=false). Never call gh pr merge + directly via run_cmd — all merges go through these named recipe steps so CI + enforcement and conflict routing are preserved." steps: sprint_entry: @@ -175,7 +156,7 @@ steps: Runs when inputs.issue_url is non-empty. Skipped otherwise. Fetches only the issue title and slug (no body, no comments). issue_number is used for feature branch naming and threaded to - open_pr_step for "Closes #N" in the PR body. + prepare_pr for "Closes #N" in the PR body. issue_slug provides a descriptive branch prefix (e.g. fix-merge-conflict-triage). claim_issue: @@ -268,7 +249,7 @@ steps: on_success: review on_failure: release_issue_failure note: > - Produces plan in .autoskillit/temp/make-plan/. Glob plan_dir for *_part_*.md or single plan file. + Produces plan in {{AUTOSKILLIT_TEMP}}/make-plan/. Glob plan_dir for *_part_*.md or single plan file. plan_parts context key contains the full ordered list of part files (sorted alphabetically). For a single-part plan, plan_parts has one entry equal to plan_path. REMEDIATION MODE: context.remediation_path is available when the orchestrator @@ -310,6 +291,7 @@ steps: implement: tool: run_skill + stale_threshold: 2400 with: skill_command: "/autoskillit:implement-worktree-no-merge ${{ context.plan_path }}" cwd: "${{ context.work_dir }}" @@ -324,23 +306,41 @@ steps: retry_worktree: tool: run_skill + stale_threshold: 2400 with: skill_command: "/autoskillit:retry-worktree ${{ context.plan_path }} ${{ context.worktree_path }}" cwd: "${{ context.worktree_path }}" step_name: "retry_worktree" capture: worktree_path: "${{ result.worktree_path }}" + phases_implemented: "${{ result.phases_implemented }}" + on_result: + - when: "${{ result.phases_implemented }} > 0" + route: test + - route: test on_exhausted: release_issue_failure - on_success: test on_failure: release_issue_failure test: tool: test_check with: worktree_path: "${{ context.worktree_path }}" - on_success: merge + on_success: commit_guard on_failure: fix + commit_guard: + tool: run_cmd + with: + cmd: "cd ${{ context.worktree_path }} && if [ -n \"$(git status --porcelain)\" ]; then git add -A && git commit -m 'chore: commit pending session changes'; fi" + cwd: "${{ context.worktree_path }}" + step_name: commit_guard + on_success: merge + on_failure: merge + note: > + Belt-and-suspenders guard: auto-commits any uncommitted changes before merge. + Catches dirty state from context-exhausted skills, cascading pre-commit auto-fixes, + or any other source. on_failure routes to merge (dirty-tree gate will catch real issues). + merge: tool: merge_worktree with: @@ -367,7 +367,7 @@ steps: By default (open_pr=true), merge_target is the feature branch named from run_name. When open_pr=false, merge_target equals base_branch — merges go directly to base. dirty_tree and test_gate failures route to fix (resolve-failures) for recovery; - all other failures route to cleanup_failure. + all other failures route to release_issue_failure. push: tool: push_to_remote @@ -375,15 +375,15 @@ steps: clone_path: "${{ context.work_dir }}" remote_url: "${{ context.remote_url }}" branch: "${{ context.merge_target }}" - on_success: open_pr_step + on_success: prepare_pr on_failure: release_issue_failure note: > Runs once at the end, after audit_impl passes. Pushes merge_target branch from the clone to the upstream remote. By default (open_pr=true), this pushes the feature branch; when open_pr=false, pushes base_branch. Uses the pre-resolved remote_url captured at clone time, preserving clone isolation. - On success, routes to open_pr_step (which opens the PR by default; skipped when open_pr=false). - On failure, cleanup_failure still removes the clone. + On success, routes to prepare_pr (which opens the PR by default; skipped when open_pr=false). + On failure, release_issue_failure registers the clone and escalates. fix: tool: run_skill @@ -391,7 +391,18 @@ steps: skill_command: "/autoskillit:resolve-failures ${{ context.worktree_path }} ${{ context.plan_path }} ${{ inputs.base_branch }}" cwd: "${{ context.worktree_path }}" step_name: "fix" - on_success: test + capture: + verdict: "${{ result.verdict }}" + fixes_applied: "${{ result.fixes_applied }}" + on_result: + - when: "${{ result.verdict }} == 'real_fix'" + route: test + - when: "${{ result.verdict }} == 'already_green'" + route: test + - when: "${{ result.verdict }} == 'flake_suspected'" + route: test + - when: "${{ result.verdict }} == 'ci_only_failure'" + route: release_issue_failure on_failure: release_issue_failure on_context_limit: test note: "Fixes test failures without merging. Routes back to test for re-validation before merge_worktree. on_context_limit routes needs_retry=True to test (worktree may already be green) instead of re-running fix blindly." @@ -441,26 +452,71 @@ steps: remediation_path: "${{ context.remediation_path }}" on_success: plan - open_pr_step: + prepare_pr: + tool: run_skill + with: + skill_command: "/autoskillit:prepare-pr ${{ context.all_plan_paths }} ${{ inputs.run_name }} ${{ inputs.base_branch }}" + cwd: "${{ context.work_dir }}" + step_name: "prepare_pr" + issue_number: "${{ context.issue_number }}" + capture: + prep_path: "${{ result.prep_path }}" + selected_lenses: "${{ result.selected_lenses }}" + lens_context_paths: "${{ result.lens_context_paths }}" + on_success: run_arch_lenses + on_failure: release_issue_failure + on_context_limit: release_issue_failure + optional: true + skip_when_false: "inputs.open_pr" + note: > + Reads plan(s), runs git diff, classifies changed files, selects 1–3 arch-lens slugs, + writes one PR context file per lens, and writes a PR prep file. Does NOT invoke + arch-lens skills. If context.issue_number is a non-empty string, append it as the + 4th positional argument so prepare-pr fetches requirements from the closing issue. + + run_arch_lenses: tool: run_skill with: - skill_command: "/autoskillit:open-pr ${{ context.all_plan_paths }} ${{ inputs.run_name }} ${{ inputs.base_branch }}" + skill_command: "/autoskillit:arch-lens-{slug} {context_path}" cwd: "${{ context.work_dir }}" - step_name: "open_pr" + step_name: "run_arch_lenses" + capture_list: + all_diagram_paths: "${{ result.diagram_path }}" + on_success: compose_pr + on_failure: compose_pr + on_context_limit: compose_pr + optional: true + skip_when_false: "inputs.open_pr" + note: > + LENS ITERATION: context.selected_lenses contains comma-separated arch-lens slugs + (e.g. "module-dependency,process-flow"). context.lens_context_paths contains the + corresponding comma-separated context file paths (same order as slugs). For each + lens slug, run: + /autoskillit:arch-lens-{slug} {matching_context_path} + Run all selected lenses in parallel (all run_skill calls in a single message). + Accumulate each diagram_path value into context.all_diagram_paths via capture_list. + If a lens fails, continue with remaining lenses — compose_pr handles empty lists + gracefully by omitting the Architecture Impact section. + + compose_pr: + tool: run_skill + with: + skill_command: "/autoskillit:compose-pr ${{ context.prep_path }} \"${{ context.all_diagram_paths }}\" ${{ context.work_dir }} ${{ inputs.base_branch }}" + cwd: "${{ context.work_dir }}" + step_name: "compose_pr" issue_number: "${{ context.issue_number }}" + capture: + pr_url: "${{ result.pr_url }}" on_success: extract_pr_number on_failure: release_issue_failure on_context_limit: release_issue_failure optional: true skip_when_false: "inputs.open_pr" note: > - Runs by default (open_pr=true). Skipped when open_pr=false. - The feature branch is already published by the push step that precedes this step. - Invokes the open-pr skill which selects arch-lens diagrams, composes a PR body, - and runs gh pr create. The skill gracefully degrades if gh is unavailable. - If context.issue_number is a non-empty string (set by fetch_issue), append it - as a 4th positional argument to the skill_command. The open-pr skill will insert - "Closes #{issue_number}" into the PR body to auto-close the issue on merge. + Reads the PR prep file, validates arch-lens diagrams (must contain ★ or ●), + composes the PR body, and runs gh pr create. Degrades gracefully if gh is + unavailable (emits pr_url=). If context.issue_number is set, append it as the + 5th positional argument for Closes #N injection in the PR body. extract_pr_number: tool: run_cmd @@ -470,18 +526,36 @@ steps: step_name: "extract_pr_number" capture: pr_number: "${{ result.stdout | trim }}" - on_success: review_pr + on_success: annotate_pr_diff on_failure: release_issue_failure optional: true skip_when_false: "inputs.open_pr" note: > - Extracts the integer PR number from the feature branch opened by open_pr_step. + Extracts the integer PR number from the feature branch opened by compose_pr. pr_number is required by the queue finale steps (enable_auto_merge, wait_for_queue). + annotate_pr_diff: + tool: run_python + with: + callable: "autoskillit.smoke_utils.annotate_pr_diff" + pr_number: "${{ context.pr_number }}" + cwd: "${{ context.work_dir }}" + output_dir: "${{ context.work_dir }}/{{AUTOSKILLIT_TEMP}}/review-pr" + capture: + annotated_diff_path: "${{ result.annotated_diff_path }}" + hunk_ranges_path: "${{ result.hunk_ranges_path }}" + on_success: review_pr + on_failure: review_pr + optional: true + skip_when_false: "inputs.open_pr" + note: > + Pre-computes annotated diff with [LNNN] markers and hunk ranges JSON for + review-pr. On failure, falls through to review_pr which uses empty fallback. + review_pr: tool: run_skill with: - skill_command: "/autoskillit:review-pr ${{ context.merge_target }} ${{ inputs.base_branch }}" + skill_command: "/autoskillit:review-pr ${{ context.merge_target }} ${{ inputs.base_branch }} annotated_diff_path=${{ context.annotated_diff_path }} hunk_ranges_path=${{ context.hunk_ranges_path }}" cwd: "${{ context.work_dir }}" step_name: "review_pr" capture: @@ -498,7 +572,7 @@ steps: optional: true skip_when_false: "inputs.open_pr" note: > - Runs after open_pr_step creates the PR. Invokes the review-pr skill as a + Runs after compose_pr creates the PR. Invokes the review-pr skill as a headless session to leave inline review comments on the PR. The skill finds the open PR by feature branch name (context.merge_target). Captures verdict and routes via on_result: changes_requested → resolve_review, @@ -511,16 +585,27 @@ steps: skill_command: "/autoskillit:resolve-review ${{ context.merge_target }} ${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" step_name: "resolve_review" + capture: + verdict: "${{ result.verdict }}" retries: 2 on_exhausted: release_issue_failure - on_success: re_push_review + on_result: + - when: "${{ result.verdict }} == 'real_fix'" + route: re_push_review + - when: "${{ result.verdict }} == 'already_green'" + route: re_push_review + - when: "${{ result.verdict }} == 'flake_suspected'" + route: release_issue_failure + - when: "${{ result.verdict }} == 'ci_only_failure'" + route: release_issue_failure on_failure: release_issue_failure note: > Runs when review_pr reports issues (verdict=changes_requested). The clone (context.work_dir) has the feature branch (context.merge_target) checked out. resolve-review fetches inline and summary review comments via the GitHub API, applies fixes for each actionable finding (critical + warning severity), and - commits each fix. Orchestrator re-pushes via re_push_review after success. + commits each fix. Routes via on_result: verdict dispatch — real_fix/already_green + both route to re_push_review; flake_suspected/ci_only_failure escalate. Retries up to 2 times (3 total attempts) before exhausting to release_issue_failure. re_push_review: @@ -540,14 +625,13 @@ steps: tool: wait_for_ci with: branch: "${{ context.merge_target }}" - workflow: "tests.yml" timeout_seconds: 300 cwd: "${{ context.work_dir }}" remote_url: "${{ context.remote_url }}" capture: ci_conclusion: "${{ result.conclusion }}" ci_failed_jobs: "${{ result.failed_jobs }}" - on_success: check_merge_queue + on_success: check_repo_merge_state on_failure: detect_ci_conflict optional: true skip_when_false: "inputs.open_pr" @@ -556,102 +640,44 @@ steps: using the wait_for_ci MCP tool (timeout: 300 s). Captures structured output (conclusion + failed job names) for downstream resolve_ci. Skipped when open_pr=false — no remote feature branch is opened in that mode. - On success, routes to check_merge_queue to determine if the PR should enter + On success, routes to check_repo_merge_state to determine if the PR should enter the merge queue. On failure, routes to detect_ci_conflict which checks whether the failure is caused by a stale base before falling through to diagnose_ci. - check_merge_queue: - tool: run_cmd - with: - cmd: > - REPO=$( { git remote get-url upstream 2>/dev/null || git remote get-url origin; } | sed 's|.*github\.com[:/]||; s|\.git$||') && - OWNER=${REPO%%/*} && REPO_NAME=${REPO##*/} && - BRANCH="${{ inputs.base_branch }}" && - gh api graphql -f query="query { - repository(owner:\"$OWNER\", name:\"$REPO_NAME\") { - mergeQueue(branch:\"$BRANCH\") { id } - } - }" | jq -r 'if .data.repository.mergeQueue != null then "true" else "false" end' - cwd: "${{ context.work_dir }}" - step_name: "check_merge_queue" - capture: - queue_available: "${{ result.stdout | trim }}" - on_success: check_merge_group_trigger - on_failure: release_issue_success - skip_when_false: "inputs.open_pr" - note: > - Detects whether the target branch has an active merge queue via GraphQL. - Captures "true" or "false" into context.queue_available. - On failure (gh error, parse error), degrades gracefully to release_issue_success - (non-queue path). On success, routes to check_merge_group_trigger to validate - that a CI workflow includes the merge_group trigger before proceeding. - Skipped when open_pr=false — no PR was opened. - - check_merge_group_trigger: - tool: run_cmd - with: - cmd: > - REPO=$( { git remote get-url upstream 2>/dev/null || git remote get-url origin; } | sed 's|.*github\.com[:/]||; s|\.git$||') && - OWNER=${REPO%%/*} && REPO_NAME=${REPO##*/} && - [ -n "$OWNER" ] && [ -n "$REPO_NAME" ] && - FOUND="" && - while IFS= read -r wf; do - content=$(gh api "repos/$OWNER/$REPO_NAME/contents/.github/workflows/$wf" -q '.content') - [ -n "$content" ] && echo "$content" | base64 -d 2>/dev/null | grep -q 'merge_group' && FOUND=true && break - done < <(gh api "repos/$OWNER/$REPO_NAME/contents/.github/workflows" 2>/dev/null | jq -r '.[] | select(.type == "file") | .name'); - if [ "$FOUND" = "true" ]; then echo "true"; else - echo "WARNING: Merge queue detected on ${{ inputs.base_branch }} but no CI workflow includes merge_group trigger -- degrading to non-queue merge path" >&2 - echo "false" - fi - cwd: "${{ context.work_dir }}" - step_name: "check_merge_group_trigger" - capture: - merge_group_trigger: "${{ result.stdout | trim }}" - on_success: check_auto_merge - on_failure: check_auto_merge - skip_when_false: "inputs.open_pr" - note: > - Validates that at least one CI workflow in .github/workflows/ includes the - merge_group event trigger; emits WARNING to stderr when absent. - Lists workflow files via GitHub API, decodes base64 content, and greps for - 'merge_group'; captures merge_group_trigger as "true" (found) or "false" - (absent). - - check_auto_merge: - tool: run_cmd + check_repo_merge_state: + tool: check_repo_merge_state + block: pre_queue_gate with: - cmd: > - REPO=$( { git remote get-url upstream 2>/dev/null || git remote get-url origin; } | sed 's|.*github\.com[:/]||; s|\.git$||') && - OWNER=${REPO%%/*} && REPO_NAME=${REPO##*/} && - gh api graphql -f query="query { - repository(owner:\"$OWNER\", name:\"$REPO_NAME\") { - autoMergeAllowed - } - }" | jq -r '.data.repository.autoMergeAllowed // false' + branch: "${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" - step_name: "check_auto_merge" + remote_url: "${{ context.remote_url }}" + step_name: "check_repo_merge_state" capture: - auto_merge_available: "${{ result.stdout | trim }}" + queue_available: "${{ result.queue_available }}" + merge_group_trigger: "${{ result.merge_group_trigger }}" + auto_merge_available: "${{ result.auto_merge_available }}" + ci_event: "${{ result.ci_event }}" on_success: route_queue_mode - on_failure: route_queue_mode + on_failure: immediate_merge skip_when_false: "inputs.open_pr" note: > - Detects whether the target repository has autoMergeAllowed enabled via GraphQL. - Captures "true" or "false" into context.auto_merge_available. - On failure (gh error, network error), falls through to route_queue_mode with - auto_merge_available unset — route_queue_mode defaults to immediate_merge (safe - non-auto path). GraphQL-level errors (rate-limit, missing auth scope) also return - exit 0 with an errors array and no .data field; the jq // false fallback outputs - false safely, so auto_merge_available defaults to false on any error path. + Single GraphQL round-trip that captures queue_available, merge_group_trigger, + auto_merge_available, and ci_event for the target branch. Consolidates the former three + sequential run_cmd steps (check_merge_queue, check_merge_group_trigger, + check_auto_merge) into one MCP tool call. On failure (network error, auth failure), + falls through to immediate_merge (non-queue direct merge path). Skipped when open_pr=false — no PR was opened. route_queue_mode: + block: pre_queue_gate action: route on_result: - when: "${{ inputs.auto_merge }} != 'true'" - route: confirm_cleanup - - when: "${{ context.queue_available }} == true and ${{ context.merge_group_trigger }} == true" + route: register_clone_success + - when: "${{ context.queue_available }} == true and ${{ context.merge_group_trigger }} == true and ${{ context.auto_merge_available }} == true" route: enable_auto_merge + - when: "${{ context.queue_available }} == true and ${{ context.merge_group_trigger }} == true and ${{ context.auto_merge_available }} == false" + route: queue_enqueue_no_auto - when: "${{ context.auto_merge_available }} == true" route: direct_merge - route: immediate_merge @@ -664,11 +690,29 @@ steps: cwd: "${{ context.work_dir }}" step_name: "enable_auto_merge" on_success: wait_for_queue - on_failure: confirm_cleanup + on_failure: register_clone_success skip_when_false: "inputs.open_pr" note: > Submits the PR to the merge queue. On failure (PR not mergeable, already merged), - degrades to confirm_cleanup. + degrades to register_clone_success. + + queue_enqueue_no_auto: + tool: run_cmd + with: + cmd: "gh pr merge '${{ context.pr_number }}' --squash" + cwd: "${{ context.work_dir }}" + step_name: "queue_enqueue_no_auto" + on_success: wait_for_queue + on_failure: register_clone_success + skip_when_false: "inputs.open_pr" + note: > + Submits the PR to the merge queue when the target branch has a configured + merge queue but the repository disallows auto-merge (autoMergeAllowed=false). + Uses plain `gh pr merge --squash` (no --auto, which would be rejected by + GitHub's API auto-merge gate). GitHub intercepts the call and enqueues + the PR because the branch has a queue. Routes to wait_for_queue (the + shared queue waiter) — never to wait_for_immediate_merge, whose 5-minute + poll is too short for queue serialization. wait_for_queue: tool: wait_for_merge_queue @@ -683,6 +727,10 @@ steps: on_result: - when: "${{ result.pr_state }} == merged" route: release_issue_success + - when: "${{ result.pr_state }} == ejected_ci_failure" + route: diagnose_ci + - when: "${{ result.pr_state }} == dropped_healthy" + route: reenter_merge_queue_cheap - when: "${{ result.pr_state }} == ejected" route: queue_ejected_fix - when: "${{ result.pr_state }} == stalled" @@ -694,7 +742,8 @@ steps: skip_when_false: "inputs.open_pr" note: > Waits up to 15 minutes for the PR to merge through the queue. - merged → release_issue_success to transition issue state then confirm_cleanup. + merged → release_issue_success to transition issue state then register_clone_success. + ejected_ci_failure → diagnose_ci (CI failure; conflict resolution cannot fix this). ejected → conflict fix cycle then re-enter. stalled → lightweight re-enrollment (disable then re-enable auto-merge). timeout → release_issue_timeout (release claim without staged label; merge unconfirmed). @@ -710,11 +759,33 @@ steps: skip_when_false: "inputs.open_pr" queue_ejected_fix: + tool: run_cmd + with: + cmd: > + if git fetch origin ${{ inputs.base_branch }} && git rebase origin/${{ inputs.base_branch }}; + then echo 'clean'; + else git rebase --abort 2>/dev/null || true; echo 'conflicts'; + fi + cwd: "${{ context.work_dir }}" + step_name: "queue_ejected_fix" + on_result: + - when: "${{ result.stdout | trim }} == clean" + route: re_push_queue_fix + - route: resolve_queue_merge_conflicts + on_failure: resolve_queue_merge_conflicts + skip_when_false: "inputs.open_pr" + note: > + Attempts a cheap rebase before invoking the full conflict-resolution skill. + On a clean rebase (stdout "clean"), skips the skill and proceeds directly to + re_push_queue_fix. On conflict, aborts the rebase and routes to + resolve_queue_merge_conflicts for goal-aware resolution. + + resolve_queue_merge_conflicts: tool: run_skill with: skill_command: "/autoskillit:resolve-merge-conflicts ${{ context.work_dir }} ${{ context.plan_path }} ${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" - step_name: "queue_ejected_fix" + step_name: "resolve_queue_merge_conflicts" capture: conflict_escalation_required: "${{ result.escalation_required }}" on_result: @@ -728,8 +799,7 @@ steps: skip_when_false: "inputs.open_pr" note: > Resolves rebase conflicts on the feature branch after queue ejection. - Uses the clone working directory (context.work_dir) with the feature branch - (context.merge_target) checked out. context.plan_path provides resolution guidance. + Only reached when the cheap rebase in queue_ejected_fix encountered conflicts. escalation_required=true → release_issue_failure for human review. re_push_queue_fix: @@ -739,10 +809,29 @@ steps: remote_url: "${{ context.remote_url }}" branch: "${{ context.merge_target }}" force: "true" - on_success: reenter_merge_queue + on_success: ci_watch_post_queue_fix on_failure: release_issue_failure skip_when_false: "inputs.open_pr" + ci_watch_post_queue_fix: + tool: wait_for_ci + with: + branch: "${{ context.merge_target }}" + event: "${{ context.ci_event }}" + timeout_seconds: 300 + cwd: "${{ context.work_dir }}" + remote_url: "${{ context.remote_url }}" + capture: + ci_conclusion: "${{ result.conclusion }}" + ci_failed_jobs: "${{ result.failed_jobs }}" + on_success: reenter_merge_queue + on_failure: detect_ci_conflict + skip_when_false: "inputs.open_pr" + note: > + Validates CI on the rebased feature branch after queue ejection fix and re-push. + Mirrors ci_watch: routes to reenter_merge_queue on CI pass, to detect_ci_conflict + on CI failure. Prevents re-entering the merge queue with a broken manifest or code. + reenter_merge_queue: tool: run_cmd with: @@ -756,6 +845,20 @@ steps: Re-submits the PR after conflict resolution. Routes back to wait_for_queue. If re-entry fails, release_issue_failure preserves the clone for debugging. + reenter_merge_queue_cheap: + tool: run_cmd + with: + cmd: "gh pr merge '${{ context.pr_number }}' --squash --auto" + cwd: "${{ context.work_dir }}" + step_name: "reenter_merge_queue_cheap" + on_success: wait_for_queue + on_failure: release_issue_failure + skip_when_false: "inputs.open_pr" + note: > + Re-submits a healthy PR into the merge queue after auto_merge was cleared + externally (DROPPED_HEALTHY state). No conflict-resolution CI wait needed. + Routes back to wait_for_queue on success. + direct_merge: tool: run_cmd with: @@ -763,12 +866,12 @@ steps: cwd: "${{ context.work_dir }}" step_name: "direct_merge" on_success: wait_for_direct_merge - on_failure: confirm_cleanup + on_failure: register_clone_success skip_when_false: "inputs.open_pr" note: > Enables GitHub native auto-merge for direct merge (no merge queue). GitHub merges automatically once all required checks pass. On failure (PR already - merged, not mergeable), degrades gracefully to confirm_cleanup. + merged, not mergeable), degrades gracefully to register_clone_success. wait_for_direct_merge: tool: run_cmd @@ -797,11 +900,32 @@ steps: timeout / unexpected → release_issue_timeout. direct_merge_conflict_fix: + tool: run_cmd + with: + cmd: > + if git fetch origin ${{ inputs.base_branch }} && git rebase origin/${{ inputs.base_branch }}; + then echo 'clean'; + else git rebase --abort 2>/dev/null || true; echo 'conflicts'; + fi + cwd: "${{ context.work_dir }}" + step_name: "direct_merge_conflict_fix" + on_result: + - when: "${{ result.stdout | trim }} == clean" + route: re_push_direct_fix + - route: resolve_direct_merge_conflicts + on_failure: resolve_direct_merge_conflicts + skip_when_false: "inputs.open_pr" + note: > + Attempts a cheap rebase before invoking the full conflict-resolution skill. + On clean rebase, proceeds to re_push_direct_fix. On conflict, routes to + resolve_direct_merge_conflicts for goal-aware resolution. + + resolve_direct_merge_conflicts: tool: run_skill with: skill_command: "/autoskillit:resolve-merge-conflicts ${{ context.work_dir }} ${{ context.plan_path }} ${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" - step_name: "direct_merge_conflict_fix" + step_name: "resolve_direct_merge_conflicts" capture: conflict_escalation_required: "${{ result.escalation_required }}" on_result: @@ -814,7 +938,8 @@ steps: on_exhausted: release_issue_failure skip_when_false: "inputs.open_pr" note: > - Resolves rebase conflicts on the feature branch after direct-merge rejection. + Resolves rebase conflicts after direct-merge rejection. + Only reached when the cheap rebase in direct_merge_conflict_fix encountered conflicts. escalation_required=true → release_issue_failure for human review. re_push_direct_fix: @@ -849,13 +974,13 @@ steps: cwd: "${{ context.work_dir }}" step_name: "immediate_merge" on_success: wait_for_immediate_merge - on_failure: confirm_cleanup + on_failure: register_clone_success skip_when_false: "inputs.open_pr" note: > Merges the PR immediately using plain --squash when autoMergeAllowed=false. Unlike direct_merge, no --auto flag is used — GitHub executes the merge synchronously rather than queueing it for when checks pass. On failure - (conflict or not-mergeable error from GitHub), degrades to confirm_cleanup. + (conflict or not-mergeable error from GitHub), degrades to register_clone_success. wait_for_immediate_merge: tool: run_cmd @@ -886,11 +1011,32 @@ steps: timeout → release_issue_timeout. immediate_merge_conflict_fix: + tool: run_cmd + with: + cmd: > + if git fetch origin ${{ inputs.base_branch }} && git rebase origin/${{ inputs.base_branch }}; + then echo 'clean'; + else git rebase --abort 2>/dev/null || true; echo 'conflicts'; + fi + cwd: "${{ context.work_dir }}" + step_name: "immediate_merge_conflict_fix" + on_result: + - when: "${{ result.stdout | trim }} == clean" + route: re_push_immediate_fix + - route: resolve_immediate_merge_conflicts + on_failure: resolve_immediate_merge_conflicts + skip_when_false: "inputs.open_pr" + note: > + Attempts a cheap rebase before invoking the full conflict-resolution skill. + On clean rebase, proceeds to re_push_immediate_fix. On conflict, routes to + resolve_immediate_merge_conflicts for goal-aware resolution. + + resolve_immediate_merge_conflicts: tool: run_skill with: skill_command: "/autoskillit:resolve-merge-conflicts ${{ context.work_dir }} ${{ context.plan_path }} ${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" - step_name: "immediate_merge_conflict_fix" + step_name: "resolve_immediate_merge_conflicts" capture: conflict_escalation_required: "${{ result.escalation_required }}" on_result: @@ -903,8 +1049,8 @@ steps: on_exhausted: release_issue_failure skip_when_false: "inputs.open_pr" note: > - Resolves rebase conflicts on the feature branch after immediate-merge rejection. - Analogous to direct_merge_conflict_fix. + Resolves rebase conflicts after immediate-merge rejection. + Only reached when the cheap rebase in immediate_merge_conflict_fix encountered conflicts. escalation_required=true → release_issue_failure for human review. re_push_immediate_fix: @@ -935,7 +1081,7 @@ steps: diagnose_ci: tool: run_skill with: - skill_command: "/autoskillit:diagnose-ci ${{ context.merge_target }} - - tests.yml" + skill_command: "/autoskillit:diagnose-ci ${{ context.merge_target }} - - - ${{ context.ci_event }}" cwd: "${{ context.work_dir }}" step_name: "diagnose_ci" ci_failed_jobs: "${{ context.ci_failed_jobs }}" @@ -948,7 +1094,7 @@ steps: skip_when_false: "inputs.open_pr" note: > Runs when ci_watch reports a CI failure. Fetches CI logs via gh API and writes - a structured diagnosis to .autoskillit/temp/diagnose-ci/. Routes to resolve_ci on success + a structured diagnosis to {{AUTOSKILLIT_TEMP}}/diagnose-ci/. Routes to resolve_ci on success OR failure (best-effort: resolve-failures proceeds even without a diagnosis). diagnosis_path is passed to resolve_ci for targeted remediation context. @@ -958,17 +1104,42 @@ steps: skill_command: "/autoskillit:resolve-failures ${{ context.work_dir }} ${{ context.plan_path }} ${{ inputs.base_branch }} ${{ context.ci_conclusion }} ${{ context.ci_failed_jobs }} ${{ context.diagnosis_path }}" cwd: "${{ context.work_dir }}" step_name: "resolve_ci" + capture: + verdict: "${{ result.verdict }}" retries: 2 on_exhausted: release_issue_failure - on_success: re_push + on_context_limit: re_push + on_result: + - when: "${{ result.verdict }} == 'real_fix'" + route: re_push + - when: "${{ result.verdict }} == 'already_green'" + route: pre_resolve_rebase + - when: "${{ result.verdict }} == 'flake_suspected'" + route: release_issue_failure + - when: "${{ result.verdict }} == 'ci_only_failure'" + route: release_issue_failure + - route: release_issue_failure on_failure: release_issue_failure note: > Runs when ci_watch reports a CI failure. Receives ci_failed_jobs from wait_for_ci - structured output to avoid redundant CI failure re-investigation. The clone - (context.work_dir) has the feature branch (context.merge_target) checked out. - The skill commits fixes and exits without merging; the orchestrator re-pushes - via re_push. Retries up to 2 times (3 total attempts) before exhausting - to cleanup_failure. + structured output to avoid redundant CI failure re-investigation. Routes via + on_result: verdict dispatch — real_fix pushes, already_green rebases and re-diagnoses + (sibling fix may have landed), flake_suspected/ci_only_failure escalate to human. + Retries up to 2 times (3 total attempts) before exhausting to release_issue_failure. + + pre_resolve_rebase: + tool: run_cmd + with: + cmd: "git -C ${{ context.work_dir }} fetch origin && git -C ${{ context.work_dir }} rebase origin/${{ inputs.base_branch }}" + step_name: "pre_resolve_rebase" + retries: 1 + on_success: diagnose_ci + on_failure: release_issue_failure + note: > + Rebases the feature branch against integration head when resolve_ci emits + already_green — the worktree was already clean because a sibling pipeline's + fix already landed on integration. Pulling it in before re-running diagnose_ci + gives the pipeline a real chance at emitting real_fix and reaching re_push. re_push: tool: push_to_remote @@ -982,7 +1153,7 @@ steps: note: > Pushes the CI-fixed feature branch back to the remote after resolve_ci succeeds. Routes back to ci_watch to verify the fix resolves CI. On push failure, escalates - via cleanup_failure. + via release_issue_failure. detect_ci_conflict: tool: run_cmd @@ -1033,13 +1204,13 @@ steps: with: issue_url: ${{ inputs.issue_url }} target_branch: ${{ inputs.base_branch }} - on_success: check_defer_cleanup - on_failure: check_defer_cleanup + on_success: register_clone_success + on_failure: register_clone_success note: > Called on the success path after PR merge is confirmed. Passes target_branch so release_issue can determine whether to apply the staged label (non-default target) or just remove in-progress (default target). - optional=true ensures pipeline still reaches confirm_cleanup if this step errors. + optional=true ensures pipeline still reaches register_clone_success if this step errors. release_issue_timeout: description: "Release in-progress claim after queue timeout without applying staged label" @@ -1048,13 +1219,13 @@ steps: skip_when_false: inputs.issue_url with: issue_url: ${{ inputs.issue_url }} - on_success: check_defer_cleanup - on_failure: check_defer_cleanup + on_success: register_clone_success + on_failure: register_clone_success note: > Called when wait_for_merge_queue times out or errors. Releases the in-progress claim without passing target_branch, so the staged label is not applied. The merge is unconfirmed; a human must verify queue state independently. - Routes to confirm_cleanup so the pipeline completes cleanly. + Routes to register_clone_success so the pipeline completes cleanly. release_issue_failure: description: "Release the in-progress claim after pipeline failure" @@ -1063,92 +1234,29 @@ steps: skip_when_false: inputs.issue_url with: issue_url: ${{ inputs.issue_url }} - on_success: check_defer_on_failure - on_failure: check_defer_on_failure - - check_defer_cleanup: - description: "Route to deferred or immediate cleanup on success path" - tool: run_python - with: - callable: "autoskillit.smoke_utils.check_cleanup_mode" - defer_cleanup: "${{ inputs.defer_cleanup }}" - on_result: - - when: "result.deferred == 'true'" - route: register_success_deferred - - route: confirm_cleanup - on_failure: confirm_cleanup + on_success: register_clone_failure + on_failure: register_clone_failure - register_success_deferred: - description: "Register clone as cleanup candidate (deferred batch cleanup mode)" + register_clone_success: + description: "Register clone as cleanup candidate for batch deletion" tool: register_clone_status with: clone_path: "${{ context.work_dir }}" status: "success" - registry_path: "${{ inputs.registry_path }}" - step_name: register_success_deferred + step_name: register_clone_success on_success: done on_failure: done - check_defer_on_failure: - description: "Route to deferred or immediate cleanup on failure path" - tool: run_python - with: - callable: "autoskillit.smoke_utils.check_cleanup_mode" - defer_cleanup: "${{ inputs.defer_cleanup }}" - on_result: - - when: "result.deferred == 'true'" - route: register_error_deferred - - route: cleanup_failure - on_failure: cleanup_failure - - register_error_deferred: - description: "Register clone as preserved (error pipeline — deferred mode)" + register_clone_failure: + description: "Register clone as preserved (error pipeline)" tool: register_clone_status with: clone_path: "${{ context.work_dir }}" status: "error" - registry_path: "${{ inputs.registry_path }}" - step_name: register_error_deferred + step_name: register_clone_failure on_success: escalate_stop on_failure: escalate_stop - confirm_cleanup: - action: confirm - message: >- - Pipeline succeeded! The clone directory at ${{ context.work_dir }} has been preserved. - Would you like to delete it now? Keeping it lets you resume any session that ran during - this pipeline (implement-worktree, audit-impl, resolve-failures, etc.). - Type yes to delete or no to keep. - on_success: delete_clone - on_failure: done - note: >- - User confirmation gate — preserves clone by default. On yes: delete_clone removes it. - On no: done is reached immediately, clone stays on disk. - - delete_clone: - tool: remove_clone - with: - clone_path: "${{ context.work_dir }}" - keep: "false" - step_name: delete_clone - on_success: done - on_failure: done - note: >- - Reached only after user explicitly confirms cleanup. Sync-check hook gates deletion — - removal approved only when branch is pushed. - - cleanup_failure: - tool: remove_clone - with: - clone_path: "${{ context.work_dir }}" - keep: "true" - on_success: escalate_stop - on_failure: escalate_stop - note: > - Clone preservation step — keep=true means the clone is never - auto-removed on failure. Remove manually: rm -rf {clone_path}. - Always routes to escalate_stop. - done: action: stop message: "Implementation pipeline complete. All tasks have been planned, implemented, tested, and merged." @@ -1157,24 +1265,3 @@ steps: action: stop message: "Pipeline failed — human intervention needed. Check the worktree and plan for details." - batch_confirm_cleanup: - action: confirm - message: >- - All parallel pipelines complete. Delete all registered successful clones? - Error pipeline clones will be preserved for investigation. - Type yes to delete or no to keep all. - note: >- - ORCHESTRATOR: Run this step ONCE after ALL parallel pipeline instances have - reached 'done' or 'escalate_stop'. Do NOT run per-pipeline instance. - Only applicable when run_mode=parallel and defer_cleanup=true. - on_success: batch_delete_clones - on_failure: done - - batch_delete_clones: - description: "Delete all registered successful clones in one batch operation" - tool: batch_cleanup_clones - with: - registry_path: "${{ inputs.registry_path }}" - step_name: batch_delete_clones - on_success: done - on_failure: done diff --git a/src/autoskillit/recipes/merge-prs.yaml b/src/autoskillit/recipes/merge-prs.yaml index 0115cd915e..df4a523943 100644 --- a/src/autoskillit/recipes/merge-prs.yaml +++ b/src/autoskillit/recipes/merge-prs.yaml @@ -11,35 +11,16 @@ ingredients: run_name: description: Run name prefix default: "pr-merge" - keep_clone_on_failure: - description: Keep clone on failure - default: "false" base_branch: description: Branch that PRs target required: false default: "" audit: description: Post-merge quality gate - default: "true" + default: "false" plans_dir: description: Plan files for audit - default: ".autoskillit/temp/merge-prs" - defer_cleanup: - description: >- - When 'true', skip per-pipeline interactive cleanup and register this clone - in the shared registry for batch deletion after all parallel pipelines - complete. Set to 'true' on every parallel instance; leave 'false' for - sequential single-pipeline runs. - default: "false" - hidden: true - registry_path: - description: >- - Absolute path to the shared clone cleanup registry file. Required when - defer_cleanup=true. Must be identical across all parallel pipeline runs in - the same batch (use a fixed path like - /path/to/project/.autoskillit/temp/clone-cleanup-registry.json). - default: "" - hidden: true + default: "{{AUTOSKILLIT_TEMP}}/merge-prs" kitchen_rules: - "NEVER use native Claude Code tools (Read, Grep, Glob, Edit, Write, @@ -115,8 +96,8 @@ steps: cmd: "git remote set-url origin \"${{ context.remote_url }}\"" cwd: "${{ context.work_dir }}" step_name: "setup_remote" - on_success: check_integration_exists - on_failure: cleanup_failure + on_success: check_repo_ci_event + on_failure: register_clone_failure note: > The clone's origin initially points to a file:// URL (set by clone_repo for isolation). This step replaces it with the actual GitHub remote URL so that gh CLI commands @@ -124,6 +105,25 @@ steps: Skills that contact remotes (resolve-merge-conflicts, retry-worktree, implement-worktree) now use REMOTE=$(upstream || origin) internally and do not depend on this step. + check_repo_ci_event: + tool: check_repo_merge_state + block: pre_merge_prs_ci_gate + with: + branch: "${{ inputs.base_branch }}" + cwd: "${{ context.work_dir }}" + remote_url: "${{ context.remote_url }}" + step_name: "check_repo_ci_event" + capture: + ci_event: "${{ result.ci_event }}" + on_success: check_integration_exists + on_failure: check_integration_exists + note: > + Detects whether the repository's CI triggers on push or merge_group events. + Captures ci_event for use by wait_for_ci steps (wait_for_conflict_ci, ci_watch_pr) + and diagnose-ci skill invocations downstream. Routes to check_integration_exists + regardless of outcome — non-blocking gate: ci_event defaults to null (match-any) + on failure, which matches the ci.py scope.event=None behavior. + check_integration_exists: tool: run_cmd with: @@ -158,7 +158,7 @@ steps: cwd: "${{ context.work_dir }}" step_name: "create_persistent_integration" on_success: fetch_merge_queue_data - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Creates base_branch from the repository's default branch (auto-detected via origin/HEAD, falls back to main). Only executes when the user confirmed @@ -171,7 +171,7 @@ steps: callable: "autoskillit.smoke_utils.fetch_merge_queue_data" base_branch: "${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" - output_dir: "${{ context.work_dir }}/.autoskillit/temp/merge-prs" + output_dir: "${{ context.work_dir }}/{{AUTOSKILLIT_TEMP}}/merge-prs" capture: merge_queue_data_path: "${{ result.merge_queue_data_path }}" on_success: analyze_prs @@ -193,7 +193,7 @@ steps: integration_branch: "${{ result.integration_branch }}" queue_mode: "${{ result.queue_mode }}" on_success: route_by_queue_mode - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Captures pr_order_file (path to JSON with ordered PRs + complexity tags), integration_branch (e.g. integration/pr-merge-20250228-143052), and @@ -226,7 +226,7 @@ steps: cwd: "${{ context.work_dir }}" step_name: "enqueue_all_prs" on_success: get_first_pr_number - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Queue mode only. Submits all PRs in analyzed order to the merge queue via gh pr merge --squash --auto. Non-fatal per-PR failures are warned but do not @@ -242,7 +242,7 @@ steps: capture: current_pr_number: "${{ result.stdout | trim }}" on_success: wait_queue_pr - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Queue mode only. Extracts the first PR's number from pr_order_file to initialize context.current_pr_number before the queue wait loop. The agent advances @@ -264,14 +264,14 @@ steps: route: next_queue_pr_or_done - when: "${{ result.pr_state }} == ejected" route: get_ejected_pr_branch - - route: cleanup_failure - on_failure: cleanup_failure + - route: register_clone_failure + on_failure: register_clone_failure note: > Queue mode only. The agent reads context.pr_order_file at context.current_pr_index to get the current PR's number and appends it to the pr_number argument. merged → advance to next PR or finish. ejected → conflict resolution cycle (get_ejected_pr_branch → checkout → resolve → push → reenter). - timeout → cleanup_failure (900s budget = 15 min per PR). + timeout → register_clone_failure (900s budget = 15 min per PR). get_ejected_pr_branch: tool: run_cmd @@ -282,7 +282,7 @@ steps: capture: ejected_pr_branch: "${{ result.stdout | trim }}" on_success: checkout_ejected_pr - on_failure: cleanup_failure + on_failure: register_clone_failure checkout_ejected_pr: tool: run_cmd @@ -294,7 +294,7 @@ steps: cwd: "${{ context.work_dir }}" step_name: "checkout_ejected_pr" on_success: resolve_ejected_conflicts - on_failure: cleanup_failure + on_failure: register_clone_failure resolve_ejected_conflicts: tool: run_skill @@ -308,11 +308,11 @@ steps: all_conflict_report_paths: "${{ result.conflict_report_path }}" on_result: - when: "${{ result.escalation_required }} == true" - route: cleanup_failure + route: register_clone_failure - route: push_ejected_fix - on_failure: cleanup_failure + on_failure: register_clone_failure retries: 1 - on_exhausted: cleanup_failure + on_exhausted: register_clone_failure note: > Resolves git-level rebase conflicts between the ejected PR's branch and the current base_branch HEAD. Uses the same resolve-merge-conflicts skill as the @@ -326,7 +326,7 @@ steps: branch: "${{ context.ejected_pr_branch }}" force: "true" on_success: reenter_queue - on_failure: cleanup_failure + on_failure: register_clone_failure reenter_queue: tool: run_cmd @@ -335,7 +335,7 @@ steps: cwd: "${{ context.work_dir }}" step_name: "reenter_queue" on_success: wait_queue_pr - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Re-submits the fixed PR to the merge queue after conflict resolution. Routes back to wait_queue_pr to continue monitoring. @@ -361,7 +361,7 @@ steps: cwd: "${{ context.work_dir }}" step_name: "create_integration_branch" on_success: publish_integration_branch - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Creates the integration branch from the latest base_branch HEAD. context.integration_branch was computed by analyze_prs. @@ -374,7 +374,7 @@ steps: remote_url: "${{ context.remote_url }}" branch: "${{ context.integration_branch }}" on_success: merge_pr - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Publishes the integration branch to origin immediately after creation so that merge_worktree can verify refs/remotes/origin/integration_branch exists @@ -400,10 +400,10 @@ steps: - when: "${{ result.needs_plan }} == true" route: plan - route: next_part_or_next_pr - on_failure: cleanup_failure + on_failure: register_clone_failure retries: 5 - on_exhausted: cleanup_failure - on_context_limit: cleanup_failure + on_exhausted: register_clone_failure + on_context_limit: register_clone_failure note: > The agent reads context.pr_order_file at context.current_pr_index to get the current PR's number and complexity. Appends them to skill_command: @@ -424,7 +424,7 @@ steps: plan_parts: "${{ result.plan_parts }}" all_plan_paths: "${{ result.plan_path }}" on_success: verify - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Glob plan_dir for *_part_*.md or single plan file. Sort alphabetically into plan_parts[]. For a single-part plan, plan_parts has one entry equal @@ -441,10 +441,10 @@ steps: cwd: "${{ context.work_dir }}" step_name: "verify" on_success: implement - on_failure: cleanup_failure + on_failure: register_clone_failure retries: 5 - on_exhausted: cleanup_failure - on_context_limit: cleanup_failure + on_exhausted: register_clone_failure + on_context_limit: register_clone_failure note: > SEQUENTIAL: For each plan_part, run the full cycle (verify → implement → test → push_worktree_branch → create_conflict_pr @@ -452,6 +452,7 @@ steps: implement: tool: run_skill + stale_threshold: 2400 with: skill_command: "/autoskillit:implement-worktree-no-merge ${{ context.pr_plan_path }}" cwd: "${{ context.work_dir }}" @@ -460,13 +461,14 @@ steps: worktree_path: "${{ result.worktree_path }}" worktree_branch_name: "${{ result.branch_name }}" on_success: test - on_failure: cleanup_failure + on_failure: register_clone_failure retries: 0 on_exhausted: retry_worktree on_context_limit: retry_worktree retry_worktree: tool: run_skill + stale_threshold: 2400 with: skill_command: "/autoskillit:retry-worktree ${{ context.pr_plan_path }} ${{ context.worktree_path }}" cwd: "${{ context.worktree_path }}" @@ -475,10 +477,10 @@ steps: worktree_path: "${{ result.worktree_path }}" worktree_branch_name: "${{ result.branch_name }}" on_success: test - on_failure: cleanup_failure + on_failure: register_clone_failure retries: 3 - on_exhausted: cleanup_failure - on_context_limit: cleanup_failure + on_exhausted: register_clone_failure + on_context_limit: register_clone_failure test: tool: test_check @@ -494,13 +496,13 @@ steps: cwd: "${{ context.worktree_path }}" step_name: "push_worktree_branch" on_success: create_conflict_pr - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Pushes the conflict-resolution worktree branch to origin so GitHub can run CI. Uses --force-with-lease to prevent clobbering concurrent updates. context.worktree_branch_name is captured from implement step output (result.branch_name). Both a lease violation (concurrent push) and a network failure route to - cleanup_failure — the recipe cannot distinguish between the two, so no safe + register_clone_failure — the recipe cannot distinguish between the two, so no safe retry is possible without re-evaluating the worktree state. create_conflict_pr: @@ -518,7 +520,7 @@ steps: capture: conflict_pr_number: "${{ result.stdout | trim }}" on_success: wait_for_conflict_ci - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Creates a GitHub PR from the worktree branch into the integration batch branch. Captures conflict_pr_number for the subsequent gh pr merge call. @@ -531,15 +533,15 @@ steps: tool: wait_for_ci with: branch: "${{ context.worktree_branch_name }}" - workflow: "tests.yml" + event: "${{ context.ci_event }}" timeout_seconds: 600 cwd: "${{ context.work_dir }}" on_success: merge_conflict_pr - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Waits for CI to pass on the worktree branch before merging. 600 second timeout matches the merge-pr skill poll timeout. - On CI failure, routes to cleanup_failure — no automated remediation + On CI failure, routes to register_clone_failure — no automated remediation for conflict-resolution CI failures. merge_conflict_pr: @@ -549,7 +551,7 @@ steps: cwd: "${{ context.work_dir }}" step_name: "merge_conflict_pr" on_success: next_part_or_next_pr - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Merges the conflict-resolution PR into the integration batch branch via GitHub API. Uses --squash to keep integration history linear. @@ -564,11 +566,22 @@ steps: cwd: "${{ context.worktree_path }}" step_name: "fix" base_branch: "${{ inputs.base_branch }}" - on_success: test - on_failure: cleanup_failure + capture: + verdict: "${{ result.verdict }}" + fixes_applied: "${{ result.fixes_applied }}" + on_result: + - when: "${{ result.verdict }} == 'real_fix'" + route: test + - when: "${{ result.verdict }} == 'already_green'" + route: test + - when: "${{ result.verdict }} == 'flake_suspected'" + route: test + - when: "${{ result.verdict }} == 'ci_only_failure'" + route: register_clone_failure + on_failure: register_clone_failure retries: 3 - on_exhausted: cleanup_failure - on_context_limit: cleanup_failure + on_exhausted: register_clone_failure + on_context_limit: register_clone_failure note: > Fixes test failures without merging. Routes back to test for re-validation before the GitHub-API merge sequence. The base_branch with: @@ -596,7 +609,7 @@ steps: remote_url: "${{ context.remote_url }}" branch: "${{ context.integration_branch }}" on_success: collect_artifacts - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Single push after ALL PR merges complete. Uses push_to_remote MCP tool (consistent with all other push steps) rather than run_cmd git push. @@ -604,14 +617,14 @@ steps: collect_artifacts: tool: run_cmd with: - cmd: "mkdir -p ${{ inputs.plans_dir }} && find .autoskillit/temp/make-plan/ -name '*_plan_*.md' -exec cp {} ${{ inputs.plans_dir }}/ \\; 2>/dev/null || true" + cmd: "mkdir -p ${{ inputs.plans_dir }} && find {{AUTOSKILLIT_TEMP}}/make-plan/ -name '*_plan_*.md' -exec cp {} ${{ inputs.plans_dir }}/ \\; 2>/dev/null || true" cwd: "${{ context.work_dir }}" step_name: "collect_artifacts" on_success: check_impl_plans on_failure: check_impl_plans note: > - Copies plan files generated during the pipeline (from .autoskillit/temp/make-plan/) into - .autoskillit/temp/merge-prs/ alongside any conflict reports already there. + Copies plan files generated during the pipeline (from {{AUTOSKILLIT_TEMP}}/make-plan/) into + {{AUTOSKILLIT_TEMP}}/merge-prs/ alongside any conflict reports already there. Always routes to check_impl_plans, which determines whether audit_impl is meaningful. In queue mode (context.queue_mode == true), the integration_branch is the base_branch itself — no batch branch push is needed. The step after @@ -649,8 +662,8 @@ steps: routes: GO: compute_domain_partitions NO GO: remediate - on_failure: cleanup_failure - on_context_limit: cleanup_failure + on_failure: register_clone_failure + on_context_limit: register_clone_failure optional: true skip_when_false: "inputs.audit" note: > @@ -679,7 +692,7 @@ steps: integration_branch: "${{ context.integration_branch }}" base_branch: "${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" - output_dir: "${{ context.work_dir }}/.autoskillit/temp/open-integration-pr" + output_dir: "${{ context.work_dir }}/{{AUTOSKILLIT_TEMP}}/open-integration-pr" capture: domain_partitions_path: "${{ result.domain_partitions_path }}" on_success: open_integration_pr @@ -699,7 +712,7 @@ steps: capture: pr_url: "${{ result.pr_url }}" on_success: wait_for_review_pr_mergeability - on_failure: cleanup_failure + on_failure: register_clone_failure wait_for_review_pr_mergeability: tool: run_cmd @@ -718,7 +731,7 @@ steps: capture: review_pr_number: "${{ result.stdout | trim }}" on_success: check_mergeability - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Extracts the review PR number from context.pr_url and polls GitHub until the mergeable field is no longer UNKNOWN (GitHub computes this asynchronously after PR @@ -735,13 +748,13 @@ steps: route: annotate_pr_diff - when: "${{ result.mergeable_status }} == CONFLICTING" route: resolve_integration_conflicts - - route: cleanup_failure - on_failure: cleanup_failure + - route: register_clone_failure + on_failure: register_clone_failure note: > Authoritative mergeability check via check_pr_mergeable MCP tool (REQ-MERGE-001). Routes MERGEABLE directly to review cycle. Routes CONFLICTING to automated conflict resolution. Any other state (UNKNOWN after timeout, tool error) escalates - to cleanup_failure (REQ-MERGE-005). + to register_clone_failure (REQ-MERGE-005). resolve_integration_conflicts: tool: run_skill @@ -756,14 +769,14 @@ steps: all_conflict_report_paths: "${{ result.conflict_report_path }}" on_result: - when: "${{ result.escalation_required }} == true" - route: cleanup_failure + route: register_clone_failure - route: force_push_after_rebase - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Automated conflict resolution when the integration PR is CONFLICTING (REQ-MERGE-003). Rebases context.integration_branch onto inputs.base_branch and resolves merge conflicts. Single attempt only — no retries — to prevent looping on unresolvable conflicts. - On failure, escalates to cleanup_failure with diagnostics (REQ-MERGE-004). + On failure, escalates to register_clone_failure with diagnostics (REQ-MERGE-004). force_push_after_rebase: tool: run_cmd @@ -772,7 +785,7 @@ steps: cwd: "${{ context.work_dir }}" step_name: "force_push_after_rebase" on_success: wait_for_post_rebase_mergeability - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Force-pushes the rebased integration branch to update the review PR after conflict resolution. Uses --force-with-lease to reject if the remote diverged during the rebase. @@ -794,7 +807,7 @@ steps: cwd: "${{ context.work_dir }}" step_name: "wait_for_post_rebase_mergeability" on_success: check_mergeability_post_rebase - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Polls GitHub until the integration PR's mergeable field is no longer UNKNOWN after the force-push following conflict resolution. GitHub resets mergeable to UNKNOWN asynchronously @@ -810,12 +823,12 @@ steps: on_result: - when: "${{ result.mergeable_status }} == MERGEABLE" route: annotate_pr_diff - - route: cleanup_failure - on_failure: cleanup_failure + - route: register_clone_failure + on_failure: register_clone_failure note: > Re-checks mergeability after the rebase and force-push. MERGEABLE proceeds to the review cycle. Any other state means automated resolution did not succeed — escalates - to cleanup_failure for human intervention (REQ-MERGE-004). No second conflict + to register_clone_failure for human intervention (REQ-MERGE-004). No second conflict resolution attempt — one cycle only. annotate_pr_diff: @@ -824,7 +837,7 @@ steps: callable: "autoskillit.smoke_utils.annotate_pr_diff" pr_number: "${{ context.review_pr_number }}" cwd: "${{ context.work_dir }}" - output_dir: "${{ context.work_dir }}/.autoskillit/temp/review-pr" + output_dir: "${{ context.work_dir }}/{{AUTOSKILLIT_TEMP}}/review-pr" capture: annotated_diff_path: "${{ result.annotated_diff_path }}" hunk_ranges_path: "${{ result.hunk_ranges_path }}" @@ -866,15 +879,27 @@ steps: skill_command: "/autoskillit:resolve-review ${{ context.integration_branch }} ${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" step_name: "resolve_review_integration" + capture: + verdict: "${{ result.verdict }}" retries: 2 - on_exhausted: cleanup_failure - on_success: re_push_review_integration - on_failure: cleanup_failure + on_exhausted: register_clone_failure + on_context_limit: re_push_review_integration + on_result: + - when: "${{ result.verdict }} == 'real_fix'" + route: re_push_review_integration + - when: "${{ result.verdict }} == 'already_green'" + route: re_push_review_integration + - when: "${{ result.verdict }} == 'flake_suspected'" + route: register_clone_failure + - when: "${{ result.verdict }} == 'ci_only_failure'" + route: register_clone_failure + on_failure: register_clone_failure note: > Resolves review findings on the integration PR (REQ-REVIEW-002). Fetches inline and summary review comments from GitHub and applies fixes. Retries up to 2 times (3 total - attempts) before escalating to cleanup_failure (REQ-REVIEW-005). On success, routes to - re_push_review_integration to push the fixes to remote. + attempts) before escalating to register_clone_failure (REQ-REVIEW-005). Routes via + on_result: verdict dispatch — real_fix/already_green push fixes; flake_suspected/ + ci_only_failure escalate to register_clone_failure. re_push_review_integration: tool: push_to_remote @@ -883,103 +908,63 @@ steps: remote_url: "${{ context.remote_url }}" branch: "${{ context.integration_branch }}" on_success: ci_watch_pr - on_failure: cleanup_failure + on_failure: register_clone_failure note: > Pushes the review-fixed integration branch to the remote (REQ-REVIEW-003). Routes to - ci_watch_pr for final CI validation. On push failure, escalates to cleanup_failure. + ci_watch_pr for final CI validation. On push failure, escalates to register_clone_failure. ci_watch_pr: tool: wait_for_ci with: branch: "${{ context.integration_branch }}" - workflow: "tests.yml" + event: "${{ context.ci_event }}" timeout_seconds: 300 cwd: "${{ context.work_dir }}" pr_url: "${{ context.pr_url }}" - on_success: check_defer_cleanup + on_success: register_clone_success on_failure: diagnose_ci note: > Waits for the GitHub Actions CI run on context.integration_branch to complete using the wait_for_ci MCP tool (timeout: 300 s). CI failures here indicate the integration branch has problems that the human reviewer should see. No automated remediation; on failure, routes to diagnose_ci to capture logs before - cleanup_failure preserves the clone for manual inspection. + register_clone_failure preserves the clone for manual inspection. diagnose_ci: tool: run_skill with: - skill_command: "/autoskillit:diagnose-ci ${{ context.integration_branch }} - - tests.yml" + skill_command: "/autoskillit:diagnose-ci ${{ context.integration_branch }} - - - ${{ context.ci_event }}" cwd: "${{ context.work_dir }}" step_name: "diagnose_ci" capture: diagnosis_path: "${{ result.diagnosis_path }}" - on_success: cleanup_failure - on_failure: cleanup_failure + on_success: register_clone_failure + on_failure: register_clone_failure note: > Runs when ci_watch_pr reports CI failure on the integration branch. - Fetches logs and writes a diagnosis to .autoskillit/temp/diagnose-ci/ for human inspection. + Fetches logs and writes a diagnosis to {{AUTOSKILLIT_TEMP}}/diagnose-ci/ for human inspection. diagnosis_path is captured for observability — no automated remediation for - integration CI, so always routes to cleanup_failure. + integration CI, so always routes to register_clone_failure. - check_defer_cleanup: - description: "Route to deferred or immediate cleanup on success path" - tool: run_python - with: - callable: "autoskillit.smoke_utils.check_cleanup_mode" - defer_cleanup: "${{ inputs.defer_cleanup }}" - on_result: - - when: "result.deferred == 'true'" - route: register_success_deferred - - route: confirm_cleanup - on_failure: confirm_cleanup - - register_success_deferred: - description: "Register clone as cleanup candidate (deferred batch cleanup mode)" + register_clone_success: + description: "Register clone as cleanup candidate for batch deletion" tool: register_clone_status with: clone_path: "${{ context.work_dir }}" status: "success" - registry_path: "${{ inputs.registry_path }}" - step_name: register_success_deferred - on_success: done - on_failure: done - - confirm_cleanup: - action: confirm - message: >- - PR-merge pipeline succeeded! PR: ${{ context.pr_url }}. - The clone at ${{ context.work_dir }} is preserved. - Delete it now? Keeping it lets you resume any session from this pipeline run. - Type yes to delete or no to keep. - on_success: delete_clone - on_failure: done - note: >- - User confirmation gate — preserves clone by default. On yes: delete_clone removes it. - On no: done is reached immediately, clone stays on disk. - - delete_clone: - tool: remove_clone - with: - clone_path: "${{ context.work_dir }}" - keep: "false" - step_name: delete_clone + step_name: register_clone_success on_success: done on_failure: done - note: >- - Reached only after user explicitly confirms cleanup. Sync-check hook gates deletion — - removal approved only when branch is pushed. - cleanup_failure: - tool: remove_clone + register_clone_failure: + description: "Register clone as preserved (error pipeline)" + tool: register_clone_status with: clone_path: "${{ context.work_dir }}" - keep: "${{ inputs.keep_clone_on_failure }}" + status: "error" + step_name: register_clone_failure on_success: escalate_stop on_failure: escalate_stop - note: > - Called on pipeline failure. Respects keep_clone_on_failure ingredient. - When keep=false, the sync-check hook gates deletion. Always routes - to escalate_stop. done: action: stop @@ -987,30 +972,9 @@ steps: escalate_stop: action: stop - message: "Pipeline failed — human intervention needed. Check the integration branch and .autoskillit/temp/merge-prs/ for details." + message: "Pipeline failed — human intervention needed. Check the integration branch and {{AUTOSKILLIT_TEMP}}/merge-prs/ for details." note: > context.task may be null when reached via escalation_required=true from merge_pr (merge-pr does not set conflict_report_path on escalation paths). Do not rely on context.task being populated when handling this stop. - batch_confirm_cleanup: - action: confirm - message: >- - All parallel pipelines complete. Delete all registered successful clones? - Error pipeline clones will be preserved for investigation. - Type yes to delete or no to keep all. - note: >- - ORCHESTRATOR: Run this step ONCE after ALL parallel pipeline instances have - reached 'done' or 'escalate_stop'. Do NOT run per-pipeline instance. - Only applicable when run_mode=parallel and defer_cleanup=true. - on_success: batch_delete_clones - on_failure: done - - batch_delete_clones: - description: "Delete all registered successful clones in one batch operation" - tool: batch_cleanup_clones - with: - registry_path: "${{ inputs.registry_path }}" - step_name: batch_delete_clones - on_success: done - on_failure: done diff --git a/src/autoskillit/recipes/remediation.yaml b/src/autoskillit/recipes/remediation.yaml index 77f1114515..3d27da2d22 100644 --- a/src/autoskillit/recipes/remediation.yaml +++ b/src/autoskillit/recipes/remediation.yaml @@ -18,9 +18,9 @@ kitchen_rules: derived from inputs.run_name and context.issue_number (e.g. investigate/42) or a date suffix (e.g. investigate/20260304) when no issue is available. All worktree merges target the feature branch (context.merge_target), not base_branch - directly. The push step publishes the feature branch, then open_pr_step + directly. The push step publishes the feature branch, then prepare_pr → run_arch_lenses → compose_pr opens a PR to base_branch. When open_pr=false, merges target base_branch - directly and open_pr_step is skipped." + directly and prepare_pr is skipped." - "SOURCE ISOLATION: After clone_repo returns, the source_dir is strictly off-limits. Never run any command in source_dir — no git checkout, git fetch, git reset, git pull, run_cmd, run_skill, or any other operation. @@ -44,7 +44,7 @@ ingredients: default: "" audit: description: Post-merge quality gate - default: "true" + default: "false" review_approach: description: Research approaches first default: "false" @@ -74,22 +74,6 @@ ingredients: step scheduling — fast steps for all pipelines before any slow step). default: "sequential" hidden: true - defer_cleanup: - description: >- - When 'true', skip per-pipeline interactive cleanup and register this clone - in the shared registry for batch deletion after all parallel pipelines - complete. Set to 'true' on every parallel instance; leave 'false' for - sequential single-pipeline runs. - default: "false" - hidden: true - registry_path: - description: >- - Absolute path to the shared clone cleanup registry file. Required when - defer_cleanup=true. Must be identical across all parallel pipeline runs in - the same batch (use a fixed path like - /path/to/project/.autoskillit/temp/clone-cleanup-registry.json). - default: "" - hidden: true steps: sprint_entry: @@ -153,7 +137,7 @@ steps: Runs when inputs.issue_url is non-empty. Skipped otherwise. Fetches only the issue title and slug (no body, no comments). issue_number is used for feature branch naming and threaded to - open_pr_step for "Closes #N" in the PR body. + prepare_pr for "Closes #N" in the PR body. issue_slug provides a descriptive branch prefix (e.g. fix-merge-conflict-triage). claim_issue: @@ -293,6 +277,7 @@ steps: implement: tool: run_skill + stale_threshold: 2400 with: skill_command: "/autoskillit:implement-worktree-no-merge ${{ context.plan_path }}" cwd: "${{ context.work_dir }}" @@ -308,6 +293,7 @@ steps: retry_worktree: tool: run_skill + stale_threshold: 2400 with: skill_command: "/autoskillit:retry-worktree ${{ context.plan_path }} ${{ context.worktree_path }}" cwd: "${{ context.worktree_path }}" @@ -316,8 +302,12 @@ steps: implementation_ref: "${{ result.worktree_path }}" worktree_path: "${{ result.worktree_path }}" branch_name: "${{ result.branch_name }}" + phases_implemented: "${{ result.phases_implemented }}" + on_result: + - when: "${{ result.phases_implemented }} > 0" + route: test + - route: test on_exhausted: release_issue_failure - on_success: test on_failure: release_issue_failure test: @@ -333,7 +323,18 @@ steps: skill_command: "/autoskillit:resolve-failures ${{ context.worktree_path }} ${{ context.plan_path }} ${{ inputs.base_branch }}" cwd: "${{ context.worktree_path }}" step_name: "assess" - on_success: test + capture: + verdict: "${{ result.verdict }}" + fixes_applied: "${{ result.fixes_applied }}" + on_result: + - when: "${{ result.verdict }} == 'real_fix'" + route: test + - when: "${{ result.verdict }} == 'already_green'" + route: test + - when: "${{ result.verdict }} == 'flake_suspected'" + route: test + - when: "${{ result.verdict }} == 'ci_only_failure'" + route: release_issue_failure on_context_limit: test on_failure: release_issue_failure on_exhausted: release_issue_failure @@ -348,7 +349,7 @@ steps: remediation_path: "${{ result.remediation_path }}" on_result: - when: "${{ result.verdict }} == GO" - route: merge + route: commit_guard - when: "result.error" route: escalate_stop - route: remediate @@ -356,7 +357,7 @@ steps: on_context_limit: escalate_stop optional: true skip_when_false: "inputs.audit" - note: Only run if inputs.audit = true. If inputs.audit = false, skip directly to merge. + note: Only run if inputs.audit = true. If inputs.audit = false, skip directly to commit_guard. remediate: action: route @@ -378,6 +379,19 @@ steps: on_success: dry_walkthrough on_failure: release_issue_failure + commit_guard: + tool: run_cmd + with: + cmd: "cd ${{ context.implementation_ref }} && if [ -n \"$(git status --porcelain)\" ]; then git add -A && git commit -m 'chore: commit pending session changes'; fi" + cwd: "${{ context.implementation_ref }}" + step_name: commit_guard + on_success: merge + on_failure: merge + note: > + Belt-and-suspenders guard: auto-commits any uncommitted changes before merge. + Catches dirty state from context-exhausted skills, cascading pre-commit auto-fixes, + or any other source. on_failure routes to merge (dirty-tree gate will catch real issues). + merge: tool: merge_worktree with: @@ -406,35 +420,81 @@ steps: clone_path: "${{ context.work_dir }}" remote_url: "${{ context.remote_url }}" branch: "${{ context.merge_target }}" - on_success: open_pr_step + on_success: prepare_pr on_failure: release_issue_failure note: > Runs once at the end. Pushes merge_target branch from the clone to the upstream remote. By default (open_pr=true), this pushes the feature branch; when open_pr=false, pushes base_branch. Uses the pre-resolved remote_url captured at clone time, preserving clone isolation. - On success, routes to open_pr_step (which opens the PR by default; skipped when open_pr=false). - On failure, cleanup_failure still removes the clone. + On success, routes to prepare_pr (which opens the PR by default; skipped when open_pr=false). + On failure, release_issue_failure registers the clone and escalates. + + prepare_pr: + tool: run_skill + with: + skill_command: "/autoskillit:prepare-pr ${{ context.plan_path }} ${{ inputs.run_name }} ${{ inputs.base_branch }}" + cwd: "${{ context.work_dir }}" + step_name: "prepare_pr" + issue_number: "${{ context.issue_number }}" + capture: + prep_path: "${{ result.prep_path }}" + selected_lenses: "${{ result.selected_lenses }}" + lens_context_paths: "${{ result.lens_context_paths }}" + on_success: run_arch_lenses + on_failure: release_issue_failure + on_context_limit: release_issue_failure + optional: true + skip_when_false: "inputs.open_pr" + note: > + Reads plan, runs git diff, classifies changed files, selects 1–3 arch-lens slugs, + writes one PR context file per lens, and writes a PR prep file. Does NOT invoke + arch-lens skills. If context.issue_number is a non-empty string, append it as the + 4th positional argument so prepare-pr fetches requirements from the closing issue. - open_pr_step: + run_arch_lenses: tool: run_skill with: - skill_command: "/autoskillit:open-pr ${{ context.plan_path }} ${{ inputs.run_name }} ${{ inputs.base_branch }}" + skill_command: "/autoskillit:arch-lens-{slug} {context_path}" cwd: "${{ context.work_dir }}" - step_name: "open_pr" + step_name: "run_arch_lenses" + capture_list: + all_diagram_paths: "${{ result.diagram_path }}" + on_success: compose_pr + on_failure: compose_pr + on_context_limit: compose_pr + optional: true + skip_when_false: "inputs.open_pr" + note: > + LENS ITERATION: context.selected_lenses contains comma-separated arch-lens slugs + (e.g. "module-dependency,process-flow"). context.lens_context_paths contains the + corresponding comma-separated context file paths (same order as slugs). For each + lens slug, run: + /autoskillit:arch-lens-{slug} {matching_context_path} + Run all selected lenses in parallel (all run_skill calls in a single message). + Accumulate each diagram_path value into context.all_diagram_paths via capture_list. + If a lens fails, continue with remaining lenses — compose_pr handles empty lists + gracefully by omitting the Architecture Impact section. + + compose_pr: + tool: run_skill + with: + skill_command: "/autoskillit:compose-pr ${{ context.prep_path }} \"${{ context.all_diagram_paths }}\" ${{ context.work_dir }} ${{ inputs.base_branch }}" + cwd: "${{ context.work_dir }}" + step_name: "compose_pr" issue_number: "${{ context.issue_number }}" + capture: + pr_url: "${{ result.pr_url }}" on_success: extract_pr_number on_failure: release_issue_failure on_context_limit: release_issue_failure optional: true skip_when_false: "inputs.open_pr" note: > - Runs by default (open_pr=true). Skipped when open_pr=false. - The feature branch is already published by the push step that precedes this step. - Invokes the open-pr skill which selects arch-lens diagrams, composes a PR body, - and runs gh pr create. The skill gracefully degrades if gh is unavailable. - If context.issue_number is a non-empty string, append it as a 4th positional - argument so the open-pr skill inserts "Closes #{issue_number}" into the PR body. + Reads the PR prep file, validates arch-lens diagrams (must contain ★ or ●), + composes the PR body, and runs gh pr create. Degrades gracefully if gh is + unavailable (emits pr_url=). If context.issue_number is set, append it as the + 5th positional argument for Closes #N injection in the PR body. extract_pr_number: tool: run_cmd @@ -444,18 +504,36 @@ steps: step_name: "extract_pr_number" capture: pr_number: "${{ result.stdout | trim }}" - on_success: review_pr + on_success: annotate_pr_diff on_failure: release_issue_failure optional: true skip_when_false: "inputs.open_pr" note: > - Extracts the integer PR number from the feature branch opened by open_pr_step. + Extracts the integer PR number from the feature branch opened by compose_pr. pr_number is required by the queue finale steps (enable_auto_merge, wait_for_queue). + annotate_pr_diff: + tool: run_python + with: + callable: "autoskillit.smoke_utils.annotate_pr_diff" + pr_number: "${{ context.pr_number }}" + cwd: "${{ context.work_dir }}" + output_dir: "${{ context.work_dir }}/{{AUTOSKILLIT_TEMP}}/review-pr" + capture: + annotated_diff_path: "${{ result.annotated_diff_path }}" + hunk_ranges_path: "${{ result.hunk_ranges_path }}" + on_success: review_pr + on_failure: review_pr + optional: true + skip_when_false: "inputs.open_pr" + note: > + Pre-computes annotated diff with [LNNN] markers and hunk ranges JSON for + review-pr. On failure, falls through to review_pr which uses empty fallback. + review_pr: tool: run_skill with: - skill_command: "/autoskillit:review-pr ${{ context.merge_target }} ${{ inputs.base_branch }}" + skill_command: "/autoskillit:review-pr ${{ context.merge_target }} ${{ inputs.base_branch }} annotated_diff_path=${{ context.annotated_diff_path }} hunk_ranges_path=${{ context.hunk_ranges_path }}" cwd: "${{ context.work_dir }}" step_name: "review_pr" capture: @@ -472,7 +550,7 @@ steps: optional: true skip_when_false: "inputs.open_pr" note: > - Runs after open_pr_step creates the PR. Invokes the review-pr skill as a + Runs after compose_pr creates the PR. Invokes the review-pr skill as a headless session to leave inline review comments on the PR. The skill finds the open PR by feature branch name (context.merge_target). Captures verdict and routes via on_result: changes_requested → resolve_review, @@ -485,16 +563,27 @@ steps: skill_command: "/autoskillit:resolve-review ${{ context.merge_target }} ${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" step_name: "resolve_review" + capture: + verdict: "${{ result.verdict }}" retries: 2 on_exhausted: release_issue_failure - on_success: re_push_review + on_result: + - when: "${{ result.verdict }} == 'real_fix'" + route: re_push_review + - when: "${{ result.verdict }} == 'already_green'" + route: re_push_review + - when: "${{ result.verdict }} == 'flake_suspected'" + route: release_issue_failure + - when: "${{ result.verdict }} == 'ci_only_failure'" + route: release_issue_failure on_failure: release_issue_failure note: > Runs when review_pr reports issues (verdict=changes_requested). The clone (context.work_dir) has the feature branch (context.merge_target) checked out. resolve-review fetches inline and summary review comments via the GitHub API, applies fixes for each actionable finding (critical + warning severity), and - commits each fix. Orchestrator re-pushes via re_push_review after success. + commits each fix. Routes via on_result: verdict dispatch — real_fix/already_green + both route to re_push_review; flake_suspected/ci_only_failure escalate. Retries up to 2 times (3 total attempts) before exhausting to release_issue_failure. re_push_review: @@ -514,14 +603,13 @@ steps: tool: wait_for_ci with: branch: "${{ context.merge_target }}" - workflow: "tests.yml" timeout_seconds: 300 cwd: "${{ context.work_dir }}" remote_url: "${{ context.remote_url }}" capture: ci_conclusion: "${{ result.conclusion }}" ci_failed_jobs: "${{ result.failed_jobs }}" - on_success: check_merge_queue + on_success: check_repo_merge_state on_failure: detect_ci_conflict optional: true skip_when_false: "inputs.open_pr" @@ -530,102 +618,44 @@ steps: using the wait_for_ci MCP tool (timeout: 300 s). Captures structured output (conclusion + failed job names) for downstream resolve_ci. Skipped when open_pr=false — no remote feature branch is opened in that mode. - On success, routes to check_merge_queue to determine if the PR should enter + On success, routes to check_repo_merge_state to determine if the PR should enter the merge queue. On failure, routes to detect_ci_conflict which checks whether the failure is caused by a stale base before falling through to diagnose_ci. - check_merge_queue: - tool: run_cmd - with: - cmd: > - REPO=$( { git remote get-url upstream 2>/dev/null || git remote get-url origin; } | sed 's|.*github\.com[:/]||; s|\.git$||') && - OWNER=${REPO%%/*} && REPO_NAME=${REPO##*/} && - BRANCH="${{ inputs.base_branch }}" && - gh api graphql -f query="query { - repository(owner:\"$OWNER\", name:\"$REPO_NAME\") { - mergeQueue(branch:\"$BRANCH\") { id } - } - }" | jq -r 'if .data.repository.mergeQueue != null then "true" else "false" end' - cwd: "${{ context.work_dir }}" - step_name: "check_merge_queue" - capture: - queue_available: "${{ result.stdout | trim }}" - on_success: check_merge_group_trigger - on_failure: release_issue_success - skip_when_false: "inputs.open_pr" - note: > - Detects whether the target branch has an active merge queue via GraphQL. - Captures "true" or "false" into context.queue_available. - On failure (gh error, parse error), degrades gracefully to release_issue_success - (non-queue path). On success, routes to check_merge_group_trigger to validate - that a CI workflow includes the merge_group trigger before proceeding. - Skipped when open_pr=false — no PR was opened. - - check_merge_group_trigger: - tool: run_cmd - with: - cmd: > - REPO=$( { git remote get-url upstream 2>/dev/null || git remote get-url origin; } | sed 's|.*github\.com[:/]||; s|\.git$||') && - OWNER=${REPO%%/*} && REPO_NAME=${REPO##*/} && - [ -n "$OWNER" ] && [ -n "$REPO_NAME" ] && - FOUND="" && - while IFS= read -r wf; do - content=$(gh api "repos/$OWNER/$REPO_NAME/contents/.github/workflows/$wf" -q '.content') - [ -n "$content" ] && echo "$content" | base64 -d 2>/dev/null | grep -q 'merge_group' && FOUND=true && break - done < <(gh api "repos/$OWNER/$REPO_NAME/contents/.github/workflows" 2>/dev/null | jq -r '.[] | select(.type == "file") | .name'); - if [ "$FOUND" = "true" ]; then echo "true"; else - echo "WARNING: Merge queue detected on ${{ inputs.base_branch }} but no CI workflow includes merge_group trigger -- degrading to non-queue merge path" >&2 - echo "false" - fi - cwd: "${{ context.work_dir }}" - step_name: "check_merge_group_trigger" - capture: - merge_group_trigger: "${{ result.stdout | trim }}" - on_success: check_auto_merge - on_failure: check_auto_merge - skip_when_false: "inputs.open_pr" - note: > - Validates that at least one CI workflow in .github/workflows/ includes the - merge_group event trigger; emits WARNING to stderr when absent. - Lists workflow files via GitHub API, decodes base64 content, and greps for - 'merge_group'; captures merge_group_trigger as "true" (found) or "false" - (absent). - - check_auto_merge: - tool: run_cmd + check_repo_merge_state: + tool: check_repo_merge_state + block: pre_queue_gate with: - cmd: > - REPO=$( { git remote get-url upstream 2>/dev/null || git remote get-url origin; } | sed 's|.*github\.com[:/]||; s|\.git$||') && - OWNER=${REPO%%/*} && REPO_NAME=${REPO##*/} && - gh api graphql -f query="query { - repository(owner:\"$OWNER\", name:\"$REPO_NAME\") { - autoMergeAllowed - } - }" | jq -r '.data.repository.autoMergeAllowed // false' + branch: "${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" - step_name: "check_auto_merge" + remote_url: "${{ context.remote_url }}" + step_name: "check_repo_merge_state" capture: - auto_merge_available: "${{ result.stdout | trim }}" + queue_available: "${{ result.queue_available }}" + merge_group_trigger: "${{ result.merge_group_trigger }}" + auto_merge_available: "${{ result.auto_merge_available }}" + ci_event: "${{ result.ci_event }}" on_success: route_queue_mode - on_failure: route_queue_mode + on_failure: immediate_merge skip_when_false: "inputs.open_pr" note: > - Detects whether the target repository has autoMergeAllowed enabled via GraphQL. - Captures "true" or "false" into context.auto_merge_available. - On failure (gh error, network error), falls through to route_queue_mode with - auto_merge_available unset — route_queue_mode defaults to immediate_merge (safe - non-auto path). GraphQL-level errors (rate-limit, missing auth scope) also return - exit 0 with an errors array and no .data field; the jq // false fallback outputs - false safely, so auto_merge_available defaults to false on any error path. + Single GraphQL round-trip that captures queue_available, merge_group_trigger, + auto_merge_available, and ci_event for the target branch. Consolidates the former three + sequential run_cmd steps (check_merge_queue, check_merge_group_trigger, + check_auto_merge) into one MCP tool call. On failure (network error, auth failure), + falls through to immediate_merge (non-queue direct merge path). Skipped when open_pr=false — no PR was opened. route_queue_mode: + block: pre_queue_gate action: route on_result: - when: "${{ inputs.auto_merge }} != 'true'" - route: confirm_cleanup - - when: "${{ context.queue_available }} == true and ${{ context.merge_group_trigger }} == true" + route: register_clone_success + - when: "${{ context.queue_available }} == true and ${{ context.merge_group_trigger }} == true and ${{ context.auto_merge_available }} == true" route: enable_auto_merge + - when: "${{ context.queue_available }} == true and ${{ context.merge_group_trigger }} == true and ${{ context.auto_merge_available }} == false" + route: queue_enqueue_no_auto - when: "${{ context.auto_merge_available }} == true" route: direct_merge - route: immediate_merge @@ -638,11 +668,29 @@ steps: cwd: "${{ context.work_dir }}" step_name: "enable_auto_merge" on_success: wait_for_queue - on_failure: confirm_cleanup + on_failure: register_clone_success skip_when_false: "inputs.open_pr" note: > Submits the PR to the merge queue. On failure (PR not mergeable, already merged), - degrades to confirm_cleanup. + degrades to register_clone_success. + + queue_enqueue_no_auto: + tool: run_cmd + with: + cmd: "gh pr merge '${{ context.pr_number }}' --squash" + cwd: "${{ context.work_dir }}" + step_name: "queue_enqueue_no_auto" + on_success: wait_for_queue + on_failure: register_clone_success + skip_when_false: "inputs.open_pr" + note: > + Submits the PR to the merge queue when the target branch has a configured + merge queue but the repository disallows auto-merge (autoMergeAllowed=false). + Uses plain `gh pr merge --squash` (no --auto, which would be rejected by + GitHub's API auto-merge gate). GitHub intercepts the call and enqueues + the PR because the branch has a queue. Routes to wait_for_queue (the + shared queue waiter) — never to wait_for_immediate_merge, whose 5-minute + poll is too short for queue serialization. wait_for_queue: tool: wait_for_merge_queue @@ -657,21 +705,28 @@ steps: on_result: - when: "${{ result.pr_state }} == merged" route: release_issue_success + - when: "${{ result.pr_state }} == ejected_ci_failure" + route: diagnose_ci + - when: "${{ result.pr_state }} == dropped_healthy" + route: reenter_merge_queue_cheap - when: "${{ result.pr_state }} == ejected" route: queue_ejected_fix - when: "${{ result.pr_state }} == stalled" route: reenroll_stalled_pr - - route: confirm_cleanup - on_failure: confirm_cleanup + - when: "${{ result.pr_state }} == timeout" + route: release_issue_timeout + - route: release_issue_timeout + on_failure: release_issue_timeout skip_when_false: "inputs.open_pr" note: > Waits up to 15 minutes for the PR to merge through the queue. - merged → release_issue_success to apply staged label, then confirm_cleanup. + merged → release_issue_success to apply staged label, then register_clone_success. release_issue_success is optional with skip_when_false: inputs.issue_url — when - issue_url is absent the step is silently skipped and pipeline continues to confirm_cleanup. + issue_url is absent the step is silently skipped and pipeline continues to register_clone_success. + ejected_ci_failure → diagnose_ci (CI failure; conflict resolution cannot fix this). ejected → conflict fix cycle then re-enter. stalled → lightweight re-enrollment (disable then re-enable auto-merge). - timeout → confirm_cleanup (pipeline done; human monitors queue). + timeout → release_issue_timeout (release claim without staged label; merge unconfirmed). reenroll_stalled_pr: tool: toggle_auto_merge @@ -684,11 +739,33 @@ steps: skip_when_false: "inputs.open_pr" queue_ejected_fix: + tool: run_cmd + with: + cmd: > + if git fetch origin ${{ inputs.base_branch }} && git rebase origin/${{ inputs.base_branch }}; + then echo 'clean'; + else git rebase --abort 2>/dev/null || true; echo 'conflicts'; + fi + cwd: "${{ context.work_dir }}" + step_name: "queue_ejected_fix" + on_result: + - when: "${{ result.stdout | trim }} == clean" + route: re_push_queue_fix + - route: resolve_queue_merge_conflicts + on_failure: resolve_queue_merge_conflicts + skip_when_false: "inputs.open_pr" + note: > + Attempts a cheap rebase before invoking the full conflict-resolution skill. + On a clean rebase (stdout "clean"), skips the skill and proceeds directly to + re_push_queue_fix. On conflict, aborts the rebase and routes to + resolve_queue_merge_conflicts for goal-aware resolution. + + resolve_queue_merge_conflicts: tool: run_skill with: skill_command: "/autoskillit:resolve-merge-conflicts ${{ context.work_dir }} ${{ context.plan_path }} ${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" - step_name: "queue_ejected_fix" + step_name: "resolve_queue_merge_conflicts" capture: conflict_escalation_required: "${{ result.escalation_required }}" on_result: @@ -702,8 +779,7 @@ steps: skip_when_false: "inputs.open_pr" note: > Resolves rebase conflicts on the feature branch after queue ejection. - Uses the clone working directory (context.work_dir) with the feature branch - (context.merge_target) checked out. context.plan_path provides resolution guidance. + Only reached when the cheap rebase in queue_ejected_fix encountered conflicts. escalation_required=true → release_issue_failure for human review. re_push_queue_fix: @@ -713,10 +789,29 @@ steps: remote_url: "${{ context.remote_url }}" branch: "${{ context.merge_target }}" force: "true" - on_success: reenter_merge_queue + on_success: ci_watch_post_queue_fix on_failure: release_issue_failure skip_when_false: "inputs.open_pr" + ci_watch_post_queue_fix: + tool: wait_for_ci + with: + branch: "${{ context.merge_target }}" + event: "${{ context.ci_event }}" + timeout_seconds: 300 + cwd: "${{ context.work_dir }}" + remote_url: "${{ context.remote_url }}" + capture: + ci_conclusion: "${{ result.conclusion }}" + ci_failed_jobs: "${{ result.failed_jobs }}" + on_success: reenter_merge_queue + on_failure: detect_ci_conflict + skip_when_false: "inputs.open_pr" + note: > + Validates CI on the rebased feature branch after queue ejection fix and re-push. + Mirrors ci_watch: routes to reenter_merge_queue on CI pass, to detect_ci_conflict + on CI failure. Prevents re-entering the merge queue with a broken manifest or code. + reenter_merge_queue: tool: run_cmd with: @@ -730,6 +825,20 @@ steps: Re-submits the PR after conflict resolution. Routes back to wait_for_queue. If re-entry fails, release_issue_failure preserves the clone for debugging. + reenter_merge_queue_cheap: + tool: run_cmd + with: + cmd: "gh pr merge '${{ context.pr_number }}' --squash --auto" + cwd: "${{ context.work_dir }}" + step_name: "reenter_merge_queue_cheap" + on_success: wait_for_queue + on_failure: release_issue_failure + skip_when_false: "inputs.open_pr" + note: > + Re-submits a healthy PR into the merge queue after auto_merge was cleared + externally (DROPPED_HEALTHY state). No conflict-resolution CI wait needed. + Routes back to wait_for_queue on success. + direct_merge: tool: run_cmd with: @@ -737,12 +846,12 @@ steps: cwd: "${{ context.work_dir }}" step_name: "direct_merge" on_success: wait_for_direct_merge - on_failure: confirm_cleanup + on_failure: register_clone_success skip_when_false: "inputs.open_pr" note: > Enables GitHub native auto-merge for direct merge (no merge queue). GitHub merges automatically once all required checks pass. On failure (PR already - merged, not mergeable), degrades gracefully to confirm_cleanup. + merged, not mergeable), degrades gracefully to register_clone_success. wait_for_direct_merge: tool: run_cmd @@ -762,7 +871,7 @@ steps: - when: "${{ result.stdout | trim }} == closed" route: direct_merge_conflict_fix - route: release_issue_timeout - on_failure: confirm_cleanup + on_failure: register_clone_success skip_when_false: "inputs.open_pr" note: > Polls GitHub PR state every 10 s for up to 15 minutes. @@ -771,11 +880,32 @@ steps: timeout → release_issue_timeout (releases claim; merge unconfirmed). direct_merge_conflict_fix: + tool: run_cmd + with: + cmd: > + if git fetch origin ${{ inputs.base_branch }} && git rebase origin/${{ inputs.base_branch }}; + then echo 'clean'; + else git rebase --abort 2>/dev/null || true; echo 'conflicts'; + fi + cwd: "${{ context.work_dir }}" + step_name: "direct_merge_conflict_fix" + on_result: + - when: "${{ result.stdout | trim }} == clean" + route: re_push_direct_fix + - route: resolve_direct_merge_conflicts + on_failure: resolve_direct_merge_conflicts + skip_when_false: "inputs.open_pr" + note: > + Attempts a cheap rebase before invoking the full conflict-resolution skill. + On clean rebase, proceeds to re_push_direct_fix. On conflict, routes to + resolve_direct_merge_conflicts for goal-aware resolution. + + resolve_direct_merge_conflicts: tool: run_skill with: skill_command: "/autoskillit:resolve-merge-conflicts ${{ context.work_dir }} ${{ context.plan_path }} ${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" - step_name: "direct_merge_conflict_fix" + step_name: "resolve_direct_merge_conflicts" capture: conflict_escalation_required: "${{ result.escalation_required }}" on_result: @@ -788,7 +918,8 @@ steps: on_exhausted: release_issue_failure skip_when_false: "inputs.open_pr" note: > - Resolves rebase conflicts on the feature branch after direct-merge rejection. + Resolves rebase conflicts after direct-merge rejection. + Only reached when the cheap rebase in direct_merge_conflict_fix encountered conflicts. escalation_required=true → release_issue_failure for human review. re_push_direct_fix: @@ -823,13 +954,13 @@ steps: cwd: "${{ context.work_dir }}" step_name: "immediate_merge" on_success: wait_for_immediate_merge - on_failure: confirm_cleanup + on_failure: register_clone_success skip_when_false: "inputs.open_pr" note: > Merges the PR immediately using plain --squash when autoMergeAllowed=false. Unlike direct_merge, no --auto flag is used — GitHub executes the merge synchronously rather than queueing it for when checks pass. On failure - (conflict or not-mergeable error from GitHub), degrades to confirm_cleanup. + (conflict or not-mergeable error from GitHub), degrades to register_clone_success. wait_for_immediate_merge: tool: run_cmd @@ -860,11 +991,32 @@ steps: timeout → release_issue_timeout. immediate_merge_conflict_fix: + tool: run_cmd + with: + cmd: > + if git fetch origin ${{ inputs.base_branch }} && git rebase origin/${{ inputs.base_branch }}; + then echo 'clean'; + else git rebase --abort 2>/dev/null || true; echo 'conflicts'; + fi + cwd: "${{ context.work_dir }}" + step_name: "immediate_merge_conflict_fix" + on_result: + - when: "${{ result.stdout | trim }} == clean" + route: re_push_immediate_fix + - route: resolve_immediate_merge_conflicts + on_failure: resolve_immediate_merge_conflicts + skip_when_false: "inputs.open_pr" + note: > + Attempts a cheap rebase before invoking the full conflict-resolution skill. + On clean rebase, proceeds to re_push_immediate_fix. On conflict, routes to + resolve_immediate_merge_conflicts for goal-aware resolution. + + resolve_immediate_merge_conflicts: tool: run_skill with: skill_command: "/autoskillit:resolve-merge-conflicts ${{ context.work_dir }} ${{ context.plan_path }} ${{ inputs.base_branch }}" cwd: "${{ context.work_dir }}" - step_name: "immediate_merge_conflict_fix" + step_name: "resolve_immediate_merge_conflicts" capture: conflict_escalation_required: "${{ result.escalation_required }}" on_result: @@ -877,8 +1029,8 @@ steps: on_exhausted: release_issue_failure skip_when_false: "inputs.open_pr" note: > - Resolves rebase conflicts on the feature branch after immediate-merge rejection. - Analogous to direct_merge_conflict_fix. + Resolves rebase conflicts after immediate-merge rejection. + Only reached when the cheap rebase in immediate_merge_conflict_fix encountered conflicts. escalation_required=true → release_issue_failure for human review. re_push_immediate_fix: @@ -909,7 +1061,7 @@ steps: diagnose_ci: tool: run_skill with: - skill_command: "/autoskillit:diagnose-ci ${{ context.merge_target }} - - tests.yml" + skill_command: "/autoskillit:diagnose-ci ${{ context.merge_target }} - - - ${{ context.ci_event }}" cwd: "${{ context.work_dir }}" step_name: "diagnose_ci" ci_failed_jobs: "${{ context.ci_failed_jobs }}" @@ -922,7 +1074,7 @@ steps: skip_when_false: "inputs.open_pr" note: > Runs when ci_watch reports a CI failure. Fetches CI logs via gh API and writes - a structured diagnosis to .autoskillit/temp/diagnose-ci/. Routes to resolve_ci on success + a structured diagnosis to {{AUTOSKILLIT_TEMP}}/diagnose-ci/. Routes to resolve_ci on success OR failure (best-effort: resolve-failures proceeds even without a diagnosis). diagnosis_path is passed to resolve_ci for targeted remediation context. @@ -932,17 +1084,42 @@ steps: skill_command: "/autoskillit:resolve-failures ${{ context.work_dir }} ${{ context.plan_path }} ${{ inputs.base_branch }} ${{ context.ci_conclusion }} ${{ context.ci_failed_jobs }} ${{ context.diagnosis_path }}" cwd: "${{ context.work_dir }}" step_name: "resolve_ci" + capture: + verdict: "${{ result.verdict }}" retries: 2 on_exhausted: release_issue_failure - on_success: re_push + on_context_limit: re_push + on_result: + - when: "${{ result.verdict }} == 'real_fix'" + route: re_push + - when: "${{ result.verdict }} == 'already_green'" + route: pre_resolve_rebase + - when: "${{ result.verdict }} == 'flake_suspected'" + route: release_issue_failure + - when: "${{ result.verdict }} == 'ci_only_failure'" + route: release_issue_failure + - route: release_issue_failure on_failure: release_issue_failure note: > Runs when ci_watch reports a CI failure. Receives ci_failed_jobs from wait_for_ci - structured output to avoid redundant CI failure re-investigation. The clone - (context.work_dir) has the feature branch (context.merge_target) checked out. - The skill commits fixes and exits without merging; the orchestrator re-pushes - via re_push. Retries up to 2 times (3 total attempts) before exhausting - to cleanup_failure. + structured output to avoid redundant CI failure re-investigation. Routes via + on_result: verdict dispatch — real_fix pushes, already_green rebases and re-diagnoses + (sibling fix may have landed), flake_suspected/ci_only_failure escalate to human. + Retries up to 2 times (3 total attempts) before exhausting to release_issue_failure. + + pre_resolve_rebase: + tool: run_cmd + with: + cmd: "git -C ${{ context.work_dir }} fetch origin && git -C ${{ context.work_dir }} rebase origin/${{ inputs.base_branch }}" + step_name: "pre_resolve_rebase" + retries: 1 + on_success: diagnose_ci + on_failure: release_issue_failure + note: > + Rebases the feature branch against integration head when resolve_ci emits + already_green — the worktree was already clean because a sibling pipeline's + fix already landed on integration. Pulling it in before re-running diagnose_ci + gives the pipeline a real chance at emitting real_fix and reaching re_push. re_push: tool: push_to_remote @@ -956,7 +1133,7 @@ steps: note: > Pushes the CI-fixed feature branch back to the remote after resolve_ci succeeds. Routes back to ci_watch to verify the fix resolves CI. On push failure, escalates - via cleanup_failure. + via release_issue_failure. detect_ci_conflict: tool: run_cmd @@ -1006,13 +1183,13 @@ steps: skip_when_false: inputs.issue_url with: issue_url: ${{ inputs.issue_url }} - on_success: check_defer_cleanup - on_failure: check_defer_cleanup + on_success: register_clone_success + on_failure: register_clone_success note: > Called when wait_for_direct_merge times out. Releases the in-progress claim without passing target_branch, so the staged label is not applied. The merge is unconfirmed; a human must verify PR state independently. - Routes to confirm_cleanup so the pipeline completes cleanly. + Routes to register_clone_success so the pipeline completes cleanly. release_issue_success: description: "Transition issue from in-progress to staged after successful pipeline completion" @@ -1022,11 +1199,11 @@ steps: with: issue_url: ${{ inputs.issue_url }} target_branch: ${{ inputs.base_branch }} - on_success: check_defer_cleanup - on_failure: check_defer_cleanup + on_success: register_clone_success + on_failure: register_clone_success note: > Applies staged label after successful PR merge; skipped when no issue_url. - optional=true so cleanup proceeds even if this step errors. + optional=true so registration proceeds even if this step errors. release_issue_failure: description: "Release the in-progress claim after pipeline failure" @@ -1035,90 +1212,28 @@ steps: skip_when_false: inputs.issue_url with: issue_url: ${{ inputs.issue_url }} - on_success: check_defer_on_failure - on_failure: check_defer_on_failure - - check_defer_cleanup: - description: "Route to deferred or immediate cleanup on success path" - tool: run_python - with: - callable: "autoskillit.smoke_utils.check_cleanup_mode" - defer_cleanup: "${{ inputs.defer_cleanup }}" - on_result: - - when: "result.deferred == 'true'" - route: register_success_deferred - - route: confirm_cleanup - on_failure: confirm_cleanup + on_success: register_clone_failure + on_failure: register_clone_failure - register_success_deferred: - description: "Register clone as cleanup candidate (deferred batch cleanup mode)" + register_clone_success: + description: "Register clone as cleanup candidate for batch deletion" tool: register_clone_status with: clone_path: "${{ context.work_dir }}" status: "success" - registry_path: "${{ inputs.registry_path }}" - step_name: register_success_deferred + step_name: register_clone_success on_success: done on_failure: done - check_defer_on_failure: - description: "Route to deferred or immediate cleanup on failure path" - tool: run_python - with: - callable: "autoskillit.smoke_utils.check_cleanup_mode" - defer_cleanup: "${{ inputs.defer_cleanup }}" - on_result: - - when: "result.deferred == 'true'" - route: register_error_deferred - - route: cleanup_failure - on_failure: cleanup_failure - - register_error_deferred: - description: "Register clone as preserved (error pipeline — deferred mode)" + register_clone_failure: + description: "Register clone as preserved (error pipeline)" tool: register_clone_status with: clone_path: "${{ context.work_dir }}" status: "error" - registry_path: "${{ inputs.registry_path }}" - step_name: register_error_deferred - on_success: escalate_stop - on_failure: escalate_stop - - confirm_cleanup: - action: confirm - message: >- - Remediation pipeline succeeded! The clone at ${{ context.work_dir }} is preserved. - Delete it now? Keeping it lets you resume any session from this pipeline run. - Type yes to delete or no to keep. - on_success: delete_clone - on_failure: done - note: >- - User confirmation gate — preserves clone by default. On yes: delete_clone removes it. - On no: done is reached immediately, clone stays on disk. - - delete_clone: - tool: remove_clone - with: - clone_path: "${{ context.work_dir }}" - keep: "false" - step_name: delete_clone - on_success: done - on_failure: done - note: >- - Reached only after user explicitly confirms cleanup. Sync-check hook gates deletion — - removal approved only when branch is pushed. - - cleanup_failure: - tool: remove_clone - with: - clone_path: "${{ context.work_dir }}" - keep: "true" + step_name: register_clone_failure on_success: escalate_stop on_failure: escalate_stop - note: > - Clone preservation step — keep=true means the clone is never - auto-removed on failure. Remove manually: rm -rf {clone_path}. - Always routes to escalate_stop. done: action: stop @@ -1128,24 +1243,3 @@ steps: action: stop message: "Human intervention needed. Review the latest output for details." - batch_confirm_cleanup: - action: confirm - message: >- - All parallel pipelines complete. Delete all registered successful clones? - Error pipeline clones will be preserved for investigation. - Type yes to delete or no to keep all. - note: >- - ORCHESTRATOR: Run this step ONCE after ALL parallel pipeline instances have - reached 'done' or 'escalate_stop'. Do NOT run per-pipeline instance. - Only applicable when run_mode=parallel and defer_cleanup=true. - on_success: batch_delete_clones - on_failure: done - - batch_delete_clones: - description: "Delete all registered successful clones in one batch operation" - tool: batch_cleanup_clones - with: - registry_path: "${{ inputs.registry_path }}" - step_name: batch_delete_clones - on_success: done - on_failure: done diff --git a/src/autoskillit/recipes/research.yaml b/src/autoskillit/recipes/research.yaml new file mode 100644 index 0000000000..6b8a7bef7c --- /dev/null +++ b/src/autoskillit/recipes/research.yaml @@ -0,0 +1,1036 @@ +name: research +autoskillit_version: "0.8.0" +requires_packs: [research, exp-lens, vis-lens] +description: > + Single-phase technical research recipe. Scopes a research question, plans an + experiment, optionally reviews the design, then always decomposes into phases, + implements, runs the experiment, writes a report to research/, and opens a PR. + Supports a skippable design review loop (bounded by retries: 2), review + resolution routing after PR open, and a post-review re-validation loop that + re-runs affected benchmarks when resolve-research-review produces rerun_required + escalations. After the final push (or when review completes), an archival + phase separates research artifacts from experimental code: opens a clean + artifact-only PR, tags the experiment branch, and closes the original PR. + No auto-merge. +summary: scope > plan > [review?] > worktree > decompose > phases > experiment > report > open-pr > [review? > resolve > [re-run?] > push] > archive + +ingredients: + task: + description: Research question or topic to investigate + required: true + issue_url: + description: > + Optional URL to an existing GitHub issue describing the research goal. + Provided as context to scope and plan_experiment. + required: false + source_dir: + description: Path to the project root + required: true + base_branch: + description: Branch to target for the research PR + default: "main" + review_design: + description: > + When 'true' (the default), run the review-design skill after plan_experiment + to validate the experiment plan before execution. Emits a verdict: GO proceeds, + REVISE loops back to plan_experiment with revision guidance (bounded by + retries: 2), STOP triggers resolve_design_review for triage — addressable + findings loop back, structural findings halt the pipeline. When 'false', skip + directly to create_worktree. + default: "true" + review_pr: + description: > + When 'true', run the review-research-pr skill after the research PR + is opened. Posts inline review comments on research quality dimensions + (methodology, reproducibility, report-quality, etc.) and emits a + verdict. Defaults to 'false' — the research PR is for human review. + default: "false" + audit_claims: + required: false + default: "false" + description: > + When 'true', run audit-claims after review_research_pr to verify citation + integrity and claim backing in the research report. Emits a verdict that + routes to resolve-claims-review when changes are needed. + output_mode: + required: false + default: "local" + description: > + Where research outputs land. 'local' (default) produces a self-contained + report.html bundle under {source_dir}/research-bundles/{date-slug}/ with + no GitHub interaction. 'pr' opens a GitHub PR alongside the HTML bundle + and runs the full review/archival flow. + +kitchen_rules: + - > + NEVER use native Claude Code tools from the orchestrator: Read, Grep, Glob, + Edit, Write, Bash, Agent, WebFetch, WebSearch, NotebookEdit are ALL forbidden. + All work is delegated through run_skill, run_cmd, run_python. + - "Do NOT auto-merge. The research PR is for human review only." + - "The research/ folder is the target for all permanent output." + - "Inconclusive results are valid findings, not failures." + - "Route to on_failure when a step fails — do not investigate directly." + - > + DESIGN REVIEW LOOP: review_design validates the plan and may + route back to plan_experiment with revision guidance. Bounded by + retries: 2 (max 3 review cycles). On exhaustion or failure, + proceed to execution with the best available plan — do not stop. + Exception: a STOP verdict triggers resolve_design_review, which triages + each stop-trigger finding as ADDRESSABLE/STRUCTURAL/DISCUSS. If any are + ADDRESSABLE or DISCUSS, revision guidance is generated and the plan loops + back for revision (via revise_design). If all are STRUCTURAL, the pipeline + halts at design_rejected (truly terminal — revision cannot address the flaws). + - > + PHASE ITERATION: decompose_phases always runs. The agent maintains + a phase queue from group_files. For each phase, run plan_phase then + implement_phase. Advance to run_experiment when all phases complete. + - > + PERMANENT ARTIFACTS: create_worktree commits the experiment plan + to research/ and supporting artifacts (scope report, design evaluation) + to research/artifacts/. These are permanent records in the PR. + - > + ARCHIVAL PHASE: After all review and re-validation cycles complete, + the pipeline extracts research/ into a clean artifact PR, tags the full + experiment branch under archive/research/, and closes the original PR. + Every archival step degrades gracefully — failures route to + research_complete without blocking the pipeline. + - > + LOCAL MODE OUTPUT: In local mode, the finalized bundle (report.html, report.md, + artifacts.tar.gz) is exported to {source_dir}/research-bundles/{date-slug}/. + This directory is created only when output_mode=local and is not committed to git. + +steps: + # --- DESIGN PHASE --- + scope: + tool: run_skill + with: + skill_command: "/autoskillit:scope ${{ inputs.task }}" + cwd: "${{ inputs.source_dir }}" + step_name: scope + capture: + scope_report: "${{ result.scope_report }}" + on_success: plan_experiment + on_failure: escalate_stop + + plan_experiment: + tool: run_skill + with: + skill_command: "/autoskillit:plan-experiment ${{ context.scope_report }} ${{ context.revision_guidance }}" + cwd: "${{ inputs.source_dir }}" + step_name: plan_experiment + optional_context_refs: [revision_guidance] + capture: + experiment_plan: "${{ result.experiment_plan }}" + on_success: review_design + on_failure: escalate_stop + + review_design: + tool: run_skill + with: + skill_command: "/autoskillit:review-design ${{ context.experiment_plan }}" + cwd: "${{ inputs.source_dir }}" + step_name: review_design + capture: + verdict: "${{ result.verdict }}" + experiment_type: "${{ result.experiment_type }}" + evaluation_dashboard: "${{ result.evaluation_dashboard }}" + revision_guidance: "${{ result.revision_guidance }}" + skip_when_false: inputs.review_design + retries: 2 + on_exhausted: create_worktree + on_context_limit: create_worktree + on_failure: create_worktree + on_result: + - when: "${{ result.verdict }} == GO" + route: plan_visualization + - when: "${{ result.verdict }} == REVISE" + route: revise_design + - when: "${{ result.verdict }} == STOP" + route: resolve_design_review + - route: create_worktree + + plan_visualization: + tool: run_skill + with: + skill_command: "/autoskillit:plan-visualization ${{ inputs.source_dir }} ${{ context.experiment_plan }} ${{ context.scope_report }}" + cwd: "${{ inputs.source_dir }}" + step_name: plan_visualization + capture: + visualization_plan_path: "${{ result.visualization_plan_path }}" + report_plan_path: "${{ result.report_plan_path }}" + on_success: create_worktree + on_failure: escalate_stop + note: > + Selects 2–4 vis-lens skills via three-tier logic, runs them in parallel, and + synthesizes outputs into visualization-plan.md and report-plan.md. + Runs before worktree creation so outputs can be committed into the research dir. + + revise_design: + action: route + on_result: + - route: plan_experiment + + resolve_design_review: + tool: run_skill + with: + skill_command: "/autoskillit:resolve-design-review ${{ context.evaluation_dashboard }} ${{ context.experiment_plan }} ${{ context.revision_guidance }}" + cwd: "${{ inputs.source_dir }}" + step_name: resolve_design_review + optional_context_refs: [evaluation_dashboard, experiment_plan, revision_guidance] + capture: + revision_guidance: "${{ result.revision_guidance }}" + retries: 1 + on_failure: design_rejected + on_context_limit: design_rejected + on_result: + - when: "${{ result.resolution }} == revised" + route: revise_design + - when: "${{ result.resolution }} == failed" + route: design_rejected + - route: design_rejected + note: > + Triages STOP-verdict findings from review_design. ADDRESSABLE/DISCUSS findings + generate revision_guidance and loop back. Only all-STRUCTURAL findings halt at + design_rejected. + + design_rejected: + action: stop + message: > + Research pipeline halted: experiment design rejected (verdict=STOP, resolution=failed). + All stop-trigger findings are structural — revision cannot address the identified flaws. + Check {{AUTOSKILLIT_TEMP}}/resolve-design-review/ for the triage report and + {{AUTOSKILLIT_TEMP}}/review-design/ for the evaluation dashboard. + + # --- EXECUTION PHASE --- + create_worktree: + tool: run_cmd + with: + cmd: > + BRANCH="research-$(date +%Y%m%d-%H%M%S)" && + WORKTREE_PATH="../worktrees/${BRANCH}" && + git worktree add -b "${BRANCH}" "${WORKTREE_PATH}" && + RESOLVED="$(cd "${WORKTREE_PATH}" && pwd)" && + case "${RESOLVED}" in /*) ;; *) echo "error: resolved worktree path is not absolute: ${RESOLVED}" >&2; exit 1;; esac && + mkdir -p "{{AUTOSKILLIT_TEMP}}/worktrees/${BRANCH}" && + echo "$(git rev-parse --abbrev-ref HEAD)" > "{{AUTOSKILLIT_TEMP}}/worktrees/${BRANCH}/base-branch" && + mkdir -p "${RESOLVED}/{{AUTOSKILLIT_TEMP}}" && + EXPERIMENT_PLAN="${{ context.experiment_plan }}" && + cp "${EXPERIMENT_PLAN}" "${RESOLVED}/{{AUTOSKILLIT_TEMP}}/experiment-plan.md" && + TASK="${{ inputs.task }}" && + SLUG=$(printf '%s' "${TASK}" | tr '[:upper:]' '[:lower:]' | tr -cs 'a-z0-9' '-' | sed 's/--*/-/g;s/^-//;s/-$//' | cut -c1-30) && + RESEARCH_DIR="${RESOLVED}/research/$(date +%Y-%m-%d)-${SLUG:-experiment}" && + mkdir -p "${RESEARCH_DIR}/artifacts" && + cp "${EXPERIMENT_PLAN}" "${RESEARCH_DIR}/experiment-plan.md" && + SCOPE_REPORT="${{ context.scope_report }}" && + EVAL_DASHBOARD="${{ context.evaluation_dashboard }}" && + if [ -n "${SCOPE_REPORT}" ] && [ -f "${SCOPE_REPORT}" ]; then cp "${SCOPE_REPORT}" "${RESEARCH_DIR}/artifacts/scope-report.md"; fi && + if [ -n "${EVAL_DASHBOARD}" ] && [ -f "${EVAL_DASHBOARD}" ]; then cp "${EVAL_DASHBOARD}" "${RESEARCH_DIR}/artifacts/design-evaluation.md"; fi && + VISUALIZATION_PLAN="${{ context.visualization_plan_path }}" && + REPORT_PLAN="${{ context.report_plan_path }}" && + if [ -n "${VISUALIZATION_PLAN}" ] && [ -f "${VISUALIZATION_PLAN}" ]; then cp "${VISUALIZATION_PLAN}" "${RESEARCH_DIR}/visualization-plan.md"; fi && + if [ -n "${REPORT_PLAN}" ] && [ -f "${REPORT_PLAN}" ]; then cp "${REPORT_PLAN}" "${RESEARCH_DIR}/report-plan.md"; fi && + SRC_TEMP="${{ inputs.source_dir }}/{{AUTOSKILLIT_TEMP}}" && + mkdir -p "${RESEARCH_DIR}/artifacts/review-cycles" && + mkdir -p "${RESEARCH_DIR}/artifacts/plan-versions" && + for f in "${SRC_TEMP}"/review-design/evaluation_dashboard_*.md; do [ -f "$f" ] && cp "$f" "${RESEARCH_DIR}/artifacts/review-cycles/"; done; + for f in "${SRC_TEMP}"/review-design/revision_guidance_*.md; do [ -f "$f" ] && cp "$f" "${RESEARCH_DIR}/artifacts/review-cycles/"; done; + for f in "${SRC_TEMP}"/plan-experiment/experiment_plan_*.md; do [ -f "$f" ] && cp "$f" "${RESEARCH_DIR}/artifacts/plan-versions/"; done; + for f in "${SRC_TEMP}"/resolve-design-review/*.md; do [ -f "$f" ] && cp "$f" "${RESEARCH_DIR}/artifacts/review-cycles/"; done; + cd "${RESOLVED}" && git add research/ && git commit -m "Add experiment plan and scope to research/" && + echo "research_dir=${RESEARCH_DIR}" && + echo "worktree_path=${RESOLVED}" + cwd: "${{ inputs.source_dir }}" + step_name: create_worktree + capture: + worktree_path: "${{ result.worktree_path }}" + research_dir: "${{ result.research_dir }}" + on_success: stage_data + on_failure: escalate_stop + note: > + Creates the shared worktree and commits the experiment plan and scope report + to research/ as permanent artifacts. All phases and experiment implementation + share this worktree. + + stage_data: + tool: run_skill + with: + skill_command: "/autoskillit:stage-data ${{ context.experiment_plan }}" + cwd: "${{ context.worktree_path }}" + step_name: stage_data + capture: + verdict: "${{ result.verdict }}" + resource_report: "${{ result.resource_report }}" + on_result: + field: verdict + routes: + PASS: decompose_phases + WARN: decompose_phases + FAIL: escalate_stop + on_failure: escalate_stop + note: > + Pre-flight resource gate. Reads the experiment plan's data_manifest, checks + available disk space and network connectivity for external/gitignored data + entries, and creates the required directory structure in the worktree. PASS + and WARN proceed to decompose_phases. FAIL escalates immediately with a + detailed resource feasibility report rather than wasting compute on doomed + downloads. + + decompose_phases: + tool: run_skill + with: + skill_command: "/autoskillit:make-groups ${{ context.experiment_plan }}" + cwd: "${{ context.worktree_path }}" + step_name: decompose + capture: + group_files: "${{ result.group_files }}" + on_success: plan_phase + on_failure: escalate_stop + note: > + Decomposes the experiment plan into sequenced phases. Each phase + becomes an independently plannable implementation unit. Typical + decomposition: infrastructure/logging -> data generators -> + plotting/analysis scripts -> experiment implementation. + ITERATION: The agent maintains a phase queue from group_files. + For each phase, run plan_phase then implement_phase before advancing. + + plan_phase: + tool: run_skill + with: + skill_command: "/autoskillit:make-plan ${{ context.group_files }}" + cwd: "${{ context.worktree_path }}" + step_name: plan_phase + group_files: "${{ context.group_files }}" + capture: + phase_plan_path: "${{ result.plan_path }}" + capture_list: + plan_parts: "${{ result.plan_parts }}" + on_success: implement_phase + on_failure: escalate_stop + note: > + Plans the current setup phase. Replace ${{ context.group_files }} in the + skill_command with the FIRST REMAINING phase file path from the list — + do NOT pass the entire list. Pass the path directly to the skill (do not read it). + Glob plan_dir for *_part_*.md or single plan file. + ITERATION: After each implement_phase cycle, advance to the next entry in + context.group_files for the following plan_phase iteration. + + implement_phase: + tool: run_skill + stale_threshold: 2400 + idle_output_timeout: 0 + with: + skill_command: "/autoskillit:implement-experiment ${{ context.phase_plan_path }}" + cwd: "${{ context.worktree_path }}" + step_name: implement_phase + capture: + worktree_path: "${{ result.worktree_path }}" + retries: 0 + on_success: next_phase_or_experiment + on_failure: troubleshoot_implement_failure + on_exhausted: run_experiment + on_context_limit: run_experiment + note: > + Implements the current phase plan in an isolated worktree via implement-experiment. + Context exhaustion is a normal termination — the worktree is intact and + run_experiment picks up what was committed. Failures route to troubleshoot + for classification before re-planning or escalation. + + troubleshoot_implement_failure: + tool: run_skill + stale_threshold: 2400 + idle_output_timeout: 0 + with: + skill_command: "/autoskillit:troubleshoot-experiment ${{ context.worktree_path }} implement_phase" + cwd: "${{ inputs.source_dir }}" + step_name: troubleshoot_implement_failure + capture: + is_fixable: "${{ result.is_fixable }}" + on_success: route_implement_failure + on_failure: escalate_stop + + route_implement_failure: + action: route + on_result: + - when: "${{ context.is_fixable }} == true" + route: plan_phase + - route: escalate_stop + + next_phase_or_experiment: + action: route + on_result: + - when: "${{ result.next }} == more_phases" + route: plan_phase + - route: run_experiment + note: > + Routing step. The agent evaluates remaining phases: + 1. If more phases remain in group_files -> route to plan_phase. + 2. If all phases complete -> route to run_experiment. + + # --- EXPERIMENT + REPORT PHASE --- + run_experiment: + tool: run_skill + stale_threshold: 2400 + idle_output_timeout: 0 + with: + skill_command: "/autoskillit:run-experiment ${{ context.worktree_path }}" + cwd: "${{ context.worktree_path }}" + step_name: run_experiment + capture: + experiment_results: "${{ result.results_path }}" + retries: 2 + on_success: generate_report + on_failure: adjust_experiment + on_exhausted: ensure_results + + adjust_experiment: + tool: run_skill + stale_threshold: 2400 + idle_output_timeout: 0 + with: + skill_command: "/autoskillit:run-experiment ${{ context.worktree_path }} --adjust" + cwd: "${{ context.worktree_path }}" + step_name: adjust + capture: + experiment_results: "${{ result.results_path }}" + on_success: run_experiment + on_failure: ensure_results + + ensure_results: + tool: run_cmd + with: + cmd: > + RESULTS="${{ context.experiment_results }}" && + if [ -z "${RESULTS}" ]; then + RESULTS="${{ context.worktree_path }}/{{AUTOSKILLIT_TEMP}}/run-experiment/results-inconclusive.md" && + mkdir -p "$(dirname "${RESULTS}")" && + printf '# Experiment Results\n\n## Status\nINCONCLUSIVE\n\nExperiment did not produce results — retries exhausted or adjustment failed.\n' > "${RESULTS}" + fi && + echo "experiment_results=${RESULTS}" + cwd: "${{ context.worktree_path }}" + step_name: ensure_results + capture: + experiment_results: "${{ result.experiment_results }}" + on_success: generate_report_inconclusive + on_failure: escalate_stop + note: > + Ensures context.experiment_results is a valid file path before calling + generate_report_inconclusive. Creates a minimal placeholder results file when + run-experiment never produced output (retries exhausted or adjust failed). + + generate_report: + tool: run_skill + with: + skill_command: "/autoskillit:generate-report ${{ context.worktree_path }} ${{ context.experiment_results }} --output-mode ${{ inputs.output_mode }} --issue-url ${{ inputs.issue_url }}" + cwd: "${{ context.worktree_path }}" + step_name: generate_report + capture: + report_path: "${{ result.report_path }}" + on_success: test + on_failure: escalate_stop + on_context_limit: test + note: "Writes a conclusive research report to research/ in the worktree." + + generate_report_inconclusive: + tool: run_skill + with: + skill_command: "/autoskillit:generate-report ${{ context.worktree_path }} ${{ context.experiment_results }} --inconclusive --output-mode ${{ inputs.output_mode }} --issue-url ${{ inputs.issue_url }}" + cwd: "${{ context.worktree_path }}" + step_name: generate_report + capture: + report_path: "${{ result.report_path }}" + on_success: test + on_failure: escalate_stop + on_context_limit: test + note: > + Writes an inconclusive research report. Experiments could not + prove or disprove the hypothesis. This is a valid outcome. + + test: + tool: test_check + with: + worktree_path: "${{ context.worktree_path }}" + on_success: push_branch + on_failure: fix_tests + + fix_tests: + tool: run_skill + with: + skill_command: "/autoskillit:resolve-failures ${{ context.worktree_path }} ${{ context.experiment_plan }} ${{ inputs.base_branch }}" + cwd: "${{ inputs.source_dir }}" + step_name: fix + capture: + verdict: "${{ result.verdict }}" + fixes_applied: "${{ result.fixes_applied }}" + on_result: + - when: "${{ result.verdict }} == 'real_fix'" + route: retest + - when: "${{ result.verdict }} == 'already_green'" + route: retest + - when: "${{ result.verdict }} == 'flake_suspected'" + route: retest + - when: "${{ result.verdict }} == 'ci_only_failure'" + route: escalate_stop + on_failure: escalate_stop + on_context_limit: retest + + retest: + tool: test_check + with: + worktree_path: "${{ context.worktree_path }}" + on_success: push_branch + on_failure: escalate_stop + + push_branch: + tool: run_cmd + with: + cmd: "cd '${{ context.worktree_path }}' && git push -u origin HEAD" + cwd: "${{ context.worktree_path }}" + step_name: push_branch + on_success: prepare_research_pr + on_failure: escalate_stop + + # --- PR + REVIEW PHASE --- + prepare_research_pr: + tool: run_skill + with: + skill_command: "/autoskillit:prepare-research-pr ${{ context.report_path }} ${{ context.experiment_plan }} ${{ context.worktree_path }} ${{ inputs.base_branch }}" + cwd: "${{ context.worktree_path }}" + step_name: prepare_research_pr + capture: + prep_path: "${{ result.prep_path }}" + selected_lenses: "${{ result.selected_lenses }}" + lens_context_paths: "${{ result.lens_context_paths }}" + on_success: run_experiment_lenses + on_failure: escalate_stop + + run_experiment_lenses: + tool: run_skill + with: + skill_command: "/autoskillit:exp-lens-{slug} {context_path} ${{ context.experiment_plan }}" + cwd: "${{ context.worktree_path }}" + step_name: run_experiment_lenses + capture_list: + all_diagram_paths: "${{ result.diagram_path }}" + on_success: stage_bundle + on_failure: stage_bundle + note: > + LENS ITERATION: context.selected_lenses contains comma-separated lens slugs + (e.g. "fair-comparison,estimand-clarity"). context.lens_context_paths contains + the corresponding comma-separated context file paths. For each lens slug, run: + /autoskillit:exp-lens-{slug} {matching_context_path} ${{ context.experiment_plan }} + Run all selected lenses in parallel (multiple run_skill calls in a single + assistant message). Accumulate each diagram_path value into context.all_diagram_paths + using comma separation via capture_list. If a lens fails, continue with remaining + lenses — partial diagrams are acceptable (compose_research_pr handles empty lists). + + stage_bundle: + tool: run_cmd + with: + cmd: > + RESEARCH_DIR="${{ context.research_dir }}" && + if [ -n "${RESEARCH_DIR}" ] && [ -d "${RESEARCH_DIR}" ]; then + WT_TEMP="${{ context.worktree_path }}/{{AUTOSKILLIT_TEMP}}" && + mkdir -p "${RESEARCH_DIR}/artifacts/phase-groups" && + mkdir -p "${RESEARCH_DIR}/artifacts/phase-plans" && + mkdir -p "${RESEARCH_DIR}/artifacts/images" && + mkdir -p "${RESEARCH_DIR}/artifacts/scripts" && + for f in "${WT_TEMP}"/make-groups/*.md; do [ -f "$f" ] && cp "$f" "${RESEARCH_DIR}/artifacts/phase-groups/"; done && + for f in "${WT_TEMP}"/make-groups/*.yaml; do [ -f "$f" ] && cp "$f" "${RESEARCH_DIR}/artifacts/phase-groups/"; done && + for f in "${WT_TEMP}"/make-plan/*.md; do [ -f "$f" ] && cp "$f" "${RESEARCH_DIR}/artifacts/phase-plans/"; done && + for f in "${WT_TEMP}"/exp-lens-*/*.md; do [ -f "$f" ] && cp "$f" "${RESEARCH_DIR}/artifacts/images/"; done && + echo "stage_bundle=done"; + else + echo "stage_bundle: no research directory found — skipped"; + fi + cwd: "${{ context.worktree_path }}" + step_name: stage_bundle + on_success: route_pr_or_local + on_failure: route_pr_or_local + note: > + Idempotent file staging step. Copies phase-group, phase-plan, and exp-lens diagram + artifacts from the worktree temp directory into research/{slug}/artifacts/. Creates + images/ and scripts/ subdirectories. No compression, no rename, no commit. Safe to + run multiple times — cp overwrites are idempotent. Runs after run_experiment_lenses + to capture all exp-lens diagrams written to AUTOSKILLIT_TEMP/exp-lens-*/. + + route_pr_or_local: + action: route + on_result: + - when: "${{ inputs.output_mode }} == local" + route: finalize_bundle + - route: compose_research_pr + note: > + Branches on output_mode after bundle staging. local → bypass PR pipeline entirely, + jump to finalize_bundle. pr (fall-through) → compose_research_pr to open PR and run + the full review/archival flow. Uses predicate route because skip_when_false only + accepts bare inputs. with no expression evaluation. + + compose_research_pr: + tool: run_skill + with: + skill_command: "/autoskillit:compose-research-pr ${{ context.prep_path }} \"${{ context.all_diagram_paths }}\" ${{ context.worktree_path }} ${{ inputs.base_branch }}" + cwd: "${{ context.worktree_path }}" + step_name: compose_research_pr + capture: + pr_url: "${{ result.pr_url }}" + on_success: guard_pr_url + on_failure: escalate_stop + + guard_pr_url: + action: route + on_result: + - when: "${{ context.pr_url }}" + route: review_research_pr + - route: research_complete + note: Guard — skip review if pr_url is empty (graceful degradation from open_research_pr). + + review_research_pr: + tool: run_skill + with: + skill_command: "/autoskillit:review-research-pr ${{ context.worktree_path }} ${{ inputs.base_branch }} ${{ context.pr_url }}" + cwd: "${{ context.worktree_path }}" + step_name: review_research_pr + capture: + review_verdict: "${{ result.verdict }}" + skip_when_false: inputs.review_pr + on_context_limit: audit_claims + on_failure: audit_claims + on_result: + - route: audit_claims + note: > + Optional research PR review step, gated by the review_pr ingredient. + Verdict captured as review_verdict for deferred routing. All paths + (skip, success, failure, context-limit) route to audit_claims so both + gates complete before any resolution step begins. When on_context_limit + or on_failure fires, the capture block does not execute and + context.review_verdict remains absent; the recipe engine treats absent + context variables as empty string in comparisons, so downstream + route_review_resolve safely falls through to route_claims_resolve. + + audit_claims: + tool: run_skill + with: + skill_command: "/autoskillit:audit-claims ${{ context.worktree_path }} ${{ inputs.base_branch }} ${{ context.pr_url }}" + cwd: "${{ context.worktree_path }}" + step_name: audit_claims + capture: + audit_verdict: "${{ result.verdict }}" + skip_when_false: inputs.audit_claims + retries: 1 + on_exhausted: route_review_resolve + on_context_limit: route_review_resolve + on_failure: route_review_resolve + on_result: + - route: route_review_resolve + note: > + Optional citation-integrity gate, gated by the audit_claims ingredient. + Runs after review_research_pr regardless of that step's verdict. + All paths (skip, success, failure) route to route_review_resolve so both + gates complete before resolution. + + route_review_resolve: + action: route + on_result: + - when: "${{ context.review_verdict }} == changes_requested" + route: resolve_research_review + - route: route_claims_resolve + note: > + Routes to resolve_research_review only when the PR review found + changes_requested. All other verdicts (approved, needs_human, empty/skipped) + proceed directly to route_claims_resolve. + + resolve_research_review: + tool: run_skill + with: + skill_command: "/autoskillit:resolve-research-review ${{ context.worktree_path }} ${{ inputs.base_branch }}" + cwd: "${{ context.worktree_path }}" + step_name: resolve_research_review + capture: + review_needs_rerun: "${{ result.needs_rerun }}" + retries: 2 + on_exhausted: route_claims_resolve + on_context_limit: route_claims_resolve + on_success: route_claims_resolve + on_failure: route_claims_resolve + + route_claims_resolve: + action: route + on_result: + - when: "${{ context.audit_verdict }} == changes_requested" + route: resolve_claims_review + - route: merge_escalations + note: > + Routes to resolve_claims_review only when the claims audit found + changes_requested. All other verdicts (approved, needs_human, empty/skipped) + proceed directly to merge_escalations. When audit_claims is skipped + (inputs.audit_claims=false), context.audit_verdict is absent; the recipe + engine treats absent variables as empty string, so the condition evaluates + false and the fallback route to merge_escalations fires safely. + + resolve_claims_review: + tool: run_skill + with: + skill_command: "/autoskillit:resolve-claims-review ${{ context.worktree_path }} ${{ inputs.base_branch }}" + cwd: "${{ context.worktree_path }}" + step_name: resolve_claims_review + capture: + claims_needs_rerun: "${{ result.needs_rerun }}" + retries: 2 + on_exhausted: merge_escalations + on_context_limit: merge_escalations + on_success: merge_escalations + on_failure: merge_escalations + + merge_escalations: + action: route + on_result: + - when: "${{ context.review_needs_rerun }} == true" + route: re_run_experiment + - when: "${{ context.claims_needs_rerun }} == true" + route: re_run_experiment + - route: re_push_research + note: > + Merged escalation consumer replacing check_escalations. Triggers a single + re_run_experiment if either review resolution or claims resolution flagged + a rerun. When only design_flaw escalations exist (or none), routes directly + to push — design_flaw escalations are already posted as inline PR comments + by the resolve skills. Both context.review_needs_rerun and + context.claims_needs_rerun may be absent if their respective resolution + steps were never reached (e.g., no changes_requested verdict on that gate); + the recipe engine evaluates absent context variables as empty string, so + absent == true is always false and routes safely fall through to + re_push_research. + + re_run_experiment: + tool: run_skill + stale_threshold: 2400 + idle_output_timeout: 0 + with: + skill_command: "/autoskillit:run-experiment ${{ context.worktree_path }} --adjust" + cwd: "${{ context.worktree_path }}" + step_name: re_run_experiment + capture: + experiment_results: "${{ result.results_path }}" + on_success: re_generate_report + on_failure: re_push_research + on_context_limit: re_push_research + note: > + Targeted re-run of affected benchmarks after review resolution applied + code fixes. Uses --adjust to read previous results and re-run only what + changed. Captures the updated results_path so re_generate_report uses the + new results. on_failure falls through to push as best-effort — the code + fixes from resolve are already committed and should still be pushed. + + re_generate_report: + tool: run_skill + with: + skill_command: "/autoskillit:generate-report ${{ context.worktree_path }} ${{ context.experiment_results }} --output-mode ${{ inputs.output_mode }} --issue-url ${{ inputs.issue_url }}" + cwd: "${{ context.worktree_path }}" + step_name: re_generate_report + capture: + report_path: "${{ result.report_path }}" + on_success: re_stage_bundle + on_failure: re_push_research + on_context_limit: re_push_research + note: > + Re-generate the research report with updated benchmark results from the + re-validation run. Passes context.experiment_results which was updated + by re_run_experiment to point to the new results file. Falls through to + push on failure. + + re_stage_bundle: + tool: run_cmd + with: + cmd: > + RESEARCH_DIR="${{ context.research_dir }}" && + if [ -n "${RESEARCH_DIR}" ] && [ -d "${RESEARCH_DIR}" ]; then + WT_TEMP="${{ context.worktree_path }}/{{AUTOSKILLIT_TEMP}}" && + mkdir -p "${RESEARCH_DIR}/artifacts/phase-groups" && + mkdir -p "${RESEARCH_DIR}/artifacts/phase-plans" && + mkdir -p "${RESEARCH_DIR}/artifacts/images" && + mkdir -p "${RESEARCH_DIR}/artifacts/scripts" && + for f in "${WT_TEMP}"/make-groups/*.md; do [ -f "$f" ] && cp "$f" "${RESEARCH_DIR}/artifacts/phase-groups/"; done && + for f in "${WT_TEMP}"/make-groups/*.yaml; do [ -f "$f" ] && cp "$f" "${RESEARCH_DIR}/artifacts/phase-groups/"; done && + for f in "${WT_TEMP}"/make-plan/*.md; do [ -f "$f" ] && cp "$f" "${RESEARCH_DIR}/artifacts/phase-plans/"; done && + for f in "${WT_TEMP}"/exp-lens-*/*.md; do [ -f "$f" ] && cp "$f" "${RESEARCH_DIR}/artifacts/images/"; done && + echo "re_stage_bundle=done"; + else + echo "re_stage_bundle: no research directory found — skipped"; + fi + cwd: "${{ context.worktree_path }}" + step_name: re_stage_bundle + on_success: re_test + on_failure: re_push_research + note: > + Idempotent re-staging after report rewrite. Same body as stage_bundle — updates + artifact directory with any newly written phase artifacts before re-testing. Falls + through to re_push_research on failure (best-effort). + + re_test: + tool: test_check + with: + worktree_path: "${{ context.worktree_path }}" + on_success: re_push_research + on_failure: re_push_research + note: > + Post-revalidation test gate. Both pass and fail route to push — + the re-validation results should be pushed regardless so the PR + reflects the current state of the code and measurements. + + re_push_research: + tool: run_cmd + with: + cmd: "cd '${{ context.worktree_path }}' && git push" + cwd: "${{ context.worktree_path }}" + step_name: re_push_research + on_success: finalize_bundle + on_failure: begin_archival + + # --- ARCHIVAL PHASE --- + finalize_bundle: + tool: run_cmd + with: + cmd: > + OUTPUT_MODE="${{ inputs.output_mode }}" && + RESEARCH_DIR="${{ context.research_dir }}" && + if [ -n "${RESEARCH_DIR}" ] && [ -d "${RESEARCH_DIR}" ]; then + if [ "${OUTPUT_MODE}" != "local" ]; then + if [ -f "${RESEARCH_DIR}/report.md" ]; then + cp "${RESEARCH_DIR}/report.md" "${RESEARCH_DIR}/README.md" && + rm "${RESEARCH_DIR}/report.md"; + fi; + fi && + REPORT_FILE=$( [ "${OUTPUT_MODE}" = "local" ] && echo "report.md" || echo "README.md" ) && + if [ "${OUTPUT_MODE}" = "local" ]; then + EXCLUDE_PATTERN='^(report\.html|mermaid\.min\.js|images|report\.md|artifacts\.tar\.gz)$'; + else + EXCLUDE_PATTERN='^(README\.md|artifacts\.tar\.gz)$'; + fi && + mapfile -t TAR_ITEMS < <(ls -1 "${RESEARCH_DIR}" | grep -vE "${EXCLUDE_PATTERN}") && + if [ ${#TAR_ITEMS[@]} -gt 0 ]; then + tar czf "${RESEARCH_DIR}/artifacts.tar.gz" -C "${RESEARCH_DIR}" "${TAR_ITEMS[@]}" && + for item in "${TAR_ITEMS[@]}"; do rm -rf "${RESEARCH_DIR}/${item}"; done; + fi && + if [ -f "${RESEARCH_DIR}/artifacts.tar.gz" ] && [ -f "${RESEARCH_DIR}/${REPORT_FILE}" ]; then + MANIFEST=$(tar tzf "${RESEARCH_DIR}/artifacts.tar.gz" | sort) && + { echo ""; echo "## Archive Manifest"; echo ""; echo "Contents of \`artifacts.tar.gz\`:"; echo ""; echo '```'; echo "${MANIFEST}"; echo '```'; } >> "${RESEARCH_DIR}/${REPORT_FILE}"; + fi && + [ -f "${RESEARCH_DIR}/artifacts.tar.gz" ] || \ + { echo "ERROR: artifacts.tar.gz not created in ${RESEARCH_DIR}"; exit 1; } && + if [ "${OUTPUT_MODE}" = "local" ]; then + LEFTOVER_PATTERN='^(report\.md|report\.html|mermaid\.min\.js|images|artifacts\.tar\.gz)$'; + else + LEFTOVER_PATTERN='^(README\.md|artifacts\.tar\.gz)$'; + fi && + LEFTOVERS=$(ls -1 "${RESEARCH_DIR}" | grep -vE "${LEFTOVER_PATTERN}") && + [ -z "${LEFTOVERS}" ] || \ + { echo "ERROR: uncompressed entries still present in ${RESEARCH_DIR}: ${LEFTOVERS}"; exit 1; } && + [ -f "${RESEARCH_DIR}/${REPORT_FILE}" ] || \ + { echo "ERROR: ${REPORT_FILE} not found in ${RESEARCH_DIR}"; exit 1; } && + if [ "${OUTPUT_MODE}" != "local" ]; then + cd "${{ context.worktree_path }}" && git add "${RESEARCH_DIR}" && { git diff --cached --quiet || git commit -m "Add compressed research artifacts"; }; + fi; + echo "report_path=${RESEARCH_DIR}/${REPORT_FILE}"; + echo "report_path_after_finalize=${RESEARCH_DIR}/${REPORT_FILE}"; + else + echo "finalize_bundle: no research directory found — artifact commit skipped"; + fi + cwd: "${{ context.worktree_path }}" + step_name: finalize_bundle + capture: + report_path_after_finalize: "${{ result.report_path_after_finalize }}" + on_success: finalize_bundle_render + on_failure: begin_archival + note: > + Single compression point. Runs exactly once per recipe run. In pr mode: renames + report.md → README.md, archives supporting artifacts, appends Archive Manifest, + commits. In local mode: keeps report.md, excludes report.html/mermaid.min.js/images + from the tar (they stay for local browsing), skips git commit. finalize_bundle_render + always runs after this step regardless of mode. + + finalize_bundle_render: + tool: run_skill + with: + skill_command: "/autoskillit:bundle-local-report ${{ context.research_dir }} ${{ context.report_path_after_finalize }} ${{ context.all_diagram_paths }} ${{ context.visualization_plan_path }}" + cwd: "${{ context.worktree_path }}" + step_name: finalize_bundle_render + capture: + html_path: "${{ result.html_path }}" + on_success: route_archive_or_export + on_failure: route_archive_or_export + note: > + HTML report rendering. Always runs after finalize_bundle on_success. Non-fatal: + routes to route_archive_or_export on both outcomes, which branches on output_mode + to either export_local_bundle (local) or begin_archival (pr). + + route_archive_or_export: + action: route + on_result: + - when: "${{ inputs.output_mode }} == local" + route: export_local_bundle + - route: begin_archival + note: > + Branches after HTML bundle rendering. local → export_local_bundle (copy to + {source_dir}/research-bundles/). pr (fall-through) → begin_archival to run + the existing archival phase. + + export_local_bundle: + tool: run_cmd + with: + cmd: > + LOCAL_ROOT="${{ inputs.source_dir }}/research-bundles" && + mkdir -p "${LOCAL_ROOT}" && + SLUG=$(basename "${{ context.research_dir }}") && + DEST="${LOCAL_ROOT}/${SLUG}" && + rm -rf "${DEST}" && + cp -a "${{ context.research_dir }}/." "${DEST}/" && + echo "local_bundle_path=${DEST}" + cwd: "${{ context.worktree_path }}" + step_name: export_local_bundle + capture: + local_bundle_path: "${{ result.local_bundle_path }}" + on_success: research_complete + on_failure: research_complete + note: > + Local mode terminal export. Copies the finalized research_dir (containing + report.html, mermaid.min.js, images/, report.md, artifacts.tar.gz) to + {source_dir}/research-bundles/{slug}/. Non-fatal — routes to research_complete + on both outcomes. The captured local_bundle_path is available to the orchestrator + via research_complete. + + begin_archival: + action: route + on_result: + - when: "${{ context.pr_url }}" + route: capture_experiment_branch + - route: research_complete + note: > + Gate step for the archival phase. Routes to artifact extraction when + a research PR exists, otherwise skips directly to completion. All paths + from review/resolve/re-push converge here. + + capture_experiment_branch: + tool: run_cmd + with: + cmd: "git -C '${{ context.worktree_path }}' rev-parse --abbrev-ref HEAD" + cwd: "${{ context.worktree_path }}" + step_name: capture_experiment_branch + capture: + experiment_branch: "${{ result.stdout | trim }}" + on_success: create_artifact_branch + on_failure: research_complete + + create_artifact_branch: + tool: run_cmd + with: + cmd: > + EXPERIMENT_BRANCH="${{ context.experiment_branch }}" && + SLUG=$(printf '%s' "${EXPERIMENT_BRANCH}" | sed 's/^research-//') && + ARTIFACT_BRANCH="research-artifacts-${SLUG}" && + ARTIFACT_DIR="$(mktemp -d)" && + trap 'git -C "${{ context.worktree_path }}" worktree remove "${ARTIFACT_DIR}" --force 2>/dev/null; rm -rf "${ARTIFACT_DIR}"' EXIT && + git -C '${{ context.worktree_path }}' fetch origin '${{ inputs.base_branch }}' && + (git -C '${{ context.worktree_path }}' branch -D "${ARTIFACT_BRANCH}" 2>/dev/null || true) && + git -C '${{ context.worktree_path }}' worktree add "${ARTIFACT_DIR}" -b "${ARTIFACT_BRANCH}" "origin/${{ inputs.base_branch }}" && + RESEARCH_SUBDIR="research/$(basename "${{ context.research_dir }}")" && + git -C "${ARTIFACT_DIR}" checkout "${EXPERIMENT_BRANCH}" -- "${RESEARCH_SUBDIR}" && + cd "${ARTIFACT_DIR}" && + git add research/ && + git commit -m "Add research artifacts: ${SLUG}" && + git push -u origin "${ARTIFACT_BRANCH}" && + cd - > /dev/null && + git -C '${{ context.worktree_path }}' worktree remove "${ARTIFACT_DIR}" --force && + echo "artifact_branch=${ARTIFACT_BRANCH}" + cwd: "${{ context.worktree_path }}" + step_name: create_artifact_branch + capture: + artifact_branch: "${{ result.artifact_branch }}" + on_success: open_artifact_pr + on_failure: research_complete + note: > + Creates a temporary worktree from the base branch, checks out only the + research/ directory from the experiment branch, commits and pushes, then + removes the temporary worktree. Produces a single clean commit with zero + production code changes. + + open_artifact_pr: + tool: run_cmd + with: + cmd: > + EXPERIMENT="${{ context.experiment_branch }}" && + ARTIFACT="${{ context.artifact_branch }}" && + ORIG_PR="${{ context.pr_url }}" && + RESEARCH_SUBDIR="research/$(basename "${{ context.research_dir }}")" && + ARTIFACT_DIR="${{ context.worktree_path }}" && + if [ -f "${ARTIFACT_DIR}/${RESEARCH_SUBDIR}/artifacts.tar.gz" ]; then + STRUCT_DETAIL=$'- `artifacts.tar.gz` \xe2\x80\x94 compressed artifact tree\n\nExtract:\n```bash\ntar xzf artifacts.tar.gz\n```'; + else + STRUCT_DETAIL="- \`artifacts/\` — uncompressed artifact tree"; + fi && + PR_BODY=$(printf '## Research Artifacts\n\nFrom experiment branch `%s`.\n\nOriginal experiment PR: %s\n\n### Structure\n\n- **README.md** — Research conclusions (browsable on GitHub)\n%s\n\nContains only files under `research/` — zero production code changes.' "${EXPERIMENT}" "${ORIG_PR}" "${STRUCT_DETAIL}") && + PR_URL=$(gh pr create + --head "${ARTIFACT}" + --base '${{ inputs.base_branch }}' + --title "Research artifacts: ${EXPERIMENT}" + --body "${PR_BODY}") && + echo "artifact_pr_url=${PR_URL}" + cwd: "${{ context.worktree_path }}" + step_name: open_artifact_pr + capture: + artifact_pr_url: "${{ result.artifact_pr_url }}" + on_success: tag_experiment_branch + on_failure: research_complete + note: > + Opens a PR containing only the research/ directory. The PR body documents + the two-file structure (README.md + artifacts.tar.gz) and provides the + extraction command. This PR is safe to merge — no production code. + + tag_experiment_branch: + tool: run_cmd + with: + cmd: > + TAG="archive/research/${{ context.experiment_branch }}" && + ARTIFACT_PR="${{ context.artifact_pr_url }}" && + git -C '${{ context.worktree_path }}' tag -a "${TAG}" '${{ context.experiment_branch }}' + -m "Research experiment: ${{ context.experiment_branch }}. Report merged via artifact PR ${ARTIFACT_PR}. Variant code preserved here for reference." && + git -C '${{ context.worktree_path }}' push origin "${TAG}" && + echo "archive_tag=${TAG}" + cwd: "${{ context.worktree_path }}" + step_name: tag_experiment_branch + capture: + archive_tag: "${{ result.archive_tag }}" + on_success: close_experiment_pr + on_failure: research_complete + note: > + Creates an annotated tag preserving the full experiment branch (including + all variant code, benchmark scaffolding, etc.) under archive/research/. + Pushed to remote before any branch cleanup can occur. + + close_experiment_pr: + tool: run_cmd + with: + cmd: > + ARTIFACT_PR="${{ context.artifact_pr_url }}" && + ARCHIVE_TAG="${{ context.archive_tag }}" && + CLOSE_BODY=$(printf '## Archived\n\nThis PR contained both research artifacts and experimental code.\n\n**Research record merged via:** %s\n**Full experiment branch preserved at:** `%s`\n\nThe artifact PR contains only files under `research/` (reports, scripts, results). The archive tag preserves the full experiment branch including variant code for reference.\n\nTo restore the full experiment: `git checkout %s`' "${ARTIFACT_PR}" "${ARCHIVE_TAG}" "${ARCHIVE_TAG}") && + gh pr close '${{ context.pr_url }}' --comment "${CLOSE_BODY}" + cwd: "${{ context.worktree_path }}" + step_name: close_experiment_pr + on_success: research_complete + on_failure: research_complete + note: > + Closes the original experiment PR with a structured comment linking to + the artifact PR (where research/ was merged) and the archive tag (where + the full experiment branch is preserved). Both success and failure route + to research_complete — closing the PR is best-effort. + + research_complete: + action: stop + message: > + Research complete. pr mode: report added to research/ folder and PR opened for + review. local mode: bundle exported to {source_dir}/research-bundles/{slug}/ + (context.local_bundle_path). + + escalate_stop: + action: stop + message: "Research pipeline failed — human intervention needed. Check the latest step output for details." diff --git a/src/autoskillit/recipes/smoke-test.yaml b/src/autoskillit/recipes/smoke-test.yaml deleted file mode 100644 index 747d6b2324..0000000000 --- a/src/autoskillit/recipes/smoke-test.yaml +++ /dev/null @@ -1,255 +0,0 @@ -name: smoke-test -autoskillit_version: "0.3.0" -description: End-to-end smoke test exercising the full orchestration path — script loading, step routing, tool dispatch, capture/context threading, retry logic, bugfix loop, and merge. -summary: setup > seed_task > set_feature_branch > create_branch? > investigate > rectify > implement > set_worktree_path > test > merge > check_summary > create_summary? > done (assess/classify loop on failure) - -ingredients: - workspace: - description: Git repo workspace directory - required: true - base_branch: - description: Merge target - default: main - collect_on_branch: - description: Collect fixes on feature branch - default: "true" - original_base_branch: - description: Original base branch for PR target - default: "main" - -kitchen_rules: - - "NEVER use native Claude Code tools (Read, Grep, Glob, Edit, Write, - Bash, Agent, WebFetch, WebSearch, NotebookEdit) from the - orchestrator. All work is delegated through run_skill." - - "Route to on_failure — never investigate or fix directly from the orchestrator." - -steps: - setup: - tool: run_cmd - with: - cmd: "git init -b main && git commit --allow-empty -m 'initial' && touch .autoskillit-workspace" - cwd: "${{ inputs.workspace }}" - step_name: "setup" - on_success: setup_remote - on_failure: escalate - - setup_remote: - tool: run_cmd - with: - cmd: >- - REMOTE="${{ inputs.workspace }}-bare.git" && - git init --bare "$REMOTE" && - git remote add origin "$REMOTE" && - printf '%s' "$REMOTE" - cwd: "${{ inputs.workspace }}" - step_name: "setup_remote" - capture: - remote_url: "${{ result.stdout }}" - on_success: seed_task - on_failure: escalate - note: > - Creates a bare git repo as a local remote and configures origin. - Captures remote_url for use by push_feature_branch. - - seed_task: - tool: run_cmd - with: - cmd: "echo 'Create ok.txt with content OK' > task.txt" - cwd: "${{ inputs.workspace }}" - step_name: "seed_task" - on_success: set_feature_branch - on_failure: escalate - - set_feature_branch: - tool: run_cmd - with: - cmd: "printf '%s' '${{ inputs.base_branch }}'" - cwd: "${{ inputs.workspace }}" - step_name: "set_feature_branch" - capture: - feature_branch: "${{ result.stdout }}" - on_success: create_branch - on_failure: escalate - note: > - Unconditionally sets feature_branch to inputs.base_branch as the default. - When collect_on_branch=true, the subsequent create_branch step overrides - feature_branch by capturing the newly-created branch name. When - collect_on_branch=false, create_branch is skipped and this default stands. - This eliminates the undefined-context-variable gap in the merge step. - - create_branch: - tool: run_cmd - with: - cmd: >- - BRANCH="autoskillit-smoke-$(date +%s)" && - git checkout -b "$BRANCH" && - echo '[]' > bug_report.json && - printf '%s' "$BRANCH" - cwd: ${{ inputs.workspace }} - step_name: "create_branch" - capture: - feature_branch: "${{ result.stdout }}" - on_success: investigate - on_failure: escalate - optional: true - skip_when_false: "inputs.collect_on_branch" - note: > - Only execute if inputs.collect_on_branch is 'true'. Otherwise skip to investigate. - Creates the feature branch, initialises bug_report.json, and overrides - context.feature_branch (set to inputs.base_branch by set_feature_branch) with - the newly-created branch name for use by the merge step. - - investigate: - tool: run_skill - with: - skill_command: "/autoskillit:smoke-task Create investigation.txt in the current directory with the text 'No critical issues found.' Then output exactly this line on its own: investigation_path=investigation.txt" - cwd: "${{ inputs.workspace }}" - on_success: rectify - on_failure: escalate - - rectify: - tool: run_skill - with: - skill_command: "/autoskillit:smoke-task Create plan.md in the current directory at ${{ inputs.workspace }}/plan.md. The file MUST have this exact first line: Dry-walkthrough verified = TRUE followed by a blank line, then # Plan and Create ok.txt with content OK." - cwd: "${{ inputs.workspace }}" - on_success: implement - on_failure: escalate - - implement: - tool: run_skill - with: - skill_command: "/autoskillit:smoke-task In the git repo at ${{ inputs.workspace }}, run: git worktree add ${{ inputs.workspace }}/.claude/worktrees/smoke-impl -b smoke-impl. Then in that worktree directory, write ok.txt with content OK. Run git add ok.txt && git commit -m 'smoke: add ok.txt'." - cwd: "${{ inputs.workspace }}" - retries: 2 - on_success: set_worktree_path - on_failure: escalate - - set_worktree_path: - tool: run_cmd - with: - cmd: "printf '%s' '${{ inputs.workspace }}/.claude/worktrees/smoke-impl'" - cwd: "${{ inputs.workspace }}" - step_name: "set_worktree_path" - capture: - worktree_path: "${{ result.stdout }}" - on_success: test - on_failure: escalate - - test: - tool: test_check - with: - worktree_path: "${{ context.worktree_path }}" - on_success: push_feature_branch - on_failure: assess - - push_feature_branch: - tool: push_to_remote - with: - clone_path: "${{ inputs.workspace }}" - remote_url: "${{ context.remote_url }}" - branch: "${{ context.feature_branch }}" - on_success: merge - on_failure: escalate - optional: true - skip_when_false: "inputs.collect_on_branch" - note: > - Only execute if collect_on_branch is 'true'. - Publishes the feature branch to the local bare remote before merge_worktree. - merge_worktree requires the base_branch ref to exist on the remote. - - assess: - tool: run_skill - with: - skill_command: "/autoskillit:smoke-task In the git worktree at ${{ context.worktree_path }}, check what file is expected by the test and create/fix it. Commit any changes. After fixing, append a JSON object to ${{ inputs.workspace }}/bug_report.json with keys: step (string 'test'), error (what failed), fix (what you did), iteration (number). The file contains a JSON array — read it, append your entry, write it back. Then output: fixed=true" - cwd: "${{ context.worktree_path }}" - retries: 2 - on_success: test - on_failure: classify - on_exhausted: classify - - classify: - tool: classify_fix - with: - worktree_path: "${{ context.worktree_path }}" - base_branch: "${{ inputs.base_branch }}" - on_result: - - when: "${{ result.restart_scope }} == full_restart" - route: investigate - - when: "result.error" - route: escalate - - route: implement - on_failure: escalate - - commit_dirty: - tool: run_cmd - with: - cmd: "git add -A && git commit -m 'chore: commit auto-generated files'" - cwd: "${{ context.worktree_path }}" - step_name: "commit_dirty" - on_success: merge - on_failure: escalate - - merge: - tool: merge_worktree - with: - worktree_path: "${{ context.worktree_path }}" - base_branch: "${{ context.feature_branch }}" - capture: - cleanup_succeeded: "${{ result.cleanup_succeeded }}" - on_result: - - when: "result.failed_step == 'dirty_tree'" - route: commit_dirty - - when: "result.failed_step == 'test_gate'" - route: escalate - - when: "result.failed_step == 'post_rebase_test_gate'" - route: escalate - - when: "result.failed_step == 'rebase'" - route: escalate - - when: "result.error" - route: escalate - - route: check_summary - on_failure: escalate - - check_summary: - python: autoskillit.smoke_utils.check_bug_report_non_empty - with: - workspace: ${{ inputs.workspace }} - on_result: - - when: "${{ result.non_empty }} == true" - route: create_summary - - when: "result.error" - route: escalate - - route: done - on_failure: escalate - note: > - Only execute if inputs.collect_on_branch is 'true'. Otherwise skip to done. - Reads bug_report.json from the workspace. Routes to create_summary when bugs - were fixed during the run (non_empty=true), otherwise routes to done. - - create_summary: - tool: run_skill - with: - skill_command: "/autoskillit:pipeline-summary ${{ inputs.workspace }}/bug_report.json ${{ context.feature_branch }} ${{ inputs.original_base_branch }} ${{ inputs.workspace }}" - cwd: "${{ inputs.workspace }}" - capture: - summary_path: "${{ result.summary_path }}" - on_success: done - on_failure: escalate - on_context_limit: done - optional: true - skip_when_false: "inputs.collect_on_branch" - note: > - Skipped when collect_on_branch is 'false' or no bugs were encountered. - Terminal reporting step — outputs (summary file, issue URL, PR URL) are written to - disk for human use and do not flow into subsequent pipeline steps. - The feature branch name passed here should be the actual branch name created - in create_branch (the agent tracks this). The skill gracefully handles - missing gh CLI by writing a local summary only. - - done: - action: stop - message: "Smoke pipeline completed successfully." - - escalate: - action: stop - message: "Smoke pipeline failed — check step output for details." diff --git a/src/autoskillit/server/__init__.py b/src/autoskillit/server/__init__.py index bb687aec76..e75955a9d6 100644 --- a/src/autoskillit/server/__init__.py +++ b/src/autoskillit/server/__init__.py @@ -1,12 +1,12 @@ -#!/usr/bin/env python3 """MCP server for orchestrating automated skill-driven workflows. -Kitchen tools (39 gated + 1 headless-tagged) are hidden at startup via FastMCP v3 +Kitchen tools (40 gated + 1 headless-tagged) are hidden at startup via FastMCP v3 mcp.disable(tags={'kitchen'}) applied once after all tool modules are imported. -Each new session sees only the 2 free-range tools (open_kitchen and close_kitchen). +Each new session sees only the 3 free-range tools (open_kitchen, close_kitchen, +and disable_quota_guard). Headless sessions (AUTOSKILLIT_HEADLESS=1) pre-reveal only headless-tagged tools (test_check) via mcp.enable(tags={'headless'}) — not all kitchen tools. -Calling the open_kitchen tool reveals all 40 kitchen-tagged tools for that session +Calling the open_kitchen tool reveals all 41 kitchen-tagged tools for that session via ctx.enable_components(tags={'kitchen'}). Transport: stdio (default for FastMCP). @@ -24,6 +24,9 @@ ToolContext, gate_error_result, ) +from autoskillit.server._lifespan import ( # noqa: F401 + _autoskillit_lifespan, +) from autoskillit.server._state import ( # noqa: E402, F401 _ctx, _get_config, @@ -33,7 +36,7 @@ version_info, ) -mcp: FastMCP = FastMCP("autoskillit") +mcp: FastMCP = FastMCP("autoskillit", lifespan=_autoskillit_lifespan) logger = get_logger(__name__) @@ -43,6 +46,8 @@ # Public utilities consumed by CLI and tests "version_info", "make_context", + # Wire-format compatibility middleware + "ClaudeCodeCompatMiddleware", ] # Import all tool sub-modules to trigger @mcp.tool() registration. @@ -72,6 +77,12 @@ # Must appear after all tool module imports so the registered tools are in place. mcp.disable(tags={"kitchen"}) +# Wire-format sanitization: strip fields that trigger Claude Code #25081 +# (silent full-tool-list rejection when outputSchema/annotations are present). +from autoskillit.server._wire_compat import ClaudeCodeCompatMiddleware # noqa: E402 + +mcp.add_middleware(ClaudeCodeCompatMiddleware()) + # Headless sessions (AUTOSKILLIT_HEADLESS=1) pre-reveal only headless-tagged tools # (test_check) so the session starts with test_check visible without calling open_kitchen. if os.environ.get("AUTOSKILLIT_HEADLESS") == "1": diff --git a/src/autoskillit/server/_factory.py b/src/autoskillit/server/_factory.py index c044271685..e2399f6200 100644 --- a/src/autoskillit/server/_factory.py +++ b/src/autoskillit/server/_factory.py @@ -11,17 +11,32 @@ import os import subprocess +from collections.abc import Callable +from pathlib import Path from typing import Any from autoskillit.config import AutomationConfig -from autoskillit.core import SubprocessRunner, WriteBehaviorSpec, get_logger, pkg_root +from autoskillit.core import ( + SubprocessRunner, + WriteBehaviorSpec, + get_logger, + pkg_root, + resolve_temp_dir, + temp_dir_display_str, +) from autoskillit.execution import ( + RECORD_SCENARIO_DIR_ENV, + RECORD_SCENARIO_ENV, + RECORD_SCENARIO_RECIPE_ENV, + REPLAY_SCENARIO_DIR_ENV, + REPLAY_SCENARIO_ENV, DefaultCIWatcher, DefaultDatabaseReader, DefaultGitHubFetcher, DefaultHeadlessExecutor, DefaultMergeQueueWatcher, DefaultTestRunner, + build_replay_runner, ) from autoskillit.migration import DefaultMigrationService, default_migration_engine from autoskillit.pipeline import ( @@ -52,6 +67,33 @@ _UNSET: Any = object() +class TokenFactory: + """Lazy-resolving, caching token factory. + + Wraps the config -> env -> gh CLI token resolution chain. Does NOT + resolve at construction time. First call resolves and caches the + result; subsequent calls return the cached value. + + Thread-safe for single-writer scenarios (GIL-safe sentinel + assignment + pattern; the MCP server is single-threaded asyncio). + """ + + _UNRESOLVED = object() + + def __init__(self, resolver: Callable[[], str | None]) -> None: + self._resolver = resolver + self._resolved: str | None = self._UNRESOLVED # type: ignore[assignment] + + def __call__(self) -> str | None: + if self._resolved is self._UNRESOLVED: + self._resolved = self._resolver() + return self._resolved + + @property + def is_resolved(self) -> bool: + return self._resolved is not self._UNRESOLVED + + def _default_plugin_dir() -> str: """Resolve the autoskillit package root.""" return str(pkg_root()) @@ -78,11 +120,18 @@ def _gh_cli_token() -> str | None: return None +def _check_plugin_installed() -> bool: + """Deferred import to avoid server→cli module-level dependency.""" + from autoskillit.cli import _is_plugin_installed # noqa: PLC0415 + + return _is_plugin_installed() + + def make_context( config: AutomationConfig, *, runner: SubprocessRunner | None = _UNSET, - plugin_dir: str | None = None, + plugin_dir: str | None = _UNSET, ) -> ToolContext: """Create a fully-wired ToolContext with all 22 service fields populated. @@ -98,8 +147,10 @@ def make_context( runner: Subprocess runner implementation. Defaults to DefaultSubprocessRunner() for production use. Pass runner=None explicitly to disable the tester (useful in tests that don't need real subprocess execution). - plugin_dir: Absolute path to the autoskillit plugin directory. Defaults - to the autoskillit package directory (parent of server/). + plugin_dir: Absolute path to the autoskillit plugin directory. + Pass None explicitly to indicate the plugin is installed + (marketplace install; no --plugin-dir needed). When omitted + (sentinel), auto-detects via _check_plugin_installed(). Returns: ToolContext with gate starting closed (enabled=False) in all contexts. @@ -113,13 +164,67 @@ def make_context( runner = DefaultSubprocessRunner() - # Resolve token: config → GITHUB_TOKEN env var → gh CLI → None (unauthenticated) - github_token = config.github.token or os.environ.get("GITHUB_TOKEN") or _gh_cli_token() + if runner is not None and os.environ.get(REPLAY_SCENARIO_ENV): + replay_dir = os.environ.get(REPLAY_SCENARIO_DIR_ENV, "") + if not replay_dir: + logger.warning( + "REPLAY_SCENARIO is set but REPLAY_SCENARIO_DIR is empty — skipping replay" + ) + elif not os.path.isdir(replay_dir): + logger.warning( + "REPLAY_SCENARIO_DIR=%r is not an existing directory — skipping replay", + replay_dir, + ) + else: + runner = build_replay_runner(replay_dir) + + elif runner is not None and os.environ.get(RECORD_SCENARIO_ENV): + scenario_dir = os.environ.get(RECORD_SCENARIO_DIR_ENV, "") + recipe_name = os.environ.get(RECORD_SCENARIO_RECIPE_ENV, "unknown") + if scenario_dir: + if not os.path.isdir(scenario_dir): + logger.warning( + "RECORD_SCENARIO_DIR=%r is not an existing directory — skipping recording", + scenario_dir, + ) + else: + try: + from api_simulator.claude import make_scenario_recorder + except ImportError: + logger.warning( + "RECORD_SCENARIO is set but 'api_simulator' is not installed " + "— skipping recording" + ) + make_scenario_recorder = None # type: ignore[assignment] + + if make_scenario_recorder is not None: + from autoskillit.execution import RecordingSubprocessRunner - resolved_dir = plugin_dir if plugin_dir is not None else _default_plugin_dir() + recorder = make_scenario_recorder( + output_dir=scenario_dir, recipe_name=recipe_name + ) + runner = RecordingSubprocessRunner(recorder=recorder, inner=runner) + + # Lazy token resolution: config → GITHUB_TOKEN env var → gh CLI → None. + # The _gh_cli_token() subprocess (up to 5s) is deferred until the first + # gated tool actually needs a GitHub token, keeping the MCP server startup + # path free of subprocess calls (REQ-STARTUP-001). + token_factory = TokenFactory( + lambda: config.github.token or os.environ.get("GITHUB_TOKEN") or _gh_cli_token() + ) + + resolved_dir = ( + plugin_dir + if plugin_dir is not _UNSET + else (_default_plugin_dir() if not _check_plugin_installed() else None) + ) gate = DefaultGateState(enabled=False) - provider = SkillsDirectoryProvider() + project_dir = Path.cwd() + temp_dir = resolve_temp_dir(project_dir, config.workspace.temp_dir) + temp_dir_relpath = temp_dir_display_str(config.workspace.temp_dir) + + provider = SkillsDirectoryProvider(temp_dir_relpath=temp_dir_relpath) ephemeral_root = resolve_ephemeral_root() session_mgr = DefaultSessionSkillManager(provider, ephemeral_root) @@ -133,16 +238,18 @@ def make_context( gate=gate, plugin_dir=resolved_dir, runner=runner, + temp_dir=temp_dir, tester=DefaultTestRunner(config=config, runner=runner) if runner is not None else None, recipes=DefaultRecipeRepository(), db_reader=DefaultDatabaseReader(), workspace_mgr=DefaultWorkspaceManager(), clone_mgr=DefaultCloneManager(), - github_client=DefaultGitHubFetcher(token=github_token), - ci_watcher=DefaultCIWatcher(token=github_token), - merge_queue_watcher=DefaultMergeQueueWatcher(token=github_token), + github_client=DefaultGitHubFetcher(token=token_factory), + ci_watcher=DefaultCIWatcher(token=token_factory), + merge_queue_watcher=DefaultMergeQueueWatcher(token=token_factory), session_skill_manager=session_mgr, skill_resolver=provider.resolver, + quota_refresh_task=None, ) def _resolve_output_patterns(skill_command: str) -> list[str]: @@ -168,6 +275,7 @@ def _resolve_write_behavior(skill_command: str) -> WriteBehaviorSpec: ctx.output_pattern_resolver = _resolve_output_patterns ctx.write_expected_resolver = _resolve_write_behavior + ctx.token_factory = token_factory ctx.executor = DefaultHeadlessExecutor(ctx) ctx.migrations = DefaultMigrationService( default_migration_engine(), run_headless=ctx.executor.run diff --git a/src/autoskillit/server/_lifespan.py b/src/autoskillit/server/_lifespan.py new file mode 100644 index 0000000000..4c76e249a4 --- /dev/null +++ b/src/autoskillit/server/_lifespan.py @@ -0,0 +1,137 @@ +"""FastMCP lifespan for server resource teardown and deferred startup. + +Provides the async context manager wired into FastMCP via ``lifespan=``. +The pre-yield section submits deferred startup work (recovery, audit loading, +stale cleanup, drift check) as background tasks so they run after the +transport opens, not on the critical startup path. +The ``__aexit__`` side calls ``recorder.finalize()`` so scenario data survives +SIGTERM (issue #745). + +Readiness synchronization: the lifespan writes a filesystem sentinel at +``core.readiness.write_readiness_sentinel()`` as the first statement inside the +``try:`` block. Integration tests poll the sentinel path rather than parsing log +lines — file existence is atomic and has no string-parse race. The sentinel is +cleaned up in ``finally:`` before ``_finalize_recorder()`` runs. +""" + +from __future__ import annotations + +import asyncio as _asyncio +from contextlib import asynccontextmanager +from typing import Any + +from autoskillit.core import cleanup_readiness_sentinel, get_logger, write_readiness_sentinel +from autoskillit.execution import RecordingSubprocessRunner +from autoskillit.server._state import _get_ctx_or_none, deferred_initialize + +logger = get_logger(__name__) + + +def run_startup_drift_check() -> None: + """Compare on-disk hooks.json hash vs HOOK_REGISTRY_HASH; regenerate if stale. + + Called as a background task from the lifespan. Any failure is logged and + swallowed — drift must never prevent the server from starting. + """ + try: + import json + + import autoskillit.core.paths as _core_paths + from autoskillit.core import atomic_write + from autoskillit.hook_registry import ( + HOOK_REGISTRY_HASH, + generate_hooks_json, + load_hooks_json_hash, + ) + + hooks_json_path = _core_paths.pkg_root() / "hooks" / "hooks.json" + on_disk_hash = load_hooks_json_hash(hooks_json_path) + if on_disk_hash != HOOK_REGISTRY_HASH: + logger.info( + "startup_drift_detected", + on_disk=on_disk_hash, + expected=HOOK_REGISTRY_HASH, + ) + atomic_write( + hooks_json_path, + json.dumps(generate_hooks_json(), indent=2) + "\n", + ) + logger.info("hooks_json_self_healed", path=str(hooks_json_path)) + else: + logger.info("startup_drift_check_ok") + except Exception: + logger.exception("startup_drift_check_failed") + + +def _finalize_recorder() -> None: + """Finalize the recording subprocess runner if one is active.""" + ctx = _get_ctx_or_none() + if ctx is not None and isinstance(ctx.runner, RecordingSubprocessRunner): + try: + ctx.runner.recorder.finalize() + except Exception: + logger.exception("recorder.finalize() failed during lifespan teardown") + + +async def _run_drift_check_async() -> None: + """Offload blocking drift check (file hashing + atomic_write) to a thread.""" + loop = _asyncio.get_running_loop() + await loop.run_in_executor(None, run_startup_drift_check) + + +async def _run_deferred_init(ready_event: _asyncio.Event) -> None: + """Run deferred_initialize, signalling *ready_event* when done.""" + ctx = _get_ctx_or_none() + if ctx is not None: + await deferred_initialize(ctx, ready_event=ready_event) + else: + ready_event.set() + + +@asynccontextmanager +async def _autoskillit_lifespan(server: Any) -> Any: + """Server lifecycle: write readiness sentinel, yield, then finalize recording. + + Readiness model: the sentinel file is written as the first statement inside + the ``try:`` block. By the time the lifespan body runs, + ``_serve_with_signal_guard()`` in ``cli/app.py`` has already armed the anyio + signal receiver via ``tg.start()``. A SIGTERM delivered after the sentinel + appears is guaranteed to be caught by the armed receiver — no race window. + + Background tasks (drift check, deferred init) are launched via + ``create_background_task`` (from ``pipeline.background``) so they run + concurrently without wrapping the ``yield`` in a task group. A task-group + ``yield`` causes a cancel-scope mismatch when FastMCP resumes the generator + on a different task at exit. + + Teardown model: ``CancelledError`` from the anyio cancel scope unwinds past + the ``yield``, triggering ``finally:``. Background tasks are cancelled, + the sentinel is cleaned up, then ``_finalize_recorder()`` writes + ``scenario.json``. Any teardown exception is logged and suppressed so the + process exits cleanly. + """ + bg_tasks: list[_asyncio.Task[None]] = [] + try: + from autoskillit.pipeline import create_background_task # noqa: PLC0415 + from autoskillit.server import _state # noqa: PLC0415 + + event = _asyncio.Event() + _state._startup_ready = event + write_readiness_sentinel() + bg_tasks.append(create_background_task(_run_drift_check_async(), label="drift_check")) + bg_tasks.append(create_background_task(_run_deferred_init(event), label="deferred_init")) + yield + finally: + for task in bg_tasks: + if not task.done(): + task.cancel() + if bg_tasks: + await _asyncio.gather(*bg_tasks, return_exceptions=True) + try: + cleanup_readiness_sentinel() + except Exception: + logger.exception("lifespan sentinel cleanup error") + try: + _finalize_recorder() + except Exception: + logger.exception("lifespan recorder finalization error") diff --git a/src/autoskillit/server/_state.py b/src/autoskillit/server/_state.py index 1a783486e1..7c7dbfd7d7 100644 --- a/src/autoskillit/server/_state.py +++ b/src/autoskillit/server/_state.py @@ -7,6 +7,8 @@ This module is the authoritative location for: - _ctx: the module-level ToolContext singleton - _initialize(ctx): called by cli/app.py serve() before mcp.run() + - deferred_initialize(ctx, ready_event): background I/O after transport opens + - _startup_ready: asyncio.Event signalling deferred init completion - _get_ctx(): raises RuntimeError if uninitialized (used by gated tools) - _get_ctx_or_none(): returns None if uninitialized (used by ungated tools) - _get_config(): convenience shortcut to _get_ctx().config @@ -15,6 +17,7 @@ from __future__ import annotations +import asyncio from datetime import UTC from autoskillit.config import AutomationConfig @@ -24,6 +27,7 @@ logger = get_logger(__name__) _ctx: ToolContext | None = None +_startup_ready: asyncio.Event | None = None def _initialize(ctx: ToolContext) -> None: @@ -47,56 +51,104 @@ def _initialize(ctx: ToolContext) -> None: exc_info=True, ) - # Recovery sweep: finalize any orphaned tmpfs trace files from crashed sessions. - try: - from autoskillit.execution import recover_crashed_sessions + # Wire MCP recording/replay middleware for scenario capture. + # Core imports are outside the try/except so a broken autoskillit installation + # surfaces as an error rather than being silently swallowed as a middleware warning. + # The _mcp_middleware_registered flag on the runner prevents double-registration + # if _initialize() is called more than once with the same runner instance. + from autoskillit.execution import ( # noqa: PLC0415 + RecordingSubprocessRunner, + ReplayingSubprocessRunner, + ) + from autoskillit.server import mcp # noqa: PLC0415 + + if isinstance(ctx.runner, RecordingSubprocessRunner) and not getattr( + ctx.runner, "_mcp_middleware_registered", False + ): + try: + from api_simulator.mcp import McpRecordingMiddleware # noqa: PLC0415 - cfg = ctx.config.linux_tracing - n = recover_crashed_sessions( - tmpfs_path=cfg.tmpfs_path, - log_dir=cfg.log_dir, - ) - if n > 0: - logger.info("Recovered %d crashed session trace(s) from tmpfs", n) - except Exception: - logger.debug("recover_crashed_sessions at startup failed", exc_info=True) - - # Telemetry recovery: restore audit data from the last 24 hours. - # Token and timing logs are per-pipeline live accumulators — they must NOT be loaded - # from disk at startup. Loading them would contaminate the singleton with data from - # unrelated pipelines that previously used the same server process. - # Skills that need pipeline-scoped token data self-retrieve from disk using cwd_filter. - try: - from datetime import datetime, timedelta + mcp.add_middleware(McpRecordingMiddleware(ctx.runner.recorder)) + ctx.runner._mcp_middleware_registered = True # type: ignore[attr-defined] + logger.info("mcp_recording_middleware_registered") + except ImportError: + logger.warning("mcp_scenario_middleware_unavailable", exc_info=True) + except Exception: + logger.warning("mcp_scenario_middleware_registration_failed", exc_info=True) + elif ( + isinstance(ctx.runner, ReplayingSubprocessRunner) + and ctx.runner.player is not None + and not getattr(ctx.runner, "_mcp_middleware_registered", False) + ): + try: + from api_simulator.mcp import McpReplayMiddleware # noqa: PLC0415 - from autoskillit.execution import read_telemetry_clear_marker, resolve_log_dir + mcp.add_middleware(McpReplayMiddleware(ctx.runner.player)) + ctx.runner._mcp_middleware_registered = True # type: ignore[attr-defined] + logger.info("mcp_replay_middleware_registered") + except ImportError: + logger.warning("mcp_scenario_middleware_unavailable", exc_info=True) + except Exception: + logger.warning("mcp_scenario_middleware_registration_failed", exc_info=True) - cfg = ctx.config.linux_tracing - log_root = resolve_log_dir(cfg.log_dir) - since_dt = datetime.now(tz=UTC) - timedelta(hours=24) - clear_marker = read_telemetry_clear_marker(log_root) - if clear_marker is not None and clear_marker > since_dt: - since_dt = clear_marker - since_str = since_dt.isoformat() - n_aud = ctx.audit.load_from_log_dir(log_root, since=since_str) +async def deferred_initialize(ctx: ToolContext, *, ready_event: asyncio.Event) -> None: + """Run deferrable startup I/O as a background task. - if n_aud: - logger.info( - "Recovered telemetry from session logs (audit=%d)", - n_aud, + Called from _autoskillit_lifespan after mcp.run() opens the transport. + Sets ready_event when complete — tools needing audit data await this event. + """ + try: + try: + from autoskillit.execution import recover_crashed_sessions # noqa: PLC0415 + + cfg = ctx.config.linux_tracing + n = recover_crashed_sessions( + tmpfs_path=cfg.tmpfs_path, + log_dir=cfg.log_dir, ) - except Exception: - logger.warning("telemetry_recovery_at_startup_failed", exc_info=True) + if n > 0: + logger.info("Recovered %d crashed session trace(s) from tmpfs", n) + except Exception: + logger.debug("recover_crashed_sessions at startup failed", exc_info=True) - # Session skill cleanup: remove ephemeral skill dirs from previous server runs. - if ctx.session_skill_manager is not None: try: - removed = ctx.session_skill_manager.cleanup_stale() - if removed: - logger.info("session_skill_cleanup", extra={"removed": removed}) + from datetime import datetime, timedelta # noqa: PLC0415 + + from autoskillit.execution import ( # noqa: PLC0415 + read_telemetry_clear_marker, + resolve_log_dir, + ) + + cfg = ctx.config.linux_tracing + log_root = resolve_log_dir(cfg.log_dir) + since_dt = datetime.now(tz=UTC) - timedelta(hours=24) + clear_marker = read_telemetry_clear_marker(log_root) + if clear_marker is not None and clear_marker > since_dt: + since_dt = clear_marker + since_str = since_dt.isoformat() + + n_aud = ctx.audit.load_from_log_dir(log_root, since=since_str) + + if n_aud: + logger.info( + "Recovered telemetry from session logs (audit=%d)", + n_aud, + ) except Exception: - logger.warning("session_skill_cleanup_failed", exc_info=True) + logger.warning("telemetry_recovery_at_startup_failed", exc_info=True) + + if ctx.session_skill_manager is not None: + try: + removed = ctx.session_skill_manager.cleanup_stale() + if removed: + logger.info("session_skill_cleanup", extra={"removed": removed}) + except Exception: + logger.warning("session_skill_cleanup_failed", exc_info=True) + + logger.info("deferred_initialize_complete") + finally: + ready_event.set() def _get_ctx() -> ToolContext: diff --git a/src/autoskillit/server/_wire_compat.py b/src/autoskillit/server/_wire_compat.py new file mode 100644 index 0000000000..54e323aff2 --- /dev/null +++ b/src/autoskillit/server/_wire_compat.py @@ -0,0 +1,41 @@ +"""Wire-format compatibility middleware for Claude Code MCP client. + +Claude Code bug #25081 silently drops ALL tools from servers whose +tools/list response includes ``outputSchema``, ``annotations``, or ``title`` +fields. FastMCP 3.2.3+ auto-generates these for typed return values and +annotated tools. This middleware strips them at the wire level so tool +registration code can use idiomatic FastMCP patterns without worrying +about client-side parser quirks. + +Ref: https://github.com/anthropics/claude-code/issues/25081 +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING + +from fastmcp.server.middleware import Middleware + +if TYPE_CHECKING: + import mcp.types as mt + from fastmcp.server.middleware import CallNext, MiddlewareContext + from fastmcp.tools.tool import Tool + + +class ClaudeCodeCompatMiddleware(Middleware): + """Strip wire fields that trigger Claude Code #25081 tool-list rejection.""" + + async def on_list_tools( + self, + context: MiddlewareContext[mt.ListToolsRequest], + call_next: CallNext[mt.ListToolsRequest, Sequence[Tool]], + ) -> Sequence[Tool]: + tools = await call_next(context) + cleaned: list[Tool] = [] + for tool in tools: + patched = tool.model_copy( + update={"output_schema": None, "annotations": None, "title": None} + ) + cleaned.append(patched) + return cleaned diff --git a/src/autoskillit/server/git.py b/src/autoskillit/server/git.py index 48e72ccc38..6991f5acbc 100644 --- a/src/autoskillit/server/git.py +++ b/src/autoskillit/server/git.py @@ -10,6 +10,7 @@ from __future__ import annotations +import dataclasses import os from pathlib import Path from typing import TYPE_CHECKING, Any @@ -75,6 +76,53 @@ async def _run_git( return result.returncode, result.stdout, result.stderr +@dataclasses.dataclass(frozen=True) +class GitMergeTarget: + """Verified merge target — proof that main_repo's branch was checked.""" + + path: str + branch: str + + +async def _verify_merge_target( + main_repo: str, + expected_branch: str, + runner: SubprocessRunner, +) -> GitMergeTarget | dict[str, Any]: + """Verify main_repo has expected_branch checked out. + + Returns GitMergeTarget on success, or an error dict on mismatch + (compatible with perform_merge return format). + """ + rc, current_out, _ = await _run_git(["git", "branch", "--show-current"], main_repo, 10, runner) + if rc != 0: + return { + "error": ( + f"Failed to determine current branch of '{main_repo}' " + f"(git branch --show-current exited with rc={rc}). " + f"Ensure the work directory has '{expected_branch}' " + f"checked out before merging." + ), + "failed_step": MergeFailedStep.MERGE, + "state": MergeState.WORKTREE_INTACT, + "worktree_path": "", # filled in by caller + } + current_branch = current_out.strip() + if current_branch != expected_branch: + return { + "error": ( + f"Target repository '{main_repo}' is on branch " + f"'{current_branch}', expected '{expected_branch}'. " + f"Ensure the work directory has '{expected_branch}' " + f"checked out before merging." + ), + "failed_step": MergeFailedStep.MERGE, + "state": MergeState.WORKTREE_INTACT, + "worktree_path": "", # filled in by caller + } + return GitMergeTarget(path=main_repo, branch=current_branch) + + async def perform_merge( worktree_path: str, base_branch: str, @@ -360,9 +408,16 @@ async def perform_merge( "worktree_path": worktree_path, } + # 7.5 Verify main_repo is on base_branch + target_or_err = await _verify_merge_target(main_repo, base_branch, runner) + if isinstance(target_or_err, dict): + target_or_err["worktree_path"] = worktree_path + return target_or_err + target = target_or_err + # 8. Merge rc, _, merge_stderr = await _run_git( - ["git", "merge", "--no-edit", worktree_branch], main_repo, 60, runner + ["git", "merge", "--no-edit", worktree_branch], target.path, 60, runner ) if rc != 0: abort_rc, _, abort_stderr = await _run_git( @@ -445,7 +500,7 @@ async def perform_merge( return { "merge_succeeded": True, "merged_branch": worktree_branch, - "into_branch": base_branch, + "into_branch": target.branch, "worktree_removed": wt_rc == 0, "branch_deleted": br_rc == 0, "cleanup_succeeded": wt_rc == 0 and br_rc == 0, diff --git a/src/autoskillit/server/helpers.py b/src/autoskillit/server/helpers.py index b356e16921..6583cefdc2 100644 --- a/src/autoskillit/server/helpers.py +++ b/src/autoskillit/server/helpers.py @@ -7,15 +7,19 @@ import json import os import time -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Mapping from pathlib import Path from typing import TYPE_CHECKING, Any from autoskillit.core import RESERVED_LOG_RECORD_KEYS, TerminationReason, get_logger from autoskillit.execution import ( + SCENARIO_STEP_NAME_ENV, # noqa: F401 — re-exported for tools_execution.py + _refresh_quota_cache, # noqa: F401 — re-exported for tools_execution.py; patched by tests + fetch_repo_merge_state, # noqa: F401 — re-exported for tools_ci.py resolve_log_dir, # noqa: F401 — used by tools_github.py, tools_status.py write_telemetry_clear_marker, # noqa: F401 — used by tools_status.py ) +from autoskillit.hooks import _HOOK_CONFIG_PATH_COMPONENTS from autoskillit.pipeline import gate_error_result from autoskillit.recipe import ( StaleItem, @@ -31,12 +35,13 @@ if TYPE_CHECKING: from fastmcp import Context + from autoskillit.config import QuotaGuardConfig from autoskillit.core import SubprocessResult logger = get_logger(__name__) -_HOOK_CONFIG_FILENAME: str = ".autoskillit_hook_config.json" -_HOOK_DIR_COMPONENTS: tuple[str, ...] = (".autoskillit", "temp") +_HOOK_CONFIG_FILENAME: str = _HOOK_CONFIG_PATH_COMPONENTS[-1] +_HOOK_DIR_COMPONENTS: tuple[str, ...] = _HOOK_CONFIG_PATH_COMPONENTS[:-1] def _hook_config_path(project_root: Path) -> Path: @@ -105,6 +110,10 @@ def track_response_size( ) -> Callable[[Callable[..., Awaitable[Any]]], Callable[..., Awaitable[Any]]]: """Decorator: measure the JSON string size of a tool response and record to response_log. + Last-resort safety net. Tool implementations SHOULD catch exceptions locally + and emit domain-specific envelopes with more helpful ``user_visible_message`` + values; this decorator only catches what slips through. + Apply BELOW @mcp.tool() so the wrapped function is what FastMCP registers: @mcp.tool(tags={"automation"}) @@ -125,6 +134,10 @@ async def wrapper(*args: Any, **kwargs: Any) -> Any: "error": f"{type(exc).__name__}: {exc}", "exit_code": -1, "subtype": "tool_exception", + "user_visible_message": ( + f"An internal error occurred in {tool_name}: " + f"{type(exc).__name__}. Run 'autoskillit doctor' or reinstall." + ), } ) logger.exception("Unhandled exception in tool %s", tool_name) @@ -258,7 +271,7 @@ async def _apply_triage_gate( if recipe_info is None: return result - cache_path = Path.cwd() / ".autoskillit" / "temp" / "recipe_staleness_cache.json" + cache_path = _ctx.temp_dir / "recipe_staleness_cache.json" t0 = time.perf_counter() cached = read_staleness_cache(cache_path, name) logger.debug( @@ -340,6 +353,7 @@ async def _run_subprocess( *, cwd: str, timeout: float, + env: Mapping[str, str] | None = None, ) -> tuple[int, str, str]: """Run a subprocess asynchronously with timeout. Returns (returncode, stdout, stderr). @@ -348,7 +362,7 @@ async def _run_subprocess( """ runner = _get_ctx().runner assert runner is not None, "No subprocess runner configured" - result = await runner(cmd, cwd=Path(cwd), timeout=timeout) + result = await runner(cmd, cwd=Path(cwd), timeout=timeout, env=env) return _process_runner_result(result, timeout) @@ -486,5 +500,66 @@ async def _prime_quota_cache() -> None: try: await check_and_sleep_if_needed(_get_ctx().config.quota_guard) - except (OSError, ValueError, RuntimeError): + except Exception: logger.warning("quota_prime_failed", exc_info=True) + + +async def _quota_refresh_loop(config: QuotaGuardConfig) -> None: + """Long-running coroutine: refreshes the quota cache every cache_refresh_interval seconds. + + Designed to run as a background asyncio.Task for the duration of a kitchen session. + The loop sleeps first, then refreshes — ensuring _prime_quota_cache's initial write + is not immediately overwritten. CancelledError from asyncio.sleep propagates + uncaught, terminating the loop cleanly when the task is cancelled. + + Guarantee: with cache_refresh_interval < cache_max_age, the cache written by any + loop tick will still be fresh when the next tick fires. The hook never sees a stale + cache as long as this loop is running. + """ + while True: + await asyncio.sleep(config.cache_refresh_interval) + try: + await _refresh_quota_cache(config) + except Exception as exc: + logger.warning("quota_refresh_loop_error", exc_info=True, error=str(exc)) + + +def _build_hook_diagnostic_warning() -> str | None: + """Run hook health and drift checks. Return a warning string if issues are found. + + Only reads; never writes or modifies state. Returns None when all hooks are healthy + or when settings.json does not yet exist (nothing to validate). + """ + from autoskillit.hook_registry import ( + _claude_settings_path, + _count_hook_registry_drift, + find_broken_hook_scripts, + ) + + settings_path = _claude_settings_path("user") + if not settings_path.exists(): + return None + + broken = find_broken_hook_scripts(settings_path) + drift = _count_hook_registry_drift(settings_path) + + issues: list[str] = [] + if broken: + issues.append(f"Hook scripts not found: {', '.join(broken)}") + if drift.orphaned > 0: + issues.append( + f"{drift.orphaned} orphaned hook entry(ies) in settings.json are not in " + f"HOOK_REGISTRY — every matching tool call will be denied with ENOENT." + ) + if drift.missing > 0: + issues.append( + f"{drift.missing} hook(s) from HOOK_REGISTRY are not deployed in settings.json." + ) + if not issues: + return None + + lines = ["\n⚠️ Hook configuration issues detected:"] + for issue in issues: + lines.append(f" • {issue}") + lines.append(" → Run 'autoskillit install' to regenerate hook configuration.\n") + return "\n".join(lines) diff --git a/src/autoskillit/server/tools_ci.py b/src/autoskillit/server/tools_ci.py index 0ab677f870..c221e46350 100644 --- a/src/autoskillit/server/tools_ci.py +++ b/src/autoskillit/server/tools_ci.py @@ -8,6 +8,7 @@ import time from typing import Literal +import httpx import structlog from fastmcp import Context from fastmcp.dependencies import CurrentContext @@ -18,6 +19,7 @@ _notify, _require_enabled, _run_subprocess, + fetch_repo_merge_state, infer_repo_from_remote, track_response_size, ) @@ -33,6 +35,7 @@ async def wait_for_ci( remote_url: str = "", head_sha: str | None = None, workflow: str | None = None, + event: str | None = None, timeout_seconds: int = 300, cwd: str = ".", step_name: str = "", @@ -54,6 +57,8 @@ async def wait_for_ci( HEAD in cwd. workflow: Workflow filename to filter runs (e.g. "tests.yml"). If omitted, falls back to the project-level ci.workflow config. + event: GitHub trigger event to filter runs (e.g. "push", "pull_request"). + If omitted, falls back to the project-level ci.event config. timeout_seconds: Maximum time to wait (default 300s). cwd: Working directory for git operations. step_name: Optional YAML step key for wall-clock timing accumulation. @@ -63,83 +68,101 @@ async def wait_for_ci( "action_required", "timed_out", "no_runs", "error", "unknown"), and failed_jobs list. Billing limit errors surface as conclusion="action_required" with failed_jobs=[]. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="wait_for_ci") - logger.info("wait_for_ci", branch=branch, repo=repo or "(infer)") - - from autoskillit.server import _get_ctx + try: + _start = time.monotonic() + _timing_ctx = None + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="wait_for_ci") + logger.info("wait_for_ci", branch=branch, repo=repo or "(infer)") + + from autoskillit.server import _get_ctx + + tool_ctx = _get_ctx() + _timing_ctx = tool_ctx + if tool_ctx.ci_watcher is None: + if step_name: + tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + return json.dumps( + { + "run_id": None, + "conclusion": "error", + "failed_jobs": [], + "error": "CI watcher not configured", + } + ) - tool_ctx = _get_ctx() - if tool_ctx.ci_watcher is None: - return json.dumps( - { - "run_id": None, - "conclusion": "error", - "failed_jobs": [], - "error": "CI watcher not configured", - } + # Infer head_sha from cwd if not provided + if head_sha is None and cwd: + try: + rc, stdout, _ = await _run_subprocess( + ["git", "rev-parse", "HEAD"], cwd=cwd, timeout=5.0 + ) + if rc == 0: + head_sha = stdout.strip() + except Exception: + logger.warning("git rev-parse HEAD failed", exc_info=True) + + scope = CIRunScope( + workflow=workflow or tool_ctx.default_ci_scope.workflow, + head_sha=head_sha, + event=event or tool_ctx.default_ci_scope.event, ) - # Infer head_sha from cwd if not provided - if head_sha is None and cwd: - try: - rc, stdout, _ = await _run_subprocess( - ["git", "rev-parse", "HEAD"], cwd=cwd, timeout=5.0 - ) - if rc == 0: - head_sha = stdout.strip() - except Exception: - logger.warning("git rev-parse HEAD failed", exc_info=True) - - scope = CIRunScope( - workflow=workflow or tool_ctx.default_ci_scope.workflow, - head_sha=head_sha, - ) - - resolved_repo = await infer_repo_from_remote(cwd, hint=remote_url or repo or None) - - await _notify( - ctx, - "info", - f"Watching CI for branch {branch}", - "autoskillit.wait_for_ci", - extra={ - "repo": resolved_repo or "(infer)", - "head_sha": scope.head_sha or "(any)", - "workflow": scope.workflow or "(any)", - }, - ) - - _start = time.monotonic() - try: - result = await tool_ctx.ci_watcher.wait( - branch, - repo=resolved_repo or None, - scope=scope, - timeout_seconds=timeout_seconds, - cwd=cwd, - ) + resolved_repo = await infer_repo_from_remote(cwd, hint=remote_url or repo or None) - conclusion = result.get("conclusion", "unknown") - level = "info" if conclusion == "success" else "error" await _notify( ctx, - level, - f"CI result: {conclusion}", + "info", + f"Watching CI for branch {branch}", "autoskillit.wait_for_ci", - extra={"run_id": result.get("run_id")}, + extra={ + "repo": resolved_repo or "(infer)", + "head_sha": scope.head_sha or "(any)", + "workflow": scope.workflow or "(any)", + }, ) - return json.dumps(result) + try: + result = await tool_ctx.ci_watcher.wait( + branch, + repo=resolved_repo or None, + scope=scope, + timeout_seconds=timeout_seconds, + cwd=cwd, + ) + + # Include head_sha used for this CI check so orchestrators can verify + # CI results correspond to the current HEAD after a force-push. + if scope.head_sha: + result = {**result, "head_sha": scope.head_sha} + + conclusion = result.get("conclusion", "unknown") + level = "info" if conclusion == "success" else "error" + await _notify( + ctx, + level, + f"CI result: {conclusion}", + "autoskillit.wait_for_ci", + extra={"run_id": result.get("run_id")}, + ) + + return json.dumps(result) + except Exception as exc: + logger.error("wait_for_ci failed", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) + finally: + if step_name: + tool_ctx.timing_log.record(step_name, time.monotonic() - _start) except Exception as exc: - logger.error("autoskillit.wait_for_ci failed", exc_info=exc) + logger.error("wait_for_ci unhandled exception", exc_info=True) + if step_name and _timing_ctx is not None: + _timing_ctx.timing_log.record(step_name, time.monotonic() - _start) return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) - finally: - if step_name: - tool_ctx.timing_log.record(step_name, time.monotonic() - _start) @mcp.tool(tags={"autoskillit", "kitchen", "github"}, annotations={"readOnlyHint": True}) @@ -152,7 +175,7 @@ async def set_commit_status( target_url: str = "", repo: str = "", cwd: str = "", -) -> dict[str, object]: +) -> str: """Post a GitHub Commit Status to a commit SHA. Use to implement review-first gating: post `pending` when review starts, @@ -167,58 +190,63 @@ async def set_commit_status( target_url: Optional URL linking to review details. repo: owner/repo format. Inferred from `cwd` git remote if absent. cwd: Working directory for repo inference. Defaults to plugin_dir. + + Never raises. """ if (gate := _require_enabled()) is not None: - return json.loads(gate) # type: ignore[return-value] + return gate if not sha: - return {"success": False, "error": "sha must not be empty"} + return json.dumps({"success": False, "error": "sha must not be empty"}) if not context: - return {"success": False, "error": "context must not be empty"} + return json.dumps({"success": False, "error": "context must not be empty"}) if len(description) > 140: - return { - "success": False, - "error": f"description exceeds 140 chars ({len(description)} chars)", - } - - from autoskillit.server import _get_ctx - - tool_ctx = _get_ctx() - effective_cwd = cwd or tool_ctx.plugin_dir or "." - - # Resolve owner/repo if not provided - owner_repo = repo - if not owner_repo: - rc, stdout, stderr = await _run_subprocess( - ["gh", "repo", "view", "--json", "nameWithOwner", "-q", ".nameWithOwner"], - cwd=effective_cwd, - timeout=30.0, + return json.dumps( + { + "success": False, + "error": f"description exceeds 140 chars ({len(description)} chars)", + } ) + + try: + from autoskillit.server import _get_ctx + + tool_ctx = _get_ctx() + effective_cwd = cwd or tool_ctx.plugin_dir or "." + + # Resolve owner/repo if not provided + owner_repo = repo + if not owner_repo: + owner_repo = await infer_repo_from_remote(effective_cwd) + if not owner_repo: + return json.dumps( + {"success": False, "error": "Could not infer owner/repo from git remote"} + ) + + cmd = [ + "gh", + "api", + "--method", + "POST", + f"/repos/{owner_repo}/statuses/{sha}", + "-f", + f"state={state}", + "-f", + f"context={context}", + "-f", + f"description={description}", + ] + if target_url: + cmd += ["-f", f"target_url={target_url}"] + + rc, _stdout, stderr = await _run_subprocess(cmd, cwd=effective_cwd, timeout=30.0) if rc != 0: - return {"success": False, "error": f"Could not infer owner/repo: {stderr}"} - owner_repo = stdout.strip() - - cmd = [ - "gh", - "api", - "--method", - "POST", - f"/repos/{owner_repo}/statuses/{sha}", - "-f", - f"state={state}", - "-f", - f"context={context}", - "-f", - f"description={description}", - ] - if target_url: - cmd += ["-f", f"target_url={target_url}"] - - rc, _stdout, stderr = await _run_subprocess(cmd, cwd=effective_cwd, timeout=30.0) - if rc != 0: - return {"success": False, "error": stderr} - - return {"success": True, "sha": sha, "state": state, "context": context} + return json.dumps({"success": False, "error": stderr}) + + return json.dumps({"success": True, "sha": sha, "state": state, "context": context}) + except Exception as exc: + logger.error("set_commit_status unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen", "ci"}, annotations={"readOnlyHint": True}) @@ -228,6 +256,7 @@ async def get_ci_status( run_id: int | None = None, repo: str | None = None, workflow: str | None = None, + event: str | None = None, cwd: str = ".", ) -> str: """Return current CI status for a branch or specific run without waiting. @@ -238,32 +267,43 @@ async def get_ci_status( repo: GitHub owner/repo. If omitted, inferred from git remote in cwd. workflow: Workflow filename to filter runs (e.g. "tests.yml"). If omitted, falls back to the project-level ci.workflow config. + event: GitHub trigger event to filter runs (e.g. "push", "pull_request"). + If omitted, falls back to the project-level ci.event config. cwd: Working directory for git operations. Returns: JSON with runs list, each containing id, status, conclusion, failed_jobs. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - from autoskillit.server import _get_ctx + try: + from autoskillit.server import _get_ctx - tool_ctx = _get_ctx() - if tool_ctx.ci_watcher is None: - return json.dumps({"runs": [], "error": "CI watcher not configured"}) + tool_ctx = _get_ctx() + if tool_ctx.ci_watcher is None: + return json.dumps({"runs": [], "error": "CI watcher not configured"}) - if branch is None and run_id is None: - return json.dumps({"runs": [], "error": "Provide branch or run_id"}) + if branch is None and run_id is None: + return json.dumps({"runs": [], "error": "Provide branch or run_id"}) - scope = CIRunScope(workflow=workflow or tool_ctx.default_ci_scope.workflow) + scope = CIRunScope( + workflow=workflow or tool_ctx.default_ci_scope.workflow, + event=event or tool_ctx.default_ci_scope.event, + ) - result = await tool_ctx.ci_watcher.status( - branch or "", - repo=repo, - run_id=run_id, - scope=scope, - cwd=cwd, - ) - return json.dumps(result) + result = await tool_ctx.ci_watcher.status( + branch or "", + repo=repo, + run_id=run_id, + scope=scope, + cwd=cwd, + ) + return json.dumps(result) + except Exception as exc: + logger.error("get_ci_status unhandled exception", exc_info=True) + return json.dumps({"runs": [], "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen", "ci"}, annotations={"readOnlyHint": False}) @@ -292,43 +332,48 @@ async def toggle_auto_merge( Returns: JSON: {"success": bool, "pr_number": int} on success, {"success": false, "error": str} on failure. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate + try: + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars( + tool="toggle_auto_merge", pr_number=pr_number, target_branch=target_branch + ) + await _notify( + ctx, + "info", + f"Toggling auto-merge for PR #{pr_number} on {target_branch!r}", + "autoskillit.toggle_auto_merge", + extra={"pr_number": pr_number, "target_branch": target_branch}, + ) - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars( - tool="toggle_auto_merge", pr_number=pr_number, target_branch=target_branch - ) - await _notify( - ctx, - "info", - f"Toggling auto-merge for PR #{pr_number} on {target_branch!r}", - "autoskillit.toggle_auto_merge", - extra={"pr_number": pr_number, "target_branch": target_branch}, - ) - - from autoskillit.server import _get_ctx + from autoskillit.server import _get_ctx - tool_ctx = _get_ctx() + tool_ctx = _get_ctx() - if tool_ctx.merge_queue_watcher is None: - return json.dumps( - { - "success": False, - "error": "merge_queue_watcher not configured (missing GITHUB_TOKEN?)", - } - ) + if tool_ctx.merge_queue_watcher is None: + return json.dumps( + { + "success": False, + "error": "merge_queue_watcher not configured (missing GITHUB_TOKEN?)", + } + ) - resolved_repo = await infer_repo_from_remote(cwd, hint=remote_url or repo or None) + resolved_repo = await infer_repo_from_remote(cwd, hint=remote_url or repo or None) - result = await tool_ctx.merge_queue_watcher.toggle( - pr_number=pr_number, - target_branch=target_branch, - repo=resolved_repo or None, - cwd=cwd, - ) - return json.dumps(result) + result = await tool_ctx.merge_queue_watcher.toggle( + pr_number=pr_number, + target_branch=target_branch, + repo=resolved_repo or None, + cwd=cwd, + ) + return json.dumps(result) + except Exception as exc: + logger.error("toggle_auto_merge unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen", "ci"}, annotations={"readOnlyHint": False}) @@ -344,6 +389,7 @@ async def wait_for_merge_queue( stall_grace_period: int = 60, max_stall_retries: int = 3, not_in_queue_confirmation_cycles: int = 2, + max_inconclusive_retries: int = 5, step_name: str = "", ctx: Context = CurrentContext(), ) -> str: @@ -367,63 +413,175 @@ async def wait_for_merge_queue( not_in_queue_confirmation_cycles: Consecutive "not in queue" cycles required before treating absence as definitive. Guards against race between queue exit and merged=true propagation (default 2). + max_inconclusive_retries: Maximum NoPositiveSignal cycles (beyond the + confirmation window) before returning pr_state="timeout" (default 5). step_name: Optional YAML step key for wall-clock timing accumulation. Returns: JSON: { "success": bool, - "pr_state": "merged"|"ejected"|"stalled"|"timeout"|"error", + "pr_state": "merged"|"ejected"|"ejected_ci_failure"|"stalled"| + "dropped_healthy"|"timeout"|"error", "reason": str, "stall_retries_attempted": int, } + + pr_state values: + merged — PR successfully merged through the queue. + ejected — PR removed from queue (conflict or other non-CI reason). + ejected_ci_failure — PR removed from queue because CI checks failed. + stalled — PR stuck in queue; max stall retries exhausted. + dropped_healthy — auto-merge disabled on a PR with no CI/conflict issues. + timeout — polling budget exhausted before a terminal state was reached. + error — watcher raised an unexpected exception. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate + try: + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars( + tool="wait_for_merge_queue", pr_number=pr_number, target_branch=target_branch + ) + await _notify( + ctx, + "info", + f"Waiting for PR #{pr_number} in merge queue on {target_branch!r}", + "autoskillit.wait_for_merge_queue", + extra={"pr_number": pr_number, "target_branch": target_branch}, + ) - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars( - tool="wait_for_merge_queue", pr_number=pr_number, target_branch=target_branch - ) - await _notify( - ctx, - "info", - f"Waiting for PR #{pr_number} in merge queue on {target_branch!r}", - "autoskillit.wait_for_merge_queue", - extra={"pr_number": pr_number, "target_branch": target_branch}, - ) + from autoskillit.server import _get_ctx - from autoskillit.server import _get_ctx + tool_ctx = _get_ctx() - tool_ctx = _get_ctx() + if tool_ctx.merge_queue_watcher is None: + if step_name: + tool_ctx.timing_log.record(step_name, 0.0) + return json.dumps( + { + "success": False, + "pr_state": "error", + "reason": "merge_queue_watcher not configured (missing GITHUB_TOKEN?)", + } + ) + + resolved_repo = await infer_repo_from_remote(cwd, hint=remote_url or repo or None) + + _start = time.monotonic() + try: + result = await tool_ctx.merge_queue_watcher.wait( + pr_number=pr_number, + target_branch=target_branch, + repo=resolved_repo or None, + cwd=cwd, + timeout_seconds=timeout_seconds, + poll_interval=poll_interval, + stall_grace_period=stall_grace_period, + max_stall_retries=max_stall_retries, + not_in_queue_confirmation_cycles=not_in_queue_confirmation_cycles, + max_inconclusive_retries=max_inconclusive_retries, + ) + return json.dumps(result) + except Exception as exc: + logger.error("wait_for_merge_queue ci_watcher error", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) + finally: + if step_name: + tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + except Exception as exc: + logger.error("wait_for_merge_queue unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) - if tool_ctx.merge_queue_watcher is None: - return json.dumps( - { - "success": False, - "pr_state": "error", - "reason": "merge_queue_watcher not configured (missing GITHUB_TOKEN?)", - } - ) - resolved_repo = await infer_repo_from_remote(cwd, hint=remote_url or repo or None) +@mcp.tool(tags={"autoskillit", "kitchen", "ci"}, annotations={"readOnlyHint": True}) +@track_response_size("check_repo_merge_state") +async def check_repo_merge_state( + branch: str, + cwd: str = ".", + remote_url: str = "", + step_name: str = "", + ctx: Context = CurrentContext(), +) -> str: + """Single GraphQL round-trip returning queue_available, merge_group_trigger, + auto_merge_available, and ci_event for the given repository branch. - _start = time.monotonic() + Consolidates the three former run_cmd shell steps in the pre_queue_gate block + into a single MCP tool call, eliminating N+2 REST/GraphQL round-trips and + making the call budget auditable by block-level semantic rules. + + Args: + branch: Target branch name to check merge queue state for. + cwd: Working directory for git remote resolution. + remote_url: Full GitHub remote URL; parsed to owner/repo if provided. + step_name: Step name for timing telemetry. + + Returns a JSON object with keys: + - ``queue_available``: branch has an active GitHub merge queue. + - ``merge_group_trigger``: a CI workflow declares the merge_group event. + - ``auto_merge_available``: repository has auto-merge enabled. + - ``ci_event``: ``"push"`` | ``"merge_group"`` | ``null`` — recommended + event to use when polling CI via wait_for_ci. + On any error, returns an error field alongside the four boolean/null defaults. + + Never raises. + """ + if (gate := _require_enabled()) is not None: + return gate try: - result = await tool_ctx.merge_queue_watcher.wait( - pr_number=pr_number, - target_branch=target_branch, - repo=resolved_repo or None, - cwd=cwd, - timeout_seconds=timeout_seconds, - poll_interval=poll_interval, - stall_grace_period=stall_grace_period, - max_stall_retries=max_stall_retries, - not_in_queue_confirmation_cycles=not_in_queue_confirmation_cycles, - ) - return json.dumps(result) + from autoskillit.server import _get_ctx + + tool_ctx = _get_ctx() + _start = time.monotonic() + try: + resolved_repo = await infer_repo_from_remote(cwd, hint=remote_url or None) + if not resolved_repo or "/" not in resolved_repo: + return json.dumps( + { + "error": f"Could not resolve owner/repo from cwd={cwd!r}", + "queue_available": False, + "merge_group_trigger": False, + "auto_merge_available": False, + "ci_event": None, + } + ) + owner, repo = resolved_repo.split("/", 1) + resolved_token = ( + tool_ctx.token_factory() + if tool_ctx.token_factory is not None + else tool_ctx.config.github.token + ) + state = await fetch_repo_merge_state( + owner=owner, + repo=repo, + branch=branch, + token=resolved_token, + ) + return json.dumps(state) + except Exception as exc: + logger.error("autoskillit.check_repo_merge_state failed", exc_info=True) + envelope: dict[str, object] = { + "error": f"{type(exc).__name__}: {exc}", + "queue_available": False, + "merge_group_trigger": False, + "auto_merge_available": False, + "ci_event": None, + } + if isinstance(exc, httpx.HTTPStatusError): + envelope["http_status"] = exc.response.status_code + return json.dumps(envelope) + finally: + if step_name: + tool_ctx.timing_log.record(step_name, time.monotonic() - _start) except Exception as exc: - logger.error("autoskillit.wait_for_merge_queue failed", exc_info=exc) - return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) - finally: - if step_name: - tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + logger.error("check_repo_merge_state unhandled exception", exc_info=True) + return json.dumps( + { + "error": f"{type(exc).__name__}: {exc}", + "queue_available": False, + "merge_group_trigger": False, + "auto_merge_available": False, + "ci_event": None, + } + ) diff --git a/src/autoskillit/server/tools_clone.py b/src/autoskillit/server/tools_clone.py index 452c30bd21..ae1701999e 100644 --- a/src/autoskillit/server/tools_clone.py +++ b/src/autoskillit/server/tools_clone.py @@ -64,51 +64,57 @@ async def clone_repo( operations (including checkout, fetch, reset, pull), run_cmd, or any other command in source_dir. All pipeline work — skill invocations, git operations, file reads — runs exclusively in clone_path (captured as work_dir in recipes). + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="clone_repo", source_dir=source_dir) - logger.info("clone_repo", source_dir=source_dir, run_name=run_name, branch=branch) - await _notify( - ctx, - "info", - f"clone_repo: {source_dir!r} run_name={run_name!r} branch={branch!r}", - "autoskillit.clone_repo", - extra={ - "source_dir": source_dir, - "run_name": run_name, - "branch": branch, - "strategy": strategy, - "remote_url": remote_url, - }, - ) - - from autoskillit.server import _get_ctx - - tool_ctx = _get_ctx() - if tool_ctx.clone_mgr is None: - return json.dumps({"error": "Clone manager not configured"}) - - _start = time.monotonic() try: - result = await asyncio.to_thread( - tool_ctx.clone_mgr.clone_repo, source_dir, run_name, branch, strategy, remote_url - ) - except (ValueError, RuntimeError) as exc: + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="clone_repo", source_dir=source_dir) + logger.info("clone_repo", source_dir=source_dir, run_name=run_name, branch=branch) await _notify( ctx, - "error", - "clone_repo failed", + "info", + f"clone_repo: {source_dir!r} run_name={run_name!r} branch={branch!r}", "autoskillit.clone_repo", - extra={"reason": str(exc)}, + extra={ + "source_dir": source_dir, + "run_name": run_name, + "branch": branch, + "strategy": strategy, + "remote_url": remote_url, + }, ) - return json.dumps({"error": str(exc)}) - finally: - if step_name: - tool_ctx.timing_log.record(step_name, time.monotonic() - _start) - return json.dumps(result) + from autoskillit.server import _get_ctx + + tool_ctx = _get_ctx() + if tool_ctx.clone_mgr is None: + return json.dumps({"error": "Clone manager not configured"}) + + _start = time.monotonic() + try: + result = await asyncio.to_thread( + tool_ctx.clone_mgr.clone_repo, source_dir, run_name, branch, strategy, remote_url + ) + except (ValueError, RuntimeError) as exc: + await _notify( + ctx, + "error", + "clone_repo failed", + "autoskillit.clone_repo", + extra={"reason": str(exc)}, + ) + return json.dumps({"error": str(exc)}) + finally: + if step_name: + tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + + return json.dumps(result) + except Exception as exc: + logger.error("clone_repo unhandled exception", exc_info=True) + return json.dumps({"error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen", "clone"}, annotations={"readOnlyHint": True}) @@ -196,75 +202,83 @@ async def push_to_remote( source_dir: Source repo path (read-only URL lookup when remote_url is empty). remote_url: Pre-resolved upstream remote URL. When provided, source_dir is skipped. step_name: Optional YAML step key for wall-clock timing accumulation. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="push_to_remote", clone_path=clone_path) - logger.info( - "push_to_remote", - clone_path=clone_path, - source_dir=source_dir, - remote_url=remote_url, - branch=branch, - ) - await _notify( - ctx, - "info", - f"push_to_remote: {clone_path!r} → branch={branch!r}", - "autoskillit.push_to_remote", - extra={ - "clone_path": clone_path, - "source_dir": source_dir, - "remote_url": remote_url, - "branch": branch, - }, - ) - - from autoskillit.server import _get_ctx - - tool_ctx = _get_ctx() - clone_mgr = tool_ctx.clone_mgr - if clone_mgr is None: - return json.dumps({"error": "Clone manager not configured", "stderr": ""}) - - _start = time.monotonic() try: - result = await asyncio.to_thread( - lambda: clone_mgr.push_to_remote( - clone_path, - source_dir, - branch, - remote_url=remote_url, - protected_branches=tool_ctx.config.safety.protected_branches, - force=force.strip().lower() == "true", - ) + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="push_to_remote", clone_path=clone_path) + logger.info( + "push_to_remote", + clone_path=clone_path, + source_dir=source_dir, + remote_url=remote_url, + branch=branch, + ) + await _notify( + ctx, + "info", + f"push_to_remote: {clone_path!r} → branch={branch!r}", + "autoskillit.push_to_remote", + extra={ + "clone_path": clone_path, + "source_dir": source_dir, + "remote_url": remote_url, + "branch": branch, + }, ) - if not result.get("success"): - await _notify( - ctx, - "error", - "push_to_remote failed", - "autoskillit.push_to_remote", - extra={ - "stderr": result.get("stderr", ""), - "error_type": result.get("error_type", ""), - }, - ) - return json.dumps( - { - "success": False, - "error": "push failed", - "stderr": result.get("stderr", ""), - "error_type": result.get("error_type", ""), - } + from autoskillit.server import _get_ctx + + tool_ctx = _get_ctx() + clone_mgr = tool_ctx.clone_mgr + if clone_mgr is None: + return json.dumps({"error": "Clone manager not configured", "stderr": ""}) + + _start = time.monotonic() + try: + result = await asyncio.to_thread( + lambda: clone_mgr.push_to_remote( + clone_path, + source_dir, + branch, + remote_url=remote_url, + protected_branches=tool_ctx.config.safety.protected_branches, + force=force.strip().lower() == "true", + ) ) - return json.dumps(result) - finally: - if step_name: - tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + if not result.get("success"): + await _notify( + ctx, + "error", + "push_to_remote failed", + "autoskillit.push_to_remote", + extra={ + "stderr": result.get("stderr", ""), + "error_type": result.get("error_type", ""), + }, + ) + return json.dumps( + { + "success": False, + "error": "push failed", + "stderr": result.get("stderr", ""), + "error_type": result.get("error_type", ""), + } + ) + + return json.dumps(result) + finally: + if step_name: + tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + except Exception as exc: + logger.error("push_to_remote unhandled exception", exc_info=True) + return json.dumps( + {"success": False, "error": f"{type(exc).__name__}: {exc}", "stderr": ""} + ) @mcp.tool(tags={"autoskillit", "kitchen", "clone"}, annotations={"readOnlyHint": False}) @@ -290,38 +304,63 @@ async def register_clone_status( registry_path: Absolute path to the shared registry file. Defaults to .autoskillit/temp/clone-cleanup-registry.json in cwd. step_name: Optional YAML step key for wall-clock timing accumulation. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="register_clone_status", clone_path=clone_path) - logger.info("register_clone_status", clone_path=clone_path, status=status) + try: + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="register_clone_status", clone_path=clone_path) + logger.info("register_clone_status", clone_path=clone_path, status=status) - if status not in ("success", "error"): - return json.dumps({"error": f"Invalid status '{status}'. Must be 'success' or 'error'."}) + if status not in ("success", "error"): + return json.dumps( + { + "registered": "false", + "reason": f"Invalid status '{status}'. Must be 'success' or 'error'.", + } + ) - from autoskillit.server import _get_ctx + from autoskillit.server import _get_ctx - tool_ctx = _get_ctx() - _start = time.monotonic() - typed_status: Literal["success", "error"] = "success" if status == "success" else "error" - try: - result = await asyncio.to_thread( - clone_registry.register_clone, clone_path, typed_status, registry_path - ) - return json.dumps(result) + tool_ctx = _get_ctx() + owner = tool_ctx.kitchen_id + if owner == "": + return json.dumps( + { + "registered": "false", + "reason": "no active kitchen (kitchen_id empty) — cannot register clone", + } + ) + _start = time.monotonic() + typed_status: Literal["success", "error"] = "success" if status == "success" else "error" + try: + result = await asyncio.to_thread( + clone_registry.register_clone, + clone_path, + typed_status, + owner, + registry_path, + tool_ctx.temp_dir, + ) + return json.dumps(result) + except Exception as exc: + logger.warning("register_clone_status failed", exc_info=True) + return json.dumps({"registered": "false", "reason": str(exc)}) + finally: + if step_name: + tool_ctx.timing_log.record(step_name, time.monotonic() - _start) except Exception as exc: - logger.warning("register_clone_status failed", exc_info=True) - return json.dumps({"registered": "false", "reason": str(exc)}) - finally: - if step_name: - tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + logger.error("register_clone_status unhandled exception", exc_info=True) + return json.dumps({"registered": "false", "reason": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen", "clone"}, annotations={"readOnlyHint": False}) @track_response_size("batch_cleanup_clones") async def batch_cleanup_clones( registry_path: str = "", + all_owners: str = "false", step_name: str = "", ctx: Context = CurrentContext(), ) -> str: @@ -330,11 +369,18 @@ async def batch_cleanup_clones( Called ONCE after all parallel pipelines have completed (after batch_confirm_cleanup action: confirm). Never raises — failures are reported in the result dict. + By default, deletion is scoped to the current kitchen's entries (owner = kitchen_id). + Pass all_owners="true" as an operator escape hatch to delete all success-status entries + regardless of owner, including legacy orphan entries from pre-owner-schema registries. + Returns {"deleted": [...], "delete_failures": [...], "preserved": [...]}. Args: registry_path: Absolute path to the shared registry file. Defaults to .autoskillit/temp/clone-cleanup-registry.json in cwd. + all_owners: "false" (default) scopes deletion to the current kitchen's entries; + "true" is the operator escape hatch that ignores owner and deletes + all success-status entries including legacy orphans. step_name: Optional YAML step key for wall-clock timing accumulation. """ try: @@ -342,7 +388,7 @@ async def batch_cleanup_clones( return gate structlog.contextvars.clear_contextvars() structlog.contextvars.bind_contextvars(tool="batch_cleanup_clones") - logger.info("batch_cleanup_clones", registry_path=registry_path) + logger.info("batch_cleanup_clones", registry_path=registry_path, all_owners=all_owners) from autoskillit.server import _get_ctx @@ -357,10 +403,31 @@ async def batch_cleanup_clones( } ) + is_escape_hatch = all_owners.strip().lower() == "true" + owner_filter: str | None + if is_escape_hatch: + owner_filter = None + else: + owner_filter = tool_ctx.kitchen_id + if owner_filter == "": + return json.dumps( + { + "deleted": [], + "delete_failures": [], + "preserved": [], + "error": "no active kitchen (kitchen_id empty) — " + "pass all_owners='true' to force-cleanup legacy entries", + } + ) + _start = time.monotonic() try: result = await asyncio.to_thread( - clone_registry.batch_delete, registry_path, tool_ctx.clone_mgr.remove_clone + clone_registry.batch_delete, + registry_path, + tool_ctx.clone_mgr.remove_clone, + tool_ctx.temp_dir, + owner_filter, ) return json.dumps(result) finally: diff --git a/src/autoskillit/server/tools_execution.py b/src/autoskillit/server/tools_execution.py index c491028818..879709aabc 100644 --- a/src/autoskillit/server/tools_execution.py +++ b/src/autoskillit/server/tools_execution.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import os import time from pathlib import Path @@ -12,6 +13,7 @@ from autoskillit.core import ( LayoutError, + SkillResult, ValidatedAddDir, get_logger, truncate_text, @@ -19,6 +21,7 @@ ) from autoskillit.server import mcp from autoskillit.server.helpers import ( + SCENARIO_STEP_NAME_ENV, _check_dry_walkthrough, _import_and_call, _notify, @@ -53,44 +56,63 @@ async def run_cmd( cwd: Working directory for the command. timeout: Max seconds before killing the process (default 600). step_name: Optional YAML step key for wall-clock timing accumulation. + + Never raises. """ if (headless := _require_not_headless("run_cmd")) is not None: return headless if (gate := _require_enabled()) is not None: return gate - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="run_cmd", cwd=cwd) - logger.info("run_cmd", cmd=cmd[:80], cwd=cwd) - await _notify(ctx, "info", f"run_cmd: {cmd[:80]}", "autoskillit.run_cmd", extra={"cwd": cwd}) - - from autoskillit.server import _get_ctx - - tool_ctx = _get_ctx() - _start = time.monotonic() try: - returncode, stdout, stderr = await _run_subprocess( - ["bash", "-c", cmd], - cwd=cwd, - timeout=float(timeout), + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="run_cmd", cwd=cwd) + logger.info("run_cmd", cmd=cmd[:80], cwd=cwd) + await _notify( + ctx, "info", f"run_cmd: {cmd[:80]}", "autoskillit.run_cmd", extra={"cwd": cwd} ) - result = { - "success": returncode == 0, - "exit_code": returncode, - "stdout": truncate_text(stdout), - "stderr": truncate_text(stderr), - } - if not result["success"]: - await _notify( - ctx, - "error", - "run_cmd failed", - "autoskillit.run_cmd", - extra={"exit_code": returncode}, + + from autoskillit.server import _get_ctx + + tool_ctx = _get_ctx() + _start = time.monotonic() + try: + _env: dict[str, str] | None = ( + {**os.environ, SCENARIO_STEP_NAME_ENV: step_name} if step_name else None ) - return json.dumps(result) - finally: - if step_name: - tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + returncode, stdout, stderr = await _run_subprocess( + ["bash", "-c", cmd], + cwd=cwd, + timeout=float(timeout), + env=_env, + ) + result = { + "success": returncode == 0, + "exit_code": returncode, + "stdout": truncate_text(stdout), + "stderr": truncate_text(stderr), + } + if not result["success"]: + await _notify( + ctx, + "error", + "run_cmd failed", + "autoskillit.run_cmd", + extra={"exit_code": returncode}, + ) + return json.dumps(result) + finally: + if step_name: + tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + except Exception as exc: + logger.error("run_cmd unhandled exception", exc_info=True) + return json.dumps( + { + "success": False, + "exit_code": -1, + "stdout": "", + "stderr": f"{type(exc).__name__}: {exc}", + } + ) @mcp.tool(tags={"autoskillit", "kitchen"}, annotations={"readOnlyHint": True}) @@ -115,31 +137,37 @@ async def run_python( callable: Dotted path to the function (e.g. "mypackage.module.function"). args: Keyword arguments to pass to the function. timeout: Max seconds before aborting the call (default 30). + + Never raises. """ if (headless := _require_not_headless("run_python")) is not None: return headless if (gate := _require_enabled()) is not None: return gate - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="run_python") - logger.info("run_python", callable=callable, timeout=timeout) - await _notify( - ctx, - "info", - f"run_python: {callable}", - "autoskillit.run_python", - extra={"callable": callable}, - ) - result = await _import_and_call(callable, args=args, timeout=float(timeout)) - if not result.get("success"): + try: + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="run_python") + logger.info("run_python", callable=callable, timeout=timeout) await _notify( ctx, - "error", - "run_python failed", + "info", + f"run_python: {callable}", "autoskillit.run_python", extra={"callable": callable}, ) - return json.dumps(result) + result = await _import_and_call(callable, args=args, timeout=float(timeout)) + if not result.get("success"): + await _notify( + ctx, + "error", + "run_python failed", + "autoskillit.run_python", + extra={"callable": callable}, + ) + return json.dumps(result) + except Exception as exc: + logger.error("run_python unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen"}, annotations={"readOnlyHint": True}) @@ -150,6 +178,8 @@ async def run_skill( model: str = "", step_name: str = "", order_id: str = "", + stale_threshold: int | None = None, + idle_output_timeout: int | None = None, ctx: Context = CurrentContext(), ) -> str: """Run a Claude Code headless session with a skill command. @@ -186,6 +216,14 @@ async def run_skill( order_id: Optional per-issue/order identifier for token telemetry scoping. When set, token and timing entries are keyed by this value, enabling per-issue isolation in get_token_summary/get_timing_summary and in the token_summary_appender hook. + stale_threshold: Override the staleness kill threshold in seconds. When set on + a RecipeStep, the recipe orchestrator passes it here. None uses the global + config default (RunSkillConfig.stale_threshold, default 1200s). + idle_output_timeout: Override the idle stdout kill threshold in seconds. + 0 = disabled for this step. None = use global config + (RunSkillConfig.idle_output_timeout, default 600s). + + Never raises. """ if (headless := _require_not_headless("run_skill")) is not None: return headless @@ -204,101 +242,134 @@ async def run_skill( ), } ) - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="run_skill", cwd=cwd) - logger.info("run_skill", command=skill_command[:80], cwd=cwd) - await _notify( - ctx, - "info", - f"run_skill: {skill_command[:80]}", - "autoskillit.run_skill", - extra={"cwd": cwd, "model": model or "default"}, - ) - - from autoskillit.server import _get_config, _get_ctx - - if _get_config().safety.require_dry_walkthrough: - if (gate_error := _check_dry_walkthrough(skill_command, cwd)) is not None: - return gate_error - - tool_ctx = _get_ctx() - if tool_ctx.executor is None: - return json.dumps({"success": False, "error": "Executor not configured"}) - - # Look up artifact validation patterns from skill contract - expected_output_patterns: list[str] = [] - if tool_ctx.output_pattern_resolver: - expected_output_patterns = list(tool_ctx.output_pattern_resolver(skill_command)) - - # Look up write-expectation metadata from skill contract - from autoskillit.core import WriteBehaviorSpec - - write_spec: WriteBehaviorSpec | None = None - if tool_ctx.write_expected_resolver: - write_spec = tool_ctx.write_expected_resolver(skill_command) - - # Build validated add_dirs via DefaultSessionSkillManager - from pathlib import Path - from uuid import uuid4 - - from autoskillit.core import resolve_target_skill - - # Resolve correct namespace and prepare for tier2 activation - resolved_command = skill_command - target_name: str | None = None - if tool_ctx.skill_resolver is not None: - resolved_command, target_name = resolve_target_skill( - skill_command, tool_ctx.skill_resolver + try: + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="run_skill", cwd=cwd) + logger.info("run_skill", command=skill_command[:80], cwd=cwd) + await _notify( + ctx, + "info", + f"run_skill: {skill_command[:80]}", + "autoskillit.run_skill", + extra={"cwd": cwd, "model": model or "default"}, ) - skill_add_dirs: list[ValidatedAddDir] = [] - if tool_ctx.session_skill_manager is not None: - session_id = f"headless-{uuid4().hex[:12]}" - session_root = tool_ctx.session_skill_manager.init_session( - session_id, - cook_session=False, - config=tool_ctx.config, - project_dir=Path(cwd), - recipe_packs=tool_ctx.active_recipe_packs, - ) - skill_add_dirs.append(session_root) + from autoskillit.server import _get_config, _get_ctx - # Activate the target skill so it's invocable in the headless session - if target_name: - tier2_skills = frozenset(tool_ctx.config.skills.tier2) - if target_name in tier2_skills: - tool_ctx.session_skill_manager.activate_tier2(session_id, target_name) - try: - skill_add_dirs.append(validate_add_dir(Path(cwd))) - except LayoutError: - pass # cwd has no project-local skills — already accessible as working dir + if _get_config().safety.require_dry_walkthrough: + if (gate_error := _check_dry_walkthrough(skill_command, cwd)) is not None: + return gate_error - _start = time.monotonic() - try: - skill_result = await tool_ctx.executor.run( - resolved_command, - cwd, - model=model, - add_dirs=skill_add_dirs, - step_name=step_name, - kitchen_id=tool_ctx.kitchen_id, - order_id=order_id, - expected_output_patterns=expected_output_patterns, - write_behavior=write_spec, - ) - if skill_result.success: - tool_ctx.audit.record_success(skill_command) - else: - await _notify( - ctx, - "error", - "run_skill failed", - "autoskillit.run_skill", - extra={"exit_code": skill_result.exit_code, "subtype": skill_result.subtype}, + tool_ctx = _get_ctx() + if tool_ctx.executor is None: + return json.dumps({"success": False, "error": "Executor not configured"}) + + # Look up artifact validation patterns from skill contract + expected_output_patterns: list[str] = [] + if tool_ctx.output_pattern_resolver: + expected_output_patterns = list(tool_ctx.output_pattern_resolver(skill_command)) + + # Look up write-expectation metadata from skill contract + from autoskillit.core import WriteBehaviorSpec + + write_spec: WriteBehaviorSpec | None = None + if tool_ctx.write_expected_resolver: + write_spec = tool_ctx.write_expected_resolver(skill_command) + + # Build validated add_dirs via DefaultSessionSkillManager + from pathlib import Path + from uuid import uuid4 + + from autoskillit.core import resolve_target_skill + + # Resolve correct namespace and prepare for tier2 activation + resolved_command = skill_command + target_name: str | None = None + if tool_ctx.skill_resolver is not None: + resolved_command, target_name = resolve_target_skill( + skill_command, tool_ctx.skill_resolver + ) + + invocation_marker = f"%%ORDER_UP::{uuid4().hex[:8]}%%" + + skill_add_dirs: list[ValidatedAddDir] = [] + if tool_ctx.session_skill_manager is not None: + allow_only: frozenset[str] | None = None + if target_name: + closure = tool_ctx.session_skill_manager.compute_skill_closure(target_name) + allow_only = closure if closure else None + + session_id = f"headless-{uuid4().hex[:12]}" + session_root = tool_ctx.session_skill_manager.init_session( + session_id, + cook_session=False, + config=tool_ctx.config, + project_dir=Path(cwd), + recipe_packs=tool_ctx.active_recipe_packs, + allow_only=allow_only, ) - if order_id: - skill_result.order_id = order_id - return skill_result.to_json() - finally: - if step_name: - tool_ctx.timing_log.record(step_name, time.monotonic() - _start, order_id=order_id) + skill_add_dirs.append(session_root) + + # Activate the target skill and its declared dependencies + if target_name: + tool_ctx.session_skill_manager.activate_skill_deps(session_id, target_name) + try: + skill_add_dirs.append(validate_add_dir(Path(cwd))) + except LayoutError: + pass # cwd has no project-local skills — already accessible as working dir + + _start = time.monotonic() + try: + skill_result = await tool_ctx.executor.run( + resolved_command, + cwd, + model=model, + add_dirs=skill_add_dirs, + step_name=step_name, + kitchen_id=tool_ctx.kitchen_id, + order_id=order_id, + expected_output_patterns=expected_output_patterns, + write_behavior=write_spec, + stale_threshold=float(stale_threshold) if stale_threshold is not None else None, + idle_output_timeout=float(idle_output_timeout) + if idle_output_timeout is not None + else None, + completion_marker=invocation_marker, + ) + if skill_result.success: + tool_ctx.audit.record_success(skill_command) + else: + await _notify( + ctx, + "error", + "run_skill failed", + "autoskillit.run_skill", + extra={"exit_code": skill_result.exit_code, "subtype": skill_result.subtype}, + ) + if order_id: + skill_result.order_id = order_id + from autoskillit.server.helpers import _refresh_quota_cache # noqa: PLC0415 + + if tool_ctx.background is not None: + tool_ctx.background.submit( + _refresh_quota_cache(tool_ctx.config.quota_guard), + label="quota_post_run_refresh", + ) + return skill_result.to_json() + except Exception as exc: + logger.error("run_skill executor raised unexpectedly", exc_info=True) + return SkillResult.crashed( + exception=exc, + skill_command=resolved_command, + order_id=order_id, + ).to_json() + finally: + if step_name: + tool_ctx.timing_log.record(step_name, time.monotonic() - _start, order_id=order_id) + except Exception as exc: + logger.error("run_skill unhandled exception", exc_info=True) + return SkillResult.crashed( + exception=exc, + skill_command=skill_command, + order_id=order_id, + ).to_json() diff --git a/src/autoskillit/server/tools_git.py b/src/autoskillit/server/tools_git.py index 9b9cabb7fb..840e36dff2 100644 --- a/src/autoskillit/server/tools_git.py +++ b/src/autoskillit/server/tools_git.py @@ -41,49 +41,55 @@ async def merge_worktree( worktree_path: Absolute path to the git worktree. base_branch: Branch to merge into (e.g. "integration"). step_name: Optional YAML step key for wall-clock timing accumulation. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="merge_worktree", cwd=worktree_path) - logger.info("merge_worktree", path=worktree_path, base=base_branch) - await _notify( - ctx, - "info", - f"merge_worktree: {worktree_path} -> {base_branch}", - "autoskillit.merge_worktree", - extra={"worktree": worktree_path, "base": base_branch}, - ) - - from autoskillit.server import _get_config, _get_ctx - from autoskillit.server.git import perform_merge - - tool_ctx = _get_ctx() - runner = tool_ctx.runner - assert runner is not None, "No subprocess runner configured" - _start = time.monotonic() try: - result = await perform_merge( - worktree_path, - base_branch, - config=_get_config(), - runner=runner, - tester=tool_ctx.tester, + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="merge_worktree", cwd=worktree_path) + logger.info("merge_worktree", path=worktree_path, base=base_branch) + await _notify( + ctx, + "info", + f"merge_worktree: {worktree_path} -> {base_branch}", + "autoskillit.merge_worktree", + extra={"worktree": worktree_path, "base": base_branch}, ) - if "error" in result: - await _notify( - ctx, - "error", - "merge_worktree failed", - "autoskillit.merge_worktree", - extra={"reason": result["error"]}, + from autoskillit.server import _get_config, _get_ctx + from autoskillit.server.git import perform_merge + + tool_ctx = _get_ctx() + runner = tool_ctx.runner + assert runner is not None, "No subprocess runner configured" + _start = time.monotonic() + try: + result = await perform_merge( + worktree_path, + base_branch, + config=_get_config(), + runner=runner, + tester=tool_ctx.tester, ) - return json.dumps(result) - finally: - if step_name: - tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + if "error" in result: + await _notify( + ctx, + "error", + "merge_worktree failed", + "autoskillit.merge_worktree", + extra={"reason": result["error"]}, + ) + + return json.dumps(result) + finally: + if step_name: + tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + except Exception as exc: + logger.error("merge_worktree unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen"}, annotations={"readOnlyHint": True}) @@ -111,109 +117,125 @@ async def classify_fix( worktree_path: Path to the git worktree with the implemented fix. base_branch: The branch the worktree was created from (for merge-base). step_name: Optional YAML step key for wall-clock timing accumulation. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="classify_fix", cwd=worktree_path) - logger.info("classify_fix", worktree=worktree_path, base=base_branch) - await _notify( - ctx, - "info", - f"classify_fix: {worktree_path}", - "autoskillit.classify_fix", - extra={"worktree": worktree_path, "base": base_branch}, - ) - - if not os.path.isdir(worktree_path): - return json.dumps( - { - "restart_scope": RestartScope.FULL_RESTART, - "reason": f"worktree_path does not exist or is not a directory: {worktree_path}", - "critical_files": [], - "all_changed_files": [], - } - ) - - from autoskillit.server import _get_config, _get_ctx - from autoskillit.server.git import _filter_changed_files - - tool_ctx = _get_ctx() - _start = time.monotonic() try: - fetch_rc, _, fetch_stderr = await _run_subprocess( - ["git", "fetch", "origin", base_branch], - cwd=worktree_path, - timeout=30, + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="classify_fix", cwd=worktree_path) + logger.info("classify_fix", worktree=worktree_path, base=base_branch) + await _notify( + ctx, + "info", + f"classify_fix: {worktree_path}", + "autoskillit.classify_fix", + extra={"worktree": worktree_path, "base": base_branch}, ) - if fetch_rc != 0: + + if not os.path.isdir(worktree_path): return json.dumps( { "restart_scope": RestartScope.FULL_RESTART, "reason": ( - f"git fetch origin {base_branch} failed — " - "remote-tracking ref may be stale. " - f"git error: {(fetch_stderr or '').strip()[:200]}" + f"worktree_path does not exist or is not a directory: {worktree_path}" ), "critical_files": [], "all_changed_files": [], } ) - returncode, stdout, stderr = await _run_subprocess( - ["git", "diff", "--name-only", f"origin/{base_branch}...HEAD"], - cwd=worktree_path, - timeout=30, - ) + from autoskillit.server import _get_config, _get_ctx + from autoskillit.server.git import _filter_changed_files - if returncode != 0: - await _notify( - ctx, - "error", - "classify_fix: git diff failed (falling back to full_restart)", - "autoskillit.classify_fix", - extra={"worktree": worktree_path}, + tool_ctx = _get_ctx() + _start = time.monotonic() + try: + fetch_rc, _, fetch_stderr = await _run_subprocess( + ["git", "fetch", "origin", base_branch], + cwd=worktree_path, + timeout=30, ) - # A missing origin/ ref (rc=128, "ambiguous argument" or - # "unknown revision") is treated as FULL_RESTART — conservative safe default. - # Any other git error also falls back to FULL_RESTART for the same reason: - # if we can't determine what changed, assume the worst. - return json.dumps( - { - "restart_scope": RestartScope.FULL_RESTART, - "reason": ( - f"Cannot diff against origin/{base_branch} — ref may not exist locally. " - f"git error: {stderr.strip()[:200]}" - ), - "critical_files": [], - "all_changed_files": [], - } + if fetch_rc != 0: + return json.dumps( + { + "restart_scope": RestartScope.FULL_RESTART, + "reason": ( + f"git fetch origin {base_branch} failed — " + "remote-tracking ref may be stale. " + f"git error: {(fetch_stderr or '').strip()[:200]}" + ), + "critical_files": [], + "all_changed_files": [], + } + ) + + returncode, stdout, stderr = await _run_subprocess( + ["git", "diff", "--name-only", f"origin/{base_branch}...HEAD"], + cwd=worktree_path, + timeout=30, ) - prefixes = _get_config().classify_fix.path_prefixes - changed_files, critical_files = _filter_changed_files(stdout, prefixes) + if returncode != 0: + await _notify( + ctx, + "error", + "classify_fix: git diff failed (falling back to full_restart)", + "autoskillit.classify_fix", + extra={"worktree": worktree_path}, + ) + # A missing origin/ ref (rc=128, "ambiguous argument" or + # "unknown revision") is treated as FULL_RESTART — conservative safe default. + # Any other git error also falls back to FULL_RESTART for the same reason: + # if we can't determine what changed, assume the worst. + return json.dumps( + { + "restart_scope": RestartScope.FULL_RESTART, + "reason": ( + f"Cannot diff against origin/{base_branch}" + f" — ref may not exist locally. " + f"git error: {stderr.strip()[:200]}" + ), + "critical_files": [], + "all_changed_files": [], + } + ) + + prefixes = _get_config().classify_fix.path_prefixes + changed_files, critical_files = _filter_changed_files(stdout, prefixes) + + if critical_files: + return json.dumps( + { + "restart_scope": RestartScope.FULL_RESTART, + "reason": f"Fix touches critical paths: {', '.join(critical_files[:5])}", + "critical_files": critical_files, + "all_changed_files": changed_files, + } + ) - if critical_files: return json.dumps( { - "restart_scope": RestartScope.FULL_RESTART, - "reason": f"Fix touches critical paths: {', '.join(critical_files[:5])}", - "critical_files": critical_files, + "restart_scope": RestartScope.PARTIAL_RESTART, + "reason": "Fix does not touch critical paths — partial restart is sufficient", + "critical_files": [], "all_changed_files": changed_files, } ) - + finally: + if step_name: + tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + except Exception as exc: + logger.error("classify_fix unhandled exception", exc_info=True) return json.dumps( { - "restart_scope": RestartScope.PARTIAL_RESTART, - "reason": "Fix does not touch critical paths — partial restart is sufficient", + "restart_scope": RestartScope.FULL_RESTART, + "reason": f"{type(exc).__name__}: {exc}", "critical_files": [], - "all_changed_files": changed_files, + "all_changed_files": [], } ) - finally: - if step_name: - tool_ctx.timing_log.record(step_name, time.monotonic() - _start) @mcp.tool(tags={"autoskillit", "kitchen", "github"}, annotations={"readOnlyHint": True}) @@ -257,89 +279,116 @@ async def create_unique_branch( base_branch_name: When provided, use this directly as the base name instead of composing from slug+issue_number. step_name: Optional YAML step key for wall-clock timing accumulation. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="create_unique_branch", cwd=cwd) - _display = base_branch_name if base_branch_name else slug - logger.info( - "create_unique_branch", - slug=slug, - issue_number=issue_number, - remote=remote, - base_branch_name=base_branch_name, - ) - await _notify( - ctx, - "info", - f"create_unique_branch: {_display}", - "autoskillit.create_unique_branch", - extra={"remote": remote}, - ) - - from autoskillit.server import _get_ctx - - tool_ctx = _get_ctx() - _start = time.monotonic() - - if base_branch_name: - base_name = base_branch_name - elif not slug: - return json.dumps( - { - "success": False, - "error": "create_unique_branch requires either base_branch_name or slug", - } - ) - else: - base_name = f"{slug}-{issue_number}" if issue_number is not None else slug - branch_name = base_name - was_unique = True - try: - rc, stdout, _ = await _run_subprocess( - ["git", "ls-remote", remote, f"refs/heads/{branch_name}"], - cwd=cwd, - timeout=30, + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="create_unique_branch", cwd=cwd) + _display = base_branch_name if base_branch_name else slug + logger.info( + "create_unique_branch", + slug=slug, + issue_number=issue_number, + remote=remote, + base_branch_name=base_branch_name, ) - - if rc == 0 and stdout.strip(): - was_unique = False - suffix = 2 - _MAX_SUFFIX = 100 - while suffix <= _MAX_SUFFIX: - candidate = f"{base_name}-{suffix}" - rc2, stdout2, _ = await _run_subprocess( - ["git", "ls-remote", remote, f"refs/heads/{candidate}"], - cwd=cwd, - timeout=30, - ) - if rc2 != 0: - branch_name = candidate - break - if not stdout2.strip(): - branch_name = candidate - break - suffix += 1 - - rc_checkout, _, _stderr_checkout = await _run_subprocess( - ["git", "checkout", "-b", branch_name], - cwd=cwd, - timeout=30, + await _notify( + ctx, + "info", + f"create_unique_branch: {_display}", + "autoskillit.create_unique_branch", + extra={"remote": remote}, ) - if rc_checkout != 0: + + from autoskillit.server import _get_ctx + + tool_ctx = _get_ctx() + _start = time.monotonic() + + if base_branch_name: + base_name = base_branch_name + elif not slug: return json.dumps( { "success": False, - "error": f"git checkout -b {branch_name!r} failed: {_stderr_checkout.strip()}", + "error": "create_unique_branch requires either base_branch_name or slug", } ) + else: + base_name = f"{slug}-{issue_number}" if issue_number is not None else slug + branch_name = base_name + was_unique = True + + try: + rc, stdout, _ = await _run_subprocess( + ["git", "ls-remote", remote, f"refs/heads/{branch_name}"], + cwd=cwd, + timeout=30, + ) + + if rc == 0 and stdout.strip(): + was_unique = False + suffix = 2 + _MAX_SUFFIX = 100 + while suffix <= _MAX_SUFFIX: + candidate = f"{base_name}-{suffix}" + rc2, stdout2, _ = await _run_subprocess( + ["git", "ls-remote", remote, f"refs/heads/{candidate}"], + cwd=cwd, + timeout=30, + ) + if rc2 != 0: + branch_name = candidate + break + if not stdout2.strip(): + branch_name = candidate + break + suffix += 1 + else: + return json.dumps( + { + "success": False, + "error": ( + f"All branch name candidates up to " + f"{base_name}-{_MAX_SUFFIX} are taken." + ), + } + ) + + rc_head, head_out, _ = await _run_subprocess( + ["git", "branch", "--show-current"], + cwd=cwd, + timeout=10, + ) + base_ref = head_out.strip() if rc_head == 0 and head_out.strip() else "DETACHED_HEAD" - return json.dumps({"branch_name": branch_name, "was_unique": was_unique}) - finally: - if step_name: - tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + rc_checkout, _, _stderr_checkout = await _run_subprocess( + ["git", "checkout", "-b", branch_name], + cwd=cwd, + timeout=30, + ) + if rc_checkout != 0: + return json.dumps( + { + "success": False, + "error": ( + f"git checkout -b {branch_name!r} failed: {_stderr_checkout.strip()}" + ), + } + ) + + return json.dumps( + {"branch_name": branch_name, "was_unique": was_unique, "base_ref": base_ref} + ) + finally: + if step_name: + tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + except Exception as exc: + logger.error("create_unique_branch unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen", "github"}, annotations={"readOnlyHint": True}) @@ -365,37 +414,43 @@ async def check_pr_mergeable( pr_number: GitHub pull request number. cwd: Working directory for gh commands. repo: Repository as owner/repo. Passed as -R flag when provided. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="check_pr_mergeable", cwd=cwd) - logger.info("check_pr_mergeable", pr_number=pr_number, repo=repo) - await _notify( - ctx, - "info", - f"check_pr_mergeable: #{pr_number}", - "autoskillit.check_pr_mergeable", - extra={"repo": repo}, - ) - - cmd = ["gh", "pr", "view", str(pr_number), "--json", "mergeable,mergeStateStatus"] - if repo: - cmd.extend(["-R", repo]) - - rc, stdout, stderr = await _run_subprocess(cmd, cwd=cwd, timeout=30) - if rc != 0: - return json.dumps({"success": False, "error": stderr.strip() or "gh command failed"}) - try: - data = json.loads(stdout) - except json.JSONDecodeError: - return json.dumps({"success": False, "error": "Failed to parse gh output"}) - - return json.dumps( - { - "mergeable": data.get("mergeable") == "MERGEABLE", - "merge_state_status": data.get("mergeStateStatus", ""), - "mergeable_status": data.get("mergeable", ""), - } - ) + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="check_pr_mergeable", cwd=cwd) + logger.info("check_pr_mergeable", pr_number=pr_number, repo=repo) + await _notify( + ctx, + "info", + f"check_pr_mergeable: #{pr_number}", + "autoskillit.check_pr_mergeable", + extra={"repo": repo}, + ) + + cmd = ["gh", "pr", "view", str(pr_number), "--json", "mergeable,mergeStateStatus"] + if repo: + cmd.extend(["-R", repo]) + + rc, stdout, stderr = await _run_subprocess(cmd, cwd=cwd, timeout=30) + if rc != 0: + return json.dumps({"success": False, "error": stderr.strip() or "gh command failed"}) + + try: + data = json.loads(stdout) + except json.JSONDecodeError: + return json.dumps({"success": False, "error": "Failed to parse gh output"}) + + return json.dumps( + { + "mergeable": data.get("mergeable") == "MERGEABLE", + "merge_state_status": data.get("mergeStateStatus", ""), + "mergeable_status": data.get("mergeable", ""), + } + ) + except Exception as exc: + logger.error("check_pr_mergeable unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) diff --git a/src/autoskillit/server/tools_github.py b/src/autoskillit/server/tools_github.py index 99c351ba81..e2b1bfa9af 100644 --- a/src/autoskillit/server/tools_github.py +++ b/src/autoskillit/server/tools_github.py @@ -64,9 +64,9 @@ async def fetch_github_issue( This tool requires the kitchen to be open (gated by open_kitchen). """ + if (gate := _require_enabled()) is not None: + return gate try: - if (gate := _require_enabled()) is not None: - return gate from autoskillit.server import _get_config, _get_ctx # Read-only query: structlog context binding is intentionally omitted. @@ -119,29 +119,35 @@ async def get_issue_title(issue_url: str) -> str: Args: issue_url: Full GitHub issue URL (https://github.com/owner/repo/issues/42) or shorthand (owner/repo#42). + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - from autoskillit.server import _get_config, _get_ctx + try: + from autoskillit.server import _get_config, _get_ctx - tool_ctx = _get_ctx() - if tool_ctx.github_client is None: - return json.dumps({"success": False, "error": "GitHub client not available."}) + tool_ctx = _get_ctx() + if tool_ctx.github_client is None: + return json.dumps({"success": False, "error": "GitHub client not available."}) - config = _get_config() - url = issue_url.strip() - if url.isdigit(): - if not config.github.default_repo: - return json.dumps( - { - "success": False, - "error": "Bare issue number requires github.default_repo in config.", - } - ) - url = f"{config.github.default_repo}#{url}" + config = _get_config() + url = issue_url.strip() + if url.isdigit(): + if not config.github.default_repo: + return json.dumps( + { + "success": False, + "error": "Bare issue number requires github.default_repo in config.", + } + ) + url = f"{config.github.default_repo}#{url}" - result = await tool_ctx.github_client.fetch_title(url) - return json.dumps(result) + result = await tool_ctx.github_client.fetch_title(url) + return json.dumps(result) + except Exception as exc: + logger.error("get_issue_title unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen", "github"}, annotations={"readOnlyHint": True}) @@ -177,121 +183,126 @@ async def report_bug( severity: "non_blocking" (fire-and-forget) or "blocking" (await completion). model: Model override. Empty string = config default. step_name: Optional label for token tracking. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate + try: + with structlog.contextvars.bound_contextvars( + tool="report_bug", cwd=cwd, severity=severity + ): + logger.info("report_bug", error_context=error_context[:80], severity=severity) + await _notify( + ctx, + "info", + f"report_bug: {error_context[:60]}", + "autoskillit.report_bug", + extra={"severity": severity, "cwd": cwd}, + ) - with structlog.contextvars.bound_contextvars(tool="report_bug", cwd=cwd, severity=severity): - logger.info("report_bug", error_context=error_context[:80], severity=severity) - await _notify( - ctx, - "info", - f"report_bug: {error_context[:60]}", - "autoskillit.report_bug", - extra={"severity": severity, "cwd": cwd}, - ) - - from autoskillit.server import _get_config, _get_ctx - - tool_ctx = _get_ctx() - if tool_ctx.executor is None: - return json.dumps({"success": False, "error": "Executor not configured"}) + from autoskillit.server import _get_config, _get_ctx - config = _get_config() - cfg = config.report_bug + tool_ctx = _get_ctx() + if tool_ctx.executor is None: + return json.dumps({"success": False, "error": "Executor not configured"}) - # Resolve and create the report directory up front so the path is stable - # before the (potentially background) session writes the file. - report_dir = ( - Path(cfg.report_dir) - if cfg.report_dir - else Path(cwd) / ".autoskillit" / "temp" / "bug-reports" - ) - report_dir.mkdir(parents=True, exist_ok=True) - timestamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%S") - report_path = report_dir / f"{timestamp}_report.md" - - effective_model = model or cfg.model or "" - skill_command = ( - f"/autoskillit:report-bug\n\n" - f"Error context:\n{error_context}\n\n" - f"Report output path: {report_path}" - ) + config = _get_config() + cfg = config.report_bug - log_dir = config.linux_tracing.log_dir if config.linux_tracing is not None else "" - - expected_output_patterns: list[str] = [] - if tool_ctx.output_pattern_resolver: - expected_output_patterns = list(tool_ctx.output_pattern_resolver(skill_command)) - - from autoskillit.core import WriteBehaviorSpec - - write_spec: WriteBehaviorSpec | None = None - if tool_ctx.write_expected_resolver: - write_spec = tool_ctx.write_expected_resolver(skill_command) - - if severity == "blocking": - result = await _run_report_session( - skill_command, - cwd, - report_path, - error_context, - tool_ctx.executor, - tool_ctx.github_client, - config, - effective_model, - step_name, - log_dir=log_dir, - expected_output_patterns=expected_output_patterns, - write_behavior=write_spec, + # Resolve and create the report directory up front so the path is stable + # before the (potentially background) session writes the file. + report_dir = ( + Path(cfg.report_dir) if cfg.report_dir else tool_ctx.temp_dir / "bug-reports" + ) + report_dir.mkdir(parents=True, exist_ok=True) + timestamp = datetime.now(UTC).strftime("%Y%m%dT%H%M%S") + report_path = report_dir / f"{timestamp}_report.md" + + effective_model = model or cfg.model or "" + skill_command = ( + f"/autoskillit:report-bug\n\n" + f"Error context:\n{error_context}\n\n" + f"Report output path: {report_path}" ) - if not result["success"]: - await _notify( - ctx, - "error", - "report_bug session failed", - "autoskillit.report_bug", - extra={"report_path": str(report_path)}, + + log_dir = config.linux_tracing.log_dir if config.linux_tracing is not None else "" + + expected_output_patterns: list[str] = [] + if tool_ctx.output_pattern_resolver: + expected_output_patterns = list(tool_ctx.output_pattern_resolver(skill_command)) + + from autoskillit.core import WriteBehaviorSpec + + write_spec: WriteBehaviorSpec | None = None + if tool_ctx.write_expected_resolver: + write_spec = tool_ctx.write_expected_resolver(skill_command) + + if severity == "blocking": + result = await _run_report_session( + skill_command, + cwd, + report_path, + error_context, + tool_ctx.executor, + tool_ctx.github_client, + config, + effective_model, + step_name, + log_dir=log_dir, + expected_output_patterns=expected_output_patterns, + write_behavior=write_spec, ) - return json.dumps(result) - - # Non-blocking: supervised background dispatch, return immediately. - status_path = report_path.with_suffix(".status.json") - atomic_write( - status_path, - json.dumps( - {"status": "pending", "dispatched_at": datetime.now(UTC).isoformat()}, - indent=2, - ), - ) - if tool_ctx.background is None: # always set by ToolContext.__post_init__ - raise RuntimeError("ToolContext.background not initialized") - tool_ctx.background.submit( - _run_report_session( - skill_command, - cwd, - report_path, - error_context, - tool_ctx.executor, - tool_ctx.github_client, - config, - effective_model, - step_name, - log_dir=log_dir, - expected_output_patterns=expected_output_patterns, - write_behavior=write_spec, - status_path=status_path, - ), - label=step_name or "report_bug", - ) - return json.dumps( - { - "success": True, - "status": "dispatched", - "report_path": str(report_path), - "status_path": str(status_path), - } - ) + if not result["success"]: + await _notify( + ctx, + "error", + "report_bug session failed", + "autoskillit.report_bug", + extra={"report_path": str(report_path)}, + ) + return json.dumps(result) + + # Non-blocking: supervised background dispatch, return immediately. + status_path = report_path.with_suffix(".status.json") + atomic_write( + status_path, + json.dumps( + {"status": "pending", "dispatched_at": datetime.now(UTC).isoformat()}, + indent=2, + ), + ) + if tool_ctx.background is None: # always set by ToolContext.__post_init__ + raise RuntimeError("ToolContext.background not initialized") + tool_ctx.background.submit( + _run_report_session( + skill_command, + cwd, + report_path, + error_context, + tool_ctx.executor, + tool_ctx.github_client, + config, + effective_model, + step_name, + log_dir=log_dir, + expected_output_patterns=expected_output_patterns, + write_behavior=write_spec, + status_path=status_path, + ), + label=step_name or "report_bug", + ) + return json.dumps( + { + "success": True, + "status": "dispatched", + "report_path": str(report_path), + "status_path": str(status_path), + } + ) + except Exception as exc: + logger.error("report_bug unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) # --------------------------------------------------------------------------- @@ -378,6 +389,8 @@ def _format_diagnostics_section(diag: dict[str, Any], condensed: bool = False) - termination = s.get("termination_reason", "—") exit_code = s.get("exit_code", "—") claude_code_log: str = s.get("claude_code_log") or "" + tracked_comm: str | None = s.get("tracked_comm") + tracked_comm_drift: bool = bool(s.get("tracked_comm_drift", False)) lines: list[str] = [ "## Session Diagnostics", @@ -391,8 +404,13 @@ def _format_diagnostics_section(diag: dict[str, Any], condensed: bool = False) - f"| Anomaly Count | {anomaly_count} |", f"| Termination | {termination} |", f"| Exit Code | {exit_code} |", - "", ] + if tracked_comm is not None: + comm_display = f"`{tracked_comm}`" + if tracked_comm_drift: + comm_display += " ⚠️ drift" + lines.append(f"| Tracked Process | {comm_display} |") + lines.append("") if condensed: return "\n".join(lines) diff --git a/src/autoskillit/server/tools_issue_lifecycle.py b/src/autoskillit/server/tools_issue_lifecycle.py index f14399a621..5d25b76422 100644 --- a/src/autoskillit/server/tools_issue_lifecycle.py +++ b/src/autoskillit/server/tools_issue_lifecycle.py @@ -190,77 +190,82 @@ async def prepare_issue( labels: Additional labels to apply beyond triage labels (optional). dry_run: When True, classifies and previews without creating or labeling. split: When True, splits mixed-concern issues into sub-issues automatically. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate + try: + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="prepare_issue", title=title[:60]) + logger.info("prepare_issue", title=title[:60], dry_run=dry_run, split=split) + await _notify( + ctx, + "info", + f"prepare_issue: {title[:60]}", + "autoskillit.prepare_issue", + extra={"dry_run": dry_run, "split": split}, + ) - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="prepare_issue", title=title[:60]) - logger.info("prepare_issue", title=title[:60], dry_run=dry_run, split=split) - await _notify( - ctx, - "info", - f"prepare_issue: {title[:60]}", - "autoskillit.prepare_issue", - extra={"dry_run": dry_run, "split": split}, - ) - - from autoskillit.server import _get_ctx - - tool_ctx = _get_ctx() - if tool_ctx.executor is None: - return json.dumps({"success": False, "error": "Executor not configured"}) + from autoskillit.server import _get_ctx - if labels: - if err := tool_ctx.config.github.check_labels_allowed(labels): - return json.dumps({"success": False, "error": err}) + tool_ctx = _get_ctx() + if tool_ctx.executor is None: + return json.dumps({"success": False, "error": "Executor not configured"}) - skill_command = _build_prepare_skill_command(title, body, repo, labels, dry_run, split) + if labels: + if err := tool_ctx.config.github.check_labels_allowed(labels): + return json.dumps({"success": False, "error": err}) - expected_output_patterns: list[str] = [] - if tool_ctx.output_pattern_resolver: - expected_output_patterns = list(tool_ctx.output_pattern_resolver(skill_command)) + skill_command = _build_prepare_skill_command(title, body, repo, labels, dry_run, split) - write_spec: WriteBehaviorSpec | None = None - if tool_ctx.write_expected_resolver: - write_spec = tool_ctx.write_expected_resolver(skill_command) + expected_output_patterns: list[str] = [] + if tool_ctx.output_pattern_resolver: + expected_output_patterns = list(tool_ctx.output_pattern_resolver(skill_command)) - result = await tool_ctx.executor.run( - skill_command, - str(Path.cwd()), - expected_output_patterns=expected_output_patterns, - write_behavior=write_spec, - ) + write_spec: WriteBehaviorSpec | None = None + if tool_ctx.write_expected_resolver: + write_spec = tool_ctx.write_expected_resolver(skill_command) - if not result.success: - return json.dumps( - _build_headless_error_response(result, error=_retry_reason_to_error(result)) + result = await tool_ctx.executor.run( + skill_command, + str(Path.cwd()), + expected_output_patterns=expected_output_patterns, + write_behavior=write_spec, ) - if result.result is None or not result.result.strip(): - return json.dumps( - _build_headless_error_response( - result, - error="session completed but output was empty (drain race)", + if not result.success: + return json.dumps( + _build_headless_error_response(result, error=_retry_reason_to_error(result)) ) - ) - parsed = _parse_prepare_result(result.result) - # Distinguish block-parse failures (block absent or malformed JSON) from skill-level data. - # The sentinel errors from _parse_prepare_result signal a block-extraction failure — - # these are not the same as skill-internal errors embedded in a valid block. - if parsed.get("error") in _BLOCK_PARSE_ERRORS: - return json.dumps(_build_headless_error_response(result, error=parsed["error"])) + if result.result is None or not result.result.strip(): + return json.dumps( + _build_headless_error_response( + result, + error="session completed but output was empty (drain race)", + ) + ) - # Block parsed successfully. result.success=True is the authoritative signal — - # the parsed block's "success" field (if any) must not overwrite it. - return json.dumps( - { - "success": True, - "status": "complete", - **_without_success_key(parsed), - } - ) + parsed = _parse_prepare_result(result.result) + # Distinguish block-parse failures (block absent or malformed JSON) from skill-level data. + # The sentinel errors from _parse_prepare_result signal a block-extraction failure — + # these are not the same as skill-internal errors embedded in a valid block. + if parsed.get("error") in _BLOCK_PARSE_ERRORS: + return json.dumps(_build_headless_error_response(result, error=parsed["error"])) + + # Block parsed successfully. result.success=True is the authoritative signal — + # the parsed block's "success" field (if any) must not overwrite it. + return json.dumps( + { + "success": True, + "status": "complete", + **_without_success_key(parsed), + } + ) + except Exception as exc: + logger.error("prepare_issue unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen", "github"}, annotations={"readOnlyHint": True}) @@ -291,73 +296,78 @@ async def enrich_issues( batch: Filter candidates by batch:N label in addition to recipe:implementation. dry_run: When True, previews generated requirements without editing issues. repo: Target repository as owner/repo. Falls back to gh default repo if None. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate + try: + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars( + tool="enrich_issues", + issue_number=issue_number, + batch=batch, + dry_run=dry_run, + ) + logger.info("enrich_issues", issue_number=issue_number, batch=batch, dry_run=dry_run) + await _notify( + ctx, + "info", + "enrich_issues: backfilling requirements on recipe:implementation issues", + "autoskillit.enrich_issues", + extra={"dry_run": dry_run}, + ) - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars( - tool="enrich_issues", - issue_number=issue_number, - batch=batch, - dry_run=dry_run, - ) - logger.info("enrich_issues", issue_number=issue_number, batch=batch, dry_run=dry_run) - await _notify( - ctx, - "info", - "enrich_issues: backfilling requirements on recipe:implementation issues", - "autoskillit.enrich_issues", - extra={"dry_run": dry_run}, - ) - - from autoskillit.server import _get_ctx - - tool_ctx = _get_ctx() - if tool_ctx.executor is None: - return json.dumps({"success": False, "error": "Executor not configured"}) - - skill_command = _build_enrich_skill_command(issue_number, batch, dry_run, repo) - - expected_output_patterns: list[str] = [] - if tool_ctx.output_pattern_resolver: - expected_output_patterns = list(tool_ctx.output_pattern_resolver(skill_command)) - - write_spec: WriteBehaviorSpec | None = None - if tool_ctx.write_expected_resolver: - write_spec = tool_ctx.write_expected_resolver(skill_command) - - result = await tool_ctx.executor.run( - skill_command, - str(Path.cwd()), - expected_output_patterns=expected_output_patterns, - write_behavior=write_spec, - ) - - if not result.success: - return json.dumps( - _build_headless_error_response(result, error=_retry_reason_to_error(result)) + from autoskillit.server import _get_ctx + + tool_ctx = _get_ctx() + if tool_ctx.executor is None: + return json.dumps({"success": False, "error": "Executor not configured"}) + + skill_command = _build_enrich_skill_command(issue_number, batch, dry_run, repo) + + expected_output_patterns: list[str] = [] + if tool_ctx.output_pattern_resolver: + expected_output_patterns = list(tool_ctx.output_pattern_resolver(skill_command)) + + write_spec: WriteBehaviorSpec | None = None + if tool_ctx.write_expected_resolver: + write_spec = tool_ctx.write_expected_resolver(skill_command) + + result = await tool_ctx.executor.run( + skill_command, + str(Path.cwd()), + expected_output_patterns=expected_output_patterns, + write_behavior=write_spec, ) - if result.result is None or not result.result.strip(): - return json.dumps( - _build_headless_error_response( - result, - error="session completed but output was empty (drain race)", + if not result.success: + return json.dumps( + _build_headless_error_response(result, error=_retry_reason_to_error(result)) + ) + + if result.result is None or not result.result.strip(): + return json.dumps( + _build_headless_error_response( + result, + error="session completed but output was empty (drain race)", + ) ) - ) - parsed = _parse_enrich_result(result.result) - if parsed.get("error") in _BLOCK_PARSE_ERRORS: - return json.dumps(_build_headless_error_response(result, error=parsed["error"])) + parsed = _parse_enrich_result(result.result) + if parsed.get("error") in _BLOCK_PARSE_ERRORS: + return json.dumps(_build_headless_error_response(result, error=parsed["error"])) - return json.dumps( - { - "success": True, - "status": "complete", - **_without_success_key(parsed), - } - ) + return json.dumps( + { + "success": True, + "status": "complete", + **_without_success_key(parsed), + } + ) + except Exception as exc: + logger.error("enrich_issues unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen", "github"}, annotations={"readOnlyHint": True}) @@ -384,11 +394,14 @@ async def claim_issue( allow_reentry: When True and the in-progress label is already present, returns claimed=True with reentry=True instead of claimed=False. Used by process-issues to re-enter recipes for upfront-claimed issues. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - - with structlog.contextvars.bound_contextvars(tool="claim_issue", issue_url=issue_url): + try: + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="claim_issue", issue_url=issue_url) logger.info("claim_issue", issue_url=issue_url) from autoskillit.server import _get_ctx @@ -460,6 +473,9 @@ async def claim_issue( "label": effective_label, } ) + except Exception as exc: + logger.error("claim_issue unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen", "github"}, annotations={"readOnlyHint": True}) @@ -486,11 +502,14 @@ async def release_issue( label: Label name to remove. Defaults to github.in_progress_label from config. target_branch: Branch the PR was merged into. When non-default, applies staged label. staged_label: Label name for staged state. Defaults to github.staged_label from config. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - - with structlog.contextvars.bound_contextvars(tool="release_issue", issue_url=issue_url): + try: + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="release_issue", issue_url=issue_url) logger.info("release_issue", issue_url=issue_url) from autoskillit.server import _get_ctx @@ -515,6 +534,7 @@ async def release_issue( return json.dumps( { "success": False, + "error": result.get("error", "remove_label failed"), "issue_number": issue_number, "label": effective_label, "staged": False, @@ -584,3 +604,6 @@ async def release_issue( "staged_label": effective_staged_label if staged else None, } ) + except Exception as exc: + logger.error("release_issue unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) diff --git a/src/autoskillit/server/tools_kitchen.py b/src/autoskillit/server/tools_kitchen.py index 09f99cfc73..9a7c7c9c3c 100644 --- a/src/autoskillit/server/tools_kitchen.py +++ b/src/autoskillit/server/tools_kitchen.py @@ -13,17 +13,19 @@ from autoskillit.config import resolve_ingredient_defaults from autoskillit.core import ( PIPELINE_FORBIDDEN_TOOLS, - TOOL_CATEGORIES, atomic_write, get_logger, pkg_root, ) +from autoskillit.pipeline import create_background_task from autoskillit.server import mcp from autoskillit.server.helpers import ( _apply_triage_gate, + _build_hook_diagnostic_warning, _find_recipe, _hook_config_path, _prime_quota_cache, + _quota_refresh_loop, _require_not_headless, track_response_size, ) @@ -31,10 +33,95 @@ logger = get_logger(__name__) +def _kitchen_failure_envelope( + exc: BaseException, + stage: str, + *, + user_hint: str | None = None, +) -> str: + """Return a JSON failure envelope for open_kitchen errors. + + Tool implementations catch exceptions locally and emit domain-specific + envelopes with helpful ``user_visible_message`` values; the + ``@track_response_size`` decorator only catches what slips through. + """ + msg = user_hint or ( + f"open_kitchen failed during {stage}: {type(exc).__name__}. " + f"Run 'autoskillit doctor' to diagnose, or reinstall if the failure persists." + ) + return json.dumps( + { + "success": False, + "kitchen": "failed", + "user_visible_message": msg, + "error": f"{type(exc).__name__}: {exc}", + "stage": stage, + } + ) + + +_DISPLAY_CATEGORIES: tuple[tuple[str, tuple[str, ...]], ...] = ( + ("Execution", ("run_cmd", "run_python", "run_skill")), + ("Testing & Workspace", ("test_check", "reset_test_dir", "classify_fix", "reset_workspace")), + ( + "Git Operations", + ("merge_worktree", "create_unique_branch", "check_pr_mergeable", "set_commit_status"), + ), + ("Recipes", ("migrate_recipe", "list_recipes", "load_recipe", "validate_recipe")), + ( + "Clone & Remote", + ( + "clone_repo", + "remove_clone", + "push_to_remote", + "register_clone_status", + "batch_cleanup_clones", + ), + ), + ( + "GitHub", + ( + "fetch_github_issue", + "get_issue_title", + "report_bug", + "prepare_issue", + "enrich_issues", + "claim_issue", + "release_issue", + "get_pr_reviews", + "bulk_close_issues", + ), + ), + ( + "CI & Automation", + ( + "wait_for_ci", + "wait_for_merge_queue", + "check_repo_merge_state", + "toggle_auto_merge", + "get_ci_status", + ), + ), + ( + "Telemetry & Diagnostics", + ( + "read_db", + "write_telemetry_files", + "kitchen_status", + "get_pipeline_report", + "get_token_summary", + "get_timing_summary", + "get_quota_events", + ), + ), + ("Kitchen", ("open_kitchen", "close_kitchen", "disable_quota_guard")), +) + + def _write_hook_config() -> None: """Write user-configured quota values to temp/.autoskillit_hook_config.json. - The hook subprocess (quota_check.py) reads this file to apply user settings + The hook subprocess (quota_guard.py) reads this file to apply user settings without importing the autoskillit package. """ from autoskillit.server import _get_ctx, logger @@ -43,11 +130,9 @@ def _write_hook_config() -> None: cfg = ctx.config.quota_guard payload = { "quota_guard": { - "threshold": cfg.threshold if cfg.threshold is not None else 90.0, - "cache_max_age": cfg.cache_max_age if cfg.cache_max_age is not None else 300, - "cache_path": cfg.cache_path - if cfg.cache_path is not None - else "~/.claude/autoskillit_quota_cache.json", + "cache_max_age": cfg.cache_max_age, + "cache_path": cfg.cache_path, + "buffer_seconds": cfg.buffer_seconds, }, "kitchen_id": ctx.kitchen_id, } @@ -59,19 +144,46 @@ def _write_hook_config() -> None: logger.warning("hook_config_write_failed", path=str(hook_cfg_path)) -async def _open_kitchen_handler() -> None: - """Set the tools-enabled flag. Extracted for testability.""" +async def _open_kitchen_handler() -> str | None: + """Set the tools-enabled flag. Extracted for testability. + + Returns ``None`` on success, or a JSON failure envelope string on error. + """ from autoskillit.server import _get_ctx, logger ctx = _get_ctx() ctx.gate.enable() ctx.kitchen_id = str(uuid4()) - # Store recipe packs — populated from LoadRecipeResult.requires_packs in #524. - # For now, store empty frozenset to establish the contract. ctx.active_recipe_packs = frozenset() logger.info("open_kitchen", gate_state="open", kitchen_id=ctx.kitchen_id) - _write_hook_config() - await _prime_quota_cache() + + try: + _write_hook_config() + except Exception as exc: + ctx.gate.disable() + logger.warning("open_kitchen_failure", stage="write_hook_config", exc_info=True) + return _kitchen_failure_envelope(exc, stage="write_hook_config") + + try: + await _prime_quota_cache() + except Exception as exc: + ctx.gate.disable() + logger.warning("open_kitchen_failure", stage="prime_quota_cache", exc_info=True) + return _kitchen_failure_envelope(exc, stage="prime_quota_cache") + + if ctx.quota_refresh_task is not None: + ctx.quota_refresh_task.cancel() + try: + ctx.quota_refresh_task = create_background_task( + _quota_refresh_loop(ctx.config.quota_guard), + label="quota_refresh_loop", + ) + except Exception as exc: + ctx.gate.disable() + logger.warning("open_kitchen_failure", stage="start_quota_refresh", exc_info=True) + return _kitchen_failure_envelope(exc, stage="start_quota_refresh") + + return None async def _redisable_subsets(ctx: Context, disabled: list[str]) -> None: @@ -89,8 +201,12 @@ def _close_kitchen_handler() -> None: """Clear the tools-enabled flag. Extracted for testability.""" from autoskillit.server import _get_ctx, logger - _get_ctx().gate.disable() - _get_ctx().active_recipe_packs = None + ctx = _get_ctx() + if ctx.quota_refresh_task is not None: + ctx.quota_refresh_task.cancel() + ctx.quota_refresh_task = None + ctx.gate.disable() + ctx.active_recipe_packs = None logger.info("close_kitchen", gate_state="closed") hook_cfg_path = _hook_config_path(Path.cwd()) try: @@ -109,9 +225,9 @@ def get_recipe(name: str) -> str: def _build_tool_category_listing() -> str: - """Return a formatted string listing all tool categories from TOOL_CATEGORIES.""" + """Return a formatted string listing all tool categories.""" lines = [] - for name, tools in TOOL_CATEGORIES: + for name, tools in _DISPLAY_CATEGORIES: lines.append(f" {name}: {', '.join(tools)}") return "\n".join(lines) @@ -132,75 +248,236 @@ async def open_kitchen( name: Optional recipe name to load immediately after opening. overrides: Optional dict of ingredient name → value to override recipe defaults. Use to activate hidden features (e.g., ``{"sprint_mode": "true"}``). + + Never raises. """ - if (h := _require_not_headless("open_kitchen")) is not None: - return h - - from autoskillit.server import _get_ctx # noqa: PLC0415 - - disabled_subsets = _get_ctx().config.subsets.disabled - await _open_kitchen_handler() - await ctx.enable_components(tags={"kitchen"}) - await _redisable_subsets(ctx, disabled_subsets) - - _forbidden_list = ", ".join(PIPELINE_FORBIDDEN_TOOLS) - _categories = _build_tool_category_listing() - - if name is not None: - tool_ctx = _get_ctx() - if tool_ctx.recipes is None: - return json.dumps({"error": "Server not initialized", "kitchen": "open"}) - suppressed = tool_ctx.config.migration.suppressed - _defaults = resolve_ingredient_defaults(Path.cwd()) - result = tool_ctx.recipes.load_and_validate( - name, - Path.cwd(), - suppressed=suppressed, - resolved_defaults=_defaults, - ingredient_overrides=overrides, + try: + # Headless guard — wrap denial in envelope shape + if (h := _require_not_headless("open_kitchen")) is not None: + parsed_h = json.loads(h) + return json.dumps( + { + "success": False, + "kitchen": "failed", + "user_visible_message": parsed_h.get( + "result", + "open_kitchen cannot be called from headless sessions.", + ), + "error": "HeadlessDenied", + "stage": "headless_guard", + } + ) + + from autoskillit.server import _get_ctx # noqa: PLC0415 + + disabled_subsets = _get_ctx().config.subsets.disabled + + handler_err = await _open_kitchen_handler() + if handler_err is not None: + return handler_err + + try: + await ctx.enable_components(tags={"kitchen"}) + except Exception as exc: + logger.warning("open_kitchen_failure", stage="enable_components", exc_info=True) + return _kitchen_failure_envelope(exc, stage="enable_components") + + try: + await _redisable_subsets(ctx, disabled_subsets) + except Exception as exc: + logger.warning("open_kitchen_failure", stage="redisable_subsets", exc_info=True) + return _kitchen_failure_envelope(exc, stage="redisable_subsets") + + _forbidden_list = ", ".join(PIPELINE_FORBIDDEN_TOOLS) + _categories = _build_tool_category_listing() + + if name is not None: + tool_ctx = _get_ctx() + if tool_ctx.recipes is None: + return _kitchen_failure_envelope( + RuntimeError("Server not initialized"), + stage="recipe_context", + user_hint=( + "open_kitchen cannot load a recipe because the server is not " + "initialized. Run 'autoskillit doctor' to diagnose." + ), + ) + suppressed = tool_ctx.config.migration.suppressed + _defaults = resolve_ingredient_defaults(Path.cwd()) + # Runtime enum check: output_mode must be validated before recipe loading + if name == "research": + _om_value = (overrides or {}).get("output_mode") + if _om_value is not None and _om_value not in {"pr", "local"}: + return json.dumps( + { + "error": ( + f"output_mode must be 'pr' or 'local', got {_om_value!r}. " + "Only two modes are supported for the research recipe." + ) + } + ) + try: + result = tool_ctx.recipes.load_and_validate( + name, + Path.cwd(), + suppressed=suppressed, + resolved_defaults=_defaults, + ingredient_overrides=overrides, + ) + except Exception as exc: + logger.warning("open_kitchen_failure", stage="load_and_validate", exc_info=True) + return _kitchen_failure_envelope(exc, stage="load_and_validate") + + tool_ctx.active_recipe_packs = frozenset(result.get("requires_packs", [])) + + try: + recipe_info = tool_ctx.recipes.find(name, Path.cwd()) + except Exception as exc: + logger.warning("open_kitchen_failure", stage="recipe_find", exc_info=True) + return _kitchen_failure_envelope(exc, stage="recipe_find") + + try: + result = await _apply_triage_gate(result, name, recipe_info=recipe_info) + except Exception as exc: + logger.warning("open_kitchen_failure", stage="apply_triage_gate", exc_info=True) + return _kitchen_failure_envelope(exc, stage="apply_triage_gate") + + result["success"] = True + result["kitchen"] = "open" + result["version"] = __version__ + + if "ingredients_table" not in result or not result["ingredients_table"]: + result["ingredients_table"] = None + + try: + warning = _build_hook_diagnostic_warning() + except Exception as exc: + logger.warning("open_kitchen_failure", stage="hook_diagnostic", exc_info=True) + return _kitchen_failure_envelope(exc, stage="hook_diagnostic") + if warning: + result["hook_warning"] = warning.strip() + return json.dumps(result) + + text = ( + f"Kitchen is open. AutoSkillit {__version__}. Tools are ready for service.\n\n" + f"Available Tools by Category:\n{_categories}\n\n" + "IMPORTANT — Orchestrator Discipline:\n" + f"NEVER use native Claude Code tools ({_forbidden_list}) " + "in this session. All code reading, searching, editing, and " + "investigation MUST be delegated through run_skill, which launches " + "headless sessions with full tool access. Do NOT use native tools to " + "investigate failures — route to on_failure " + "and let the downstream skill handle diagnosis." ) - tool_ctx.active_recipe_packs = frozenset(result.get("requires_packs", [])) - recipe_info = tool_ctx.recipes.find(name, Path.cwd()) - result = await _apply_triage_gate(result, name, recipe_info=recipe_info) - result["kitchen"] = "open" - result["version"] = __version__ - return json.dumps(result) - - text = ( - f"Kitchen is open. AutoSkillit {__version__}. Tools are ready for service.\n\n" - f"Available Tools by Category:\n{_categories}\n\n" - "IMPORTANT — Orchestrator Discipline:\n" - f"NEVER use native Claude Code tools ({_forbidden_list}) " - "in this session. All code reading, searching, editing, and " - "investigation MUST be delegated through run_skill, which launches " - "headless sessions with full tool access. Do NOT use native tools to " - "investigate failures — route to on_failure and let the downstream skill handle diagnosis." - ) - # Inject sous-chef global orchestration rules (graceful degradation if absent) - _sous_chef_path = pkg_root() / "skills" / "sous-chef" / "SKILL.md" - if _sous_chef_path.exists(): - text += "\n\n" + _sous_chef_path.read_text() - - # Check if the project needs an upgrade - scripts_dir = Path.cwd() / ".autoskillit" / "scripts" - recipes_dir = Path.cwd() / ".autoskillit" / "recipes" - if scripts_dir.exists() and not recipes_dir.exists(): - text += ( - "\n\n⚠️ UPGRADE NEEDED: This project has not been migrated to the new recipe format.\n" - "`.autoskillit/scripts/` still exists. Run `autoskillit upgrade` in this directory\n" - "to migrate automatically, or ask me to do it for you." + # Inject sous-chef global orchestration rules (graceful degradation if absent) + _sous_chef_path = pkg_root() / "skills" / "sous-chef" / "SKILL.md" + try: + if _sous_chef_path.exists(): + text += "\n\n" + _sous_chef_path.read_text() + except Exception as exc: + logger.warning("open_kitchen_failure", stage="read_sous_chef", exc_info=True) + return _kitchen_failure_envelope(exc, stage="read_sous_chef") + + # Check if the project needs an upgrade + scripts_dir = Path.cwd() / ".autoskillit" / "scripts" + recipes_dir = Path.cwd() / ".autoskillit" / "recipes" + if scripts_dir.exists() and not recipes_dir.exists(): + text += ( + "\n\n⚠️ UPGRADE NEEDED: This project has not been migrated" + " to the new recipe format.\n" + "`.autoskillit/scripts/` still exists." + " Run `autoskillit upgrade` in this directory\n" + "to migrate automatically, or ask me to do it for you." + ) + + try: + warning = _build_hook_diagnostic_warning() + except Exception as exc: + logger.warning("open_kitchen_failure", stage="hook_diagnostic", exc_info=True) + return _kitchen_failure_envelope(exc, stage="hook_diagnostic") + if warning: + text += warning + + return json.dumps( + { + "success": True, + "kitchen": "open", + "content": text, + "ingredients_table": None, + "version": __version__, + } ) - - return text + except Exception as exc: + logger.error("open_kitchen unhandled exception", exc_info=True) + return _kitchen_failure_envelope(exc, stage="unhandled") @mcp.tool(tags={"autoskillit"}, annotations={"readOnlyHint": True}) @track_response_size("close_kitchen") async def close_kitchen(ctx: Context = CurrentContext()) -> str: - """Close the AutoSkillit kitchen.""" - if (h := _require_not_headless("close_kitchen")) is not None: - return h - _close_kitchen_handler() - await ctx.reset_visibility() - return "Kitchen is closed." + """Close the AutoSkillit kitchen. + + Never raises. + """ + try: + if (h := _require_not_headless("close_kitchen")) is not None: + return h + _close_kitchen_handler() + await ctx.reset_visibility() + return "Kitchen is closed." + except Exception as exc: + logger.error("close_kitchen unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) + + +@mcp.tool(tags={"autoskillit"}) +@track_response_size("disable_quota_guard") +async def disable_quota_guard() -> str: + """Disable the quota guard for the remainder of this kitchen session. + + The quota guard blocks run_skill calls when API utilization exceeds a + threshold. Invoke this tool when you decide the work is worth the quota + spend and want to override the guard for the current session. + + Session-scoped only: the guard re-activates when the kitchen is closed + and reopened. Does not modify persistent configuration. + + Never raises. + """ + try: + if (h := _require_not_headless("disable_quota_guard")) is not None: + return h + hook_cfg_path = _hook_config_path(Path.cwd()) + if not hook_cfg_path.exists(): + return json.dumps( + { + "success": False, + "error": "Kitchen is not open — hook config file absent.", + } + ) + try: + payload = json.loads(hook_cfg_path.read_text()) + except (OSError, json.JSONDecodeError) as exc: + return json.dumps( + { + "success": False, + "error": f"Failed to read hook config: {type(exc).__name__}: {exc}", + } + ) + quota_section = payload.get("quota_guard", {}) + quota_section["disabled"] = True + payload["quota_guard"] = quota_section + atomic_write(hook_cfg_path, json.dumps(payload)) + return json.dumps( + { + "success": True, + "content": ( + "Quota guard disabled for this session. " + "run_skill calls will no longer be blocked by quota checks." + ), + } + ) + except Exception as exc: + logger.error("disable_quota_guard unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) diff --git a/src/autoskillit/server/tools_pr_ops.py b/src/autoskillit/server/tools_pr_ops.py index 48a464587b..556273e884 100644 --- a/src/autoskillit/server/tools_pr_ops.py +++ b/src/autoskillit/server/tools_pr_ops.py @@ -87,46 +87,51 @@ async def get_pr_reviews( cwd: Working directory for gh commands. repo: Repository as owner/repo. Uses gh api path when provided; uses gh pr view when omitted. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - - with structlog.contextvars.bound_contextvars(tool="get_pr_reviews", cwd=cwd): - logger.info("get_pr_reviews", pr_number=pr_number, repo=repo) - await _notify( - ctx, - "info", - f"get_pr_reviews: #{pr_number}", - "autoskillit.get_pr_reviews", - extra={"repo": repo}, - ) - - if repo: - cmd = ["gh", "api", f"repos/{repo}/pulls/{pr_number}/reviews"] - rc, stdout, stderr = await _run_subprocess(cmd, cwd=cwd, timeout=30) - if rc != 0: - return json.dumps( - {"success": False, "error": stderr.strip() or "gh command failed"} - ) - try: - raw = json.loads(stdout) - except json.JSONDecodeError: - return json.dumps({"success": False, "error": "Failed to parse gh output"}) - reviews = _map_api_reviews(raw) - else: - cmd = ["gh", "pr", "view", str(pr_number), "--json", "reviews"] - rc, stdout, stderr = await _run_subprocess(cmd, cwd=cwd, timeout=30) - if rc != 0: - return json.dumps( - {"success": False, "error": stderr.strip() or "gh command failed"} - ) - try: - data = json.loads(stdout) - except json.JSONDecodeError: - return json.dumps({"success": False, "error": "Failed to parse gh output"}) - reviews = _map_pr_view_reviews(data) - - return json.dumps({"reviews": reviews}) + try: + with structlog.contextvars.bound_contextvars(tool="get_pr_reviews", cwd=cwd): + logger.info("get_pr_reviews", pr_number=pr_number, repo=repo) + await _notify( + ctx, + "info", + f"get_pr_reviews: #{pr_number}", + "autoskillit.get_pr_reviews", + extra={"repo": repo}, + ) + + if repo: + cmd = ["gh", "api", f"repos/{repo}/pulls/{pr_number}/reviews"] + rc, stdout, stderr = await _run_subprocess(cmd, cwd=cwd, timeout=30) + if rc != 0: + return json.dumps( + {"success": False, "error": stderr.strip() or "gh command failed"} + ) + try: + raw = json.loads(stdout) + except json.JSONDecodeError: + return json.dumps({"success": False, "error": "Failed to parse gh output"}) + reviews = _map_api_reviews(raw) + else: + cmd = ["gh", "pr", "view", str(pr_number), "--json", "reviews"] + rc, stdout, stderr = await _run_subprocess(cmd, cwd=cwd, timeout=30) + if rc != 0: + return json.dumps( + {"success": False, "error": stderr.strip() or "gh command failed"} + ) + try: + data = json.loads(stdout) + except json.JSONDecodeError: + return json.dumps({"success": False, "error": "Failed to parse gh output"}) + reviews = _map_pr_view_reviews(data) + + return json.dumps({"reviews": reviews}) + except Exception as exc: + logger.error("get_pr_reviews unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen", "github"}, annotations={"readOnlyHint": True}) @@ -151,19 +156,24 @@ async def bulk_close_issues( issue_numbers: List of GitHub issue numbers to close. comment: Optional comment to post when closing. Omitted when empty. cwd: Working directory for gh commands. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - - with structlog.contextvars.bound_contextvars(tool="bulk_close_issues", cwd=cwd): - logger.info("bulk_close_issues", count=len(issue_numbers)) - await _notify( - ctx, - "info", - f"bulk_close_issues: {len(issue_numbers)} issue(s)", - "autoskillit.bulk_close_issues", - extra={}, - ) - - closed, failed = await _close_issues_sequentially(issue_numbers, comment, cwd) - return json.dumps({"closed": closed, "failed": failed}) + try: + with structlog.contextvars.bound_contextvars(tool="bulk_close_issues", cwd=cwd): + logger.info("bulk_close_issues", count=len(issue_numbers)) + await _notify( + ctx, + "info", + f"bulk_close_issues: {len(issue_numbers)} issue(s)", + "autoskillit.bulk_close_issues", + extra={}, + ) + + closed, failed = await _close_issues_sequentially(issue_numbers, comment, cwd) + return json.dumps({"closed": closed, "failed": failed}) + except Exception as exc: + logger.error("bulk_close_issues unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) diff --git a/src/autoskillit/server/tools_recipe.py b/src/autoskillit/server/tools_recipe.py index b14d3a7caa..4accbf1e3e 100644 --- a/src/autoskillit/server/tools_recipe.py +++ b/src/autoskillit/server/tools_recipe.py @@ -10,7 +10,7 @@ from fastmcp.dependencies import CurrentContext from autoskillit.config import resolve_ingredient_defaults -from autoskillit.core import get_logger +from autoskillit.core import get_logger, temp_dir_display_str from autoskillit.pipeline import GATED_TOOLS, UNGATED_TOOLS # noqa: F401 from autoskillit.server import mcp from autoskillit.server._state import _get_ctx_or_none @@ -41,14 +41,22 @@ async def list_recipes() -> str: .autoskillit/skills/ or any other directory). This tool requires the kitchen to be open (gated by open_kitchen). + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - tool_ctx = _get_ctx_or_none() - if tool_ctx is None or tool_ctx.recipes is None: + try: + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="list_recipes") + tool_ctx = _get_ctx_or_none() + if tool_ctx is None or tool_ctx.recipes is None: + return json.dumps([]) + result = tool_ctx.recipes.list_all(Path.cwd()) + return json.dumps(result) + except Exception: + logger.error("list_recipes unhandled exception", exc_info=True) return json.dumps([]) - result = tool_ctx.recipes.list_all(Path.cwd()) - return json.dumps(result) @mcp.tool(tags={"autoskillit", "kitchen"}, annotations={"readOnlyHint": True}) @@ -111,7 +119,7 @@ async def load_recipe(name: str, overrides: dict[str, str] | None = None) -> str "summary" → the open_pr skill self-retrieves its own token summary from disk (pipeline-scoped). Do NOT call get_token_summary for this purpose and do NOT pre-stage - .autoskillit/temp/open-pr/token_summary.md — the skill handles it. + /open-pr/token_summary.md — the skill handles it. "none" → do NOT call get_token_summary. Skip token reporting entirely. - Do NOT print or render a token usage table after individual steps. Only one call to get_token_summary is permitted per pipeline run, @@ -165,23 +173,33 @@ async def load_recipe(name: str, overrides: dict[str, str] | None = None) -> str ``diagram`` (pre-generated Markdown string or null), and ``suggestions`` (list of semantic findings, possibly empty) keys. On error: JSON with ``error`` key. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - tool_ctx = _get_ctx_or_none() - if tool_ctx is None or tool_ctx.recipes is None: - return json.dumps({"error": "Server not initialized"}) - suppressed = tool_ctx.config.migration.suppressed - _defaults = resolve_ingredient_defaults(Path.cwd()) - result = tool_ctx.recipes.load_and_validate( - name, - Path.cwd(), - suppressed=suppressed, - resolved_defaults=_defaults, - ingredient_overrides=overrides, - ) - recipe_info = tool_ctx.recipes.find(name, Path.cwd()) - return json.dumps(await _apply_triage_gate(result, name, recipe_info=recipe_info)) + try: + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="load_recipe") + tool_ctx = _get_ctx_or_none() + if tool_ctx is None or tool_ctx.recipes is None: + return json.dumps({"error": "Server not initialized"}) + suppressed = tool_ctx.config.migration.suppressed + _defaults = resolve_ingredient_defaults(Path.cwd()) + result = tool_ctx.recipes.load_and_validate( + name, + Path.cwd(), + suppressed=suppressed, + resolved_defaults=_defaults, + ingredient_overrides=overrides, + temp_dir=tool_ctx.temp_dir, + temp_dir_relpath=temp_dir_display_str(tool_ctx.config.workspace.temp_dir), + ) + recipe_info = tool_ctx.recipes.find(name, Path.cwd()) + return json.dumps(await _apply_triage_gate(result, name, recipe_info=recipe_info)) + except Exception as exc: + logger.error("load_recipe unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen"}, annotations={"readOnlyHint": True}) @@ -207,14 +225,25 @@ async def validate_recipe(script_path: str) -> str: Args: script_path: Absolute path to the .yaml recipe file to validate. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - tool_ctx = _get_ctx_or_none() - if tool_ctx is None or tool_ctx.recipes is None: - return json.dumps({"valid": False, "errors": ["Server not initialized"]}) - result = tool_ctx.recipes.validate_from_path(Path(script_path)) - return json.dumps(result) + try: + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="validate_recipe") + tool_ctx = _get_ctx_or_none() + if tool_ctx is None or tool_ctx.recipes is None: + return json.dumps({"valid": False, "errors": ["Server not initialized"]}) + result = tool_ctx.recipes.validate_from_path( + Path(script_path), + temp_dir_relpath=temp_dir_display_str(tool_ctx.config.workspace.temp_dir), + ) + return json.dumps(result) + except Exception as exc: + logger.error("validate_recipe unhandled exception", exc_info=True) + return json.dumps({"valid": False, "errors": [f"{type(exc).__name__}: {exc}"]}) @mcp.tool(tags={"autoskillit", "kitchen"}, annotations={"readOnlyHint": True}) @@ -240,35 +269,41 @@ async def migrate_recipe(name: str, ctx: Context = CurrentContext()) -> str: Args: name: The recipe name (without .yaml extension) to migrate. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="migrate_recipe", recipe_name=name) - logger.info("migrate_recipe", recipe_name=name) - await _notify( - ctx, - "info", - f"migrate_recipe: {name}", - "autoskillit.migrate_recipe", - extra={"recipe_name": name}, - ) - - from autoskillit.server import _get_config, _get_ctx - - tool_ctx = _get_ctx() - - # Check suppression list before attempting migration - if name in _get_config().migration.suppressed: - return json.dumps({"status": "up_to_date", "name": name}) - - if tool_ctx.recipes is None: - return json.dumps({"error": "Recipe repository not configured"}) - recipe = tool_ctx.recipes.find(name, Path.cwd()) - if recipe is None: - return json.dumps({"error": f"No recipe named '{name}' found"}) - - if tool_ctx.migrations is None: - return json.dumps({"error": "Migration service not configured", "name": name}) - result = await tool_ctx.migrations.migrate(recipe.path) - return json.dumps(result) + try: + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="migrate_recipe", recipe_name=name) + logger.info("migrate_recipe", recipe_name=name) + await _notify( + ctx, + "info", + f"migrate_recipe: {name}", + "autoskillit.migrate_recipe", + extra={"recipe_name": name}, + ) + + from autoskillit.server import _get_config, _get_ctx + + tool_ctx = _get_ctx() + + # Check suppression list before attempting migration + if name in _get_config().migration.suppressed: + return json.dumps({"status": "up_to_date", "name": name}) + + if tool_ctx.recipes is None: + return json.dumps({"error": "Recipe repository not configured"}) + recipe = tool_ctx.recipes.find(name, Path.cwd()) + if recipe is None: + return json.dumps({"error": f"No recipe named '{name}' found"}) + + if tool_ctx.migrations is None: + return json.dumps({"error": "Migration service not configured", "name": name}) + result = await tool_ctx.migrations.migrate(recipe.path) + return json.dumps(result) + except Exception as exc: + logger.error("migrate_recipe unhandled exception", exc_info=True) + return json.dumps({"error": f"{type(exc).__name__}: {exc}", "name": name}) diff --git a/src/autoskillit/server/tools_status.py b/src/autoskillit/server/tools_status.py index de4ab38fd5..a2f291c5b9 100644 --- a/src/autoskillit/server/tools_status.py +++ b/src/autoskillit/server/tools_status.py @@ -42,33 +42,41 @@ async def kitchen_status() -> str: enabling tools or anytime you need to verify the server is healthy. This tool requires the kitchen to be open (gated by open_kitchen). + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - from autoskillit.server import _get_config, _get_ctx, version_info - - info = version_info() - status = { - "package_version": info["package_version"], - "plugin_json_version": info["plugin_json_version"], - "versions_match": info["match"], - "tools_enabled": _get_ctx().gate.enabled, - } - if not info["match"]: - status["warning"] = ( - f"Version mismatch: package is {info['package_version']} but " - f"plugin.json reports {info['plugin_json_version']}. " - f"Run `autoskillit doctor` for details or " - f"`autoskillit install` to refresh the plugin cache." - ) - status["token_usage_verbosity"] = _get_config().token_usage.verbosity - status["quota_guard_enabled"] = _get_config().quota_guard.enabled - github_client = _get_ctx().github_client - status["github_token_configured"] = ( - github_client.has_token if github_client is not None else False - ) - status["github_default_repo"] = _get_config().github.default_repo - return json.dumps(status) + try: + structlog.contextvars.clear_contextvars() + with structlog.contextvars.bound_contextvars(tool="kitchen_status"): + from autoskillit.server import _get_config, _get_ctx, version_info + + info = version_info() + status = { + "package_version": info["package_version"], + "plugin_json_version": info["plugin_json_version"], + "versions_match": info["match"], + "tools_enabled": _get_ctx().gate.enabled, + } + if not info["match"]: + status["warning"] = ( + f"Version mismatch: package is {info['package_version']} but " + f"plugin.json reports {info['plugin_json_version']}. " + f"Run `autoskillit doctor` for details or " + f"`autoskillit install` to refresh the plugin cache." + ) + status["token_usage_verbosity"] = _get_config().token_usage.verbosity + status["quota_guard_enabled"] = _get_config().quota_guard.enabled + github_client = _get_ctx().github_client + status["github_token_configured"] = ( + github_client.has_token if github_client is not None else False + ) + status["github_default_repo"] = _get_config().github.default_repo + return json.dumps(status) + except Exception as exc: + logger.error("kitchen_status unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen"}, annotations={"readOnlyHint": True}) @@ -86,24 +94,49 @@ async def get_pipeline_report(clear: bool = False) -> str: needs_retry, retry_reason, stderr} This tool requires the kitchen to be open (gated by open_kitchen). + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - from autoskillit.server import _get_ctx - - failures = _get_ctx().audit.get_report_as_dicts() - if clear: - _get_ctx().audit.clear() - try: - write_telemetry_clear_marker(_get_log_root()) - except Exception: - logger.debug("write_telemetry_clear_marker failed", exc_info=True) - return json.dumps( - { - "total_failures": len(failures), - "failures": failures, - } - ) + try: + structlog.contextvars.clear_contextvars() + with structlog.contextvars.bound_contextvars(tool="get_pipeline_report"): + from autoskillit.server._state import _startup_ready + + if _startup_ready is not None and not _startup_ready.is_set(): + try: + await asyncio.wait_for(_startup_ready.wait(), timeout=30.0) + except TimeoutError: + logger.warning("startup_ready_timeout", timeout=30.0) + return json.dumps( + { + "total_failures": 0, + "failures": [], + "warning": "Startup initialization did not complete within 30s", + } + ) + + from autoskillit.server import _get_ctx + + failures = _get_ctx().audit.get_report_as_dicts() + if clear: + _get_ctx().audit.clear() + try: + write_telemetry_clear_marker(_get_log_root()) + except Exception: + logger.debug("write_telemetry_clear_marker failed", exc_info=True) + return json.dumps( + { + "total_failures": len(failures), + "failures": failures, + } + ) + except Exception as exc: + logger.error("get_pipeline_report unhandled exception", exc_info=True) + return json.dumps( + {"total_failures": 0, "failures": [], "error": f"{type(exc).__name__}: {exc}"} + ) def _merge_wall_clock_seconds(steps: list[dict], timing_report: list[dict]) -> list[dict]: @@ -135,38 +168,46 @@ async def get_token_summary(clear: bool = False, format: str = "json", order_id: "table" returns a pre-formatted markdown table string. order_id: If non-empty, return only token entries for this specific order/issue. Empty string (default) returns aggregated data for all orders. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - from autoskillit.server import _get_ctx - - ctx = _get_ctx() - steps = _merge_wall_clock_seconds( - ctx.token_log.get_report(order_id=order_id), - ctx.timing_log.get_report(order_id=order_id), - ) - total = ctx.token_log.compute_total(order_id=order_id) - mcp_report = ctx.response_log.get_report() - mcp_total = ctx.response_log.compute_total() - if clear: - ctx.token_log.clear() - ctx.response_log.clear() - try: - write_telemetry_clear_marker(_get_log_root()) - except Exception: - logger.debug("write_telemetry_clear_marker failed", exc_info=True) - if format == "table": - return TelemetryFormatter.format_token_table(steps, total) - return json.dumps( - { - "steps": steps, - "total": total, - "mcp_responses": { - "steps": mcp_report, - "total": mcp_total, - }, - } - ) + try: + structlog.contextvars.clear_contextvars() + with structlog.contextvars.bound_contextvars(tool="get_token_summary"): + from autoskillit.server import _get_ctx + + ctx = _get_ctx() + steps = _merge_wall_clock_seconds( + ctx.token_log.get_report(order_id=order_id), + ctx.timing_log.get_report(order_id=order_id), + ) + total = ctx.token_log.compute_total(order_id=order_id) + mcp_report = ctx.response_log.get_report() + mcp_total = ctx.response_log.compute_total() + if clear: + ctx.token_log.clear() + ctx.response_log.clear() + try: + write_telemetry_clear_marker(_get_log_root()) + except Exception: + logger.debug("write_telemetry_clear_marker failed", exc_info=True) + if format == "table": + return TelemetryFormatter.format_token_table(steps, total) + return json.dumps( + { + "steps": steps, + "total": total, + "mcp_responses": { + "steps": mcp_report, + "total": mcp_total, + }, + } + ) + except Exception as exc: + logger.error("get_token_summary unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen", "telemetry"}, annotations={"readOnlyHint": True}) @@ -184,22 +225,30 @@ async def get_timing_summary(clear: bool = False, format: str = "json", order_id "table" returns a pre-formatted markdown table string. order_id: If non-empty, return only timing entries for this specific order/issue. Empty string (default) returns aggregated data for all orders. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - from autoskillit.server import _get_ctx - - steps = _get_ctx().timing_log.get_report(order_id=order_id) - total = _get_ctx().timing_log.compute_total(order_id=order_id) - if clear: - _get_ctx().timing_log.clear() - try: - write_telemetry_clear_marker(_get_log_root()) - except Exception: - logger.debug("write_telemetry_clear_marker failed", exc_info=True) - if format == "table": - return TelemetryFormatter.format_timing_table(steps, total) - return json.dumps({"steps": steps, "total": total}) + try: + structlog.contextvars.clear_contextvars() + with structlog.contextvars.bound_contextvars(tool="get_timing_summary"): + from autoskillit.server import _get_ctx + + steps = _get_ctx().timing_log.get_report(order_id=order_id) + total = _get_ctx().timing_log.compute_total(order_id=order_id) + if clear: + _get_ctx().timing_log.clear() + try: + write_telemetry_clear_marker(_get_log_root()) + except Exception: + logger.debug("write_telemetry_clear_marker failed", exc_info=True) + if format == "table": + return TelemetryFormatter.format_timing_table(steps, total) + return json.dumps({"steps": steps, "total": total}) + except Exception as exc: + logger.error("get_timing_summary unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) def _read_quota_events(log_root: Path, n: int) -> tuple[list[dict], int]: @@ -231,13 +280,14 @@ def _read_quota_events(log_root: Path, n: int) -> tuple[list[dict], int]: async def get_quota_events(n: int = 50) -> str: """Return the most recent quota guard events from the diagnostic log. - Events are written by the quota_check.py PreToolUse hook each time it + Events are written by the quota_guard.py PreToolUse hook each time it approves or blocks a run_skill call. Use this to diagnose quota throttling during long pipeline runs. Returns JSON with: - - events: list of {ts, event, threshold, utilization?, sleep_seconds?, - resets_at?, cache_path?} (most recent first) + - events: list of {ts, event, effective_threshold?, window_name?, + utilization?, sleep_seconds?, resets_at?, cache_path?} + (most recent first) - total_count: int (total events in the log, before limiting to n) Args: @@ -245,15 +295,23 @@ async def get_quota_events(n: int = 50) -> str: This tool requires the kitchen to be open (gated by open_kitchen). This tool sends no MCP progress notifications. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - from autoskillit.server import _get_ctx - - ctx = _get_ctx() - log_root = resolve_log_dir(ctx.config.linux_tracing.log_dir) - events, total = _read_quota_events(log_root, n) - return json.dumps({"events": events, "total_count": total}) + try: + structlog.contextvars.clear_contextvars() + with structlog.contextvars.bound_contextvars(tool="get_quota_events"): + from autoskillit.server import _get_ctx + + ctx = _get_ctx() + log_root = resolve_log_dir(ctx.config.linux_tracing.log_dir) + events, total = _read_quota_events(log_root, n) + return json.dumps({"events": events, "total_count": total}) + except Exception as exc: + logger.error("get_quota_events unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen", "telemetry"}, annotations={"readOnlyHint": True}) @@ -275,57 +333,67 @@ async def write_telemetry_files( Args: output_dir: Directory to write the markdown files into. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="write_telemetry_files", output_dir=output_dir) - logger.info("write_telemetry_files", output_dir=output_dir) - await _notify( - ctx, - "info", - f"write_telemetry_files: {output_dir}", - "autoskillit.write_telemetry_files", - extra={"output_dir": output_dir}, - ) - - from autoskillit.server import _get_ctx - - tool_ctx = _get_ctx() - out = Path(output_dir) - out.mkdir(parents=True, exist_ok=True) - - token_steps = _merge_wall_clock_seconds( - tool_ctx.token_log.get_report(), tool_ctx.timing_log.get_report() - ) - token_total = tool_ctx.token_log.compute_total() - - token_path = out / "token_summary.md" - atomic_write(token_path, TelemetryFormatter.format_token_table(token_steps, token_total)) - - timing_path = out / "timing_summary.md" - atomic_write( - timing_path, - TelemetryFormatter.format_timing_table( - tool_ctx.timing_log.get_report(), tool_ctx.timing_log.compute_total() - ), - ) - - mcp_path = out / "mcp_response_metrics.json" - mcp_data = { - "steps": tool_ctx.response_log.get_report(), - "total": tool_ctx.response_log.compute_total(), - } - atomic_write(mcp_path, json.dumps(mcp_data, indent=2)) - - return json.dumps( - { - "token_summary_path": str(token_path), - "timing_summary_path": str(timing_path), - "mcp_response_metrics_path": str(mcp_path), - } - ) + try: + structlog.contextvars.clear_contextvars() + with structlog.contextvars.bound_contextvars( + tool="write_telemetry_files", output_dir=output_dir + ): + logger.info("write_telemetry_files", output_dir=output_dir) + await _notify( + ctx, + "info", + f"write_telemetry_files: {output_dir}", + "autoskillit.write_telemetry_files", + extra={"output_dir": output_dir}, + ) + + from autoskillit.server import _get_ctx + + tool_ctx = _get_ctx() + out = Path(output_dir) + out.mkdir(parents=True, exist_ok=True) + + token_steps = _merge_wall_clock_seconds( + tool_ctx.token_log.get_report(), tool_ctx.timing_log.get_report() + ) + token_total = tool_ctx.token_log.compute_total() + + token_path = out / "token_summary.md" + atomic_write( + token_path, TelemetryFormatter.format_token_table(token_steps, token_total) + ) + + timing_path = out / "timing_summary.md" + atomic_write( + timing_path, + TelemetryFormatter.format_timing_table( + tool_ctx.timing_log.get_report(), tool_ctx.timing_log.compute_total() + ), + ) + + mcp_path = out / "mcp_response_metrics.json" + mcp_data = { + "steps": tool_ctx.response_log.get_report(), + "total": tool_ctx.response_log.compute_total(), + } + atomic_write(mcp_path, json.dumps(mcp_data, indent=2)) + + return json.dumps( + { + "token_summary_path": str(token_path), + "timing_summary_path": str(timing_path), + "mcp_response_metrics_path": str(mcp_path), + } + ) + except Exception as exc: + logger.error("write_telemetry_files unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen"}, annotations={"readOnlyHint": True}) @@ -348,108 +416,128 @@ async def read_db( query: SQL SELECT query. Use ? for positional or :name for named placeholders. params: JSON-encoded array or object of query parameter values (default "[]"). timeout: Query timeout in seconds. 0 uses the configured default. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="read_db") - logger.info("read_db", db_path=db_path, query=query[:80]) - await _notify( - ctx, "info", f"read_db: {query[:80]}", "autoskillit.read_db", extra={"db_path": db_path} - ) - - # Parse params try: - parsed_params = json.loads(params) - except json.JSONDecodeError as exc: - await _notify( - ctx, - "error", - "read_db: invalid params JSON", - "autoskillit.read_db", - extra={"error": str(exc)}, - ) - return json.dumps({"error": f"Invalid params JSON: {exc}"}) - if not isinstance(parsed_params, (list, dict)): - await _notify( - ctx, - "error", - "read_db: params must be JSON array or object", - "autoskillit.read_db", - extra={}, - ) - return json.dumps({"error": "params must be a JSON array or object"}) - - # Validate db_path - db = Path(db_path).resolve() - if not db.exists(): - await _notify( - ctx, - "error", - "read_db: database does not exist", - "autoskillit.read_db", - extra={"db_path": db_path}, - ) - return json.dumps({"error": f"Database does not exist: {db}"}) - if not db.is_file(): - await _notify( - ctx, - "error", - "read_db: path is not a file", - "autoskillit.read_db", - extra={"db_path": db_path}, - ) - return json.dumps({"error": f"Path is not a file: {db}"}) - - from autoskillit.server import _get_config, _get_ctx - - tool_ctx = _get_ctx() - if tool_ctx.db_reader is None: - return json.dumps({"error": "Database reader not configured"}) - - # Resolve timeout - effective_timeout = timeout if timeout > 0 else _get_config().read_db.timeout - max_rows = _get_config().read_db.max_rows - - # Execute in thread (sqlite3 is blocking) - loop = asyncio.get_running_loop() - try: - result = await loop.run_in_executor( - None, - tool_ctx.db_reader.query, - str(db), - query, - parsed_params, - effective_timeout, - max_rows, - ) - return json.dumps(result) - except ValueError as exc: - # Non-SELECT SQL rejected by db_reader's defence-in-depth validation - await _notify( - ctx, - "error", - "read_db: non-SELECT query rejected", - "autoskillit.read_db", - extra={"error": str(exc)}, - ) - return json.dumps({"error": str(exc), "hint": "Only SELECT queries are allowed"}) - except TimeoutError: - await _notify( - ctx, - "error", - "read_db: query timed out", - "autoskillit.read_db", - extra={"timeout": effective_timeout}, - ) - return json.dumps({"error": f"Query exceeded {effective_timeout}s timeout"}) + structlog.contextvars.clear_contextvars() + with structlog.contextvars.bound_contextvars(tool="read_db"): + logger.info("read_db", db_path=db_path, query=query[:80]) + await _notify( + ctx, + "info", + f"read_db: {query[:80]}", + "autoskillit.read_db", + extra={"db_path": db_path}, + ) + + # Parse params + try: + parsed_params = json.loads(params) + except json.JSONDecodeError as exc: + await _notify( + ctx, + "error", + "read_db: invalid params JSON", + "autoskillit.read_db", + extra={"error": str(exc)}, + ) + return json.dumps({"success": False, "error": f"Invalid params JSON: {exc}"}) + if not isinstance(parsed_params, (list, dict)): + await _notify( + ctx, + "error", + "read_db: params must be JSON array or object", + "autoskillit.read_db", + extra={}, + ) + return json.dumps( + {"success": False, "error": "params must be a JSON array or object"} + ) + + # Validate db_path + db = Path(db_path).resolve() + if not db.exists(): + await _notify( + ctx, + "error", + "read_db: database does not exist", + "autoskillit.read_db", + extra={"db_path": db_path}, + ) + return json.dumps({"success": False, "error": f"Database does not exist: {db}"}) + if not db.is_file(): + await _notify( + ctx, + "error", + "read_db: path is not a file", + "autoskillit.read_db", + extra={"db_path": db_path}, + ) + return json.dumps({"success": False, "error": f"Path is not a file: {db}"}) + + from autoskillit.server import _get_config, _get_ctx + + tool_ctx = _get_ctx() + if tool_ctx.db_reader is None: + return json.dumps({"success": False, "error": "Database reader not configured"}) + + # Resolve timeout + effective_timeout = timeout if timeout > 0 else _get_config().read_db.timeout + max_rows = _get_config().read_db.max_rows + + # Execute in thread (sqlite3 is blocking) + loop = asyncio.get_running_loop() + try: + result = await loop.run_in_executor( + None, + tool_ctx.db_reader.query, + str(db), + query, + parsed_params, + effective_timeout, + max_rows, + ) + return json.dumps(result) + except ValueError as exc: + # Non-SELECT SQL rejected by db_reader's defence-in-depth validation + await _notify( + ctx, + "error", + "read_db: non-SELECT query rejected", + "autoskillit.read_db", + extra={"error": str(exc)}, + ) + return json.dumps( + { + "success": False, + "error": str(exc), + "hint": "Only SELECT queries are allowed", + } + ) + except TimeoutError: + await _notify( + ctx, + "error", + "read_db: query timed out", + "autoskillit.read_db", + extra={"timeout": effective_timeout}, + ) + return json.dumps( + {"success": False, "error": f"Query exceeded {effective_timeout}s timeout"} + ) + except Exception as exc: + logger.warning("read_db query failed", error=type(exc).__name__) + await _notify( + ctx, + "error", + "read_db: query failed", + "autoskillit.read_db", + extra={"error": type(exc).__name__}, + ) + return json.dumps({"success": False, "error": f"Query failed: {exc}"}) except Exception as exc: - logger.warning("read_db query failed", error=type(exc).__name__) - await _notify( - ctx, - "error", - "read_db: query failed", - "autoskillit.read_db", - extra={"error": type(exc).__name__}, - ) - return json.dumps({"error": f"Query failed: {exc}"}) + logger.error("read_db unhandled exception", exc_info=True) + return json.dumps({"success": False, "error": f"{type(exc).__name__}: {exc}"}) diff --git a/src/autoskillit/server/tools_workspace.py b/src/autoskillit/server/tools_workspace.py index b76406b07d..918ee92bff 100644 --- a/src/autoskillit/server/tools_workspace.py +++ b/src/autoskillit/server/tools_workspace.py @@ -43,48 +43,54 @@ async def test_check( Args: worktree_path: Path to the git worktree to run tests in. step_name: Optional YAML step key for wall-clock timing accumulation. + + Never raises. """ - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="test_check", cwd=worktree_path) - logger.info("test_check", worktree=worktree_path) - await _notify( - ctx, - "info", - f"test_check: {worktree_path}", - "autoskillit.test_check", - extra={"worktree": worktree_path}, - ) - - from autoskillit.server import _get_ctx - - tool_ctx = _get_ctx() - if tool_ctx.tester is None: - return json.dumps({"passed": False, "error": "Test runner not configured"}) - - _start = time.monotonic() try: - resolved = os.path.realpath(worktree_path) - test_result = await tool_ctx.tester.run(Path(resolved)) + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="test_check", cwd=worktree_path) + logger.info("test_check", worktree=worktree_path) + await _notify( + ctx, + "info", + f"test_check: {worktree_path}", + "autoskillit.test_check", + extra={"worktree": worktree_path}, + ) - if not test_result.passed: - await _notify( - ctx, - "error", - "test_check: tests failed", - "autoskillit.test_check", - extra={"worktree": worktree_path}, - ) + from autoskillit.server import _get_ctx - return json.dumps( - { - "passed": test_result.passed, - "stdout": truncate_text(test_result.stdout), - "stderr": truncate_text(test_result.stderr), - } - ) - finally: - if step_name: - tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + tool_ctx = _get_ctx() + if tool_ctx.tester is None: + return json.dumps({"passed": False, "error": "Test runner not configured"}) + + _start = time.monotonic() + try: + resolved = os.path.realpath(worktree_path) + test_result = await tool_ctx.tester.run(Path(resolved)) + + if not test_result.passed: + await _notify( + ctx, + "error", + "test_check: tests failed", + "autoskillit.test_check", + extra={"worktree": worktree_path}, + ) + + return json.dumps( + { + "passed": test_result.passed, + "stdout": truncate_text(test_result.stdout), + "stderr": truncate_text(test_result.stderr), + } + ) + finally: + if step_name: + tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + except Exception as exc: + logger.error("test_check unhandled exception", exc_info=True) + return json.dumps({"passed": False, "error": f"{type(exc).__name__}: {exc}"}) @mcp.tool(tags={"autoskillit", "kitchen"}, annotations={"readOnlyHint": True}) @@ -105,44 +111,116 @@ async def reset_test_dir( force: Override the marker check. When True, all contents are deleted including the marker file itself. step_name: Optional YAML step key for wall-clock timing accumulation. + + Never raises. """ if (gate := _require_enabled()) is not None: return gate - resolved = os.path.realpath(test_dir) - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="reset_test_dir", cwd=resolved) - logger.info("reset_test_dir", resolved=str(resolved), force=force) - await _notify( - ctx, - "info", - f"reset_test_dir: {resolved}", - "autoskillit.reset_test_dir", - extra={"resolved": resolved, "force": force}, - ) - - from autoskillit.server import _get_config, _get_ctx - - tool_ctx = _get_ctx() - _start = time.monotonic() try: + resolved = os.path.realpath(test_dir) + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="reset_test_dir", cwd=resolved) + logger.info("reset_test_dir", resolved=str(resolved), force=force) + await _notify( + ctx, + "info", + f"reset_test_dir: {resolved}", + "autoskillit.reset_test_dir", + extra={"resolved": resolved, "force": force}, + ) + + from autoskillit.server import _get_config, _get_ctx + + tool_ctx = _get_ctx() + _start = time.monotonic() + try: + if not os.path.isdir(resolved): + await _notify( + ctx, + "error", + "reset_test_dir failed", + "autoskillit.reset_test_dir", + extra={"reason": "directory does not exist"}, + ) + return json.dumps({"error": f"Directory does not exist: {resolved}"}) + + marker_name = _get_config().safety.reset_guard_marker + marker_path = Path(resolved) / marker_name + if not force and not marker_path.is_file(): + await _notify( + ctx, + "error", + "reset_test_dir failed", + "autoskillit.reset_test_dir", + extra={"reason": "marker missing"}, + ) + return json.dumps( + { + "error": f"Safety: directory missing reset guard marker ({marker_name})", + "hint": f"Create the marker with: autoskillit workspace init {resolved}", + } + ) + + if tool_ctx.workspace_mgr is None: + return json.dumps({"error": "Workspace manager not configured"}) + + preserve = None if force else {marker_name} + cleanup = tool_ctx.workspace_mgr.delete_contents(Path(resolved), preserve=preserve) + return json.dumps({**cleanup.to_dict(), "forced": force}) + finally: + if step_name: + tool_ctx.timing_log.record(step_name, time.monotonic() - _start) + except Exception as exc: + logger.error("reset_test_dir unhandled exception", exc_info=True) + return json.dumps({"error": f"{type(exc).__name__}: {exc}"}) + + +@mcp.tool(tags={"autoskillit", "kitchen"}, annotations={"readOnlyHint": True}) +@track_response_size("reset_workspace") +async def reset_workspace(test_dir: str, ctx: Context = CurrentContext()) -> str: + """Runs a configured reset command then deletes directory contents, + preserving configured directories and the reset guard marker. + + Args: + test_dir: Path to the test project directory. Must contain the reset guard marker. + + Never raises. + """ + if (gate := _require_enabled()) is not None: + return gate + try: + resolved = os.path.realpath(test_dir) + structlog.contextvars.clear_contextvars() + structlog.contextvars.bind_contextvars(tool="reset_workspace", cwd=resolved) + logger.info("reset_workspace", resolved=str(resolved)) + await _notify( + ctx, + "info", + f"reset_workspace: {resolved}", + "autoskillit.reset_workspace", + extra={"resolved": resolved}, + ) + if not os.path.isdir(resolved): await _notify( ctx, "error", - "reset_test_dir failed", - "autoskillit.reset_test_dir", + "reset_workspace failed", + "autoskillit.reset_workspace", extra={"reason": "directory does not exist"}, ) return json.dumps({"error": f"Directory does not exist: {resolved}"}) + from autoskillit.server import _get_config + marker_name = _get_config().safety.reset_guard_marker marker_path = Path(resolved) / marker_name - if not force and not marker_path.is_file(): + if not marker_path.is_file(): await _notify( ctx, "error", - "reset_test_dir failed", - "autoskillit.reset_test_dir", + "reset_workspace failed", + "autoskillit.reset_workspace", extra={"reason": "marker missing"}, ) return json.dumps( @@ -152,108 +230,48 @@ async def reset_test_dir( } ) - if tool_ctx.workspace_mgr is None: - return json.dumps({"error": "Workspace manager not configured"}) - - preserve = None if force else {marker_name} - cleanup = tool_ctx.workspace_mgr.delete_contents(Path(resolved), preserve=preserve) - return json.dumps({**cleanup.to_dict(), "forced": force}) - finally: - if step_name: - tool_ctx.timing_log.record(step_name, time.monotonic() - _start) - - -@mcp.tool(tags={"autoskillit", "kitchen"}, annotations={"readOnlyHint": True}) -@track_response_size("reset_workspace") -async def reset_workspace(test_dir: str, ctx: Context = CurrentContext()) -> str: - """Runs a configured reset command then deletes directory contents, - preserving configured directories and the reset guard marker. - - Args: - test_dir: Path to the test project directory. Must contain the reset guard marker. - """ - if (gate := _require_enabled()) is not None: - return gate - resolved = os.path.realpath(test_dir) - structlog.contextvars.clear_contextvars() - structlog.contextvars.bind_contextvars(tool="reset_workspace", cwd=resolved) - logger.info("reset_workspace", resolved=str(resolved)) - await _notify( - ctx, - "info", - f"reset_workspace: {resolved}", - "autoskillit.reset_workspace", - extra={"resolved": resolved}, - ) - - if not os.path.isdir(resolved): - await _notify( - ctx, - "error", - "reset_workspace failed", - "autoskillit.reset_workspace", - extra={"reason": "directory does not exist"}, - ) - return json.dumps({"error": f"Directory does not exist: {resolved}"}) - - from autoskillit.server import _get_config - - marker_name = _get_config().safety.reset_guard_marker - marker_path = Path(resolved) / marker_name - if not marker_path.is_file(): - await _notify( - ctx, - "error", - "reset_workspace failed", - "autoskillit.reset_workspace", - extra={"reason": "marker missing"}, - ) - return json.dumps( - { - "error": f"Safety: directory missing reset guard marker ({marker_name})", - "hint": f"Create the marker with: autoskillit workspace init {resolved}", - } - ) + reset_cmd = _get_config().reset_workspace.command + if reset_cmd is None: + await _notify( + ctx, + "error", + "reset_workspace failed", + "autoskillit.reset_workspace", + extra={"reason": "not configured"}, + ) + return json.dumps({"error": "reset_workspace not configured for this project"}) - reset_cmd = _get_config().reset_workspace.command - if reset_cmd is None: - await _notify( - ctx, - "error", - "reset_workspace failed", - "autoskillit.reset_workspace", - extra={"reason": "not configured"}, + returncode, stdout, stderr = await _run_subprocess( + reset_cmd, + cwd=resolved, + timeout=60, ) - return json.dumps({"error": "reset_workspace not configured for this project"}) - returncode, stdout, stderr = await _run_subprocess( - reset_cmd, - cwd=resolved, - timeout=60, - ) - - if returncode != 0: - await _notify( - ctx, - "error", - "reset_workspace failed", - "autoskillit.reset_workspace", - extra={"reason": "reset command failed", "exit_code": returncode}, - ) - return json.dumps( - { - "error": "reset command failed", - "exit_code": returncode, - "stderr": truncate_text(stderr), - } - ) + if returncode != 0: + await _notify( + ctx, + "error", + "reset_workspace failed", + "autoskillit.reset_workspace", + extra={"reason": "reset command failed", "exit_code": returncode}, + ) + return json.dumps( + { + "error": "reset command failed", + "exit_code": returncode, + "stderr": truncate_text(stderr), + } + ) - from autoskillit.server import _get_ctx + from autoskillit.server import _get_ctx - tool_ctx = _get_ctx() - if tool_ctx.workspace_mgr is None: - return json.dumps({"error": "Workspace manager not configured"}) + tool_ctx = _get_ctx() + if tool_ctx.workspace_mgr is None: + return json.dumps({"error": "Workspace manager not configured"}) - preserve = set(_get_config().reset_workspace.preserve_dirs) | {marker_name} - cleanup = tool_ctx.workspace_mgr.delete_contents(Path(resolved), preserve=preserve) - return json.dumps(cleanup.to_dict()) + preserve = set(_get_config().reset_workspace.preserve_dirs) | {marker_name} + cleanup = tool_ctx.workspace_mgr.delete_contents(Path(resolved), preserve=preserve) + return json.dumps(cleanup.to_dict()) + except Exception as exc: + logger.error("reset_workspace unhandled exception", exc_info=True) + return json.dumps({"error": f"{type(exc).__name__}: {exc}"}) diff --git a/src/autoskillit/skills/sous-chef/SKILL.md b/src/autoskillit/skills/sous-chef/SKILL.md index 74e4f1cd53..d2b6681522 100644 --- a/src/autoskillit/skills/sous-chef/SKILL.md +++ b/src/autoskillit/skills/sous-chef/SKILL.md @@ -241,28 +241,39 @@ Capture the result as `auto_merge_available`. If detection fails, default to `"f perform both detections automatically via `check_merge_queue` + `check_auto_merge` — **do not repeat them manually when following a recipe**. -### 2. Route based on queue availability - -**When `queue_available == true`:** -GitHub's merge queue serializes concurrent merges. Each pipeline's -`enable_auto_merge → wait_for_queue` sequence is safe to proceed in parallel — the -queue handles ordering. No additional sequencing is required from the orchestrator. - -**When `queue_available == false` and `auto_merge_available == true`:** -Use `gh pr merge --squash --auto` (direct_merge path). GitHub merges the PR once -all required status checks pass. PRs must not be merged concurrently — never execute -two `direct_merge` steps concurrently on a non-queue branch. - -**When `queue_available == false` and `auto_merge_available == false`:** -Use `gh pr merge --squash` (immediate_merge path — no `--auto` flag). GitHub -executes the merge synchronously without waiting for status checks (there are none -to wait for when `autoMergeAllowed=false`). PRs MUST still be merged one at a time. - -- If following a recipe: the recipe's `route_queue_mode` step routes to the correct - path automatically based on `context.auto_merge_available`. -- **NEVER** use `gh pr merge --squash --auto` when `auto_merge_available == false` — - this command fails with "auto-merge is not allowed for this repository"; in recipe - context it silently routes to `confirm_cleanup`, leaving the PR unmerged. +### 2. Route based on queue availability and auto-merge availability + +The recipes route on the four-cell matrix `queue_available × auto_merge_available`: + +| `queue_available` | `auto_merge_available` | Recipe path | +|-------------------|------------------------|------------------------------------------------| +| `true` | `true` | `enable_auto_merge` → `wait_for_queue` | +| `true` | `false` | `queue_enqueue_no_auto` → `wait_for_queue` | +| `false` | `true` | `direct_merge` → `wait_for_direct_merge` | +| `false` | `false` | `immediate_merge` → `wait_for_immediate_merge` | + +**When `queue_available == true`:** GitHub's merge queue intercepts every merge +request on the branch regardless of the `--auto` flag. Both queue cells route +through `wait_for_queue` (the merge-queue-aware waiter). The +`enable_auto_merge` cell uses `--auto` so the queue serializes via GitHub +auto-merge; the `queue_enqueue_no_auto` cell (condition: +`queue_available == true and auto_merge_available == false`) uses plain `--squash` +because the repository's `autoMergeAllowed=false` setting causes `--auto` to be +rejected by the API auto-merge gate **before** the queue interception. + +**When `queue_available == false`:** there is no queue, so behaviour matches +the historical paths — `direct_merge` waits via auto-merge, `immediate_merge` +executes synchronously. + +- If following a recipe: `route_queue_mode` selects the correct cell + automatically from `context.queue_available` and `context.auto_merge_available`. +- **NEVER use** `gh pr merge --squash --auto` when `auto_merge_available == false`, + regardless of `queue_available`. The `--auto` flag is rejected by GitHub's API + auto-merge gate before the queue intercepts. Use plain `gh pr merge --squash`; + if a queue exists on the branch the queue still enqueues the call. +- **NEVER** route a queue+no-auto enqueue call through `wait_for_immediate_merge` + — its 5-minute poll is too short for a busy queue and on timeout the recipe + reports `merge unconfirmed` even though the PR will eventually merge. For ad-hoc (off-recipe) merges: - If merging multiple PRs collected from parallel pipelines: route through the @@ -272,7 +283,7 @@ For ad-hoc (off-recipe) merges: **NEVER use `run_cmd` with `gh pr merge` to merge a PR outside of a named recipe step.** All PR merges must flow through the recipe's `merge_pr`, `direct_merge`, -`immediate_merge`, or `enable_auto_merge` steps. Bypassing these steps skips CI +`immediate_merge`, `enable_auto_merge` or `queue_enqueue_no_auto` steps. Bypassing these steps skips CI enforcement, conflict detection, and conflict routing. ### 4. Merge conflict failure handling @@ -287,3 +298,52 @@ closed due to a stale base): and `immediate_merge_conflict_fix` has full diagnostic access. - **NEVER abandon a pipeline** because merge failed — route through the conflict recovery cycle until the PR merges or escalation is required. + +--- + +## QUOTA WAIT PROTOCOL — MANDATORY + +When quota-related events occur during pipeline execution: + +### PreToolUse Denial (run_skill blocked) + +When a `run_skill` call is DENIED by the quota guard hook: + +1. This is a **temporary** block — NOT a permanent error, NOT a pipeline failure. +2. The deny message contains a `run_cmd` sleep command with the required duration. +3. **MANDATORY**: Execute the sleep command via `run_cmd` immediately. +4. After the sleep completes, retry the **exact same** `run_skill` call with + identical arguments (`skill_command`, `cwd`, `model`, `step_name`). +5. Do NOT follow `on_failure`. Do NOT report to the user. Do NOT skip the step. +6. Before executing, state aloud: "Quota denied. Sleeping N seconds, then retrying." + +### Post-Execution Warning (quota high after run_skill) + +When `run_skill` output contains `--- QUOTA WARNING ---`: + +1. The warning contains a `run_cmd` sleep command. +2. **MANDATORY**: Execute the sleep command via `run_cmd` BEFORE calling the next + `run_skill` (whether it is the next pipeline step or a retry). +3. After sleeping, proceed normally with the next step. +4. Before executing, state aloud: "Quota warning. Sleeping N seconds before next step." + +### Key Rules + +- Quota denials are **always temporary**. The API enforces multiple rate-limit windows (e.g. one-minute, one-hour, five-hour, one-day). The guard waits for the most constrained window — the one that resets latest among all windows above the threshold — to reset before retrying. +- A denied `run_skill` has **zero side effects** — no partial state, no worktree changes. + Retrying with the same arguments is always safe. +- Multiple consecutive denials may occur if the sleep duration was underestimated. + Keep sleeping and retrying until the call succeeds. +- NEVER use `AskUserQuestion` for quota events — they are fully automated. + +--- + +## NARRATION SUPPRESSION — MANDATORY + +Do NOT output prose status text, phase announcements, or progress summaries between +tool calls. Every non-final assistant turn MUST invoke at least one tool. + +The only permitted text-only turn is a final response containing structured output +tokens (`plan_path = ...`, `worktree_path = ...`, etc.). + +This applies to all skills invoked interactively within a cook session. diff --git a/src/autoskillit/skills_extended/analyze-prs/SKILL.md b/src/autoskillit/skills_extended/analyze-prs/SKILL.md index 6e23f38633..9397cf547d 100644 --- a/src/autoskillit/skills_extended/analyze-prs/SKILL.md +++ b/src/autoskillit/skills_extended/analyze-prs/SKILL.md @@ -27,7 +27,7 @@ complexity, and produce machine-readable output for the `merge-prs` recipe. **NEVER:** - Merge, close, or modify any PR - Modify any source code files -- Create files outside `.autoskillit/temp/merge-prs/` directory +- Create files outside `{{AUTOSKILLIT_TEMP}}/merge-prs/` directory **ALWAYS:** - Use subagents to fetch PR data in parallel @@ -242,9 +242,9 @@ Compute a timestamp: `YYYY-MM-DD_HHMMSS`. Compute integration branch name: `pr-batch/pr-merge-{YYYYMMDD-HHMMSS}`. -Ensure `.autoskillit/temp/merge-prs/` exists. +Ensure `{{AUTOSKILLIT_TEMP}}/merge-prs/` exists. -**5a. Machine-readable order file:** `.autoskillit/temp/merge-prs/pr_order_{ts}.json` +**5a. Machine-readable order file:** `{{AUTOSKILLIT_TEMP}}/merge-prs/pr_order_{ts}.json` ```json { @@ -287,7 +287,7 @@ Ensure `.autoskillit/temp/merge-prs/` exists. `pr_count` reflects the number of **eligible** PRs (i.e., `${#ELIGIBLE_PRS[@]}`). -**5b. Human-readable analysis plan:** `.autoskillit/temp/merge-prs/pr_analysis_plan_{ts}.md` +**5b. Human-readable analysis plan:** `{{AUTOSKILLIT_TEMP}}/merge-prs/pr_analysis_plan_{ts}.md` This file is named `*_plan_*.md` so `audit-impl` can discover it as the baseline specification. @@ -363,7 +363,7 @@ Report to terminal: ## Output Location ``` -.autoskillit/temp/merge-prs/ +{{AUTOSKILLIT_TEMP}}/merge-prs/ ├── pr_order_{ts}.json # Machine-readable manifest (captured by recipe) └── pr_analysis_plan_{ts}.md # Human-readable analysis (discovered by audit-impl) ``` @@ -394,4 +394,4 @@ queue_mode = {queue_mode} # true when merge queue has ≥1 MERGEABLE entry; fa - **`/autoskillit:merge-pr`** — Merges individual PRs from this skill's ordered list - **`/autoskillit:make-plan`** — Called for complex PRs that need conflict resolution plans -- **`/autoskillit:audit-impl`** — Receives `.autoskillit/temp/merge-prs/` as plans_input +- **`/autoskillit:audit-impl`** — Receives `{{AUTOSKILLIT_TEMP}}/merge-prs/` as plans_input diff --git a/src/autoskillit/skills_extended/arch-lens-c4-container/SKILL.md b/src/autoskillit/skills_extended/arch-lens-c4-container/SKILL.md index 18b2627f18..4f41bff74e 100644 --- a/src/autoskillit/skills_extended/arch-lens-c4-container/SKILL.md +++ b/src/autoskillit/skills_extended/arch-lens-c4-container/SKILL.md @@ -1,6 +1,7 @@ --- name: arch-lens-c4-container categories: [arch-lens] +activate_deps: [mermaid] description: Create C4 Container architecture diagram showing static structure, building blocks, and technology choices. Anatomical lens answering "How is it built?" hooks: PreToolUse: @@ -36,19 +37,39 @@ hooks: - Show technology choices for each container - Identify external systems and integrations - BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. - After writing the diagram file, emit the **absolute path** as a structured output - token immediately before `%%ORDER_UP%%`. Resolve the relative `temp/arch-lens-c4-container/...` + token as your final output. Resolve the relative `temp/arch-lens-c4-container/...` save path to absolute by prepending the full CWD: ``` diagram_path = /absolute/cwd/temp/arch-lens-c4-container/{filename}.md - %%ORDER_UP%% ``` This token is MANDATORY — the pipeline cannot proceed without it. +## Arguments + +`/autoskillit:arch-lens-c4-container [context_path]` + +- **context_path** (optional) — Absolute path to a PR context file containing new files + (★-prefixed) and modified files (●-prefixed) from the PR diff. When provided, read + this file before beginning analysis and focus the diagram on the architectural areas + affected by these specific files. When absent, explore the full CWD. + --- ## Analysis Workflow +### Step 0: Read PR context (when provided) + +If a `context_path` positional argument is present: +1. Read the file at `context_path` +2. Extract: new files list (★-prefixed), modified files list (●-prefixed) +3. Focus Step 1 exploration on the modules/components these files belong to +4. Apply ★ prefix on diagram nodes representing new files/components +5. Apply ● prefix on diagram nodes representing modified files/components + +If no `context_path` is provided, skip this step and explore the full CWD in Step 1. + ### Step 1: Launch Parallel Exploration Subagents Spawn Explore subagents to investigate: @@ -133,7 +154,7 @@ Use the mermaid skill conventions to create a diagram with: ### Step 5: Write Output -Write the diagram to: `.autoskillit/temp/arch-lens-c4-container/arch_diag_c4_container_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/arch-lens-c4-container/arch_diag_c4_container_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) After writing the diagram file, emit a structured output line: diff --git a/src/autoskillit/skills_extended/arch-lens-concurrency/SKILL.md b/src/autoskillit/skills_extended/arch-lens-concurrency/SKILL.md index 67cbd8dbdd..aade0ee5ad 100644 --- a/src/autoskillit/skills_extended/arch-lens-concurrency/SKILL.md +++ b/src/autoskillit/skills_extended/arch-lens-concurrency/SKILL.md @@ -1,6 +1,7 @@ --- name: arch-lens-concurrency categories: [arch-lens] +activate_deps: [mermaid] description: Create Concurrency architecture diagram showing parallel execution patterns, thread pools, synchronization, and barriers. Physiological lens answering "How does parallelism work?" hooks: PreToolUse: @@ -37,19 +38,39 @@ hooks: - Identify thread safety guarantees - Document the concurrency MODEL used - BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. - After writing the diagram file, emit the **absolute path** as a structured output - token immediately before `%%ORDER_UP%%`. Resolve the relative `temp/arch-lens-concurrency/...` + token as your final output. Resolve the relative `temp/arch-lens-concurrency/...` save path to absolute by prepending the full CWD: ``` diagram_path = /absolute/cwd/temp/arch-lens-concurrency/{filename}.md - %%ORDER_UP%% ``` This token is MANDATORY — the pipeline cannot proceed without it. +## Arguments + +`/autoskillit:arch-lens-concurrency [context_path]` + +- **context_path** (optional) — Absolute path to a PR context file containing new files + (★-prefixed) and modified files (●-prefixed) from the PR diff. When provided, read + this file before beginning analysis and focus the diagram on the architectural areas + affected by these specific files. When absent, explore the full CWD. + --- ## Analysis Workflow +### Step 0: Read PR context (when provided) + +If a `context_path` positional argument is present: +1. Read the file at `context_path` +2. Extract: new files list (★-prefixed), modified files list (●-prefixed) +3. Focus Step 1 exploration on the modules/components these files belong to +4. Apply ★ prefix on diagram nodes representing new files/components +5. Apply ● prefix on diagram nodes representing modified files/components + +If no `context_path` is provided, skip this step and explore the full CWD in Step 1. + ### Step 1: Launch Parallel Exploration Subagents Spawn Explore subagents to investigate: @@ -139,7 +160,7 @@ Use flowchart with: ### Step 5: Write Output -Write the diagram to: `.autoskillit/temp/arch-lens-concurrency/arch_diag_concurrency_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/arch-lens-concurrency/arch_diag_concurrency_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) After writing the diagram file, emit a structured output line: diff --git a/src/autoskillit/skills_extended/arch-lens-data-lineage/SKILL.md b/src/autoskillit/skills_extended/arch-lens-data-lineage/SKILL.md index 937f4e2bcc..7ec1ee4221 100644 --- a/src/autoskillit/skills_extended/arch-lens-data-lineage/SKILL.md +++ b/src/autoskillit/skills_extended/arch-lens-data-lineage/SKILL.md @@ -1,6 +1,7 @@ --- name: arch-lens-data-lineage categories: [arch-lens] +activate_deps: [mermaid] description: Create Data Lineage architecture diagram showing information flow, transformations, and storage destinations. Data-centric lens answering "Where is the data?" hooks: PreToolUse: @@ -37,19 +38,39 @@ hooks: - Identify the single source of truth - Distinguish read vs write operations - BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. - After writing the diagram file, emit the **absolute path** as a structured output - token immediately before `%%ORDER_UP%%`. Resolve the relative `temp/arch-lens-data-lineage/...` + token as your final output. Resolve the relative `temp/arch-lens-data-lineage/...` save path to absolute by prepending the full CWD: ``` diagram_path = /absolute/cwd/temp/arch-lens-data-lineage/{filename}.md - %%ORDER_UP%% ``` This token is MANDATORY — the pipeline cannot proceed without it. +## Arguments + +`/autoskillit:arch-lens-data-lineage [context_path]` + +- **context_path** (optional) — Absolute path to a PR context file containing new files + (★-prefixed) and modified files (●-prefixed) from the PR diff. When provided, read + this file before beginning analysis and focus the diagram on the architectural areas + affected by these specific files. When absent, explore the full CWD. + --- ## Analysis Workflow +### Step 0: Read PR context (when provided) + +If a `context_path` positional argument is present: +1. Read the file at `context_path` +2. Extract: new files list (★-prefixed), modified files list (●-prefixed) +3. Focus Step 1 exploration on the modules/components these files belong to +4. Apply ★ prefix on diagram nodes representing new files/components +5. Apply ● prefix on diagram nodes representing modified files/components + +If no `context_path` is provided, skip this step and explore the full CWD in Step 1. + ### Step 1: Launch Parallel Exploration Subagents Spawn Explore subagents to investigate: @@ -142,7 +163,7 @@ Use flowchart with: ### Step 5: Write Output -Write the diagram to: `.autoskillit/temp/arch-lens-data-lineage/arch_diag_data_lineage_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/arch-lens-data-lineage/arch_diag_data_lineage_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) After writing the diagram file, emit a structured output line: diff --git a/src/autoskillit/skills_extended/arch-lens-deployment/SKILL.md b/src/autoskillit/skills_extended/arch-lens-deployment/SKILL.md index e5a49637e5..9972bf6997 100644 --- a/src/autoskillit/skills_extended/arch-lens-deployment/SKILL.md +++ b/src/autoskillit/skills_extended/arch-lens-deployment/SKILL.md @@ -1,6 +1,7 @@ --- name: arch-lens-deployment categories: [arch-lens] +activate_deps: [mermaid] description: Create Deployment/Physical architecture diagram showing infrastructure topology, process boundaries, and network communication. Physical lens answering "Where does it run?" hooks: PreToolUse: @@ -37,19 +38,39 @@ hooks: - Include network/communication protocols - Document storage locations - BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. - After writing the diagram file, emit the **absolute path** as a structured output - token immediately before `%%ORDER_UP%%`. Resolve the relative `temp/arch-lens-deployment/...` + token as your final output. Resolve the relative `temp/arch-lens-deployment/...` save path to absolute by prepending the full CWD: ``` diagram_path = /absolute/cwd/temp/arch-lens-deployment/{filename}.md - %%ORDER_UP%% ``` This token is MANDATORY — the pipeline cannot proceed without it. +## Arguments + +`/autoskillit:arch-lens-deployment [context_path]` + +- **context_path** (optional) — Absolute path to a PR context file containing new files + (★-prefixed) and modified files (●-prefixed) from the PR diff. When provided, read + this file before beginning analysis and focus the diagram on the architectural areas + affected by these specific files. When absent, explore the full CWD. + --- ## Analysis Workflow +### Step 0: Read PR context (when provided) + +If a `context_path` positional argument is present: +1. Read the file at `context_path` +2. Extract: new files list (★-prefixed), modified files list (●-prefixed) +3. Focus Step 1 exploration on the modules/components these files belong to +4. Apply ★ prefix on diagram nodes representing new files/components +5. Apply ● prefix on diagram nodes representing modified files/components + +If no `context_path` is provided, skip this step and explore the full CWD in Step 1. + ### Step 1: Launch Parallel Exploration Subagents Spawn Explore subagents to investigate: @@ -137,7 +158,7 @@ Use flowchart with: ### Step 5: Write Output -Write the diagram to: `.autoskillit/temp/arch-lens-deployment/arch_diag_deployment_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/arch-lens-deployment/arch_diag_deployment_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) After writing the diagram file, emit a structured output line: diff --git a/src/autoskillit/skills_extended/arch-lens-development/SKILL.md b/src/autoskillit/skills_extended/arch-lens-development/SKILL.md index 7f24cae09e..28b088b5d4 100644 --- a/src/autoskillit/skills_extended/arch-lens-development/SKILL.md +++ b/src/autoskillit/skills_extended/arch-lens-development/SKILL.md @@ -1,6 +1,7 @@ --- name: arch-lens-development categories: [arch-lens] +activate_deps: [mermaid] description: Create Development architecture diagram showing project structure, build tools, and quality gates. Development lens answering "How is it built and tested?" hooks: PreToolUse: @@ -37,19 +38,39 @@ hooks: - Document test framework setup - Include entry points - BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. - After writing the diagram file, emit the **absolute path** as a structured output - token immediately before `%%ORDER_UP%%`. Resolve the relative `temp/arch-lens-development/...` + token as your final output. Resolve the relative `temp/arch-lens-development/...` save path to absolute by prepending the full CWD: ``` diagram_path = /absolute/cwd/temp/arch-lens-development/{filename}.md - %%ORDER_UP%% ``` This token is MANDATORY — the pipeline cannot proceed without it. +## Arguments + +`/autoskillit:arch-lens-development [context_path]` + +- **context_path** (optional) — Absolute path to a PR context file containing new files + (★-prefixed) and modified files (●-prefixed) from the PR diff. When provided, read + this file before beginning analysis and focus the diagram on the architectural areas + affected by these specific files. When absent, explore the full CWD. + --- ## Analysis Workflow +### Step 0: Read PR context (when provided) + +If a `context_path` positional argument is present: +1. Read the file at `context_path` +2. Extract: new files list (★-prefixed), modified files list (●-prefixed) +3. Focus Step 1 exploration on the modules/components these files belong to +4. Apply ★ prefix on diagram nodes representing new files/components +5. Apply ● prefix on diagram nodes representing modified files/components + +If no `context_path` is provided, skip this step and explore the full CWD in Step 1. + ### Step 1: Launch Parallel Exploration Subagents Spawn Explore subagents to investigate: @@ -143,7 +164,7 @@ Use flowchart with: ### Step 5: Write Output -Write the diagram to: `.autoskillit/temp/arch-lens-development/arch_diag_development_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/arch-lens-development/arch_diag_development_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) After writing the diagram file, emit a structured output line: diff --git a/src/autoskillit/skills_extended/arch-lens-error-resilience/SKILL.md b/src/autoskillit/skills_extended/arch-lens-error-resilience/SKILL.md index 5e07921de5..b0b7b0cf14 100644 --- a/src/autoskillit/skills_extended/arch-lens-error-resilience/SKILL.md +++ b/src/autoskillit/skills_extended/arch-lens-error-resilience/SKILL.md @@ -1,6 +1,7 @@ --- name: arch-lens-error-resilience categories: [arch-lens] +activate_deps: [mermaid] description: Create Error/Resilience architecture diagram showing failure handling, recovery mechanisms, and circuit breakers. Diagnostic lens answering "How are failures handled?" hooks: PreToolUse: @@ -37,19 +38,39 @@ hooks: - Document retry limits and circuit breakers - Include exception hierarchy if present - BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. - After writing the diagram file, emit the **absolute path** as a structured output - token immediately before `%%ORDER_UP%%`. Resolve the relative `temp/arch-lens-error-resilience/...` + token as your final output. Resolve the relative `temp/arch-lens-error-resilience/...` save path to absolute by prepending the full CWD: ``` diagram_path = /absolute/cwd/temp/arch-lens-error-resilience/{filename}.md - %%ORDER_UP%% ``` This token is MANDATORY — the pipeline cannot proceed without it. +## Arguments + +`/autoskillit:arch-lens-error-resilience [context_path]` + +- **context_path** (optional) — Absolute path to a PR context file containing new files + (★-prefixed) and modified files (●-prefixed) from the PR diff. When provided, read + this file before beginning analysis and focus the diagram on the architectural areas + affected by these specific files. When absent, explore the full CWD. + --- ## Analysis Workflow +### Step 0: Read PR context (when provided) + +If a `context_path` positional argument is present: +1. Read the file at `context_path` +2. Extract: new files list (★-prefixed), modified files list (●-prefixed) +3. Focus Step 1 exploration on the modules/components these files belong to +4. Apply ★ prefix on diagram nodes representing new files/components +5. Apply ● prefix on diagram nodes representing modified files/components + +If no `context_path` is provided, skip this step and explore the full CWD in Step 1. + ### Step 1: Launch Parallel Exploration Subagents Spawn Explore subagents to investigate: @@ -140,7 +161,7 @@ Use flowchart with: ### Step 5: Write Output -Write the diagram to: `.autoskillit/temp/arch-lens-error-resilience/arch_diag_error_resilience_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/arch-lens-error-resilience/arch_diag_error_resilience_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) After writing the diagram file, emit a structured output line: diff --git a/src/autoskillit/skills_extended/arch-lens-module-dependency/SKILL.md b/src/autoskillit/skills_extended/arch-lens-module-dependency/SKILL.md index f621591333..3284f44e96 100644 --- a/src/autoskillit/skills_extended/arch-lens-module-dependency/SKILL.md +++ b/src/autoskillit/skills_extended/arch-lens-module-dependency/SKILL.md @@ -1,6 +1,7 @@ --- name: arch-lens-module-dependency categories: [arch-lens] +activate_deps: [mermaid] description: Create Module Dependency architecture diagram showing package coupling, layering, and fan-in/fan-out. Structural lens answering "How are modules coupled?" hooks: PreToolUse: @@ -37,19 +38,39 @@ hooks: - Flag circular dependencies and violations - Calculate fan-in for key modules - BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. - After writing the diagram file, emit the **absolute path** as a structured output - token immediately before `%%ORDER_UP%%`. Resolve the relative `temp/arch-lens-module-dependency/...` + token as your final output. Resolve the relative `temp/arch-lens-module-dependency/...` save path to absolute by prepending the full CWD: ``` diagram_path = /absolute/cwd/temp/arch-lens-module-dependency/{filename}.md - %%ORDER_UP%% ``` This token is MANDATORY — the pipeline cannot proceed without it. +## Arguments + +`/autoskillit:arch-lens-module-dependency [context_path]` + +- **context_path** (optional) — Absolute path to a PR context file containing new files + (★-prefixed) and modified files (●-prefixed) from the PR diff. When provided, read + this file before beginning analysis and focus the diagram on the architectural areas + affected by these specific files. When absent, explore the full CWD. + --- ## Analysis Workflow +### Step 0: Read PR context (when provided) + +If a `context_path` positional argument is present: +1. Read the file at `context_path` +2. Extract: new files list (★-prefixed), modified files list (●-prefixed) +3. Focus Step 1 exploration on the modules/components these files belong to +4. Apply ★ prefix on diagram nodes representing new files/components +5. Apply ● prefix on diagram nodes representing modified files/components + +If no `context_path` is provided, skip this step and explore the full CWD in Step 1. + ### Step 1: Launch Parallel Exploration Subagents Spawn Explore subagents to investigate: @@ -134,7 +155,7 @@ Use graph with: ### Step 5: Write Output -Write the diagram to: `.autoskillit/temp/arch-lens-module-dependency/arch_diag_module_dependency_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/arch-lens-module-dependency/arch_diag_module_dependency_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) After writing the diagram file, emit a structured output line: diff --git a/src/autoskillit/skills_extended/arch-lens-operational/SKILL.md b/src/autoskillit/skills_extended/arch-lens-operational/SKILL.md index 0748ca7cd5..94b8e22351 100644 --- a/src/autoskillit/skills_extended/arch-lens-operational/SKILL.md +++ b/src/autoskillit/skills_extended/arch-lens-operational/SKILL.md @@ -1,6 +1,7 @@ --- name: arch-lens-operational categories: [arch-lens] +activate_deps: [mermaid] description: Create Operational architecture diagram showing CLI workflows, configuration, and observability. Administration lens answering "How is it run and monitored?" hooks: PreToolUse: @@ -37,19 +38,39 @@ hooks: - Document configuration hierarchy - Include monitoring and logging outputs - BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. - After writing the diagram file, emit the **absolute path** as a structured output - token immediately before `%%ORDER_UP%%`. Resolve the relative `temp/arch-lens-operational/...` + token as your final output. Resolve the relative `temp/arch-lens-operational/...` save path to absolute by prepending the full CWD: ``` diagram_path = /absolute/cwd/temp/arch-lens-operational/{filename}.md - %%ORDER_UP%% ``` This token is MANDATORY — the pipeline cannot proceed without it. +## Arguments + +`/autoskillit:arch-lens-operational [context_path]` + +- **context_path** (optional) — Absolute path to a PR context file containing new files + (★-prefixed) and modified files (●-prefixed) from the PR diff. When provided, read + this file before beginning analysis and focus the diagram on the architectural areas + affected by these specific files. When absent, explore the full CWD. + --- ## Analysis Workflow +### Step 0: Read PR context (when provided) + +If a `context_path` positional argument is present: +1. Read the file at `context_path` +2. Extract: new files list (★-prefixed), modified files list (●-prefixed) +3. Focus Step 1 exploration on the modules/components these files belong to +4. Apply ★ prefix on diagram nodes representing new files/components +5. Apply ● prefix on diagram nodes representing modified files/components + +If no `context_path` is provided, skip this step and explore the full CWD in Step 1. + ### Step 1: Launch Parallel Exploration Subagents Spawn Explore subagents to investigate: @@ -72,7 +93,7 @@ Spawn Explore subagents to investigate: **Logging & Monitoring** - Find logging configuration - Identify observability outputs -- Look for: logging configuration, log files, metrics, activity logs, .autoskillit/temp/ output directories +- Look for: logging configuration, log files, metrics, activity logs, {{AUTOSKILLIT_TEMP}}/ output directories **Status & Health** - Find status/health commands @@ -142,7 +163,7 @@ Use flowchart with: ### Step 5: Write Output -Write the diagram to: `.autoskillit/temp/arch-lens-operational/arch_diag_operational_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/arch-lens-operational/arch_diag_operational_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) After writing the diagram file, emit a structured output line: @@ -204,7 +225,7 @@ flowchart TB subgraph Monitoring ["OBSERVABILITY"] direction TB LOGS["Activity Logs
    ━━━━━━━━━━
    Step-by-step"] - DEBUG["Debug Artifacts
    ━━━━━━━━━━
    .autoskillit/temp/ directory"] + DEBUG["Debug Artifacts
    ━━━━━━━━━━
    {{AUTOSKILLIT_TEMP}}/ directory"] end subgraph Tasks ["TASK COMMANDS"] diff --git a/src/autoskillit/skills_extended/arch-lens-process-flow/SKILL.md b/src/autoskillit/skills_extended/arch-lens-process-flow/SKILL.md index 7528120b26..7a02b64641 100644 --- a/src/autoskillit/skills_extended/arch-lens-process-flow/SKILL.md +++ b/src/autoskillit/skills_extended/arch-lens-process-flow/SKILL.md @@ -1,6 +1,7 @@ --- name: arch-lens-process-flow categories: [arch-lens] +activate_deps: [mermaid] description: Create Process/Execution Flow architecture diagram showing runtime behavior, state transitions, and decision points. Physiological lens answering "How does it behave?" hooks: PreToolUse: @@ -36,19 +37,39 @@ hooks: - Show decision points as diamonds - Include loop mechanisms and retry logic - BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. - After writing the diagram file, emit the **absolute path** as a structured output - token immediately before `%%ORDER_UP%%`. Resolve the relative `temp/arch-lens-process-flow/...` + token as your final output. Resolve the relative `temp/arch-lens-process-flow/...` save path to absolute by prepending the full CWD: ``` diagram_path = /absolute/cwd/temp/arch-lens-process-flow/{filename}.md - %%ORDER_UP%% ``` This token is MANDATORY — the pipeline cannot proceed without it. +## Arguments + +`/autoskillit:arch-lens-process-flow [context_path]` + +- **context_path** (optional) — Absolute path to a PR context file containing new files + (★-prefixed) and modified files (●-prefixed) from the PR diff. When provided, read + this file before beginning analysis and focus the diagram on the architectural areas + affected by these specific files. When absent, explore the full CWD. + --- ## Analysis Workflow +### Step 0: Read PR context (when provided) + +If a `context_path` positional argument is present: +1. Read the file at `context_path` +2. Extract: new files list (★-prefixed), modified files list (●-prefixed) +3. Focus Step 1 exploration on the modules/components these files belong to +4. Apply ★ prefix on diagram nodes representing new files/components +5. Apply ● prefix on diagram nodes representing modified files/components + +If no `context_path` is provided, skip this step and explore the full CWD in Step 1. + ### Step 1: Launch Parallel Exploration Subagents Spawn Explore subagents to investigate: @@ -135,7 +156,7 @@ Use flowchart with: ### Step 5: Write Output -Write the diagram to: `.autoskillit/temp/arch-lens-process-flow/arch_diag_process_flow_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/arch-lens-process-flow/arch_diag_process_flow_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) After writing the diagram file, emit a structured output line: diff --git a/src/autoskillit/skills_extended/arch-lens-repository-access/SKILL.md b/src/autoskillit/skills_extended/arch-lens-repository-access/SKILL.md index faf336de19..e551281c61 100644 --- a/src/autoskillit/skills_extended/arch-lens-repository-access/SKILL.md +++ b/src/autoskillit/skills_extended/arch-lens-repository-access/SKILL.md @@ -1,6 +1,7 @@ --- name: arch-lens-repository-access categories: [arch-lens] +activate_deps: [mermaid] description: Create Repository/Data Access architecture diagram showing the repository pattern, entity relationships, and data access patterns. Data-centric lens answering "How is data accessed?" hooks: PreToolUse: @@ -37,19 +38,39 @@ hooks: - Document key query patterns - Identify format conversion boundaries - BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. - After writing the diagram file, emit the **absolute path** as a structured output - token immediately before `%%ORDER_UP%%`. Resolve the relative `temp/arch-lens-repository-access/...` + token as your final output. Resolve the relative `temp/arch-lens-repository-access/...` save path to absolute by prepending the full CWD: ``` diagram_path = /absolute/cwd/temp/arch-lens-repository-access/{filename}.md - %%ORDER_UP%% ``` This token is MANDATORY — the pipeline cannot proceed without it. +## Arguments + +`/autoskillit:arch-lens-repository-access [context_path]` + +- **context_path** (optional) — Absolute path to a PR context file containing new files + (★-prefixed) and modified files (●-prefixed) from the PR diff. When provided, read + this file before beginning analysis and focus the diagram on the architectural areas + affected by these specific files. When absent, explore the full CWD. + --- ## Analysis Workflow +### Step 0: Read PR context (when provided) + +If a `context_path` positional argument is present: +1. Read the file at `context_path` +2. Extract: new files list (★-prefixed), modified files list (●-prefixed) +3. Focus Step 1 exploration on the modules/components these files belong to +4. Apply ★ prefix on diagram nodes representing new files/components +5. Apply ● prefix on diagram nodes representing modified files/components + +If no `context_path` is provided, skip this step and explore the full CWD in Step 1. + ### Step 1: Launch Parallel Exploration Subagents Spawn Explore subagents to investigate: @@ -141,7 +162,7 @@ Use flowchart with: ### Step 5: Write Output -Write the diagram to: `.autoskillit/temp/arch-lens-repository-access/arch_diag_repository_access_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/arch-lens-repository-access/arch_diag_repository_access_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) After writing the diagram file, emit a structured output line: diff --git a/src/autoskillit/skills_extended/arch-lens-scenarios/SKILL.md b/src/autoskillit/skills_extended/arch-lens-scenarios/SKILL.md index 59af55a20d..413333ef74 100644 --- a/src/autoskillit/skills_extended/arch-lens-scenarios/SKILL.md +++ b/src/autoskillit/skills_extended/arch-lens-scenarios/SKILL.md @@ -1,6 +1,7 @@ --- name: arch-lens-scenarios categories: [arch-lens] +activate_deps: [mermaid] description: Create Scenarios architecture diagram showing end-to-end user journeys and component cooperation validation. Validation lens answering "Do the components work together?" hooks: PreToolUse: @@ -37,19 +38,39 @@ hooks: - Select 3-5 representative scenarios - Validate components work together - BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. - After writing the diagram file, emit the **absolute path** as a structured output - token immediately before `%%ORDER_UP%%`. Resolve the relative `temp/arch-lens-scenarios/...` + token as your final output. Resolve the relative `temp/arch-lens-scenarios/...` save path to absolute by prepending the full CWD: ``` diagram_path = /absolute/cwd/temp/arch-lens-scenarios/{filename}.md - %%ORDER_UP%% ``` This token is MANDATORY — the pipeline cannot proceed without it. +## Arguments + +`/autoskillit:arch-lens-scenarios [context_path]` + +- **context_path** (optional) — Absolute path to a PR context file containing new files + (★-prefixed) and modified files (●-prefixed) from the PR diff. When provided, read + this file before beginning analysis and focus the diagram on the architectural areas + affected by these specific files. When absent, explore the full CWD. + --- ## Analysis Workflow +### Step 0: Read PR context (when provided) + +If a `context_path` positional argument is present: +1. Read the file at `context_path` +2. Extract: new files list (★-prefixed), modified files list (●-prefixed) +3. Focus Step 1 exploration on the modules/components these files belong to +4. Apply ★ prefix on diagram nodes representing new files/components +5. Apply ● prefix on diagram nodes representing modified files/components + +If no `context_path` is provided, skip this step and explore the full CWD in Step 1. + ### Step 1: Launch Parallel Exploration Subagents Spawn Explore subagents to investigate: @@ -134,7 +155,7 @@ Use flowchart with: ### Step 5: Write Output -Write the diagram to: `.autoskillit/temp/arch-lens-scenarios/arch_diag_scenarios_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/arch-lens-scenarios/arch_diag_scenarios_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) After writing the diagram file, emit a structured output line: diff --git a/src/autoskillit/skills_extended/arch-lens-security/SKILL.md b/src/autoskillit/skills_extended/arch-lens-security/SKILL.md index 3ce775ff9d..07935eaadd 100644 --- a/src/autoskillit/skills_extended/arch-lens-security/SKILL.md +++ b/src/autoskillit/skills_extended/arch-lens-security/SKILL.md @@ -1,6 +1,7 @@ --- name: arch-lens-security categories: [arch-lens] +activate_deps: [mermaid] description: Create Security architecture diagram showing trust boundaries, validation layers, and process isolation. Security lens answering "Where are the trust boundaries?" hooks: PreToolUse: @@ -37,19 +38,39 @@ hooks: - Document path contracts and restrictions - Include process isolation mechanisms - BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. - After writing the diagram file, emit the **absolute path** as a structured output - token immediately before `%%ORDER_UP%%`. Resolve the relative `temp/arch-lens-security/...` + token as your final output. Resolve the relative `temp/arch-lens-security/...` save path to absolute by prepending the full CWD: ``` diagram_path = /absolute/cwd/temp/arch-lens-security/{filename}.md - %%ORDER_UP%% ``` This token is MANDATORY — the pipeline cannot proceed without it. +## Arguments + +`/autoskillit:arch-lens-security [context_path]` + +- **context_path** (optional) — Absolute path to a PR context file containing new files + (★-prefixed) and modified files (●-prefixed) from the PR diff. When provided, read + this file before beginning analysis and focus the diagram on the architectural areas + affected by these specific files. When absent, explore the full CWD. + --- ## Analysis Workflow +### Step 0: Read PR context (when provided) + +If a `context_path` positional argument is present: +1. Read the file at `context_path` +2. Extract: new files list (★-prefixed), modified files list (●-prefixed) +3. Focus Step 1 exploration on the modules/components these files belong to +4. Apply ★ prefix on diagram nodes representing new files/components +5. Apply ● prefix on diagram nodes representing modified files/components + +If no `context_path` is provided, skip this step and explore the full CWD in Step 1. + ### Step 1: Launch Parallel Exploration Subagents Spawn Explore subagents to investigate: @@ -145,7 +166,7 @@ Use flowchart with: ### Step 5: Write Output -Write the diagram to: `.autoskillit/temp/arch-lens-security/arch_diag_security_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/arch-lens-security/arch_diag_security_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) After writing the diagram file, emit a structured output line: diff --git a/src/autoskillit/skills_extended/arch-lens-state-lifecycle/SKILL.md b/src/autoskillit/skills_extended/arch-lens-state-lifecycle/SKILL.md index a6e6cbd324..eaed162994 100644 --- a/src/autoskillit/skills_extended/arch-lens-state-lifecycle/SKILL.md +++ b/src/autoskillit/skills_extended/arch-lens-state-lifecycle/SKILL.md @@ -1,6 +1,7 @@ --- name: arch-lens-state-lifecycle categories: [arch-lens] +activate_deps: [mermaid] description: Create State Lifecycle architecture diagram showing field contracts, validation gates, and resume safety. Contract overlay lens answering "How is state corruption prevented?" hooks: PreToolUse: @@ -37,19 +38,39 @@ hooks: - Document validation gates - Include resume detection strategy - BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. - After writing the diagram file, emit the **absolute path** as a structured output - token immediately before `%%ORDER_UP%%`. Resolve the relative `temp/arch-lens-state-lifecycle/...` + token as your final output. Resolve the relative `temp/arch-lens-state-lifecycle/...` save path to absolute by prepending the full CWD: ``` diagram_path = /absolute/cwd/temp/arch-lens-state-lifecycle/{filename}.md - %%ORDER_UP%% ``` This token is MANDATORY — the pipeline cannot proceed without it. +## Arguments + +`/autoskillit:arch-lens-state-lifecycle [context_path]` + +- **context_path** (optional) — Absolute path to a PR context file containing new files + (★-prefixed) and modified files (●-prefixed) from the PR diff. When provided, read + this file before beginning analysis and focus the diagram on the architectural areas + affected by these specific files. When absent, explore the full CWD. + --- ## Analysis Workflow +### Step 0: Read PR context (when provided) + +If a `context_path` positional argument is present: +1. Read the file at `context_path` +2. Extract: new files list (★-prefixed), modified files list (●-prefixed) +3. Focus Step 1 exploration on the modules/components these files belong to +4. Apply ★ prefix on diagram nodes representing new files/components +5. Apply ● prefix on diagram nodes representing modified files/components + +If no `context_path` is provided, skip this step and explore the full CWD in Step 1. + ### Step 1: Launch Parallel Exploration Subagents Spawn Explore subagents to investigate: @@ -137,7 +158,7 @@ Use flowchart with: ### Step 5: Write Output -Write the diagram to: `.autoskillit/temp/arch-lens-state-lifecycle/arch_diag_state_lifecycle_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/arch-lens-state-lifecycle/arch_diag_state_lifecycle_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) After writing the diagram file, emit a structured output line: diff --git a/src/autoskillit/skills_extended/audit-arch/SKILL.md b/src/autoskillit/skills_extended/audit-arch/SKILL.md index 915d8f974e..7c39041ebd 100644 --- a/src/autoskillit/skills_extended/audit-arch/SKILL.md +++ b/src/autoskillit/skills_extended/audit-arch/SKILL.md @@ -27,7 +27,7 @@ Audit the codebase for adherence to architectural standards and rules. **ALWAYS:** - Use subagents for parallel exploration -- Write report to `.autoskillit/temp/audit-arch/arch_audit_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +- Write report to `{{AUTOSKILLIT_TEMP}}/audit-arch/arch_audit_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) - Provide file paths and line numbers - Categorize by severity (CRITICAL, HIGH, MEDIUM, LOW) @@ -263,7 +263,7 @@ These apply across all principles when evaluating architectural decisions: `REVISED – `. These notes are for internal quality control and do not appear in the final report. -7. **Write report** to `.autoskillit/temp/audit-arch/arch_audit_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +7. **Write report** to `{{AUTOSKILLIT_TEMP}}/audit-arch/arch_audit_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) 8. **Output summary** to terminal --- diff --git a/src/autoskillit/skills_extended/audit-bugs/SKILL.md b/src/autoskillit/skills_extended/audit-bugs/SKILL.md index 2016aa1743..f3b1acc3f2 100644 --- a/src/autoskillit/skills_extended/audit-bugs/SKILL.md +++ b/src/autoskillit/skills_extended/audit-bugs/SKILL.md @@ -29,12 +29,12 @@ The user may provide a "since" date (e.g., `2/7`, `2026-02-07`, `last week`). If **NEVER:** - Modify any source code files -- Create files outside `.autoskillit/temp/audit-bugs/` directory +- Create files outside `{{AUTOSKILLIT_TEMP}}/audit-bugs/` directory **ALWAYS:** - Use subagents heavily for parallel log analysis -- All output goes under `.autoskillit/temp/audit-bugs/` (create if needed) -- Final report: `.autoskillit/temp/audit-bugs/bug_pattern_audit_{YYYY-MM-DD_HHMMSS}.md` +- All output goes under `{{AUTOSKILLIT_TEMP}}/audit-bugs/` (create if needed) +- Final report: `{{AUTOSKILLIT_TEMP}}/audit-bugs/bug_pattern_audit_{YYYY-MM-DD_HHMMSS}.md` - Subagents must NOT create their own files - they return findings in their response text only - Do not change any code @@ -76,7 +76,7 @@ Split the matching files into batches of ~5 and dispatch general-purpose subagen - JSONL format: each line is a JSON object - `"type": "human"` entries contain user messages (error reports) - `"type": "assistant"` entries with text content contain investigation findings -- Look for tool calls writing to `.autoskillit/temp/investigate/investigation_*.md` or `.autoskillit/temp/rectify/rectify_*.md` for structured findings +- Look for tool calls writing to `{{AUTOSKILLIT_TEMP}}/investigate/investigation_*.md` or `{{AUTOSKILLIT_TEMP}}/rectify/rectify_*.md` for structured findings - Search for keywords: "root cause", "Root Cause", "fix", "summary", "finding" - Read the first ~500 lines for context, then search for conclusions @@ -94,9 +94,9 @@ After subagents return, group findings into recurring patterns: ### Step 5: Write Report -Ensure `.autoskillit/temp/audit-bugs/` exists (`mkdir -p`). +Ensure `{{AUTOSKILLIT_TEMP}}/audit-bugs/` exists (`mkdir -p`). -Save to: `.autoskillit/temp/audit-bugs/bug_pattern_audit_{YYYY-MM-DD_HHMMSS}.md` +Save to: `{{AUTOSKILLIT_TEMP}}/audit-bugs/bug_pattern_audit_{YYYY-MM-DD_HHMMSS}.md` Structure: ```markdown diff --git a/src/autoskillit/skills_extended/audit-claims/SKILL.md b/src/autoskillit/skills_extended/audit-claims/SKILL.md new file mode 100644 index 0000000000..e931666e27 --- /dev/null +++ b/src/autoskillit/skills_extended/audit-claims/SKILL.md @@ -0,0 +1,378 @@ +--- +name: audit-claims +categories: [research] +description: > + Parallel subagent-driven claim extraction and citation integrity audit for + research PRs. Extracts claims by section, matches against available evidence, + classifies unsupported claims as findings, and emits a verdict for recipe routing. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: audit-claims] Auditing research claims for citation integrity...'" + once: true +--- + +# Audit Claims Skill + +Perform a two-phase citation integrity audit on an open GitHub research PR using +parallel subagents. Phase 1 extracts claims by report section; Phase 2 matches +each claim against available evidence and generates findings. Posts inline review +comments and emits a verdict for recipe routing. + +## Arguments + +`/autoskillit:audit-claims ` + +- **worktree_path** — Absolute path to the research worktree (skill derives + `feature_branch` from `git rev-parse --abbrev-ref HEAD` inside it) +- **base_branch** — The base branch the PR targets (e.g., "main") +- **pr_url** — Explicit PR URL passed by the recipe (avoids re-discovering the PR) + +## When to Use + +- Called by the research recipe orchestrator after `review_research_pr` +- Both read-only gates complete before any resolution step begins +- Can be invoked standalone to audit citation integrity for any open research PR + +## Critical Constraints + +**NEVER:** +- Create files outside `{{AUTOSKILLIT_TEMP}}/audit-claims/` +- Approve a PR that has `changes_requested` findings +- Post review comments when `gh` is unavailable — output `verdict=approved` and exit 0 +- Review files outside the PR diff — scope all audit to diff content only +- Modify any source code +- Run deterministic diff annotation (claim positions are report-level, not line-level) +- Generate findings for `experimental` claims — they are self-evidencing by definition + +**ALWAYS:** +- Use the explicit `pr_url` argument instead of re-discovering via `gh pr list` +- Output `verdict=` on the final line +- Exit 0 in all normal cases; verdict drives recipe routing via on_result, not exit code +- Exit non-zero only for unrecoverable errors (e.g., gh CLI truly unavailable after graceful degradation) +- Use `model: "sonnet"` when spawning all subagents via the Task tool +- Deduplicate findings by (file, line) pairs before posting + +## Workflow + +### Step 0: Validate Arguments + +Parse three positional arguments: `worktree_path`, `base_branch`, `pr_url`. + +Derive `feature_branch`: + +```bash +if [ -d "$worktree_path" ]; then + feature_branch=$(git -C "$worktree_path" rev-parse --abbrev-ref HEAD 2>/dev/null || echo "") +else + echo "Error: worktree_path '$worktree_path' does not exist or is not a directory" >&2 + exit 1 +fi +``` + +If `pr_url` is missing or positional args are insufficient, abort with: +`"Usage: /autoskillit:audit-claims "` + +### Step 0.5 — Code-Index Initialization (required before any code-index tool call) + +Call `set_project_path` with the repo root where this skill was invoked (not a worktree path): + +``` +mcp__code-index__set_project_path(path="{PROJECT_ROOT}") +``` + +Code-index tools require **project-relative paths**. Always use paths like: + + src/mypackage/core/module.py + +NOT absolute paths like: + + /path/to/project/src/mypackage/core/module.py + +Agents launched via `run_skill` inherit no code-index state from the parent session — this +call is mandatory at the start of every headless session that uses code-index tools. + +### Step 1: Use the Explicit PR URL + +Parse `pr_number` from `pr_url` (last path segment). + +Get owner/repo (must run inside the worktree to resolve the correct repository): +```bash +gh repo view --json nameWithOwner -q .nameWithOwner -C "$worktree_path" +``` + +If `gh` is unavailable or not authenticated: +- Log "gh unavailable — skipping citation audit" +- Output `verdict=approved` +- Exit 0 (graceful degradation) + +### Step 2: Get PR Diff + +```bash +mkdir -p {{AUTOSKILLIT_TEMP}}/audit-claims +gh pr diff {pr_number} > {{AUTOSKILLIT_TEMP}}/audit-claims/diff_{pr_number}.txt +``` + +Save the diff to `{{AUTOSKILLIT_TEMP}}/audit-claims/diff_{pr_number}.txt` (relative to the +current working directory). + +Do NOT run deterministic diff annotation — claim positions are report-level, not +line-level. Subagents use section structure, not line markers. + +### Step 3: Two-Phase Claim Analysis + +#### Phase 1 — Claim Extraction (parallel subagents by report section) + +Divide the diff by top-level markdown section: `## Executive Summary`, `## Results`, +`## Methodology`, `## Discussion`, `## Limitations`, and any other top-level `##` section. + +Launch one Task tool subagent (`model: "sonnet"`) per section containing `+` diff lines. +Each subagent returns a JSON array of extracted claims: + +```json +[{ + "file": "research/report.md", + "line": 42, + "claim_text": "Our method reduces latency by 40% compared to baseline X", + "claim_type": "experimental|external|methodological|comparative", + "section": "Results" +}] +``` + +**Claim type guidance:** +- `experimental` — derived from the experiment's own measured data; self-evidencing +- `external` — references domain knowledge, papers, web data, or datasets not in this PR +- `methodological` — asserts that a methodology choice is appropriate or valid +- `comparative` — compares to prior work, published results, or other baselines + +Subagent prompt template: + +> You are extracting factual claims from a section of a GitHub PR diff for a research report. +> Section: [{section_name}] +> Scope: examine only the `+` lines in the diff content provided. +> Return a JSON array of claims. Each claim must have: +> file, line (new-file line number from the diff), claim_text, claim_type +> (one of: experimental, external, methodological, comparative), section. +> +> Claim type guidance: +> - experimental: derived from experiment data in this PR (self-evidencing) +> - external: references external knowledge, papers, or datasets not in this PR +> - methodological: asserts a methodology choice is appropriate or valid +> - comparative: compares to prior work, published results, or baselines +> +> If no claims found in this section, return an empty array []. +> Diff content for section [{section_name}]: +> {section_diff_content} + +Aggregate all extracted claims from all subagents. Save to +`{{AUTOSKILLIT_TEMP}}/audit-claims/claims_{pr_number}.json`. + +#### Phase 2 — Evidence Matching (parallel subagents by claim type) + +Group extracted claims by `claim_type`. Launch one Task tool subagent (`model: "sonnet"`) +per non-empty group. Each subagent receives the claim list and the full PR diff, and +returns findings: + +```json +[{ + "file": "research/report.md", + "line": 42, + "dimension": "external|methodological|comparative", + "severity": "critical|warning|info", + "message": "Claim references [Paper X] but no citation appears in the diff", + "requires_decision": false +}] +``` + +**Evidence rules per claim type:** +- `experimental` — always self-evidencing; no finding generated (skip this group) +- `external` — requires a citation `[N]` or inline reference within the report; absence + of citation is `warning`; absence for a specific numeric comparison is `critical` +- `methodological` — requires a rationale or supporting reference; absence is `warning` +- `comparative` — requires attribution; "comparable to state-of-the-art" without citation + is `critical` + +Subagent prompt template: + +> You are checking citation evidence for [{claim_type}] claims in a GitHub PR diff. +> For each claim, determine whether adequate supporting evidence exists in the diff. +> Return a JSON array of findings for claims that lack evidence. Each finding must have: +> file, line, severity (critical/warning/info), dimension (the claim_type value), +> message, requires_decision (boolean). +> +> Set requires_decision=true ONLY when the correct path forward is genuinely ambiguous +> and cannot be determined without human judgment. +> Set requires_decision=false for all cases with a clear fix (add citation, qualify claim, +> remove claim). +> +> Evidence rules for [{claim_type}]: +> {evidence_rules_for_type} +> +> If all claims have adequate evidence, return an empty array []. +> Claims to check: +> {claims_json} +> Full PR diff: +> {diff_content} + +Save findings to `{{AUTOSKILLIT_TEMP}}/audit-claims/findings_{pr_number}.json`. + +### Step 4: Aggregate and Deduplicate Findings + +1. Collect all Phase 2 subagent JSON responses +2. Deduplicate by `(file, line)` pairs — keep highest severity for each pair +3. Bucket by actionability: + - `actionable_findings` — requires_decision=false AND severity in ("critical", "warning") + - `decision_findings` — requires_decision=true (any severity) + - `info_findings` — severity == "info" AND requires_decision=false + +### Step 4.5: Echo Primary Obligation + +After aggregating all subagent findings, before proceeding to verdict or posting, you MUST state aloud: + +> "I have N findings. My primary job is to post inline comments on specific code lines for each finding. I must use the GitHub Reviews API to leave comments anchored to the exact lines in the diff." + +This is not optional. Do not proceed to Step 5 without stating this. + +### Step 5: Determine Verdict + +```python +decision_findings = [f for f in all_findings if f.get("requires_decision")] +actionable_findings = [ + f for f in all_findings + if not f.get("requires_decision") and f["severity"] in ("critical", "warning") +] + +if actionable_findings: + verdict = "changes_requested" +elif decision_findings: + verdict = "needs_human" +else: + verdict = "approved" +``` + +### Step 6: Post Inline Review Comments + +Build review comment bodies for each critical and warning finding. Use the `line` and +`side` fields (modern GitHub Reviews API — not the deprecated `position` field). + +```bash +COMMENTS_JSON=$(jq -n --argjson findings "$FINDINGS" ' + $findings + | map(select(.line != null and (.line | type) == "number" and .line > 0)) + | map({ + path: .file, + line: .line, + side: "RIGHT", + body: ("[" + .severity + "] " + .dimension + ": " + .message) + }) +') + +jq -n \ + --arg body "AutoSkillit Citation Audit — Verdict: {verdict}" \ + --arg event "{APPROVE|COMMENT|REQUEST_CHANGES}" \ + --argjson comments "$COMMENTS_JSON" \ + '{body: $body, event: $event, comments: $comments}' | \ +gh api /repos/{owner}/{repo}/pulls/{pr_number}/reviews \ + --method POST --input - +``` + +Event mapping: +- `approved` → `APPROVE` +- `needs_human` → `COMMENT` +- `changes_requested` → `REQUEST_CHANGES` + +**Fallback Tier 1 — Individual Comments (if batch POST fails):** + +Track success and failure counts across all individual post attempts: + +```bash +COMMIT_ID=$(gh pr view {pr_number} --json headRefOid -q .headRefOid) +tier1_success=0 +tier1_failed=0 + +# For each finding: +if gh api /repos/{owner}/{repo}/pulls/{pr_number}/comments \ + --method POST \ + --field path="{finding.file}" \ + --field line={finding.line} \ + --field side="RIGHT" \ + --field commit_id="$COMMIT_ID" \ + --field body="[{finding.severity}] {finding.dimension}: {finding.message}"; then + tier1_success=$((tier1_success + 1)) +else + tier1_failed=$((tier1_failed + 1)) + echo "Warning: failed to post individual comment for {finding.file}:{finding.line}" >&2 +fi + +echo "Fallback Tier 1: $tier1_success succeeded, $tier1_failed failed" +``` + +Proceed to Fallback Tier 2 only if `tier1_success == 0` (all individual posts failed). +If at least one post succeeded, skip Tier 2. + +**Fallback Tier 2 — DEGRADED: Bullet-List Summary Dump (if all individual posts fail):** + +Before posting, state: + +> "FALLBACK: I was unable to post inline comments. Posting summary as review body instead. This is a DEGRADED review." + +```bash +gh pr review {pr_number} --comment --body "{summary_markdown}" +``` + +### Step 6.5: Post-Completion Confirmation + +After completing Step 6, you MUST state: + +> "I confirm that I posted N inline comments on the following files: [list files]. If I posted 0 inline comments and had findings, this review has FAILED its primary purpose." + +### Step 7: Submit Summary Review + +```bash +# approved +gh pr review {pr_number} --approve --body "AutoSkillit citation audit passed. No unsupported claims found." + +# changes_requested +gh pr review {pr_number} --request-changes --body "AutoSkillit citation audit found {N} claims lacking evidence. See inline comments." + +# needs_human +gh pr review {pr_number} --comment --body "AutoSkillit citation audit: uncertain citation requirements detected. Please review. See inline comments." +``` + +### Step 8: Write Summary and Emit Verdict + +Save findings summary to `{{AUTOSKILLIT_TEMP}}/audit-claims/summary_{pr_number}_{timestamp}.md`. + +Output the verdict as the final line: + +> **IMPORTANT:** Emit the structured output tokens as **literal plain text with no +> markdown formatting on the token names**. Do not wrap token names in `**bold**`, +> `*italic*`, or any other markdown. The adjudicator performs a regex match on the +> exact token name — decorators cause match failure. + +``` +verdict = {approved|changes_requested|needs_human} +``` + +Exit 0 in all normal cases (approved, needs_human, changes_requested). +Exit 1 only for unrecoverable tool-level errors. + +## Temp File Layout + +``` +{{AUTOSKILLIT_TEMP}}/audit-claims/ +├── diff_{pr_number}.txt +├── claims_{pr_number}.json (Phase 1 output) +├── findings_{pr_number}.json (Phase 2 output) +└── summary_{pr_number}_{ts}.md +``` + +## Output + +- `verdict=approved` — No unsupported claims; citation integrity is clear +- `verdict=changes_requested` — Missing citations or unsupported claims found; recipe routes to resolve step +- `verdict=needs_human` — Ambiguous citation requirements; human review requested + +Summary written to: `{{AUTOSKILLIT_TEMP}}/audit-claims/summary_{pr_number}_{timestamp}.md` diff --git a/src/autoskillit/skills_extended/audit-cohesion/SKILL.md b/src/autoskillit/skills_extended/audit-cohesion/SKILL.md index 43126db0d4..1b779e6822 100644 --- a/src/autoskillit/skills_extended/audit-cohesion/SKILL.md +++ b/src/autoskillit/skills_extended/audit-cohesion/SKILL.md @@ -32,8 +32,8 @@ Audit the codebase for internal cohesion: how well components integrate and main **ALWAYS:** - Use subagents for parallel exploration (one per cohesion dimension) -- All output goes under `.autoskillit/temp/audit-cohesion/` (create if needed) -- Final report: `.autoskillit/temp/audit-cohesion/cohesion_audit_{YYYY-MM-DD_HHMMSS}.md` +- All output goes under `{{AUTOSKILLIT_TEMP}}/audit-cohesion/` (create if needed) +- Final report: `{{AUTOSKILLIT_TEMP}}/audit-cohesion/cohesion_audit_{YYYY-MM-DD_HHMMSS}.md` - Subagents must NOT create their own files — they return findings in their response text only - Score each dimension (STRONG, ADEQUATE, WEAK, FRACTURED) @@ -405,9 +405,9 @@ After all subagents return: ### Step 3: Write Report -Ensure `.autoskillit/temp/audit-cohesion/` exists (`mkdir -p`). +Ensure `{{AUTOSKILLIT_TEMP}}/audit-cohesion/` exists (`mkdir -p`). -Write to `.autoskillit/temp/audit-cohesion/cohesion_audit_{YYYY-MM-DD_HHMMSS}.md`. (relative to the current working directory) +Write to `{{AUTOSKILLIT_TEMP}}/audit-cohesion/cohesion_audit_{YYYY-MM-DD_HHMMSS}.md`. (relative to the current working directory) The report WILL be long. This is expected and correct — thoroughness over brevity. @@ -469,7 +469,7 @@ Do NOT flag: - Generated files (Alembic migrations, PowerSync DDL) - Third-party vendored code - Test fixtures and cached LLM responses -- Temporary/debug files in `.autoskillit/temp/` +- Temporary/debug files in `{{AUTOSKILLIT_TEMP}}/` - Configuration template files in `config/` --- diff --git a/src/autoskillit/skills_extended/audit-defense-standards/SKILL.md b/src/autoskillit/skills_extended/audit-defense-standards/SKILL.md index f7adfc9827..db349c9e93 100644 --- a/src/autoskillit/skills_extended/audit-defense-standards/SKILL.md +++ b/src/autoskillit/skills_extended/audit-defense-standards/SKILL.md @@ -31,8 +31,8 @@ Standards are added here when `/autoskillit:design-guards` recommends them and t **ALWAYS:** - Use subagents for parallel exploration (one per standard or group) -- All output goes under `.autoskillit/temp/audit-defense-standards/` (create if needed) -- Final report: `.autoskillit/temp/audit-defense-standards/defense_audit_{YYYY-MM-DD_HHMMSS}.md` +- All output goes under `{{AUTOSKILLIT_TEMP}}/audit-defense-standards/` (create if needed) +- Final report: `{{AUTOSKILLIT_TEMP}}/audit-defense-standards/defense_audit_{YYYY-MM-DD_HHMMSS}.md` - Subagents must NOT create their own files - they return findings in their response text only - Provide file paths and line numbers for violations - Categorize by severity @@ -121,8 +121,8 @@ Defense standards come from the `/autoskillit:design-guards` pipeline: 1. **Launch parallel subagents** - one per standard or group of related standards 2. **Each subagent:** runs the audit strategy, reports violations with file paths and line numbers 3. **Consolidate findings** by standard and severity -4. Ensure `.autoskillit/temp/audit-defense-standards/` exists (`mkdir -p`) -5. **Write report** to `.autoskillit/temp/audit-defense-standards/defense_audit_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +4. Ensure `{{AUTOSKILLIT_TEMP}}/audit-defense-standards/` exists (`mkdir -p`) +5. **Write report** to `{{AUTOSKILLIT_TEMP}}/audit-defense-standards/defense_audit_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) 6. **Output summary** to terminal: violation count per standard, total by severity ## Report Structure diff --git a/src/autoskillit/skills_extended/audit-friction/SKILL.md b/src/autoskillit/skills_extended/audit-friction/SKILL.md index 96c63f3bea..4b671b5040 100644 --- a/src/autoskillit/skills_extended/audit-friction/SKILL.md +++ b/src/autoskillit/skills_extended/audit-friction/SKILL.md @@ -29,14 +29,14 @@ The user may provide a "since" date (e.g., `2/7`, `2026-02-07`, `last month`). I **NEVER:** - Modify any source code files -- Create files outside `.autoskillit/temp/audit-friction/` directory +- Create files outside `{{AUTOSKILLIT_TEMP}}/audit-friction/` directory - Have subagents write files — they return all findings in response text only - Analyze subagent log subdirectories (`*/subagents/`) — top-level session files only **ALWAYS:** - Use subagents heavily for parallel log analysis -- All output goes under `.autoskillit/temp/audit-friction/` (create if needed) -- Final report: `.autoskillit/temp/audit-friction/friction_audit_{YYYY-MM-DD_HHMMSS}.md` +- All output goes under `{{AUTOSKILLIT_TEMP}}/audit-friction/` (create if needed) +- Final report: `{{AUTOSKILLIT_TEMP}}/audit-friction/friction_audit_{YYYY-MM-DD_HHMMSS}.md` - Report the file and line counts to the terminal before choosing analysis mode ## Friction Categories @@ -173,9 +173,9 @@ After all subagents return: ### Step 6: Write Report -Ensure `.autoskillit/temp/audit-friction/` exists (`mkdir -p`). +Ensure `{{AUTOSKILLIT_TEMP}}/audit-friction/` exists (`mkdir -p`). -Save to: `.autoskillit/temp/audit-friction/friction_audit_{YYYY-MM-DD_HHMMSS}.md` +Save to: `{{AUTOSKILLIT_TEMP}}/audit-friction/friction_audit_{YYYY-MM-DD_HHMMSS}.md` Structure: diff --git a/src/autoskillit/skills_extended/audit-impl/SKILL.md b/src/autoskillit/skills_extended/audit-impl/SKILL.md index 40b1d426c2..0b8cb65d66 100644 --- a/src/autoskillit/skills_extended/audit-impl/SKILL.md +++ b/src/autoskillit/skills_extended/audit-impl/SKILL.md @@ -48,7 +48,7 @@ requirements, scope creep, and unexpected changes. Produces a GO or NO GO verdic **NEVER:** - Modify source files, plan files, or any other files — read-only audit only - Run tests — this skill audits, it does not fix -- Create files outside `.autoskillit/temp/audit-impl/` +- Create files outside `{{AUTOSKILLIT_TEMP}}/audit-impl/` - Emit a GO verdict when any `MISSING` or `CONFLICT` finding exists **ALWAYS:** @@ -57,12 +57,11 @@ requirements, scope creep, and unexpected changes. Produces a GO or NO GO verdic - Resolve all plan files before starting (abort early if any are missing) - Write `Dry-walkthrough verified = TRUE` as the absolute first line of any remediation file - On a NO GO verdict, after writing the remediation file, emit the **absolute path** as a - structured output token immediately before `%%ORDER_UP%%`. Resolve the relative + structured output token as your final output. Resolve the relative `temp/audit-impl/...` save path to absolute by prepending the full CWD: ``` verdict = NO GO remediation_path = /absolute/cwd/temp/audit-impl/{filename}.md - %%ORDER_UP%% ``` On a GO verdict, emit only `verdict = GO` (no remediation_path token). The remediation_path token is MANDATORY on NO GO — the pipeline cannot proceed without it. @@ -113,7 +112,7 @@ store as `conflict_report_path_list`. Proceed even if empty — the cross-refere Step 2.5 is skipped when the list is empty. **Path-existence guard:** Before issuing a `Read` call on a path that is not guaranteed to -exist (e.g., plan file arguments, `.autoskillit/temp/investigate/` reports, external file references), use +exist (e.g., plan file arguments, `{{AUTOSKILLIT_TEMP}}/investigate/` reports, external file references), use `Glob` or `ls` to confirm the path exists first. This prevents ENOENT errors that cascade into sibling parallel-call cancellations. @@ -296,7 +295,7 @@ verdict = GO #### If NO GO -Generate `.autoskillit/temp/audit-impl/remediation_{topic}_{YYYY-MM-DD_HHMMSS}.md`: +Generate `{{AUTOSKILLIT_TEMP}}/audit-impl/remediation_{topic}_{YYYY-MM-DD_HHMMSS}.md`: ```markdown Dry-walkthrough verified = TRUE @@ -376,7 +375,7 @@ NO GO; omit the `remediation_path=` line entirely on GO). ## Output Location ``` -.autoskillit/temp/audit-impl/ +{{AUTOSKILLIT_TEMP}}/audit-impl/ └── remediation_{topic}_{YYYY-MM-DD_HHMMSS}.md (written on NO GO only) ``` diff --git a/src/autoskillit/skills_extended/audit-tests/SKILL.md b/src/autoskillit/skills_extended/audit-tests/SKILL.md index 915718ccdc..4327520603 100644 --- a/src/autoskillit/skills_extended/audit-tests/SKILL.md +++ b/src/autoskillit/skills_extended/audit-tests/SKILL.md @@ -1,7 +1,7 @@ --- name: audit-tests categories: [audit] -description: Audit the test suite for useless tests, consolidation opportunities, over-mocking, weak assertions, and other test quality issues. Use when user says "audit tests", "audit test suite", "review tests", or "test quality check". Generates an improvement plan in .autoskillit/temp/ with explanations for each proposed change. +description: Audit the test suite for useless tests, consolidation opportunities, over-mocking, weak assertions, and other test quality issues. Use when user says "audit tests", "audit test suite", "review tests", or "test quality check". Generates an improvement plan in {{AUTOSKILLIT_TEMP}}/ with explanations for each proposed change. hooks: PreToolUse: - matcher: "*" @@ -33,7 +33,7 @@ Audit the test suite to identify useless tests, consolidation opportunities, qua - Use subagents for parallel exploration - Read both the test AND the code it tests before judging - Provide file paths, line numbers, and an explanation for each finding -- Write the improvement plan to `.autoskillit/temp/audit-tests/test_audit_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +- Write the improvement plan to `{{AUTOSKILLIT_TEMP}}/audit-tests/test_audit_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) - Categorize findings by issue type and severity --- @@ -152,7 +152,7 @@ After subagents complete: ### Step 3: Generate Improvement Plan -Write a structured plan to: `.autoskillit/temp/audit-tests/test_audit_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Write a structured plan to: `{{AUTOSKILLIT_TEMP}}/audit-tests/test_audit_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) Organize the plan into phases grouped by issue type. Each finding must include: - **File path and line range** diff --git a/src/autoskillit/skills_extended/bundle-local-report/SKILL.md b/src/autoskillit/skills_extended/bundle-local-report/SKILL.md new file mode 100644 index 0000000000..25dbddec08 --- /dev/null +++ b/src/autoskillit/skills_extended/bundle-local-report/SKILL.md @@ -0,0 +1,282 @@ +--- +name: bundle-local-report +categories: [rendering] +--- + +# bundle-local-report + +Convert a research markdown report into a self-contained `report.html` with inlined +mermaid diagrams and inserted plot images from `yaml:figure-spec` blocks. + +## Critical Constraints + +**NEVER:** +- Raise a fatal error on missing diagrams or missing visualization-plan — log and continue. +- Use the ESM mermaid build — ESM triggers CORS under `file://`; always use the UMD bundle (`mermaid.min.js`). +- Exit without emitting `html_path = ` (even empty) as your final output — the recipe `capture:` block expects it. + +**ALWAYS:** +- Emit `html_path = {path}` (or `html_path = ` if report_path is absent) as your final output. +- Use `{AUTOSKILLIT_TEMP}` as the base for temp files. +- Using ONLY classDef styles from the mermaid skill (no invented colors). + +## Arguments + +Positional (space-separated, injected by recipe): +1. `research_dir` — absolute path to the research directory +2. `report_path` — absolute path to the markdown report (README.md post-finalize) +3. `all_diagram_paths` — comma-separated list of exp-lens diagram paths (may be empty) +4. `visualization_plan_path` — absolute path to visualization-plan.md (may be empty string) + +Output: `html_path = {absolute_path_to_report.html}` as your final output. + +## Steps + +### Step 0 — Parse arguments + +Capture positional args: +- `$1` → `research_dir` +- `$2` → `report_path` +- `$3` → `all_diagram_paths` (comma-separated, may be empty) +- `$4` → `visualization_plan_path` (may be empty string) + +If `report_path` does not exist, emit `html_path = ` (empty) as your final output immediately +(graceful non-fatal exit — the pipeline continues to begin_archival). + +### Step 1 — Write and execute the embedded renderer + +Write the Python renderer block below to `{AUTOSKILLIT_TEMP}/bundle-local-report-render.py` +in the current working directory (the worktree), then execute it: + +```bash +python3 {AUTOSKILLIT_TEMP}/bundle-local-report-render.py "$1" "$2" "$3" "$4" +``` + +Capture the stdout line `html_path = ...` and emit it as the structured output token +as your final output. + +**ALWAYS** emit `html_path = ` (even empty) as your final output — the recipe `capture:` +block expects it. + +**NEVER** raise a fatal error on missing diagrams or missing visualization-plan — log and +continue. + +**ALWAYS** use the UMD bundle (`mermaid.min.js`), never the ESM build — ESM triggers CORS +under `file://`. + +### Embedded renderer + +```python +# bundle-local-report renderer +#!/usr/bin/env python3 +"""Self-contained HTML renderer for bundle-local-report. + +Args (positional): + 1 research_dir — directory containing README.md + 2 report_path — path to the markdown report + 3 all_diagram_paths — comma-separated diagram paths (may be empty) + 4 visualization_plan_path — path to visualization-plan.md (may be empty) + +Writes: + {research_dir}/report.html + {research_dir}/mermaid.min.js (copied from assets) +""" +import re +import shutil +import sys +from pathlib import Path + +# Validation keywords for mermaid diagrams (mirrors compose-research-pr) +VALIDATION_KEYWORDS = { + "treatment", "outcome", "hypothesis", "H0", "H1", + "IV", "DV", "causal", "confound", "mechanism", + "effect", "comparison", "baseline", "threshold", +} + +HTML_TEMPLATE = """\ + + + + +Research Report + + + + +

    +{mermaid_section} +{body_html} +
    + + + + +""" + + +def _count_keywords(text: str) -> int: + return sum(1 for kw in VALIDATION_KEYWORDS if kw in text) + + +def _extract_mermaid_blocks(text: str) -> list[str]: + """Return list of mermaid diagram source strings from a markdown file.""" + _T3 = chr(96) * 3 + return re.findall(rf"{_T3}mermaid\n(.*?){_T3}", text, re.DOTALL) + + +def _validate_diagram_paths(paths_str: str) -> list[str]: + """Return mermaid source strings for diagrams with ≥2 validation keywords.""" + validated = [] + if not paths_str.strip(): + return validated + for raw in paths_str.split(","): + p = Path(raw.strip()) + if not p.exists(): + continue + content = p.read_text() + if _count_keywords(content) >= 2: + blocks = _extract_mermaid_blocks(content) + validated.extend(blocks) + return validated + + +def _parse_figure_specs(viz_plan_path: str) -> list[dict]: + """Parse yaml:figure-spec blocks from visualization-plan.md.""" + specs = [] + if not viz_plan_path or not Path(viz_plan_path).exists(): + return specs + text = Path(viz_plan_path).read_text() + _T3 = chr(96) * 3 + raw_blocks = re.findall(rf"{_T3}yaml:figure-spec\n(.*?){_T3}", text, re.DOTALL) + for block in raw_blocks: + spec = {} + for line in block.splitlines(): + if ":" in line: + k, _, v = line.partition(":") + spec[k.strip()] = v.strip() + if spec: + specs.append(spec) + return specs + + +def _insert_images(html: str, specs: list[dict]) -> str: + """Insert tags after heading matches for each figure-spec.""" + for spec in specs: + section = spec.get("report_section", "") + title = spec.get("figure_title", "") + img_path = spec.get("image_path", "") + if not section or not img_path: + continue + img_tag = f'{title}' + # Insert after the first heading that contains the section name + pattern = rf"(]*>[^<]*{re.escape(section)}[^<]*)" + html = re.sub(pattern, rf"\1\n{img_tag}", html, count=1, flags=re.IGNORECASE) + return html + + +def _markdown_to_html(md_text: str) -> str: + """Convert markdown to HTML using markdown-it-py.""" + try: + from markdown_it import MarkdownIt # type: ignore[import] + md = MarkdownIt() + # Render standard markdown; mermaid fenced blocks become
    
    +        html = md.render(md_text)
    +        # Convert mermaid code blocks to 
    +        html = re.sub(
    +            r'
    (.*?)
    ', + lambda m: f'
    {m.group(1)}
    ', + html, + flags=re.DOTALL, + ) + return html + except ImportError: + # Fallback: minimal paragraph wrapping (no markdown-it-py installed) + paragraphs = md_text.strip().split("\n\n") + return "".join(f"

    {p.replace(chr(10), ' ')}

    \n" for p in paragraphs) + + +def _find_mermaid_assets() -> tuple[Path | None, str]: + """Locate mermaid.min.js and read the VERSION string.""" + candidates = [ + Path(__file__).parent.parent.parent.parent + / "src" / "autoskillit" / "assets" / "mermaid", + # Walk up to find the assets/ directory relative to any working directory + *[ + p / "src" / "autoskillit" / "assets" / "mermaid" + for p in Path(__file__).parents + if (p / "src" / "autoskillit" / "assets" / "mermaid").exists() + ], + ] + for d in candidates: + js = d / "mermaid.min.js" + ver_file = d / "VERSION" + if js.exists(): + version = ver_file.read_text().strip() if ver_file.exists() else "unknown" + return js, version + return None, "unknown" + + +def main() -> None: + if len(sys.argv) < 3: + print("html_path = ", flush=True) + sys.exit(0) + + research_dir = Path(sys.argv[1]) + report_path = Path(sys.argv[2]) + all_diagram_paths = sys.argv[3] if len(sys.argv) > 3 else "" + viz_plan_path = sys.argv[4] if len(sys.argv) > 4 else "" + + if not report_path.exists(): + print(f"html_path = ", flush=True) + sys.exit(0) + + # 1. Validate and collect mermaid diagram sources + validated_diagrams = _validate_diagram_paths(all_diagram_paths) + + # 2. Build the mermaid section (injected at top of report body) + mermaid_section = "\n".join( + f'
    {src}
    ' for src in validated_diagrams + ) + + # 3. Parse figure specs + specs = _parse_figure_specs(viz_plan_path) + + # 4. Convert report markdown → HTML + md_text = report_path.read_text() + body_html = _markdown_to_html(md_text) + + # 5. Insert figure images at section headings + if specs: + body_html = _insert_images(body_html, specs) + + # 6. Locate mermaid assets + mermaid_js_src, mermaid_version = _find_mermaid_assets() + + # 7. Render full HTML + html = HTML_TEMPLATE.format( + mermaid_version=mermaid_version, + mermaid_section=mermaid_section, + body_html=body_html, + ) + + # 8. Write report.html + out_html = research_dir / "report.html" + out_html.write_text(html, encoding="utf-8") + + # 9. Copy mermaid.min.js as sibling + dest_js = research_dir / "mermaid.min.js" + if mermaid_js_src and mermaid_js_src.exists(): + shutil.copy2(mermaid_js_src, dest_js) + + print(f"html_path = {out_html}", flush=True) + + +if __name__ == "__main__": + main() +``` diff --git a/src/autoskillit/skills_extended/collapse-issues/SKILL.md b/src/autoskillit/skills_extended/collapse-issues/SKILL.md index 130f5494f2..270bc55cd5 100644 --- a/src/autoskillit/skills_extended/collapse-issues/SKILL.md +++ b/src/autoskillit/skills_extended/collapse-issues/SKILL.md @@ -54,12 +54,16 @@ Grouping analysis is performed as in-context LLM reasoning. No parallel sessions - Collapse issues with different `recipe:*` labels into one combined issue - Delegate grouping to parallel sessions — grouping analysis is in-context LLM reasoning only - Use parallel session spawning (Agent/Task) for grouping analysis — it is in-context LLM reasoning -- Create files outside `.autoskillit/temp/collapse-issues/` +- Create files outside `{{AUTOSKILLIT_TEMP}}/collapse-issues/` - Skip emitting the `---collapse-issues-result---` block (emit even on error or no-collapse) - Summarize, paraphrase, truncate, or abbreviate the body of a source issue - Substitute a hyperlink, URL reference, or cross-reference for inlined body content - Use angle-bracket placeholder syntax (`<...>`) in the combined issue body — always paste actual retrieved content from fetch_github_issue - Use the body field from `gh issue list` for body assembly — only fetched_content[N] from per-issue fetch is authoritative +- Use `--body` inline for `gh issue create` when the body contains verbatim multi-issue content — + always write to `{{AUTOSKILLIT_TEMP}}/collapse-issues/combined_body_{timestamp}.md` and use + `--body-file` (the combined body can exceed shell arg limits and the inline form contradicts + the SWITCH TO COPY MODE verbatim guarantee) **ALWAYS:** - Include `--force` on all label creation calls (`gh label create --force`) for idempotency @@ -156,8 +160,6 @@ For each issue in each qualifying group (not standalone issues), call: where `issue_url` is constructed as: https://github.com/{repo}/issues/{number} -Do not output any prose between fetch calls — immediately proceed to the next issue. - Store the returned `content` field from the response. If `fetch_github_issue` returns `success: false` for an issue, log the failure and proceed using the issue title and a note that full body content was unavailable (do not fabricate body content). @@ -190,8 +192,6 @@ Emit result block with `"dry_run": true` and exit without any GitHub mutations: For each qualifying group (in-context LLM reasoning for title synthesis): -Do not emit any prose or status text between groups — immediately proceed to create each combined issue. - **7a. Synthesize title:** Write a title that describes the combined scope of all issues in the group. @@ -199,6 +199,16 @@ Format: `"Combined: "` **7b. Build combined issue body:** +Initialize the temp file: +```bash +ts=$(date +%Y-%m-%d_%H%M%S) +COMBINED_BODY="{{AUTOSKILLIT_TEMP}}/collapse-issues/combined_body_${ts}.md" +mkdir -p "{{AUTOSKILLIT_TEMP}}/collapse-issues" +``` + +Write the verbatim combined body to `${COMBINED_BODY}` using the Write tool (one section at a +time via `>>` append). Write exactly this structure: + ``` @@ -206,7 +216,7 @@ This issue combines related work originally tracked in #N, #M, and #P. ## From #N: {original title of issue N} -{Paste the complete, unmodified text of fetched_content[N].body here exactly +{Write the complete, unmodified text of fetched_content[N].body here exactly as returned by fetch_github_issue. Do not summarize, paraphrase, truncate, or abbreviate any part of the body. Do not substitute a hyperlink, cross-reference, or descriptive sentence. Every heading, list item, code block, and paragraph @@ -220,7 +230,7 @@ generate new prose. Copy only.} ## From #M: {original title of issue M} -{Paste the complete, unmodified text of fetched_content[M].body here exactly +{Write the complete, unmodified text of fetched_content[M].body here exactly as returned by fetch_github_issue. Do not summarize, paraphrase, truncate, or abbreviate any part of the body. Do not substitute a hyperlink, cross-reference, or descriptive sentence. Every heading, list item, code block, and paragraph @@ -234,7 +244,7 @@ generate new prose. Copy only.} ## From #P: {original title of issue P} -{Paste the complete, unmodified text of fetched_content[P].body here exactly +{Write the complete, unmodified text of fetched_content[P].body here exactly as returned by fetch_github_issue. Do not summarize, paraphrase, truncate, or abbreviate any part of the body. Do not substitute a hyperlink, cross-reference, or descriptive sentence. Every heading, list item, code block, and paragraph @@ -264,7 +274,7 @@ Repeat for each unique label in the collected set (e.g., `recipe:remediation`, ` ```bash gh issue create \ --title "Combined: " \ - --body "" \ + --body-file "${COMBINED_BODY}" \ --label "recipe:implementation" \ --label "enhancement" \ [--repo {repo}] @@ -317,7 +327,7 @@ On error, emit: ## Output Location -Dry-run reports (if any): `.autoskillit/temp/collapse-issues/` +Dry-run reports (if any): `{{AUTOSKILLIT_TEMP}}/collapse-issues/` ## Error Handling diff --git a/src/autoskillit/skills_extended/compose-pr/SKILL.md b/src/autoskillit/skills_extended/compose-pr/SKILL.md new file mode 100644 index 0000000000..f30857d1fb --- /dev/null +++ b/src/autoskillit/skills_extended/compose-pr/SKILL.md @@ -0,0 +1,242 @@ +--- +name: compose-pr +categories: [github] +description: > + Reads the PR prep file and validated arch-lens diagrams, composes the PR body, + and creates the GitHub PR. Does NOT invoke sub-skills. Part 3 of 3 in the + decomposed PR flow. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: compose-pr] Composing and opening PR...'" + once: true +--- + +# Compose PR + +Read the PR prep file from `prepare-pr`, validate arch-lens diagrams, compose the PR body, +and create the GitHub PR via `gh pr create`. + +This skill Does NOT invoke any sub-skills or slash commands. It is Part 3 of 3 in the +decomposed PR flow (prepare → run_arch_lenses → compose). + +## Arguments + +`/autoskillit:compose-pr {prep_path} {all_diagram_paths} {work_dir} {base_branch} [closing_issue]` + +- **prep_path** — Absolute path to the PR prep file from `prepare-pr` +- **all_diagram_paths** — Quoted comma-separated absolute paths to diagram `.md` files + (may be empty string if no lenses succeeded) +- **work_dir** — Worktree root (for deriving `feature_branch` via `git rev-parse`) +- **base_branch** — PR target branch +- **closing_issue** (optional) — GitHub issue number for `Closes #N` + +## Critical Constraints + +**NEVER:** +- Invoke any sub-skills or slash commands +- Fail the pipeline if `gh` is unavailable — emit `pr_url = ` (empty) and exit successfully +- Create files outside `{{AUTOSKILLIT_TEMP}}/compose-pr/` +- Invent mermaid classDef colors — when embedding validated diagrams, include them verbatim. + Using ONLY classDef styles from the mermaid skill (no invented colors). + +**ALWAYS:** +- Check `gh auth status` before attempting GitHub operations +- Emit `pr_url` token (empty string when GitHub unavailable) +- Validate diagrams with ★ or ● markers before including them +- Degrade gracefully when `all_diagram_paths` is empty or all diagrams fail validation + (omit Architecture Impact section; do not include a placeholder) +- Handle `no diagrams` case: when `all_diagram_paths is empty` or every path fails + marker check, set `validated_diagrams = []` and omit the Architecture Impact section + +## Context Limit Behavior + +When context is exhausted mid-execution, temp files may be written but the PR may +not yet be created. The recipe routes to `on_context_limit` (typically +`release_issue_failure`), bypassing the normal completion protocol. + +**Before emitting structured output tokens:** +1. Emit `pr_url = ` (empty) if the PR was not successfully created +2. Emit whatever was completed; the orchestrator will handle the context-limit route + +## Workflow + +### Step 0: Parse Arguments and Initialize + +Parse positional arguments: +- arg[1] = `prep_path` +- arg[2] = `all_diagram_paths` (may be empty string) +- arg[3] = `work_dir` +- arg[4] = `base_branch` +- arg[5] = `closing_issue` (optional — overrides value in prep file if set) + +Derive `feature_branch` and set shell variables: +```bash +FEATURE_BRANCH=$(git -C $WORK_DIR rev-parse --abbrev-ref HEAD) +BASE_BRANCH=$4 +``` + +Create temp dir (relative to the current working directory): +```bash +mkdir -p {{AUTOSKILLIT_TEMP}}/compose-pr/ +ts=$(date +%Y-%m-%d_%H%M%S) +``` +Timestamp `ts` is assigned in the bash block above. + +### Step 1: Read PR Prep File + +Read the file at `prep_path`. Extract: +- `task_title` (from `## Title` section) +- Plan summaries (from `## Plan Summary` — detect single vs multi-plan by presence of group headings) +- `requirements_section` (from `## Requirements` — empty if section is blank) +- `conflict_resolution_table` (from `## Conflict Resolution Table` — empty if section is blank) +- `new_files` (from `## Changed Files > ### New (★):`) +- `modified_files` (from `## Changed Files > ### Modified (●):`) +- `feature_branch` from `## Metadata` (use the git-derived value from Step 0 if set) +- `closing_issue` from `## Metadata` (overridden by arg[5] if arg[5] is non-empty) + +### Step 2: Read and Validate Diagrams + +Split `all_diagram_paths` by comma; trim whitespace from each path. + +For each path: +1. Read the file +2. Extract mermaid block(s) +3. Check for `★` or `●` character in the mermaid block + - If found → add to `validated_diagrams` + - If not found → discard silently + +If `all_diagram_paths` is empty or all diagrams fail → `validated_diagrams = []`. + +### Step 3: Compose PR Body + +Write PR body to `{{AUTOSKILLIT_TEMP}}/compose-pr/pr_body_$ts.md` (using the `ts` variable from Step 0). + +#### Single plan format: + +```markdown +## Summary + +{First paragraph of the plan's ## Summary section, or first 5 lines after the heading} + +{If requirements_section is non-empty:} +## Requirements + +{requirements_section} + +{If conflict_resolution_table is non-empty:} +## Conflict Resolution Decisions + +The following files had merge conflicts that were automatically resolved. + +{conflict_resolution_table} + +{## Architecture Impact — include ONLY if validated_diagrams is non-empty:} +## Architecture Impact + +### {Lens Name} Diagram + +```mermaid +{diagram content} +``` + +{If closing_issue is non-empty:} +Closes #{closing_issue} + +## Implementation Plan + +Plan file: `{plan_path}` + +🤖 Generated with [Claude Code](https://claude.com/claude-code) via AutoSkillit +``` + +#### Multiple plans format: + +```markdown +## Summary + +{Synthesized overall summary — 2-3 sentences. Spawn a sonnet subagent if needed.} + +
    +Individual Group Plans + +### Group 1: {heading from plan 1} +{Summary from plan 1} + +### Group 2: {heading from plan 2} +{Summary from plan 2} + +
    + +{If requirements_section is non-empty:} +## Requirements + +{requirements_section} + +{If conflict_resolution_table is non-empty:} +## Conflict Resolution Decisions + +The following files had merge conflicts that were automatically resolved. + +{conflict_resolution_table} + +{## Architecture Impact — include ONLY if validated_diagrams is non-empty:} +## Architecture Impact + +### {Lens Name} Diagram + +```mermaid +{diagram content} +``` + +{If closing_issue is non-empty:} +Closes #{closing_issue} + +## Implementation Plan + +Plan files: +- `{plan_path_1}` +- `{plan_path_2}` + +🤖 Generated with [Claude Code](https://claude.com/claude-code) via AutoSkillit +``` + +### Step 4: Check GitHub Availability + +Run: +```bash +gh auth status 2>/dev/null +``` + +If exit code is non-zero: +- Log: "GitHub CLI not available or not authenticated — skipping PR creation" +- Output: `pr_url = ` (empty) +- Exit successfully + +### Step 5: Create Pull Request + +```bash +gh pr create \ + --base $BASE_BRANCH \ + --head $FEATURE_BRANCH \ + --title "$TASK_TITLE" \ + --body-file {{AUTOSKILLIT_TEMP}}/compose-pr/pr_body_$ts.md +``` + +Capture PR URL from stdout. + +## Output + +Emit these structured output tokens (literal plain text, no markdown decoration): + +On success: +``` +pr_url = https://github.com/owner/repo/pull/N +``` + +On graceful degradation (no `gh` or not authenticated): +``` +pr_url = +``` diff --git a/src/autoskillit/skills_extended/compose-research-pr/SKILL.md b/src/autoskillit/skills_extended/compose-research-pr/SKILL.md new file mode 100644 index 0000000000..4a21449b44 --- /dev/null +++ b/src/autoskillit/skills_extended/compose-research-pr/SKILL.md @@ -0,0 +1,194 @@ +--- +name: compose-research-pr +categories: [research] +description: > + Reads a PR prep file and validated experiment diagrams, composes the PR body, + and creates the GitHub PR. Part 3 of 3 in the decomposed research-PR flow. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: compose-research-pr] Composing and opening research PR...'" + once: true +--- + +# Compose Research PR + +Reads the PR prep file produced by `prepare-research-pr`, validates experiment design +diagrams, composes a structured PR body, and creates the GitHub PR using `gh pr create`. +Does NOT invoke lens skills or other sub-skills. + +## Arguments + +`/autoskillit:compose-research-pr {prep_path} {all_diagram_paths} {worktree_path} {base_branch} [closing_issue]` + +- **prep_path** — Absolute path to the PR prep file from `prepare-research-pr` +- **all_diagram_paths** — Quoted comma-separated absolute paths to diagram `.md` files + (may be empty string if no lenses succeeded) +- **worktree_path** — Worktree root directory (derives `feature_branch`) +- **base_branch** — PR target branch +- **closing_issue** (optional) — GitHub issue number for auto-close on merge + +## Critical Constraints + +**NEVER:** +- Invoke any sub-skills or slash commands during execution +- Auto-merge or approve the PR — research PRs are for human review only +- Fail the pipeline if `gh` is unavailable — emit `pr_url = ` (empty string) and exit 0 +- Create files outside `{{AUTOSKILLIT_TEMP}}/compose-research-pr/` (relative to the current working directory) +- Invent mermaid classDef colors — when embedding validated diagrams, include them verbatim. + Using ONLY classDef styles from the mermaid skill when composing the PR body. + +**ALWAYS:** +- Check `gh auth status` before attempting GitHub operations +- Emit `pr_url` token as your final output (even if empty) +- Use Agent subagents to read the prep file + +## Diagram Validation Keywords + +A diagram passes validation if its content contains 2 or more of: +`treatment`, `outcome`, `hypothesis`, `H0`, `H1`, `IV`, `DV`, `causal`, `confound`, +`mechanism`, `effect`, `comparison`, `baseline`, `threshold` + +--- + +## Workflow + +### Step 0: Parse arguments and setup + +Parse positional args: +- arg[1] = prep_path +- arg[2] = all_diagram_paths (comma-separated, may be empty) +- arg[3] = worktree_path +- arg[4] = base_branch +- arg[5] = closing_issue (optional) + +Derive `feature_branch`: + + FEATURE_BRANCH=$(git -C "{worktree_path}" rev-parse --abbrev-ref HEAD) + +Create temp directory: + + mkdir -p {{AUTOSKILLIT_TEMP}}/compose-research-pr/ + +Generate a timestamp `ts` for unique file naming. + +### Step 1: Read prep file via Agent subagent + +Spawn an **Explore** subagent to read `{prep_path}` and extract: +- `report_path` (from Metadata section) +- `experiment_plan_path` (from Metadata section) +- `feature_branch` (from Metadata section) +- `base_branch` (from Metadata section) +- `experiment_type` +- `status_badge` +- `recommendation` (Recommendation section) +- `results_summary` (Results Summary section) +- Hypothesis table (H0, H1) +- Metrics table +- `methodology` (Methodology section) +- Report title (from `# PR Prep: {title}` heading) +- `selected_lenses` (Selected Lenses section) + +### Step 2: Read and validate diagrams + +Split `all_diagram_paths` by comma; trim whitespace from each path. +For each path: +1. Skip if the path is empty or the file does not exist +2. Read the file content +3. Count how many validation keywords appear: `treatment`, `outcome`, `hypothesis`, + `H0`, `H1`, `IV`, `DV`, `causal`, `confound`, `mechanism`, `effect`, `comparison`, + `baseline`, `threshold` +4. If count >= 2, add the mermaid block(s) from the file to `validated_diagrams` +5. Otherwise, discard silently + +If `all_diagram_paths` is empty or all diagrams fail validation, set `validated_diagrams = []` +and continue (the Experiment Design section will be omitted). + +### Step 3: Compose PR body + +Write to `{{AUTOSKILLIT_TEMP}}/compose-research-pr/pr_body_{ts}.md`: + +```markdown +## Recommendation + +{recommendation} + +## Experiment Design + +{if validated_diagrams non-empty: include each mermaid block with a caption; omit this section otherwise} + +| Hypothesis | | +|---|---| +| H0 | {H0} | +| H1 | {H1} | + +| Metric | Unit | Threshold | +|--------|------|-----------| +{metrics rows} + +## Key Results + +{status_badge} + +{results_summary} + +## Methodology + +{methodology} + +## What We Learned + +{from results_summary or prep file if a "What We Learned" section exists} + +## Full Report & Artifacts + +- Report: `{report_path relative to repo root}` +- Experiment plan: `{experiment_plan_path relative to repo root}` + +{if closing_issue is set} +Closes #{closing_issue} +{/if} + +🤖 Generated with [Claude Code](https://claude.com/claude-code) via AutoSkillit +``` + +Store the body file path as `pr_body_path`. + +### Step 4: Check GitHub availability + +```bash +gh auth status 2>/dev/null +``` + +If **not available or not authenticated**: emit `pr_url = ` (empty) then stop. + +### Step 5: Create PR + +```bash +gh pr create \ + --base "{base_branch}" \ + --head "{feature_branch}" \ + --title "Research: {title}" \ + --body-file "{pr_body_path}" +``` + +Capture the PR URL from the output. + +--- + +## Output + +Emit these tokens as **literal plain text** (no markdown formatting on the token names) +as your final output: + +``` +pr_url = https://github.com/owner/repo/pull/N +``` + +Where `pr_url` is the absolute GitHub PR URL, or an empty string if GitHub is unavailable: + +``` +pr_url = +``` diff --git a/src/autoskillit/skills_extended/design-guards/SKILL.md b/src/autoskillit/skills_extended/design-guards/SKILL.md index 3926630a31..fe31aa1176 100644 --- a/src/autoskillit/skills_extended/design-guards/SKILL.md +++ b/src/autoskillit/skills_extended/design-guards/SKILL.md @@ -22,21 +22,21 @@ Take a bug pattern audit report and design architectural guards that make each p ## Arguments -Path to a bug pattern audit report (typically under `.autoskillit/temp/audit-bugs/`). If not specified, use the most recent `.autoskillit/temp/audit-bugs/bug_pattern_audit_*.md`. +Path to a bug pattern audit report (typically under `{{AUTOSKILLIT_TEMP}}/audit-bugs/`). If not specified, use the most recent `{{AUTOSKILLIT_TEMP}}/audit-bugs/bug_pattern_audit_*.md`. ## Critical Constraints **NEVER:** - Modify any source code files - Propose bandaid fixes or direct-only patches -- Create files outside `.autoskillit/temp/design-guards/` directory +- Create files outside `{{AUTOSKILLIT_TEMP}}/design-guards/` directory **ALWAYS:** - Use subagents for parallel codebase exploration - Focus on structural immunity over one-off fixes - Each guard must be concrete and testable -- All output goes under `.autoskillit/temp/design-guards/` (create if needed) -- Final report: `.autoskillit/temp/design-guards/defense_guards_{YYYY-MM-DD_HHMMSS}.md` +- All output goes under `{{AUTOSKILLIT_TEMP}}/design-guards/` (create if needed) +- Final report: `{{AUTOSKILLIT_TEMP}}/design-guards/defense_guards_{YYYY-MM-DD_HHMMSS}.md` - Subagents must NOT create their own files - they return findings in their response text only - Do not change any code @@ -82,9 +82,9 @@ Prioritize guards by: ### Step 4: Write Report -Ensure `.autoskillit/temp/design-guards/` exists (`mkdir -p`). +Ensure `{{AUTOSKILLIT_TEMP}}/design-guards/` exists (`mkdir -p`). -Save to: `.autoskillit/temp/design-guards/defense_guards_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Save to: `{{AUTOSKILLIT_TEMP}}/design-guards/defense_guards_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) ```markdown # Defense Guards: {Report Title} diff --git a/src/autoskillit/skills_extended/diagnose-ci/SKILL.md b/src/autoskillit/skills_extended/diagnose-ci/SKILL.md index 97c6db0ec8..9ef557cb9f 100644 --- a/src/autoskillit/skills_extended/diagnose-ci/SKILL.md +++ b/src/autoskillit/skills_extended/diagnose-ci/SKILL.md @@ -13,13 +13,13 @@ hooks: # diagnose-ci Skill Fetch CI logs for a failing branch, classify the failure type, and write a structured -diagnosis report to `.autoskillit/temp/diagnose-ci/`. Called by the orchestrator on `ci_watch` failure +diagnosis report to `{{AUTOSKILLIT_TEMP}}/diagnose-ci/`. Called by the orchestrator on `ci_watch` failure before routing to `resolve-failures`. ## Invocation ``` -/autoskillit:diagnose-ci {branch} [run_id] [ci_failed_jobs] [workflow] +/autoskillit:diagnose-ci {branch} [run_id] [ci_failed_jobs] [workflow] [event] ``` **Positional args:** @@ -27,19 +27,31 @@ before routing to `resolve-failures`. - `run_id` (optional) — specific workflow run ID; if absent, discover from `gh run list` - `ci_failed_jobs` (optional) — JSON array of failed job names from `wait_for_ci`, used to scope log fetching - `workflow` (optional) — workflow filename (e.g. `tests.yml`); if provided, scopes `gh run list` to that workflow only; use `-` to skip +- `event` (optional) — GitHub Actions trigger event (e.g. `push`, `pull_request`); if provided, scopes `gh run list` to that event only; use `-` to skip ## Critical Constraints **NEVER:** - Modify any source code files - Run the test suite -- Write files outside `.autoskillit/temp/diagnose-ci/` +- Write files outside `{{AUTOSKILLIT_TEMP}}/diagnose-ci/` - Block on missing `gh` CLI — write a minimal `failure_type=unknown` diagnosis instead **ALWAYS:** - Initialize code-index: call `set_project_path` to current cwd before any search - Write the diagnosis file before emitting output tokens -- Emit the three output tokens (`diagnosis_path`, `failure_type`, `is_fixable`) at the end of the response on their own lines +- Emit the four output tokens (`diagnosis_path`, `failure_type`, `failure_subtype`, `is_fixable`) at the end of the response on their own lines + +## Context Limit Behavior + +When context is exhausted mid-execution, the diagnosis file may be partially written +or absent. The recipe routes to `on_context_limit: resolve_ci`, which proceeds +best-effort with whatever diagnosis was written (or none). + +**Before emitting structured output tokens:** +1. If the diagnosis file was not fully written, emit `diagnosis_path = ` (empty) +2. Emit `failure_type = unknown`, `failure_subtype = unknown`, `is_fixable = false` + as fallback values when analysis was interrupted ## Workflow @@ -51,14 +63,25 @@ mcp__code-index__set_project_path(path=) ### Step 2: Discover Run ID (if not provided) -If `run_id` is not provided as an argument (or is `-`): +If `run_id` is not provided as an argument (or is `-`), construct the `gh run list` command +with any provided filters: + ```bash +# Base command (always used): gh run list --branch {branch} --limit 1 --json databaseId,status,conclusion + +# If workflow is provided and is not `-`, add: + --workflow {workflow} + +# If event is provided and is not `-`, add: + --event {event} ``` -If `workflow` is provided and is not `-`: + +Example with both filters: ```bash -gh run list --branch {branch} --workflow {workflow} --limit 1 --json databaseId,status,conclusion +gh run list --branch {branch} --workflow {workflow} --event {event} --limit 1 --json databaseId,status,conclusion ``` + Parse the JSON to extract `databaseId` as `run_id`. If `gh` is unavailable or the command fails, skip to Step 5 (write minimal diagnosis). @@ -93,22 +116,54 @@ Analyze the log output to classify `failure_type` as one of: - `env` — missing environment variables, secrets, or infrastructure issues - `unknown` — cannot determine from logs +#### Step 5a: Subtype Classification + +After determining `failure_type`, classify `failure_subtype` using the following error-pattern decision tree (first match wins): + +| Pattern match in log output | `failure_subtype` | +|---|---| +| `TimeoutError`, `deadline exceeded`, `flake`, `intermittent` | `timing_race` | +| `pytest.*FLAKY`, `rerun`, three-or-more identical test runs | `flaky` | +| `ImportError`, `ModuleNotFoundError` | `import` | +| `fixture`, `pytest.fixture`, collection error | `fixture` | +| `environ`, missing `ENV_VAR`, `KeyError.*environ` | `env` | +| Assertion error with stable stack trace (same file/line across runs) | `deterministic` | +| No pattern matched | `unknown` | + +**Guidance for `resolve-failures`:** Include a supplementary "Suggested Starting Verdict" field in the +Recommended Fix Approach section that maps the subtype to an initial verdict for `resolve-failures` to +consider (not authoritative — `resolve-failures` makes its own verdict decision from the subtype + +local test result): + +| `failure_subtype` | Suggested starting verdict | +|---|---| +| `flaky` or `timing_race` | `flake_suspected` | +| `deterministic` | `ci_only_failure` (if local tests pass) or `real_fix` (if fixable locally) | +| `fixture` or `import` | `ci_only_failure` (if local tests pass) | +| `env` | `ci_only_failure` (conservative) | +| `unknown` | `ci_only_failure` (conservative) | + Determine `is_fixable`: - `true` for `test`, `lint`, `build`, `type_check` - `false` for `env`, `unknown` ### Step 6: Write Diagnosis Report -Create directory `.autoskillit/temp/diagnose-ci/` if it doesn't exist. Write the diagnosis file: +Create directory `{{AUTOSKILLIT_TEMP}}/diagnose-ci/` if it doesn't exist. Write the diagnosis file: ```markdown # CI Diagnosis: {branch} **Run ID:** {run_id} **Failure Type:** {failure_type} +**Failure Subtype:** {failure_subtype} **Is Fixable:** {is_fixable} **Branch:** {branch} +## Structured Output (machine-readable) + +failure_subtype = {failure_subtype} + ## Log Excerpt ``` @@ -118,9 +173,11 @@ Create directory `.autoskillit/temp/diagnose-ci/` if it doesn't exist. Write the ## Recommended Fix Approach {1-3 sentences describing how resolve-failures should approach this} + +**Suggested Starting Verdict:** {suggested starting verdict from the subtype table above} ``` -Save to `.autoskillit/temp/diagnose-ci/diagnosis_{timestamp}.md`. (relative to the current working directory) +Save to `{{AUTOSKILLIT_TEMP}}/diagnose-ci/diagnosis_{timestamp}.md`. (relative to the current working directory) ### Step 7: Emit Output Tokens @@ -132,16 +189,18 @@ Emit these tokens on their own lines at the end of your response: > exact token name — decorators cause match failure. ``` -diagnosis_path = /absolute/path/to/.autoskillit/temp/diagnose-ci/diagnosis_{timestamp}.md +diagnosis_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/diagnose-ci/diagnosis_{timestamp}.md failure_type = test|lint|build|type_check|env|unknown +failure_subtype = flaky|timing_race|deterministic|fixture|import|env|unknown is_fixable = true|false ``` ## gh Unavailable Fallback If `gh` is unavailable at any step, write a minimal diagnosis: -- `failure_type=unknown` -- `is_fixable=false` +- `failure_type = unknown` +- `failure_subtype = unknown` +- `is_fixable = false` - Diagnosis body: "gh CLI unavailable — logs could not be fetched. Manual inspection required." Then emit the output tokens and exit. \ No newline at end of file diff --git a/src/autoskillit/skills_extended/dry-walkthrough/SKILL.md b/src/autoskillit/skills_extended/dry-walkthrough/SKILL.md index 6d50773002..f31b025e1e 100644 --- a/src/autoskillit/skills_extended/dry-walkthrough/SKILL.md +++ b/src/autoskillit/skills_extended/dry-walkthrough/SKILL.md @@ -29,7 +29,7 @@ The plan file must remain a **clean, self-contained implementation instruction s ## Arguments -`{plan_path}` — Absolute path to the plan file to validate (optional: falls back to most recent .autoskillit/temp/ artifact if omitted) +`{plan_path}` — Absolute path to the plan file to validate (optional: falls back to most recent {{AUTOSKILLIT_TEMP}}/ artifact if omitted) ## Critical Constraints @@ -56,6 +56,15 @@ The plan file must remain a **clean, self-contained implementation instruction s - Make sure the plan includes warning against using the codebase as a notepad with useless comments - Prefer the long term health of project over quick, easy, and minimal fixes +## Context Limit Behavior + +When context is exhausted mid-execution, plan file edits may be partially applied. +The recipe routes to `on_context_limit` (typically `register_clone_failure` or a +restart step), abandoning the partial walkthrough. + +This skill modifies only the plan file (not source code), so partial edits have +limited blast radius. The downstream step will restart the walkthrough on retry. + ## Dry Walkthrough Workflow ### Step 1: Load the Plan @@ -63,7 +72,7 @@ The plan file must remain a **clean, self-contained implementation instruction s Read the plan from: - Path provided by user - Plan content pasted directly -- Most recent plan in .autoskillit/temp/ subdirectories +- Most recent plan in {{AUTOSKILLIT_TEMP}}/ subdirectories ### Multi-Part Plan Detection @@ -72,7 +81,7 @@ After resolving the plan path, check whether this is a part file of a multi-part 1. **Detect the part suffix:** If the plan filename contains `_part_` (e.g., `_part_a`, `_part_b`, `_part_1`), this is one part of a multi-part plan. Extract the part identifier (A, B, C… or number) from the suffix. 2. **⚠️ SCOPE BOUNDARY — CRITICAL:** If a part suffix is detected, immediately output to the terminal: - > "⚠️ MULTI-PART PLAN DETECTED: Validating PART {X} ONLY. This session MUST NOT read, open, reference, or validate any other part files. Sibling part files visible in .autoskillit/temp/ or any other directory are entirely out of scope and must be ignored." + > "⚠️ MULTI-PART PLAN DETECTED: Validating PART {X} ONLY. This session MUST NOT read, open, reference, or validate any other part files. Sibling part files visible in {{AUTOSKILLIT_TEMP}}/ or any other directory are entirely out of scope and must be ignored." 3. **Verify the scope warning block:** Check that the plan file contains the mandatory scope warning block immediately after the title line. The block must match this form: ``` @@ -237,7 +246,7 @@ After updating the plan, output a summary to the terminal (your response text): ## Example -**Input:** User says "dry walkthrough .autoskillit/temp/make-plan/api_retry_plan.md" +**Input:** User says "dry walkthrough {{AUTOSKILLIT_TEMP}}/make-plan/api_retry_plan.md" **Process:** 1. Read the plan @@ -251,7 +260,7 @@ After updating the plan, output a summary to the terminal (your response text): ``` ## Dry Walkthrough Complete -**Plan:** .autoskillit/temp/make-plan/api_retry_plan.md +**Plan:** {{AUTOSKILLIT_TEMP}}/make-plan/api_retry_plan.md **Status:** REVISED ### Changes Made diff --git a/src/autoskillit/skills_extended/elaborate-phase/SKILL.md b/src/autoskillit/skills_extended/elaborate-phase/SKILL.md index 0d0a6a5133..1a943e6df4 100644 --- a/src/autoskillit/skills_extended/elaborate-phase/SKILL.md +++ b/src/autoskillit/skills_extended/elaborate-phase/SKILL.md @@ -1,5 +1,6 @@ --- name: elaborate-phase +activate_deps: [dry-walkthrough] description: Elaborate a migration plan phase into a complete self-contained implementation plan. Use when user says "elaborate phase", "elaborate phase N", or "phase elaboration". Assesses codebase, writes detailed phase plan, then validates with dry walkthrough. hooks: PreToolUse: diff --git a/src/autoskillit/skills_extended/enrich-issues/SKILL.md b/src/autoskillit/skills_extended/enrich-issues/SKILL.md index 510b6af9f2..749c60ec15 100644 --- a/src/autoskillit/skills_extended/enrich-issues/SKILL.md +++ b/src/autoskillit/skills_extended/enrich-issues/SKILL.md @@ -177,11 +177,19 @@ The API layer exposes skill execution to MCP clients through the headless execut **not** call `gh issue edit`. Set `dry_run: true` in the result. - Otherwise: append the section to the original issue body: ```bash - gh issue edit N --body "$(gh issue view N --json body -q .body) + ts=$(date +%Y-%m-%d_%H%M%S) + EDIT_BODY_FILE="{{AUTOSKILLIT_TEMP}}/enrich-issues/edit_body_${ts}.md" + REQUIREMENTS_FILE="${EDIT_BODY_FILE%.md}_req.md" + mkdir -p "{{AUTOSKILLIT_TEMP}}/enrich-issues" -## Requirements + # Fetch current body immediately before editing (avoids shell interpolation): + gh issue view N --json body -q .body > "${EDIT_BODY_FILE}" + + # Populate ${REQUIREMENTS_FILE} with generated requirements, then: + printf '\n\n## Requirements\n\n' >> "${EDIT_BODY_FILE}" + cat "${REQUIREMENTS_FILE}" >> "${EDIT_BODY_FILE}" -$(generated_requirements_section)" + gh issue edit N --body-file "${EDIT_BODY_FILE}" ``` Always fetch the current body immediately before editing to avoid overwriting @@ -212,6 +220,8 @@ After processing all candidates, emit to stdout: - Apply `## Requirements` to an issue that already has one (idempotency) - Skip the result block — always emit it, even on dry-run or when all issues were skipped +- Use `--body` shell substitution (`--body "$(...)`) for `gh issue edit` — always write to + `{{AUTOSKILLIT_TEMP}}/enrich-issues/edit_body_{timestamp}.md` and use `--body-file` **ALWAYS:** - Respect `--dry-run`: never call `gh issue edit` when this flag is set diff --git a/src/autoskillit/skills_extended/exp-lens-benchmark-representativeness/SKILL.md b/src/autoskillit/skills_extended/exp-lens-benchmark-representativeness/SKILL.md new file mode 100644 index 0000000000..f9e3ae6cde --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-benchmark-representativeness/SKILL.md @@ -0,0 +1,272 @@ +--- +name: exp-lens-benchmark-representativeness +categories: [exp-lens] +activate_deps: [mermaid] +description: Create Benchmark Representativeness experimental design diagram showing coverage matrix, generalization gaps, and untested regions. Generalizability lens answering "Does this generalize beyond the test bed?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Benchmark Representativeness Lens - Analyzing generalization coverage...'" + once: true +--- + +# Benchmark Representativeness Experimental Design Lens + +**Philosophical Mode:** Generalizability +**Primary Question:** "Does this generalize beyond the test bed?" +**Focus:** Task Distribution, Scenario Coverage, Missing Regions, Dataset Selection, Generalization Claims + +## Arguments + +`/autoskillit:exp-lens-benchmark-representativeness [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Evaluating claims that extend beyond specific benchmarks +- Checking coverage of evaluation suite +- Assessing dataset diversity +- User invokes `/autoskillit:exp-lens-benchmark-representativeness` or `/autoskillit:make-experiment-diag benchmark` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-benchmark-representativeness/` + +**ALWAYS:** +- Focus on GENERALIZATION GAP between benchmark coverage and claimed scope +- Show which regions of the target space are untested +- Document the relationship between benchmark selection and generalization claims +- Include a coverage matrix mapping scenarios to metrics +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-benchmark-representativeness/exp_diag_benchmark_representativeness_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-benchmark-representativeness/exp_diag_benchmark_representativeness_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Benchmark & Dataset Inventory** +- Find all datasets, benchmarks, test suites used +- Look for: `benchmark`, `dataset`, `test_suite`, `eval`, `corpus`, `split`, `GLUE`, `ImageNet` + +**Task & Scenario Coverage** +- Find what scenarios, conditions, and domains are tested +- Look for: `task`, `scenario`, `domain`, `category`, `difficulty`, `subset` + +**Metric Coverage** +- Find all evaluation metrics used +- Look for: `metric`, `accuracy`, `f1`, `bleu`, `rouge`, `latency`, `cost`, `fairness` + +**Claimed Generalization Scope** +- Find claims about generality in docs, papers, READMEs +- Look for: `generalize`, `real-world`, `production`, `deploy`, `robust`, `transfer`, `domain` + +**Distribution Characteristics** +- Find data distribution analysis, class balance, domain stats +- Look for: `distribution`, `balance`, `skew`, `size`, `demographics`, `diversity` + +### Step 2: Build the Coverage Matrix + +Build the coverage matrix: rows = scenarios/domains tested, columns = metrics measured. Identify which cells are populated and which are gaps. Compare the coverage to the stated generalization claims. + +### Step 3: CRITICAL — Analyze Generalization Gap + +For every generalization claim: +- **Target population**: What is the full population the claim extends to? +- **Benchmark representation**: What subset of that population is represented in the benchmark? +- **Untested regions**: What regions of the space are untested? +- **Coverage ratio**: Is the coverage sufficient to support the claim? + +Distinguish clearly: +- **Strong claims** (e.g., "production-ready"): require broad, diverse coverage +- **Scoped claims** (e.g., "best on GLUE"): only require benchmark-specific coverage +- **Implicit claims**: claims made in framing but not stated explicitly + +### Step 4: Create the Diagram + +Use flowchart with: + +**Direction:** `TB` (claims flow from benchmarks up to generalization) + +**Subgraphs:** +- `BENCHMARKS USED` +- `SCENARIOS TESTED` +- `METRICS MEASURED` +- `GENERALIZATION CLAIMS` +- `UNTESTED REGIONS` + +**Node Styling:** +- `stateNode` class: benchmarks/datasets +- `handler` class: tested scenarios +- `output` class: measured metrics +- `cli` class: generalization claims +- `gap` class: untested regions/missing coverage +- `detector` class: validation of generalization + +### Step 5: Write Output + +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/exp-lens-benchmark-representativeness/exp_diag_benchmark_representativeness_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Output Template + +```markdown +# Benchmark Representativeness Diagram: {System Name} + +**Lens:** Benchmark Representativeness (Generalizability) +**Question:** Does this generalize beyond the test bed? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Coverage Matrix + +| Scenario / Domain | {Metric A} | {Metric B} | {Metric C} | Coverage | +|-------------------|-----------|-----------|-----------|----------| +| {Scenario 1} | ✓ | ✓ | ✗ | Partial | +| {Scenario 2} | ✗ | ✗ | ✗ | None | +| {Scenario 3} | ✓ | ✓ | ✓ | Full | + +## Benchmark Representativeness Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff; + classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000; + classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff; + + subgraph Benchmarks ["BENCHMARKS USED"] + direction TB + B1["{Benchmark 1}
    ━━━━━━━━━━
    {size}, {domain}"] + B2["{Benchmark 2}
    ━━━━━━━━━━
    {size}, {domain}"] + end + + subgraph Scenarios ["SCENARIOS TESTED"] + direction TB + S1["{Scenario 1}
    ━━━━━━━━━━
    {conditions}"] + S2["{Scenario 2}
    ━━━━━━━━━━
    {conditions}"] + end + + subgraph Metrics ["METRICS MEASURED"] + direction TB + M1["{Metric A}
    ━━━━━━━━━━
    {what it captures}"] + M2["{Metric B}
    ━━━━━━━━━━
    {what it captures}"] + end + + subgraph Claims ["GENERALIZATION CLAIMS"] + direction TB + C1["{Claim 1}
    ━━━━━━━━━━
    {source of claim}"] + C2["{Claim 2}
    ━━━━━━━━━━
    {source of claim}"] + end + + subgraph Gaps ["UNTESTED REGIONS"] + direction TB + G1["{Gap 1}
    ━━━━━━━━━━
    {why it matters}"] + G2["{Gap 2}
    ━━━━━━━━━━
    {why it matters}"] + end + + VALIDATE["{Generalization Validity Check}
    ━━━━━━━━━━
    Coverage vs. Claim scope"] + + B1 --> S1 + B2 --> S2 + S1 --> M1 + S2 --> M2 + M1 --> C1 + M2 --> C2 + C1 --> VALIDATE + C2 --> VALIDATE + G1 -.->|missing| VALIDATE + G2 -.->|missing| VALIDATE + + %% CLASS ASSIGNMENTS %% + class B1,B2 stateNode; + class S1,S2 handler; + class M1,M2 output; + class C1,C2 cli; + class G1,G2 gap; + class VALIDATE detector; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Teal | Benchmarks | Datasets and test suites used | +| Orange | Scenarios | Tested scenarios and conditions | +| Teal | Metrics | Measured evaluation metrics | +| Dark Blue | Claims | Generalization claims made | +| Yellow/Amber | Gaps | Untested regions of target space | +| Red | Validation | Generalization validity check | + +## Generalization Gap Analysis + +| Claim | Evidence (Benchmarks) | Gap (Untested) | Risk | +|-------|----------------------|----------------|------| +| {Claim 1} | {What covers it} | {What is missing} | High/Med/Low | +| {Claim 2} | {What covers it} | {What is missing} | High/Med/Low | + +## Representativeness Assessment + +| Dimension | Current Coverage | Required for Claim | Verdict | +|-----------|-----------------|-------------------|---------| +| Domain diversity | {count} domains | {needed} | ✓/✗ | +| Task variety | {count} tasks | {needed} | ✓/✗ | +| Scale range | {min}–{max} | {needed} | ✓/✗ | +| Distribution shift | {tested?} | {needed} | ✓/✗ | +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill for lens selection +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-measurement-validity` - For metric quality analysis +- `/autoskillit:exp-lens-validity-threats` - For systematic threat inventory diff --git a/src/autoskillit/skills_extended/exp-lens-causal-assumptions/SKILL.md b/src/autoskillit/skills_extended/exp-lens-causal-assumptions/SKILL.md new file mode 100644 index 0000000000..174611d0b2 --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-causal-assumptions/SKILL.md @@ -0,0 +1,254 @@ +--- +name: exp-lens-causal-assumptions +categories: [exp-lens] +activate_deps: [mermaid] +description: Create Causal Assumptions experimental design diagram showing confounders, mediators, colliders, and identification strategy. Causal-structural lens answering "What causal assumptions support this design?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Causal Assumptions Lens - Tracing causal structure...'" + once: true +--- + +# Causal Assumptions Experimental Design Lens + +**Philosophical Mode:** Causal-Structural +**Primary Question:** "What causal assumptions support this design?" +**Focus:** Confounders, Mediators, Colliders, Adjustment Sets, Identification Strategy + +## Arguments + +`/autoskillit:exp-lens-causal-assumptions [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Experiment claims causal effects +- Pipeline has shared components that might confound +- Need to verify identification strategy +- User invokes `/autoskillit:exp-lens-causal-assumptions` or `/autoskillit:make-experiment-diag causal` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-causal-assumptions/` + +**ALWAYS:** +- Classify every variable as Treatment, Outcome, Confounder, Mediator, Collider, Instrument, or Selection variable +- Map every directed edge to a concrete code-level data flow +- Flag all unblocked backdoor paths explicitly +- Document the identification strategy with testable assumptions +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-causal-assumptions/exp_diag_causal_assumptions_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-causal-assumptions/exp_diag_causal_assumptions_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Treatment & Outcome Definition** +- Find experiment config, treatment assignment code, outcome measurement +- Look for: treatment, control, outcome, response, endpoint, metric + +**Confounding Pathways** +- Find shared data sources, preprocessing, environment variables +- Look for: shared, common, config, environment, seed, global + +**Mediator & Mechanism Variables** +- Find intermediate processing steps between treatment and outcome +- Look for: transform, preprocess, feature, intermediate, pipeline + +**Collider & Selection Variables** +- Find filtering, subsetting, or conditional logic applied post-treatment +- Look for: filter, subset, exclude, condition, threshold, select + +**Randomization & Assignment** +- Find how experimental units are assigned to conditions +- Look for: random, assign, allocate, split, stratify, block + +### Step 2: Build the Causal Graph Structure + +For each variable identified, classify as: Treatment, Outcome, Confounder, Mediator, Collider, Instrument, or Selection variable. Map directed edges based on code-level data flow. Flag any unblocked backdoor paths. + +### Step 3: Identify Causal Assumptions + +**CRITICAL — Analyze Claim Direction:** +For every edge in the causal graph, determine: +- Does code implement a causal mechanism (A produces B) or merely a statistical association? +- Is the direction grounded in temporal ordering or domain knowledge? +- Are there feedback loops? + +Document each assumption as either testable or untestable, and record the evidence (or lack of evidence) from the codebase. + +### Step 4: Create the Diagram + +Use flowchart with: + +**Direction:** `TB` (causes flow downward to effects) + +**Subgraphs:** +- TREATMENT ASSIGNMENT +- MEDIATING MECHANISMS +- OUTCOME MEASUREMENT +- CONFOUNDERS +- SELECTION/COLLIDERS + +**Node Styling:** +- `cli` class: Treatment variables +- `output` class: Outcome variables +- `handler` class: Mediators +- `stateNode` class: Confounders +- `detector` class: Colliders and selection variables +- `gap` class: Unblocked backdoor paths +- `newComponent` class: Instruments + +**Edge Labels:** causal, confounds, selects, mediates, blocks + +### Step 5: Write Output + +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/exp-lens-causal-assumptions/exp_diag_causal_assumptions_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Output Template + +```markdown +# Causal Assumptions Diagram: {Experiment Name} + +**Lens:** Causal Assumptions (Causal-Structural) +**Question:** What causal assumptions support this design? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Causal Variables + +| Variable | Type | Measured? | Controlled? | +|----------|------|-----------|-------------| +| {name} | {Treatment/Outcome/Confounder/Mediator/Collider/Instrument/Selection} | {Yes/No} | {Yes/No} | + +## Causal DAG + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff; + classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000; + classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff; + + subgraph Confounders ["CONFOUNDERS"] + CONF["Confounder Variable
    ━━━━━━━━━━
    Shared source
    Controlled?"] + end + + subgraph Treatment ["TREATMENT ASSIGNMENT"] + TREAT["Treatment
    ━━━━━━━━━━
    Assignment mechanism
    Randomized?"] + INSTR["Instrument
    ━━━━━━━━━━
    Exclusion restriction"] + end + + subgraph Mediators ["MEDIATING MECHANISMS"] + MED["Mediator
    ━━━━━━━━━━
    Intermediate step"] + end + + subgraph Outcome ["OUTCOME MEASUREMENT"] + OUT["Outcome
    ━━━━━━━━━━
    Metric / endpoint"] + end + + subgraph Selection ["SELECTION/COLLIDERS"] + COLL["Collider
    ━━━━━━━━━━
    Post-treatment filter"] + end + + %% CAUSAL EDGES %% + CONF -->|"confounds"| TREAT + CONF -->|"confounds"| OUT + INSTR -->|"causal"| TREAT + TREAT -->|"causal"| MED + MED -->|"mediates"| OUT + TREAT -->|"selects"| COLL + OUT -->|"selects"| COLL + + %% CLASS ASSIGNMENTS %% + class TREAT cli; + class OUT output; + class MED handler; + class CONF stateNode; + class COLL detector; + class INSTR newComponent; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Blue | Treatment | Treatment assignment variables | +| Dark Teal | Outcome | Outcome measurement variables | +| Orange | Mediator | Intermediate mechanism variables | +| Teal | Confounder | Shared causes of treatment and outcome | +| Red | Collider/Selection | Post-treatment filters (conditioning risk) | +| Green | Instrument | Variables affecting only treatment | +| Amber | Backdoor Path | Unblocked confounding path | + +## Identification Strategy + +| Assumption | Testable? | Evidence | +|------------|-----------|----------| +| {assumption} | {Yes/No} | {evidence from codebase} | + +## Unblocked Backdoor Paths + +| Path | Variables | Severity | Mitigation | +|------|-----------|----------|------------| +| {path} | {A -> ... -> B} | {High/Medium/Low} | {adjustment/unavailable} | +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill for lens selection +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-estimand-clarity` - For clarifying the target estimand +- `/autoskillit:exp-lens-validity-threats` - For broader validity threat inventory diff --git a/src/autoskillit/skills_extended/exp-lens-comparator-construction/SKILL.md b/src/autoskillit/skills_extended/exp-lens-comparator-construction/SKILL.md new file mode 100644 index 0000000000..eeb45adb7b --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-comparator-construction/SKILL.md @@ -0,0 +1,248 @@ +--- +name: exp-lens-comparator-construction +categories: [exp-lens] +activate_deps: [mermaid] +description: Create Comparator Construction experimental design analysis assessing whether baselines and controls are fair and relevant. Counterfactual lens answering "Is the comparator fair and relevant?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Comparator Construction Lens - Analyzing baseline fairness...'" + once: true +--- + +# Comparator Construction Experimental Design Lens + +**Philosophical Mode:** Counterfactual +**Primary Question:** "Is the comparator fair and relevant?" +**Focus:** Baseline Choice, Control Realism, Version Matching, Effort Symmetry, Baseline Drift + +## Arguments + +`/autoskillit:exp-lens-comparator-construction [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Benchmark comparisons where baseline quality is questioned +- Ablation studies needing fair controls +- Claims of improvement over prior work +- User invokes `/autoskillit:exp-lens-comparator-construction` or `/autoskillit:make-experiment-diag comparator` + +## Critical Constraints + +**NEVER:** +- Modify any source code or experiment files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Accept at face value that baselines received symmetric treatment +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-comparator-construction/` + +**ALWAYS:** +- Build a fairness matrix covering all treatment-vs-comparator pairs +- Check for confounding differences in implementation, tuning, data access, and compute +- Assess whether each comparator is the best available alternative at the time of the experiment +- Identify temporal drift in baseline relevance +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-comparator-construction/exp_diag_comparator_construction_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-comparator-construction/exp_diag_comparator_construction_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Baseline/Control Definitions** +- Find what the proposed method is compared against +- Look for: baseline, control, comparison, prior, state-of-the-art, vanilla, default, reference + +**Implementation Parity** +- Find whether baselines get equal engineering effort +- Look for: reproduce, reimplement, original, paper, author, tuned, optimized, hyperparameter + +**Version & Environment Match** +- Find whether baselines use the same software/hardware environment +- Look for: version, library, framework, gpu, hardware, environment, checkpoint + +**Tuning Protocol Symmetry** +- Find whether hyperparameter tuning is symmetric +- Look for: tune, search, grid, optuna, sweep, budget, trials, epochs + +**Temporal Baseline Drift** +- Find whether baselines have been updated or are stale +- Look for: date, published, year, updated, latest, deprecated, legacy + +### Step 2: Build the Comparator Inventory + +For each comparator, assess: +1. Is it the best available alternative? +2. Is it given equal engineering effort? +3. Is it run in the same environment? +4. Is the tuning budget symmetric? +5. Has it drifted since originally published? + +### Step 3: Construct the Fairness Matrix + +**CRITICAL — Analyze Counterfactual Quality:** +For each treatment-vs-comparator pair: +- Does the comparison isolate the intended factor? +- Are there confounding differences in implementation, tuning, data access, or compute? + +Build a fairness matrix with rows = comparators, columns = fairness dimensions. + +### Step 4: Create the Optional Comparison Diagram + +If a diagram adds value, create a simplified flowchart. This is OPTIONAL for this hybrid lens — the tables are the primary output. + +**Direction:** `LR` (treatment and comparator flow in parallel toward evaluation) + +**Subgraphs:** "PROPOSED METHOD", "COMPARATOR(S)", "SHARED EVALUATION" + +**Node Styling:** +- `cli` class: proposed method nodes +- `phase` class: comparator method nodes +- `handler` class: shared evaluation pipeline nodes +- `output` class: results nodes +- `gap` class: asymmetries flagged +- `detector` class: parity checks + +### Step 5: Write Output + +Write the analysis to: `{{AUTOSKILLIT_TEMP}}/exp-lens-comparator-construction/exp_diag_comparator_construction_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Output Template + +```markdown +# Comparator Construction Analysis: {Experiment Name} + +**Lens:** Comparator Construction (Counterfactual) +**Question:** Is the comparator fair and relevant? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Comparator Inventory + +| Comparator | Source | Reimplemented? | Same Environment? | Same Tuning Budget? | +|------------|--------|---------------|-------------------|---------------------| +| {name} | {paper/repo} | Yes / No / Partial | Yes / No | Yes / No / Unknown | + +## Fairness Matrix + +| Comparator | Best Available? | Equal Effort? | Same Env? | Symmetric Tuning? | Temporally Current? | +|------------|----------------|--------------|-----------|-------------------|---------------------| +| {name} | Yes / No | Yes / No | Yes / No | Yes / No | Yes / No | + +## Comparison Diagram (Optional) + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart LR + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff; + classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000; + classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff; + + subgraph Proposed ["PROPOSED METHOD"] + METHOD["Proposed Method
    ━━━━━━━━━━
    {method name}"] + end + + subgraph Comparators ["COMPARATOR(S)"] + COMP1["Comparator 1
    ━━━━━━━━━━
    {name}"] + COMP2["Comparator 2
    ━━━━━━━━━━
    {name}"] + end + + subgraph Evaluation ["SHARED EVALUATION"] + EVAL["Evaluation Pipeline
    ━━━━━━━━━━
    {dataset/benchmark}"] + RESULTS["Results
    ━━━━━━━━━━
    {metrics reported}"] + PARITY["Parity Check
    ━━━━━━━━━━
    {asymmetry found}"] + ASYM["Asymmetry
    ━━━━━━━━━━
    {description}"] + end + + METHOD -->|"evaluated on"| EVAL + COMP1 -->|"evaluated on"| EVAL + COMP2 -->|"evaluated on"| EVAL + EVAL --> RESULTS + RESULTS --> PARITY + PARITY -.->|"flagged"| ASYM + + class METHOD cli; + class COMP1,COMP2 phase; + class EVAL handler; + class RESULTS output; + class PARITY detector; + class ASYM gap; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Blue | Proposed Method | The method being evaluated | +| Purple | Comparators | Baselines and controls | +| Orange | Evaluation | Shared evaluation pipeline | +| Dark Teal | Results | Reported outcomes | +| Red | Parity Checks | Fairness verification points | +| Yellow | Asymmetries | Flagged unfair differences | + +## Asymmetry Register + +| # | Asymmetry | Affects | Impact Assessment | Remediation | +|---|-----------|---------|-------------------|-------------| +| 1 | {description} | {comparator(s)} | High / Medium / Low | {how to fix} | + +## Recommendations + +1. {Most critical fairness fix — e.g., retune baseline with same budget} +2. {Version alignment or environment standardization needed} +3. {Additional comparator that should be included} +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill for lens selection +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-estimand-clarity` - For clarifying what the comparison is measuring +- `/autoskillit:exp-lens-fair-comparison` - For deeper analysis of evaluation protocol fairness diff --git a/src/autoskillit/skills_extended/exp-lens-error-budget/SKILL.md b/src/autoskillit/skills_extended/exp-lens-error-budget/SKILL.md new file mode 100644 index 0000000000..0616bd48ed --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-error-budget/SKILL.md @@ -0,0 +1,138 @@ +--- +name: exp-lens-error-budget +categories: [exp-lens] +activate_deps: [mermaid] +description: Analyze statistical error budget showing Type I/II errors, power, minimum detectable effect, multiplicity corrections, and sequential monitoring. Statistical lens answering "Are error risks sized and controlled?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Error Budget Lens - Analyzing statistical error risks...'" + once: true +--- + +# Error Budget Experimental Design Lens + +**Philosophical Mode:** Statistical +**Primary Question:** "Are error risks sized and controlled?" +**Focus:** Type I/II Errors, Power, Minimum Detectable Effect, Multiplicity, Sequential Monitoring + +## Arguments + +`/autoskillit:exp-lens-error-budget [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Need to verify statistical power before running an experiment +- Multiple comparisons are performed without a stated correction strategy +- Sequential testing or interim analysis is in use without defined stopping rules +- User invokes `/autoskillit:exp-lens-error-budget` or `/autoskillit:make-experiment-diag error` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Accept default alpha=0.05 without checking whether it is appropriate for the decision context +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-error-budget/` + +**ALWAYS:** +- Enumerate every statistical test and account for its error contribution +- Distinguish per-test error rates from family-wise error rates +- Flag any sequential peeking without a formal stopping rule as a critical defect +- Evaluate whether the minimum detectable effect is practically meaningful, not just statistically chosen +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-error-budget/exp_diag_error_budget_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-error-budget/exp_diag_error_budget_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Sample Size & Power** +- Find power calculations or sample size justifications +- Look for: power, sample_size, n_samples, effect_size, minimum_detectable, mde + +**Multiple Comparisons** +- Find all statistical tests performed and correction strategies +- Look for: bonferroni, fdr, holm, bh, correction, multiple, comparisons, tests + +**Sequential Analysis** +- Find interim analyses, stopping rules, or sequential monitoring +- Look for: interim, early_stopping, sequential, alpha_spending, peek, monitor + +**Decision Thresholds** +- Find significance thresholds and decision rules +- Look for: alpha, p_value, threshold, significance, reject, null, hypothesis + +**Effect Size Context** +- Find practical significance alongside statistical significance +- Look for: effect_size, cohen, practical, meaningful, magnitude, difference + +### Step 2: Build the Error Budget + +For each statistical claim: +1. What is the per-test Type I error rate? +2. What is the family-wise Type I error rate? +3. What is the power (1 - Type II error)? +4. What is the minimum detectable effect? +5. Is sequential monitoring in use, and if so, what stopping rule is defined? +6. Is the chosen alpha appropriate for the decision context? + +### Step 3: Analyze Error Allocation + +For each test, rate alignment as: ALIGNED / CONVENTIONAL / MISALIGNED + +### Step 4: Create Optional Decision-Flow Diagram + +If a diagram adds value, show Data → Tests → Thresholds → Conclusions, with labeled error rates. + +### Step 5: Write Output + +Write the analysis to: `{{AUTOSKILLIT_TEMP}}/exp-lens-error-budget/exp_diag_error_budget_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-severity-testing` +- `/autoskillit:exp-lens-variance-stability` diff --git a/src/autoskillit/skills_extended/exp-lens-estimand-clarity/SKILL.md b/src/autoskillit/skills_extended/exp-lens-estimand-clarity/SKILL.md new file mode 100644 index 0000000000..9cfedead24 --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-estimand-clarity/SKILL.md @@ -0,0 +1,238 @@ +--- +name: exp-lens-estimand-clarity +categories: [exp-lens] +activate_deps: [mermaid] +description: Create Estimand Clarity experimental design analysis decomposing the implicit estimand from code vs. explicit claims from prose. Evidential lens answering "What exactly is the claim?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Estimand Clarity Lens - Analyzing claim precision...'" + once: true +--- + +# Estimand Clarity Experimental Design Lens + +**Philosophical Mode:** Evidential +**Primary Question:** "What exactly is the claim?" +**Focus:** Effect Definition, Target Population, Outcome Specification, Comparator, Aggregation Level, Complication Handling + +## Arguments + +`/autoskillit:exp-lens-estimand-clarity [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Experiment has unclear or shifting hypotheses +- Multiple stakeholders interpret results differently +- Claims mix causal and predictive language +- User invokes `/autoskillit:exp-lens-estimand-clarity` or `/autoskillit:make-experiment-diag estimand` + +## Critical Constraints + +**NEVER:** +- Modify any source code or experiment files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-estimand-clarity/` + +**ALWAYS:** +- Decompose every stated claim into formal contrast notation (Treatment A vs Treatment B on Outcome Y in Population Z) +- Flag every mismatch between prose claims and code implementation +- Identify the aggregation level (unit, group, time) explicitly +- Document how complications (missing data, failures, exclusions) are handled +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-estimand-clarity/exp_diag_estimand_clarity_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-estimand-clarity/exp_diag_estimand_clarity_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Stated Claims & Hypotheses** +- Find hypothesis statements, research questions, README claims +- Look for: hypothesis, claim, goal, objective, question, we show, we demonstrate, improves, outperforms + +**Treatment Definition** +- Find what intervention or manipulation is applied +- Look for: treatment, intervention, method, approach, condition, configuration, ablation + +**Outcome Definition** +- Find what is measured as the result +- Look for: outcome, metric, measure, endpoint, target, response, dependent + +**Population & Scope** +- Find what units, datasets, or contexts the claim covers +- Look for: dataset, population, sample, domain, task, benchmark, scenario, setting + +**Complication Handling** +- Find how missing data, failures, timeouts, or exclusions are handled +- Look for: missing, exclude, timeout, fail, drop, impute, censor, incomplete + +### Step 2: Extract the Implicit Estimand + +Answer each question from the code (not the docs): +1. What is the treatment? +2. What is the comparator? +3. What is the outcome? +4. What is the population? +5. What is the time horizon? +6. How are complications handled? + +### Step 3: Compare Claims to Implementation + +Compare the explicit claims (from docs/papers) to the implicit estimand (from code). Flag mismatches between what the prose asserts and what the implementation actually measures. + +**CRITICAL — Analyze Claim Precision:** +For every stated claim: +- Can you write it as a formal contrast (Treatment A vs Treatment B on Outcome Y in Population Z)? If not, what is ambiguous? +- Does the code measure what the prose claims? + +### Step 4: Create the Optional Claim-Flow Diagram + +If a diagram adds value, create a simplified flowchart. This is OPTIONAL for this hybrid lens — the tables are the primary output. + +**Direction:** `TB` (claim flows from intervention through measurement to conclusion) + +**Small diagram: 4-6 nodes showing Treatment → Mechanism → Outcome → Claim** + +**Node Styling:** +- `cli` class: treatment/intervention nodes +- `handler` class: mechanism/pipeline nodes +- `output` class: measured outcome nodes +- `phase` class: stated claim nodes +- `gap` class: ambiguity or mismatch between claim and measurement + +### Step 5: Write Output + +Write the analysis to: `{{AUTOSKILLIT_TEMP}}/exp-lens-estimand-clarity/exp_diag_estimand_clarity_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Output Template + +```markdown +# Estimand Clarity Analysis: {Experiment Name} + +**Lens:** Estimand Clarity (Evidential) +**Question:** What exactly is the claim? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Estimand Decomposition + +| Component | Stated | Implemented | Match? | +|-----------|--------|-------------|--------| +| Treatment | {from prose} | {from code} | Yes / No / Partial | +| Comparator | {from prose} | {from code} | Yes / No / Partial | +| Outcome | {from prose} | {from code} | Yes / No / Partial | +| Population | {from prose} | {from code} | Yes / No / Partial | +| Time Horizon | {from prose} | {from code} | Yes / No / Partial | +| Complication Handling | {from prose} | {from code} | Yes / No / Partial | + +## Claim Precision Assessment + +| Claim | Formal Contrast | Ambiguities | +|-------|----------------|-------------| +| "{stated claim}" | Treatment A vs B on Y in Z | {list ambiguities} | + +## Claim-Flow Diagram (Optional) + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff; + classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000; + classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff; + + TREATMENT["Treatment
    ━━━━━━━━━━
    {intervention name}"] + MECHANISM["Mechanism
    ━━━━━━━━━━
    {pipeline step}"] + OUTCOME["Measured Outcome
    ━━━━━━━━━━
    {metric}"] + CLAIM["Stated Claim
    ━━━━━━━━━━
    {claim text}"] + MISMATCH["Mismatch
    ━━━━━━━━━━
    {ambiguity description}"] + + TREATMENT --> MECHANISM + MECHANISM --> OUTCOME + OUTCOME --> CLAIM + OUTCOME -.->|"diverges"| MISMATCH + + class TREATMENT cli; + class MECHANISM handler; + class OUTCOME output; + class CLAIM phase; + class MISMATCH gap; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Blue | Treatment | Intervention applied | +| Orange | Mechanism | Pipeline processing | +| Dark Teal | Outcome | Measured result | +| Purple | Claim | Stated conclusion | +| Yellow | Mismatch | Ambiguity or claim-code divergence | + +## Ambiguity Register + +| # | Ambiguity | Location | Severity | Resolution Needed | +|---|-----------|----------|----------|-------------------| +| 1 | {description} | {file/section} | High / Medium / Low | {what to clarify} | + +## Recommendations + +1. {Specific action to resolve most critical ambiguity} +2. {Rewrite suggestion for vague claim} +3. {Code change to align implementation with stated estimand} +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill for lens selection +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-causal-assumptions` - For causal structure of the stated claim +- `/autoskillit:exp-lens-measurement-validity` - For whether the outcome metric is valid diff --git a/src/autoskillit/skills_extended/exp-lens-exploratory-confirmatory/SKILL.md b/src/autoskillit/skills_extended/exp-lens-exploratory-confirmatory/SKILL.md new file mode 100644 index 0000000000..425aecd444 --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-exploratory-confirmatory/SKILL.md @@ -0,0 +1,130 @@ +--- +name: exp-lens-exploratory-confirmatory +categories: [exp-lens] +activate_deps: [mermaid] +description: Assess whether analytic decisions were pre-specified or post-hoc and whether exploratory/confirmatory norms are aligned. Boundary lens answering "Is this discovery or test, and are norms aligned?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Exploratory-Confirmatory Lens - Analyzing boundary integrity...'" + once: true +--- + +# Exploratory-Confirmatory Experimental Design Lens + +**Philosophical Mode:** Boundary +**Primary Question:** "Is this discovery or test, and are norms aligned?" +**Focus:** Pre-specification, Analytic Flexibility, HARKing Detection, Garden of Forking Paths, Transparent Reporting + +## Arguments + +`/autoskillit:exp-lens-exploratory-confirmatory [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Study mixes exploration and confirmation without clear boundaries +- Post-hoc hypotheses presented as pre-specified +- Many analyses run but only significant ones reported +- User invokes `/autoskillit:exp-lens-exploratory-confirmatory` or `/autoskillit:make-experiment-diag exploratory` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-exploratory-confirmatory/` + +**ALWAYS:** +- Map the full analytic timeline — what was decided before vs. after seeing data +- Count forking paths honestly — every analysis choice is a potential fork +- Distinguish genuine exploration (hypothesis-generating) from HARKing (hypothesis-after-results) +- Flag absent preregistration as a finding without assuming bad faith +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-exploratory-confirmatory/exp_diag_exploratory_confirmatory_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-exploratory-confirmatory/exp_diag_exploratory_confirmatory_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Pre-specified Plans** +- Find pre-registration documents, analysis plans, hypothesis files +- Look for: preregister, analysis_plan, hypothesis, registered, protocol, spec + +**Analytic Flexibility** +- Find places where multiple analysis paths were possible +- Look for: alternatively, could_also, option, variant, subset, sensitivity, robustness + +**Selective Reporting Signals** +- Find evidence of selective reporting or cherry-picking +- Look for: not_significant, excluded, not_shown, supplementary, additional, hidden + +**Post-Hoc Rationalization** +- Find language suggesting post-hoc hypothesis generation +- Look for: we_noticed, interestingly, surprisingly, unexpectedly, upon_inspection + +**Exploration-Confirmation Separation** +- Find explicit statements about exploratory vs. confirmatory intent +- Look for: exploratory, pilot, hypothesis_generating, confirmatory, pre_specified + +### Step 2: Map Analytic Timeline + +What was decided before vs. after seeing data? Where is the exploration/confirmation boundary? Count forking paths. + +### Step 3: Analyze Boundary Integrity + +For every reported result: Was the analysis plan fixed pre-outcome? How many alternatives could have been run? Does reporting distinguish exploratory from confirmatory? Assess survivorship bias. + +### Step 4: Create the Diagram (Optional) + +**Direction:** LR (time flows left to right). Pre-data decisions → Data collection → Post-data decisions → Reporting + +### Step 5: Write Output + +Write the output to: `{{AUTOSKILLIT_TEMP}}/exp-lens-exploratory-confirmatory/exp_diag_exploratory_confirmatory_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-severity-testing` +- `/autoskillit:exp-lens-sensitivity-robustness` diff --git a/src/autoskillit/skills_extended/exp-lens-fair-comparison/SKILL.md b/src/autoskillit/skills_extended/exp-lens-fair-comparison/SKILL.md new file mode 100644 index 0000000000..7a6a14b798 --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-fair-comparison/SKILL.md @@ -0,0 +1,249 @@ +--- +name: exp-lens-fair-comparison +categories: [exp-lens] +activate_deps: [mermaid] +description: Create a comparison fairness matrix assessing whether alternatives are evaluated under symmetric constraints. Fairness lens answering "Are alternatives compared under symmetric constraints?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Fair Comparison Lens - Analyzing symmetry of constraints...'" + once: true +--- + +# Fair Comparison Experimental Design Lens + +**Philosophical Mode:** Fairness +**Primary Question:** "Are alternatives compared under symmetric constraints?" +**Focus:** Compute Budget Symmetry, Tuning Protocol Parity, Data Access Equality, Engineering Effort Balance, Winner's Curse + +## Arguments + +`/autoskillit:exp-lens-fair-comparison [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Method comparisons where tuning effort differs +- Benchmark results where compute budgets are unequal +- Claims of SOTA that may reflect process differences +- User invokes `/autoskillit:exp-lens-fair-comparison` or `/autoskillit:make-experiment-diag fairness` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-fair-comparison/` + +**ALWAYS:** +- Build the full symmetry matrix — every method against every resource dimension +- Attribute improvements to method vs. process — both deserve accounting +- Flag undisclosed compute or tuning as a finding, not an assumption +- Assess the winner's curse: did the proposed method benefit from more selection pressure? +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-fair-comparison/exp_diag_fair_comparison_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-fair-comparison/exp_diag_fair_comparison_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Compute & Resource Allocation** +- Find compute resources used per method +- Look for: gpu, tpu, hours, cost, memory, flops, compute_budget, machine, cluster + +**Tuning Protocol per Method** +- Find tuning procedures for each compared method +- Look for: grid_search, optuna, bayesian_opt, hyperband, tune, sweep, trials, budget, early_stop + +**Data Access & Preprocessing** +- Find whether all methods use the same data pipeline +- Look for: data_augmentation, preprocessing, feature, embedding, pretrained, extra_data, auxiliary + +**Engineering Effort Indicators** +- Find differential engineering investment +- Look for: custom, specialized, trick, hack, ensemble, post_process, calibrate, threshold_tune + +**Reporting Completeness** +- Find whether resource usage is disclosed +- Look for: report, disclose, computational_cost, wall_time, parameter_count, training_time + +### Step 2: Build Symmetry Matrix + +Build the symmetry matrix: rows = methods compared, columns = resource dimensions (compute, tuning, data, engineering, disclosure). + +For each cell: +- Is the allocation symmetric? +- If not, does the asymmetry favor the proposed method? +- Estimate the magnitude of bias from each asymmetry. + +### Step 3: Analyze Effort Attribution + +**CRITICAL — Analyze Effort Attribution:** +For every claimed improvement: +- What fraction of the improvement can be attributed to the method itself vs. differential engineering effort, tuning budget, or data access? + +### Step 4: Create the Diagram + +Use the mermaid skill conventions to create a symmetry diagram with: + +**Direction:** `LR` (methods flow through resource allocation to evaluation) + +**Subgraphs:** +- METHODS +- RESOURCE ALLOCATION +- EVALUATION + +**Node Styling:** +- `cli` class: Proposed method +- `phase` class: Comparator methods +- `handler` class: Shared resources +- `gap` class: Asymmetric resources +- `detector` class: Symmetry checks +- `output` class: Results + +### Step 5: Write Output + +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/exp-lens-fair-comparison/exp_diag_fair_comparison_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Output Template + +```markdown +# Fair Comparison Analysis: {Experiment Name} + +**Lens:** Fair Comparison (Fairness) +**Question:** Are alternatives compared under symmetric constraints? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Symmetry Matrix + +| Method | Compute | Tuning Budget | Data Access | Engineering | Disclosure | +|--------|---------|---------------|-------------|-------------|------------| +| {proposed method} | {allocation} | {budget} | {access} | {effort} | {disclosed?} | +| {comparator} | {allocation} | {budget} | {access} | {effort} | {disclosed?} | + +## Resource Disclosure + +| Resource Type | Proposed Method | Comparators | Symmetric? | +|---------------|-----------------|-------------|------------| +| {GPU hours} | {value} | {value} | {Yes/No} | +| {Tuning trials} | {value} | {value} | {Yes/No} | +| {Extra data} | {value} | {value} | {Yes/No} | + +## Symmetry Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +graph LR + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff; + classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000; + classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff; + + subgraph Methods ["METHODS"] + direction TB + PROP["Proposed Method
    ━━━━━━━━━━
    Method under
    evaluation"] + COMP["Comparator Methods
    ━━━━━━━━━━
    Baseline and
    prior work"] + end + + subgraph Resources ["RESOURCE ALLOCATION"] + direction TB + SHARED["Shared Resources
    ━━━━━━━━━━
    Same data, same
    evaluation protocol"] + ASYM["Asymmetric Resources
    ━━━━━━━━━━
    Differential compute
    or tuning budget"] + CHECK["Symmetry Check
    ━━━━━━━━━━
    Verify parity
    across methods"] + end + + subgraph Eval ["EVALUATION"] + direction TB + RESULT["Results
    ━━━━━━━━━━
    Reported
    performance"] + end + + PROP --> SHARED + COMP --> SHARED + PROP --> ASYM + SHARED --> CHECK + ASYM --> CHECK + CHECK --> RESULT + + %% CLASS ASSIGNMENTS %% + class PROP cli; + class COMP phase; + class SHARED handler; + class ASYM gap; + class CHECK detector; + class RESULT output; +``` + +## Winner's Curse Assessment + +| Factor | Proposed Method Advantage | Impact on Claimed Improvement | +|--------|--------------------------|-------------------------------| +| {tuning trials} | {advantage} | {estimated impact} | +| {engineering tricks} | {advantage} | {estimated impact} | + +## Process-vs-Method Attribution Analysis + +- Method contribution: {estimated fraction} +- Tuning contribution: {estimated fraction} +- Engineering contribution: {estimated fraction} +- Data access contribution: {estimated fraction} + +## Key Findings + +- {Description of most significant asymmetries and their impact on claimed improvements} +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill for lens selection +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-comparator-construction` - For baseline selection and construction adequacy +- `/autoskillit:exp-lens-sensitivity-robustness` - For sensitivity analysis across conditions diff --git a/src/autoskillit/skills_extended/exp-lens-governance-risk/SKILL.md b/src/autoskillit/skills_extended/exp-lens-governance-risk/SKILL.md new file mode 100644 index 0000000000..84ef227096 --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-governance-risk/SKILL.md @@ -0,0 +1,142 @@ +--- +name: exp-lens-governance-risk +categories: [exp-lens] +activate_deps: [mermaid] +description: Create a risk register and stakeholder impact assessment for experiments with deployment implications. Governance lens answering "What risks arise from acting on this result?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Governance Risk Lens - Analyzing deployment risks and stakeholder impacts...'" + once: true +--- + +# Governance Risk Experimental Design Lens + +**Philosophical Mode:** Governance +**Primary Question:** "What risks arise from acting on this result?" +**Focus:** Deployment Risks, Subgroup Harms, Monitoring Plans, Limitation Disclosure, Responsible Decision-Making + +## Arguments + +`/autoskillit:exp-lens-governance-risk [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- AI evaluation with deployment implications +- Experiments whose results will affect real users +- Safety-relevant benchmarks +- User invokes `/autoskillit:exp-lens-governance-risk` or `/autoskillit:make-experiment-diag governance` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-governance-risk/` + +**ALWAYS:** +- Identify subgroups for whom the experimental evidence may not generalize +- Assess decision sufficiency — does the experiment actually answer the deployment question? +- Treat absent limitation disclosure as a finding requiring explicit flagging +- Distinguish risks that are monitored from risks that are merely acknowledged +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-governance-risk/exp_diag_governance_risk_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-governance-risk/exp_diag_governance_risk_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Intended Use & Deployment Context** +- Find intended deployment scenario and audience +- Look for: deploy, production, use_case, audience, user, stakeholder, decision + +**Subgroup & Fairness Analysis** +- Find evidence of subgroup analysis or fairness evaluation +- Look for: subgroup, demographic, fairness, equity, bias, disaggregate, protected + +**Harm & Risk Metrics** +- Find safety or harm metrics tracked +- Look for: harm, safety, risk, adverse, negative, side_effect, failure_mode + +**Monitoring & Feedback Plans** +- Find post-deployment monitoring or feedback loops +- Look for: monitor, alert, feedback, drift, rollback, incident, threshold, canary + +**Limitation Disclosure** +- Find explicit acknowledgment of limitations +- Look for: limitation, caveat, not_suitable, generalize, scope, restriction, caveat + +### Step 2: Build Risk Register + +For each potential action: Who is affected? What could go wrong? Severity? Likelihood? Monitoring? Evidence? +Classify by severity × likelihood. + +### Step 3: Analyze Decision Sufficiency + +For every deployment decision: Does the experiment provide sufficient evidence? What additional evidence is needed? Are there subgroups with insufficient evidence? + +### Step 4: Create the Diagram (Optional) + +**Direction:** TB. Results → Decisions → Stakeholder Impacts + +### Step 5: Write Output + +Write the output to: `{{AUTOSKILLIT_TEMP}}/exp-lens-governance-risk/exp_diag_governance_risk_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Responsible Deployment Checklist + +- [ ] Subgroup performance disaggregated and analyzed +- [ ] Deployment context matches experimental conditions +- [ ] Monitoring plan defined with specific thresholds +- [ ] Rollback criteria specified +- [ ] Limitations disclosed to decision-makers +- [ ] Affected communities consulted where applicable + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-validity-threats` +- `/autoskillit:exp-lens-measurement-validity` diff --git a/src/autoskillit/skills_extended/exp-lens-iterative-learning/SKILL.md b/src/autoskillit/skills_extended/exp-lens-iterative-learning/SKILL.md new file mode 100644 index 0000000000..6977af37b1 --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-iterative-learning/SKILL.md @@ -0,0 +1,133 @@ +--- +name: exp-lens-iterative-learning +categories: [exp-lens] +activate_deps: [mermaid] +description: Create Iterative Learning experimental design diagram showing factor space exploration, adaptive allocation, and next-experiment recommendations. Decision-Theoretic lens answering "How does this maximize learning per cost?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Iterative Learning Lens - Analyzing learning efficiency and design space...'" + once: true +--- + +# Iterative Learning Experimental Design Lens + +**Philosophical Mode:** Decision-Theoretic +**Primary Question:** "How does this maximize learning per cost?" +**Focus:** Factor Selection, Interaction Probing, Adaptive Allocation, Stopping Rules, Next-Experiment Planning + +## Arguments + +`/autoskillit:exp-lens-iterative-learning [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Planning a sequence of experiments +- Optimizing hyperparameter search +- Ablation study design +- User invokes `/autoskillit:exp-lens-iterative-learning` or `/autoskillit:make-experiment-diag iterative` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Recommend one-factor-at-a-time exploration when interactions are plausible +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-iterative-learning/` + +**ALWAYS:** +- Evaluate exploration efficiency against the key uncertainty being reduced +- Identify high-value unexplored regions of the factor space +- Assess whether the stopping rule is principled or arbitrary +- Surface interaction structure that one-factor-at-a-time designs would miss +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-iterative-learning/exp_diag_iterative_learning_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-iterative-learning/exp_diag_iterative_learning_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Factor Space** +- Find all factors being varied across experiments +- Look for: factor, parameter, variable, condition, treatment, level, dimension + +**Interaction Structure** +- Find evidence of interaction effects between factors +- Look for: interaction, joint, combined, synergy, cross, factorial + +**Cost & Resource Model** +- Find cost per experiment and total budget +- Look for: cost, budget, time, compute, trials, epochs, samples + +**Sequential Decision Logic** +- Find how next experiments are chosen based on previous results +- Look for: adaptive, sequential, bayesian, acquisition, exploration, exploitation, bandit + +**Learning Objectives** +- Find what uncertainty is being reduced by the experiment sequence +- Look for: objective, uncertainty, information, knowledge, goal, optimize + +### Step 2: Map the Design Space + +Map factors × levels, explored regions, probed interactions, next high-value experiments. Assess efficiency vs. key uncertainty. + +### Step 3: CRITICAL — Analyze Learning Efficiency + +Per factor/round: Information gain, Interaction risk, Cost-efficiency, Exploration-exploitation, Stopping rule + +Distinguish: Full factorial / Fractional factorial / One-factor-at-a-time / Adaptive/Bayesian + +### Step 4: Create the Diagram + +**Direction:** LR. Subgraphs: FACTOR SPACE, EXPLORATION STRATEGY, RESULTS SO FAR, NEXT EXPERIMENTS, STOPPING CRITERIA + +### Step 5: Write Output + +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/exp-lens-iterative-learning/exp_diag_iterative_learning_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-sensitivity-robustness` +- `/autoskillit:exp-lens-error-budget` diff --git a/src/autoskillit/skills_extended/exp-lens-measurement-validity/SKILL.md b/src/autoskillit/skills_extended/exp-lens-measurement-validity/SKILL.md new file mode 100644 index 0000000000..2a401dbc5e --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-measurement-validity/SKILL.md @@ -0,0 +1,267 @@ +--- +name: exp-lens-measurement-validity +categories: [exp-lens] +activate_deps: [mermaid] +description: Analyze measurement validity for experimental design — auditing metric-construct alignment, proxy validity, reliability, sensitivity, and consequential validity. Argumentative lens answering "Do measurements justify the interpretation?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Measurement Validity Lens - Auditing metric-construct alignment...'" + once: true +--- + +# Measurement Validity Experimental Design Lens + +**Philosophical Mode:** Psychometric +**Primary Question:** "Do measurements justify the interpretation?" +**Focus:** Metric-Construct Alignment, Proxy Validity, Reliability, Sensitivity, Consequential Validity + +## Arguments + +`/autoskillit:exp-lens-measurement-validity [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Metrics may not measure what they claim to; proxy metrics used instead of true objectives +- Evaluation scores treated as "truth" without validation +- Metric choice is contested or under-specified +- User invokes `/autoskillit:exp-lens-measurement-validity` or `/autoskillit:make-experiment-diag measurement` + +## Critical Constraints + +**NEVER:** +- Modify any source code or experimental artifacts +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-measurement-validity/` + +**ALWAYS:** +- Treat every reported metric as a claim requiring a validity argument +- Enumerate known failure modes: gaming, saturation, proxy collapse, and aggregation artifacts +- Assess reliability (stability under reruns) and sensitivity (ability to distinguish meaningful differences) for each metric +- Identify where metric-construct alignment is weak or unsupported by evidence +- BEFORE creating any optional diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-measurement-validity/exp_diag_measurement_validity_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-measurement-validity/exp_diag_measurement_validity_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Metric Definitions** +- Find all metrics computed and reported +- Look for: metric, score, accuracy, f1, precision, recall, bleu, rouge, loss, error_rate, latency + +**Intended Interpretations** +- Find what conclusions are drawn from each metric +- Look for: better, worse, improves, indicates, measures, reflects, captures, proxy + +**Metric Computation Details** +- Find exactly how each metric is computed (aggregation, weighting, edge cases) +- Look for: average, macro, micro, weighted, threshold, cutoff, aggregate + +**Alternative Metrics Considered** +- Find whether alternative metrics were evaluated and why they were rejected +- Look for: also measured, alternative, we chose, instead of, limitation + +**Construct-Metric Gap** +- Find where the metric diverges from the construct it claims to measure +- Look for: limitation, caveat, imperfect, proxy, approximate, does not capture + +### Step 2: Build Validity Arguments + +For each reported metric, construct a validity argument: +1. What construct does this metric claim to measure? +2. What evidence supports this claim? +3. What are the known failure modes (gaming, saturation, proxy collapse)? +4. Is the metric reliable (stable under reruns)? +5. Is it sensitive (can it distinguish meaningful differences)? + +### Step 3: Analyze Metric-Construct Alignment + +**CRITICAL — for every metric-to-claim link:** +- Is there a logical argument connecting the number to the concept? +- Could a system score high on this metric while being poor on the intended construct? +- What would gaming look like? +- Does the aggregation method (macro vs micro, mean vs median) preserve the intended construct? +- Are there known saturation regimes where the metric stops being informative? + +### Step 4: Optional Metric-Construct Mapping Diagram + +This lens does NOT produce a primary mermaid diagram. The output is a structured validity argument. An optional simplified metric mapping diagram may be included if it clarifies the metric-construct relationship. + +If including the optional diagram: + +**Direction:** `LR` (constructs on left, metrics on right) + +**Minimal diagram:** Construct nodes on the left, Metric nodes on the right, with edge labels indicating strength of alignment + +**Node Styling:** +- `cli` class: Constructs and intended properties being claimed +- `output` class: Measured metrics (what is actually computed) +- `gap` class: Weak or missing alignments, proxy collapses +- `handler` class: Proxy relationships and intermediate mappings + +**Connection Types:** +- Solid arrows for strong, well-evidenced alignment +- Dashed arrows for proxy or contested alignment +- Edge labels naming the type of relationship or its weakness + +### Step 5: Write Output + +Write the output to: `{{AUTOSKILLIT_TEMP}}/exp-lens-measurement-validity/exp_diag_measurement_validity_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Output Template + +```markdown +# Measurement Validity Analysis: {Experiment Name} + +**Lens:** Measurement Validity (Psychometric) +**Question:** Do measurements justify the interpretation? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Metric Inventory + +| Metric | Construct Claimed | Computation | Reliability | Sensitivity | +|--------|-------------------|-------------|-------------|-------------| +| {metric name} | {what it claims to measure} | {aggregation/formula} | {stable / unstable / unknown} | {high / low / saturated} | + +## Validity Arguments + +### {Metric Name} + +**Construct claimed:** {The property this metric is presented as measuring} + +**Evidence for alignment:** +- {Supporting argument or citation} + +**Evidence against alignment / known failure modes:** +- {Failure mode 1: e.g., gameable by surface pattern matching} +- {Failure mode 2: e.g., proxy collapses when distribution shifts} + +**Reliability assessment:** {Stable under reruns? Sensitive to seed?} + +**Sensitivity assessment:** {Can it distinguish meaningful differences in the relevant range?} + +**Verdict:** {Strong / Partial / Weak / Unsupported} + +--- + +## Proxy Collapse Risks + +| Metric | Proxy For | Collapse Condition | Consequence | +|--------|-----------|--------------------|-------------| +| {metric} | {true construct} | {when proxy diverges from construct} | {what is falsely concluded} | + +## Gaming Vulnerabilities + +| Metric | Gaming Strategy | Detection Method | +|--------|----------------|-----------------| +| {metric} | {how to maximize score without improving construct} | {how to detect gaming} | + +## Optional: Metric-Construct Mapping Diagram + +{Include only if it clarifies alignment; omit if argument tables are sufficient} + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart LR + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff; + classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000; + classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff; + + subgraph Constructs ["Intended Constructs"] + C1["Construct A
    ━━━━━━━━━━
    The property claimed"] + C2["Construct B
    ━━━━━━━━━━
    Another property"] + end + + subgraph Metrics ["Measured Metrics"] + M1["Metric X
    ━━━━━━━━━━
    Computation method"] + M2["Metric Y
    ━━━━━━━━━━
    Computation method"] + end + + subgraph Gaps ["Weak / Missing Alignments"] + G1["Proxy Collapse Risk
    ━━━━━━━━━━
    Condition for divergence"] + end + + %% ALIGNMENTS %% + C1 -->|"strong alignment"| M1 + C2 -->|"proxy (weak)"| M2 + M2 -.->|"diverges under"| G1 + + %% CLASS ASSIGNMENTS %% + class C1,C2 cli; + class M1,M2 output; + class G1 gap; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Blue | Construct | Intended properties being claimed | +| Dark Teal | Metric | What is actually computed and reported | +| Yellow | Gap | Weak alignment, proxy collapse, or missing evidence | +| Orange | Proxy | Intermediate proxy relationships | + +## Summary Verdict + +| Metric | Verdict | Primary Concern | +|--------|---------|----------------| +| {metric} | {Strong / Partial / Weak / Unsupported} | {One-line summary of the key validity concern} | +``` + +--- + +## Pre-Diagram Checklist + +Before creating any optional diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill for lens selection +- `/autoskillit:mermaid` - MUST BE LOADED before creating any optional diagram +- `/autoskillit:exp-lens-estimand-clarity` - For auditing the upstream claim the metric is meant to support +- `/autoskillit:exp-lens-benchmark-representativeness` - For auditing whether the evaluation set generalizes diff --git a/src/autoskillit/skills_extended/exp-lens-pipeline-integrity/SKILL.md b/src/autoskillit/skills_extended/exp-lens-pipeline-integrity/SKILL.md new file mode 100644 index 0000000000..c4aebedfd9 --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-pipeline-integrity/SKILL.md @@ -0,0 +1,268 @@ +--- +name: exp-lens-pipeline-integrity +categories: [exp-lens] +activate_deps: [mermaid] +description: Create Pipeline Integrity experimental design diagram showing data splits, leakage points, preprocessing order, and label contamination. Integrity lens answering "Could data handling create optimistic bias?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Pipeline Integrity Lens - Auditing for data leakage...'" + once: true +--- + +# Pipeline Integrity Experimental Design Lens + +**Philosophical Mode:** Integrity +**Primary Question:** "Could data handling create optimistic bias?" +**Focus:** Data Splits, Leakage Points, Preprocessing Order, Label Contamination, Pipeline Invariants + +## Arguments + +`/autoskillit:exp-lens-pipeline-integrity [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- ML pipeline with train/test splits +- Preprocessing before or after splitting is ambiguous +- Feature engineering touching labels +- User invokes `/autoskillit:exp-lens-pipeline-integrity` or `/autoskillit:make-experiment-diag pipeline` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-pipeline-integrity/` + +**ALWAYS:** +- Classify every pipeline stage as pre-split or post-split +- Trace whether transforms are fitted on full data or train-only +- Flag all label-touching feature engineering steps +- Document pipeline invariants that guard against leakage +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-pipeline-integrity/exp_diag_pipeline_integrity_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-pipeline-integrity/exp_diag_pipeline_integrity_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Data Loading & Sources** +- Find data ingestion code, raw data paths +- Look for: load, read, fetch, dataset, csv, parquet, download + +**Preprocessing & Transforms** +- Find normalization, encoding, imputation steps +- Look for: transform, normalize, scale, encode, impute, clean, preprocess + +**Split Logic** +- Find train/test/validation split code +- Look for: split, train_test, fold, cross_val, stratify, group + +**Feature Engineering** +- Find feature creation, selection, extraction +- Look for: feature, extract, select, engineer, embed, vectorize + +**Model Training & Evaluation** +- Find training loops and evaluation metrics +- Look for: fit, train, predict, evaluate, score, metric, loss + +### Step 2: Map the Complete Pipeline + +Map the full pipeline from raw data to reported metrics. For each stage, determine: +- What information flows in? +- What information flows out? +- Could any downstream information leak upstream? +- Classify each stage as pre-split or post-split. + +### Step 3: Identify Leakage Risks + +**CRITICAL — Analyze Leakage Direction:** +For every data transformation: +- Does it use information from the full dataset (leakage risk) or only from the training partition? +- Is normalization fitted on train-only or all data? +- Are features derived from labels? + +Assign a severity level (High/Medium/Low) to each leakage risk based on whether it would invalidate reported metrics. + +### Step 4: Create the Diagram + +Use flowchart with: + +**Direction:** `LR` (data flows left to right) + +**Subgraphs:** +- RAW DATA +- PREPROCESSING +- SPLIT POINT +- TRAIN PATH +- TEST PATH +- EVALUATION + +**Node Styling:** +- `cli` class: Data sources +- `handler` class: Transforms +- `detector` class: Split point and validation gates +- `stateNode` class: Data stores +- `gap` class: Leakage risks +- `output` class: Metrics and results +- `phase` class: Model training + +**Edge Labels:** full data, train only, test only, LEAKAGE RISK + +### Step 5: Write Output + +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/exp-lens-pipeline-integrity/exp_diag_pipeline_integrity_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Output Template + +```markdown +# Pipeline Integrity Diagram: {Experiment Name} + +**Lens:** Pipeline Integrity (Integrity) +**Question:** Could data handling create optimistic bias? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Pipeline Stages + +| Stage | Input | Output | Pre/Post Split | Leakage Risk? | +|-------|-------|--------|----------------|---------------| +| {stage} | {input} | {output} | {Pre/Post} | {Yes/No} | + +## Pipeline Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart LR + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff; + classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000; + classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff; + + subgraph Raw ["RAW DATA"] + SRC["Raw Dataset
    ━━━━━━━━━━
    Source path
    N samples"] + end + + subgraph Preprocessing ["PREPROCESSING"] + PREP["Normalization / Encoding
    ━━━━━━━━━━
    Fitted on: full/train?"] + LEAK["Leaky Transform
    ━━━━━━━━━━
    Uses full dataset"] + end + + subgraph SplitPoint ["SPLIT POINT"] + SPLIT["Train/Test Split
    ━━━━━━━━━━
    Stratified? Ratio?"] + end + + subgraph TrainPath ["TRAIN PATH"] + TRAIN_DATA["Train Set
    ━━━━━━━━━━
    N_train samples"] + MODEL["Model Training
    ━━━━━━━━━━
    fit()"] + end + + subgraph TestPath ["TEST PATH"] + TEST_DATA["Test Set
    ━━━━━━━━━━
    N_test samples"] + end + + subgraph Evaluation ["EVALUATION"] + METRIC["Reported Metric
    ━━━━━━━━━━
    score / loss"] + end + + %% PIPELINE FLOWS %% + SRC -->|"full data"| PREP + PREP -->|"full data"| LEAK + LEAK -.->|"LEAKAGE RISK"| METRIC + PREP -->|"full data"| SPLIT + SPLIT -->|"train only"| TRAIN_DATA + SPLIT -->|"test only"| TEST_DATA + TRAIN_DATA -->|"fit"| MODEL + MODEL -->|"predict"| TEST_DATA + TEST_DATA -->|"evaluate"| METRIC + + %% CLASS ASSIGNMENTS %% + class SRC cli; + class PREP handler; + class LEAK gap; + class SPLIT detector; + class TRAIN_DATA,TEST_DATA stateNode; + class MODEL phase; + class METRIC output; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Blue | Data Source | Raw input datasets | +| Orange | Transform | Preprocessing and feature engineering steps | +| Red | Split / Gate | Split point and validation gates | +| Teal | Data Store | Partitioned data stores (train/test) | +| Purple | Training | Model training stages | +| Dark Teal | Output | Reported metrics and results | +| Amber | Leakage Risk | Transforms using full-dataset information | + +## Leakage Assessment + +| Risk | Stage | Mechanism | Severity | +|------|-------|-----------|----------| +| {risk name} | {stage} | {how leakage occurs} | {High/Medium/Low} | + +## Pipeline Invariants + +- [ ] All scalers/encoders fitted on train partition only +- [ ] Feature selection criteria computed from train partition only +- [ ] No label information used in feature construction +- [ ] Test set never seen by any fitting step +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill for lens selection +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-reproducibility-artifacts` - For artifact completeness audit +- `/autoskillit:exp-lens-measurement-validity` - For outcome measurement validity diff --git a/src/autoskillit/skills_extended/exp-lens-randomization-blocking/SKILL.md b/src/autoskillit/skills_extended/exp-lens-randomization-blocking/SKILL.md new file mode 100644 index 0000000000..e909984b91 --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-randomization-blocking/SKILL.md @@ -0,0 +1,133 @@ +--- +name: exp-lens-randomization-blocking +categories: [exp-lens] +activate_deps: [mermaid] +description: Create Randomization & Blocking experimental design diagram showing assignment mechanisms, blocking factors, and comparability sources. Design-Structural lens answering "Where does comparability come from?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Randomization & Blocking Lens - Analyzing assignment and comparability...'" + once: true +--- + +# Randomization & Blocking Experimental Design Lens + +**Philosophical Mode:** Design-Structural +**Primary Question:** "Where does comparability come from?" +**Focus:** Assignment Mechanisms, Blocking Factors, Stratification, Balanced Designs, Replication + +## Arguments + +`/autoskillit:exp-lens-randomization-blocking [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Experiment uses randomization or structured assignment +- Need to verify blocking and stratification +- Checking for pseudoreplication +- User invokes `/autoskillit:exp-lens-randomization-blocking` or `/autoskillit:make-experiment-diag randomization` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Assume comparability without tracing its source +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-randomization-blocking/` + +**ALWAYS:** +- Trace the exact mechanism that creates comparability between treatment groups +- Identify every nuisance factor and how it is controlled +- Flag pseudoreplication risks (replicating at the wrong unit) +- Verify that replication is adequate for the claimed inferential precision +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-randomization-blocking/exp_diag_randomization_blocking_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-randomization-blocking/exp_diag_randomization_blocking_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Assignment Mechanism** +- Find how experimental units are assigned to conditions +- Look for: random, assign, allocate, split, stratify, block, hash, bucket + +**Blocking & Stratification** +- Find blocking factors and stratification variables +- Look for: block, strata, stratify, covariate, match, pair, group_by + +**Replication Structure** +- Find how many independent replicates exist per condition +- Look for: replicate, repeat, trial, run, seed, fold, n_replications + +**Order & Timing Effects** +- Find potential for carryover or order effects +- Look for: order, sequence, carryover, period, washout, crossover, time + +**Exclusion & Attrition** +- Find how units are excluded or drop out during the experiment +- Look for: exclude, drop, attrition, missing, censor, incomplete, filter + +### Step 2: Map the Allocation Flow + +Trace: Population → assignment → analysis. Identify randomization unit, blocking factors, replication adequacy, and potential confounds. + +### Step 3: CRITICAL — Analyze Comparability Source + +Distinguish: True randomization / Blocked randomization / Matched pairs / Deterministic assignment + +For each: Is the comparability mechanism strong enough for the claimed inference? + +### Step 4: Create the Diagram + +**Direction:** TB. Subgraphs: POPULATION/POOL, BLOCKING, RANDOMIZATION, TREATMENT ARMS, ANALYSIS + +### Step 5: Write Output + +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/exp-lens-randomization-blocking/exp_diag_randomization_blocking_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-causal-assumptions` +- `/autoskillit:exp-lens-unit-interference` diff --git a/src/autoskillit/skills_extended/exp-lens-reproducibility-artifacts/SKILL.md b/src/autoskillit/skills_extended/exp-lens-reproducibility-artifacts/SKILL.md new file mode 100644 index 0000000000..e535ef6f02 --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-reproducibility-artifacts/SKILL.md @@ -0,0 +1,275 @@ +--- +name: exp-lens-reproducibility-artifacts +categories: [exp-lens] +activate_deps: [mermaid] +description: Create Reproducibility Artifacts experimental design diagram showing run instructions, environment capture, data availability, determinism controls, and audit trail. Transparency lens answering "Could an independent party reproduce this?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Reproducibility Artifacts Lens - Auditing reproduction chain...'" + once: true +--- + +# Reproducibility Artifacts Experimental Design Lens + +**Philosophical Mode:** Transparency +**Primary Question:** "Could an independent party reproduce this?" +**Focus:** Run Instructions, Environment Capture, Data Availability, Determinism Controls, Audit Trail + +## Arguments + +`/autoskillit:exp-lens-reproducibility-artifacts [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Evaluating reproducibility of computational experiments +- Auditing artifact completeness +- Checking for undocumented dependencies +- User invokes `/autoskillit:exp-lens-reproducibility-artifacts` or `/autoskillit:make-experiment-diag reproducibility` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-reproducibility-artifacts/` + +**ALWAYS:** +- Trace the full chain from "clone repo" to "reproduce figures" +- Classify every artifact as available/unavailable and versioned/floating +- Identify the weakest link in the reproduction chain +- Flag all silent non-determinism risks +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-reproducibility-artifacts/exp_diag_reproducibility_artifacts_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-reproducibility-artifacts/exp_diag_reproducibility_artifacts_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Environment & Dependencies** +- Find dependency files, container definitions, environment setup +- Look for: requirements, Dockerfile, environment.yml, conda, pip, nix, lock + +**Data Provenance** +- Find data download scripts, checksums, versioning +- Look for: download, checksum, hash, version, dvc, data_url, manifest + +**Execution Entry Points** +- Find run scripts, Makefiles, workflow managers +- Look for: Makefile, run.sh, snakemake, nextflow, main, entrypoint, cli + +**Random Seed & Determinism** +- Find seed setting, nondeterminism controls +- Look for: seed, random_state, deterministic, cudnn, PYTHONHASHSEED + +**Output Artifacts & Logging** +- Find result storage, logging, figure generation +- Look for: save, log, output, results, figures, checkpoint, wandb, mlflow + +### Step 2: Map the Reproduction Chain + +Map the full chain from "clone repo" to "reproduce figures." Identify each link: +- Is it documented? +- Is it automated? +- Is it deterministic? +- What is the weakest link? + +### Step 3: Classify Each Artifact Dependency + +**CRITICAL — Analyze Reproduction Chain:** +For every artifact dependency: +- Is the source available (open vs gated)? +- Is the version pinned or floating? +- Is the transform deterministic? +- Could silent environment differences change results? + +Assign a status of Pass, Warn, or Fail to each link in the chain based on reproducibility confidence. + +### Step 4: Create the Diagram + +Use flowchart with: + +**Direction:** `LR` (reproduction chain flows left to right) + +**Subgraphs:** +- SOURCE CODE +- ENVIRONMENT +- DATA +- EXECUTION +- OUTPUTS + +**Node Styling:** +- `cli` class: Entry points and run commands +- `stateNode` class: Versioned and pinned artifacts +- `handler` class: Transforms and scripts +- `output` class: Results and figures +- `gap` class: Missing or undocumented links +- `detector` class: Checksum and validation gates +- `phase` class: External dependencies + +**Edge Labels:** pinned, floating, deterministic, nondeterministic, gated + +### Step 5: Write Output + +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/exp-lens-reproducibility-artifacts/exp_diag_reproducibility_artifacts_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Output Template + +```markdown +# Reproducibility Artifacts Diagram: {Experiment Name} + +**Lens:** Reproducibility Artifacts (Transparency) +**Question:** Could an independent party reproduce this? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Artifact Inventory + +| Artifact | Available? | Versioned? | Deterministic? | +|----------|------------|------------|----------------| +| {artifact} | {Yes/No/Gated} | {Pinned/Floating/None} | {Yes/No/Unknown} | + +## Reproduction Chain Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart LR + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff; + classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000; + classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff; + + subgraph Source ["SOURCE CODE"] + REPO["Git Repository
    ━━━━━━━━━━
    Commit hash
    Branch"] + ENTRY["Entry Point
    ━━━━━━━━━━
    run.sh / Makefile"] + end + + subgraph Env ["ENVIRONMENT"] + DEPS["Dependencies
    ━━━━━━━━━━
    requirements.txt / lock"] + MISSING["Undocumented Dep
    ━━━━━━━━━━
    No version pin"] + EXTDEP["External Service
    ━━━━━━━━━━
    API / cloud resource"] + end + + subgraph Data ["DATA"] + RAW["Raw Dataset
    ━━━━━━━━━━
    Checksum available?"] + CHKSUM["Checksum Gate
    ━━━━━━━━━━
    sha256 / md5"] + GATED["Gated Dataset
    ━━━━━━━━━━
    Access required"] + end + + subgraph Exec ["EXECUTION"] + SEED["Seed Control
    ━━━━━━━━━━
    PYTHONHASHSEED
    random_state"] + SCRIPT["Pipeline Script
    ━━━━━━━━━━
    Deterministic?"] + end + + subgraph Outputs ["OUTPUTS"] + RESULTS["Results / Metrics
    ━━━━━━━━━━
    Logged?"] + FIGS["Figures
    ━━━━━━━━━━
    Reproducible?"] + end + + %% REPRODUCTION CHAIN %% + REPO -->|"pinned"| ENTRY + ENTRY -->|"loads"| DEPS + DEPS -.->|"floating"| MISSING + MISSING -.->|"nondeterministic"| SCRIPT + EXTDEP -->|"gated"| SCRIPT + RAW -->|"verify"| CHKSUM + CHKSUM -->|"deterministic"| SCRIPT + GATED -.->|"gated"| SCRIPT + SEED -->|"controls"| SCRIPT + SCRIPT -->|"produces"| RESULTS + SCRIPT -->|"generates"| FIGS + + %% CLASS ASSIGNMENTS %% + class REPO,ENTRY cli; + class DEPS,RAW stateNode; + class SCRIPT,SEED handler; + class EXTDEP phase; + class RESULTS,FIGS output; + class CHKSUM detector; + class MISSING,GATED gap; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Blue | Entry Point | Run commands and source code | +| Teal | Versioned Artifact | Pinned dependencies and checksummed data | +| Orange | Transform / Script | Pipeline scripts and execution steps | +| Purple | External Dependency | External services and APIs | +| Dark Teal | Output | Results, metrics, and figures | +| Red | Validation Gate | Checksum and integrity checks | +| Amber | Missing Link | Undocumented or gated dependencies | + +## Reproduction Checklist + +Step-by-step instructions with pass/fail status: + +- [ ] Clone repository at pinned commit +- [ ] Reproduce environment from lock/container file +- [ ] Download data and verify checksums +- [ ] Set all random seeds as documented +- [ ] Execute pipeline via documented entry point +- [ ] Compare output metrics/figures to reported values + +## Weakest Links + +| Link | Issue | Severity | Recommendation | +|------|-------|----------|----------------| +| {link} | {undocumented/gated/floating/nondeterministic} | {High/Medium/Low} | {action} | +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill for lens selection +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-pipeline-integrity` - For data leakage audit +- `/autoskillit:exp-lens-variance-stability` - For result stability across seeds diff --git a/src/autoskillit/skills_extended/exp-lens-sensitivity-robustness/SKILL.md b/src/autoskillit/skills_extended/exp-lens-sensitivity-robustness/SKILL.md new file mode 100644 index 0000000000..ab912b79b1 --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-sensitivity-robustness/SKILL.md @@ -0,0 +1,255 @@ +--- +name: exp-lens-sensitivity-robustness +categories: [exp-lens] +activate_deps: [mermaid] +description: Create Sensitivity & Robustness experimental design analysis identifying load-bearing analytic choices and untested perturbations. Robustness lens answering "Which assumptions are load-bearing?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Sensitivity & Robustness Lens - Analyzing assumption load...'" + once: true +--- + +# Sensitivity & Robustness Experimental Design Lens + +**Philosophical Mode:** Robustness +**Primary Question:** "Which assumptions are load-bearing?" +**Focus:** Ablation Structure, Preprocessing Sensitivity, Metric Sensitivity, Hyperparameter Sensitivity, Distribution Shift + +## Arguments + +`/autoskillit:exp-lens-sensitivity-robustness [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Results may depend on specific preprocessing choices +- Need to verify robustness of conclusions across conditions +- Ablation study seems incomplete or cherry-picked +- User invokes `/autoskillit:exp-lens-sensitivity-robustness` or `/autoskillit:make-experiment-diag sensitivity` + +## Critical Constraints + +**NEVER:** +- Modify any source code or experiment files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Treat "untested" as equivalent to "robust" +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-sensitivity-robustness/` + +**ALWAYS:** +- Build a full sensitivity matrix (choices x perturbation types) +- Classify every analytic choice as load-bearing, minor, or untested +- Flag cases where the most impactful choices are the least tested +- Distinguish between ablations that were run and choices that were simply fixed +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-sensitivity-robustness/exp_diag_sensitivity_robustness_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-sensitivity-robustness/exp_diag_sensitivity_robustness_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Analytic Choices Made** +- Find all decision points in the analysis pipeline +- Look for: choice, option, default, parameter, threshold, method, alternative + +**Ablation Coverage** +- Find which factors have been ablated +- Look for: ablation, without, remove, disable, vary, sweep, drop + +**Preprocessing Variations** +- Find preprocessing steps that could be done differently +- Look for: normalize, tokenize, augment, crop, resize, filter, clean, impute + +**Hyperparameter Sensitivity** +- Find which hyperparameters were tuned vs fixed +- Look for: learning_rate, batch_size, epochs, dropout, hidden_size, temperature, alpha, beta + +**Distribution/Environment Variations** +- Find evidence of testing under different conditions +- Look for: shift, domain, transfer, cross, out_of_distribution, generalize, different + +### Step 2: Build the Sensitivity Matrix + +Rows = analytic choices. Columns = perturbation types (remove, change, stress). + +For each cell: Does the conclusion survive the perturbation? + +### Step 3: Classify Analytic Choices + +**CRITICAL — Analyze Assumption Load:** +For every analytic choice: +- What happens if this choice were made differently? +- Is there evidence from ablations, sweeps, or prior literature? +- Are the most impactful choices the least tested? + +Classify each choice as: +- **Load-bearing**: Conclusion changes if this choice changes +- **Minor**: Conclusion is robust to changes in this choice +- **Untested**: No evidence either way + +### Step 4: Create the Optional Perturbation Diagram + +If a diagram adds value, create a simplified flowchart. This is OPTIONAL for this hybrid lens — the tables are the primary output. + +**Direction:** `TB` (choices flow down through perturbation to conclusion stability) + +**Subgraphs:** "ANALYTIC CHOICES", "PERTURBATIONS TESTED", "CONCLUSION STABILITY" + +**Node Styling:** +- `stateNode` class: analytic choice nodes +- `handler` class: perturbation type nodes +- `output` class: stable conclusion nodes +- `gap` class: load-bearing untested choice nodes +- `detector` class: sensitivity threshold nodes + +### Step 5: Write Output + +Write the analysis to: `{{AUTOSKILLIT_TEMP}}/exp-lens-sensitivity-robustness/exp_diag_sensitivity_robustness_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Output Template + +```markdown +# Sensitivity & Robustness Analysis: {Experiment Name} + +**Lens:** Sensitivity & Robustness (Robustness) +**Question:** Which assumptions are load-bearing? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Sensitivity Matrix + +| Analytic Choice | Remove | Change Value | Stress Test | Overall Classification | +|----------------|--------|-------------|-------------|------------------------| +| {choice name} | Stable / Fragile / Untested | Stable / Fragile / Untested | Stable / Fragile / Untested | Load-bearing / Minor / Untested | + +## Load-Bearing Assumptions + +| Assumption | Evidence Type | Impact if Changed | Tested? | +|------------|--------------|-------------------|---------| +| {assumption} | Ablation / Sweep / Literature / None | High / Medium / Low | Yes / No | + +## Ablation Coverage Assessment + +| Factor | Ablated? | Result | Interpretation | +|--------|----------|--------|----------------| +| {factor name} | Yes / No | {delta metric if yes} | Conclusion holds / Fragile / Unknown | + +## Robustness Profile + +| Dimension | Status | Notes | +|-----------|--------|-------| +| Preprocessing choices | Robust / Fragile / Untested | {detail} | +| Hyperparameter choices | Robust / Fragile / Untested | {detail} | +| Metric choices | Robust / Fragile / Untested | {detail} | +| Distribution shift | Robust / Fragile / Untested | {detail} | + +## Perturbation Diagram (Optional) + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff; + classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000; + classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff; + + subgraph Choices ["ANALYTIC CHOICES"] + CHOICE1["Preprocessing Choice
    ━━━━━━━━━━
    {e.g., normalization}"] + CHOICE2["Model Choice
    ━━━━━━━━━━
    {e.g., architecture}"] + LOAD_BEARING["Load-Bearing Choice
    ━━━━━━━━━━
    {untested critical choice}"] + end + + subgraph Perturbations ["PERTURBATIONS TESTED"] + PERTURB1["Remove
    ━━━━━━━━━━
    Ablation"] + PERTURB2["Change Value
    ━━━━━━━━━━
    Sensitivity sweep"] + THRESHOLD["Sensitivity Threshold
    ━━━━━━━━━━
    {delta that changes conclusion}"] + end + + subgraph Stability ["CONCLUSION STABILITY"] + STABLE["Stable Conclusion
    ━━━━━━━━━━
    {holds under perturbation}"] + end + + CHOICE1 --> PERTURB1 + CHOICE2 --> PERTURB2 + PERTURB1 --> THRESHOLD + PERTURB2 --> THRESHOLD + THRESHOLD --> STABLE + LOAD_BEARING -.->|"untested risk"| THRESHOLD + + class CHOICE1,CHOICE2 stateNode; + class LOAD_BEARING gap; + class PERTURB1,PERTURB2 handler; + class THRESHOLD detector; + class STABLE output; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Teal | Analytic Choices | Decision points in the pipeline | +| Yellow | Load-Bearing Untested | Critical choices with no perturbation evidence | +| Orange | Perturbations | Types of tests applied | +| Red | Sensitivity Thresholds | Points where conclusion may change | +| Dark Teal | Stable Conclusions | Results robust to perturbation | + +## Recommendations + +1. {Most urgent ablation to run — highest impact untested choice} +2. {Preprocessing sensitivity test needed} +3. {Distribution shift or domain generalization test needed} +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill for lens selection +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-estimand-clarity` - For clarifying which conclusions are being stress-tested +- `/autoskillit:exp-lens-iterative-learning` - For tracking robustness improvements across experiment iterations diff --git a/src/autoskillit/skills_extended/exp-lens-severity-testing/SKILL.md b/src/autoskillit/skills_extended/exp-lens-severity-testing/SKILL.md new file mode 100644 index 0000000000..09f4776ad9 --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-severity-testing/SKILL.md @@ -0,0 +1,136 @@ +--- +name: exp-lens-severity-testing +categories: [exp-lens] +activate_deps: [mermaid] +description: Analyze severity of experimental tests — adversarial cases, negative controls, falsification tests, easy-pass detection, and confirmatory theater. Falsificationist lens answering "Would this design have caught the error?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Severity Testing Lens - Analyzing adversarial robustness of experimental conclusions...'" + once: true +--- + +# Severity Testing Experimental Design Lens + +**Philosophical Mode:** Falsificationist +**Primary Question:** "Would this design have caught the error?" +**Focus:** Adversarial Cases, Negative Controls, Falsification Tests, Easy-Pass Detection, Confirmatory Theater + +## Arguments + +`/autoskillit:exp-lens-severity-testing [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Evaluating whether positive results are meaningful or trivially achievable +- Checking for adversarial robustness of experimental conclusions +- User invokes `/autoskillit:exp-lens-severity-testing` or `/autoskillit:make-experiment-diag severity` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Accept a "pass" result without asking what a false result would have looked like under this design +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-severity-testing/` + +**ALWAYS:** +- For every positive claim, identify what error the test was capable of detecting +- Inventory negative controls and sanity checks explicitly — their absence is a finding +- Rate severity before reporting conclusions, not after +- Flag confirmatory theater: experiments designed to confirm rather than risk refutation +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-severity-testing/exp_diag_severity_testing_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-severity-testing/exp_diag_severity_testing_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Positive Results Claimed** +- Find all conclusions and positive claims in the experiment +- Look for: demonstrates, improves, outperforms, achieves, shows, confirms, validates + +**Negative Controls & Sanity Checks** +- Find negative controls, baselines, and sanity check tests +- Look for: negative_control, sanity, ablation, degenerate, trivial, null, random + +**Adversarial Conditions** +- Find adversarial or stress-test conditions applied +- Look for: adversarial, attack, stress, perturbation, corruption, noise, edge_case + +**Alternative Explanations Tested** +- Find whether alternative explanations were examined +- Look for: alternative, confound, artifact, spurious, coincidence, luck + +**Prediction Specificity** +- Find how specific the predictions were before seeing data +- Look for: prediction, hypothesis, preregistered, expected, prior + +### Step 2: Assess Severity for Each Claim + +For each claim: +1. What error was the test capable of detecting? +2. What would a false positive result have looked like under this design? +3. Were negative controls or sanity checks included? +4. Were adversarial conditions tested? +5. Is the test informative (would a bad result look different from a good result)? + +### Step 3: Rate Severity and Identify Gaps + +Severity ratings: HIGH / MEDIUM / LOW +Flag **confirmatory theater** when design is structured to confirm rather than risk refutation. + +### Step 4: Create Optional Severity-Flow Diagram + +Show Claims → HIGH/MEDIUM/LOW severity tests → Severity verdicts. + +### Step 5: Write Output + +Write the analysis to: `{{AUTOSKILLIT_TEMP}}/exp-lens-severity-testing/exp_diag_severity_testing_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-error-budget` +- `/autoskillit:exp-lens-validity-threats` diff --git a/src/autoskillit/skills_extended/exp-lens-unit-interference/SKILL.md b/src/autoskillit/skills_extended/exp-lens-unit-interference/SKILL.md new file mode 100644 index 0000000000..4f82797382 --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-unit-interference/SKILL.md @@ -0,0 +1,170 @@ +--- +name: exp-lens-unit-interference +categories: [exp-lens] +activate_deps: [mermaid] +description: Create Unit Interference experimental design diagram showing unit hierarchy, cluster structure, shared resources, and SUTVA violation pathways. Causal-Structural lens answering "What is the unit, and can treatments spill over?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Unit Interference Lens - Analyzing experimental units and spillover...'" + once: true +--- + +# Unit Interference Experimental Design Lens + +**Philosophical Mode:** Causal-Structural +**Primary Question:** "What is the unit, and can treatments spill over?" +**Focus:** Experimental Unit, Cluster Structure, Shared Resources, Network Effects, SUTVA Violations + +## Arguments + +`/autoskillit:exp-lens-unit-interference [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Online A/B tests with shared infrastructure +- Distributed systems where units share caches, queues, or services +- Social or network experiments where units are connected +- User invokes `/autoskillit:exp-lens-unit-interference` or `/autoskillit:make-experiment-diag unit` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-unit-interference/` + +**ALWAYS:** +- Focus on the unit definition and whether SUTVA is plausible +- Map the full unit-cluster-resource hierarchy before assessing interference +- Identify every shared resource that could transmit treatment effects across groups +- Distinguish direct spillover (shared cache) from indirect spillover (market equilibrium) +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-unit-interference/exp_diag_unit_interference_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-unit-interference/exp_diag_unit_interference_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Unit Definition** +- Find what constitutes one experimental unit +- Is it a user, request, session, query, item, sample, trial, or instance? +- Look for: user, request, session, query, item, sample, trial, instance + +**Cluster & Group Structure** +- Find groupings of units that might share treatment effects +- Identify natural clustering that predates treatment assignment +- Look for: cluster, group, shard, server, region, batch, household, team + +**Shared Resources** +- Find infrastructure shared across treatment groups +- Identify components both treatment and control units touch +- Look for: cache, queue, pool, database, service, load_balancer, gpu, memory + +**Network & Social Connections** +- Find connections between units that could transmit treatment effects +- Identify paths by which a treated unit could alter a control unit's experience +- Look for: network, graph, friend, neighbor, link, message, recommend, influence + +**Treatment Assignment Boundary** +- Find where the treatment boundary is drawn +- Identify whether the assignment is at the unit level or a coarser level +- Look for: bucket, hash, experiment_id, variant, flag, feature_flag, rollout + +### Step 2: Map the Unit-Cluster-Resource Hierarchy + +For each level of the hierarchy: +- Can treatment at one level affect outcomes at another? +- Identify specific spillover pathways between levels +- Assess whether SUTVA (stable unit treatment value assumption) is plausible at each level + +Document: +- **Unit Level**: The atomic entity receiving treatment +- **Cluster Level**: Natural groupings of units with shared context +- **System Level**: Infrastructure shared across all groups + +### Step 3: Analyze Interference Pathways + +**CRITICAL — Analyze Interference Pathways:** +For every shared resource or connection: +- Could treatment group A's behavior change the experience of control group B? +- Is this interference direct (shared cache hit rates) or indirect (market-level equilibrium effects)? +- What is the likely magnitude: negligible, moderate, or invalidating? +- Is there a mitigation strategy (cluster-level randomization, holdout, depletion correction)? + +Rate each pathway: +- **HIGH**: Interference almost certainly contaminates the control group +- **MEDIUM**: Plausible interference under realistic usage patterns +- **LOW**: Theoretical but unlikely to affect measured outcomes + +### Step 4: Create the Diagram + +Use flowchart with: + +**Direction:** `TB` (units nested within clusters nested within the system) + +**Subgraphs:** +- "EXPERIMENTAL UNITS" (the atomic entities being randomized) +- "CLUSTER STRUCTURE" (groupings above the unit level) +- "SHARED RESOURCES" (infrastructure accessible by both groups) +- "INTERFERENCE PATHWAYS" (explicit spillover routes) + +**Node Styling:** +- `cli` class: Experimental units +- `phase` class: Cluster / group nodes +- `stateNode` class: Shared resources +- `gap` class: Interference pathways +- `handler` class: Treatment assignment +- `detector` class: SUTVA boundary + +### Step 5: Write Output + +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/exp-lens-unit-interference/exp_diag_unit_interference_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill for experimental lens selection +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-causal-assumptions` - For DAG-level causal structure analysis +- `/autoskillit:exp-lens-randomization-blocking` - For randomization strategy and blocking design diff --git a/src/autoskillit/skills_extended/exp-lens-validity-threats/SKILL.md b/src/autoskillit/skills_extended/exp-lens-validity-threats/SKILL.md new file mode 100644 index 0000000000..0ee326958e --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-validity-threats/SKILL.md @@ -0,0 +1,146 @@ +--- +name: exp-lens-validity-threats +categories: [exp-lens] +activate_deps: [mermaid] +description: Create a validity threat matrix identifying alternative explanations and design mitigations. Adversarial lens answering "What alternative explanations survive?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Validity Threats Lens - Analyzing alternative explanations...'" + once: true +--- + +# Validity Threats Experimental Design Lens + +**Philosophical Mode:** Adversarial +**Primary Question:** "What alternative explanations survive?" +**Focus:** History Effects, Instrumentation Changes, Selection Effects, Co-interventions, Treatment Diffusion + +## Arguments + +`/autoskillit:exp-lens-validity-threats [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Quasi-experimental designs without full randomization +- System experiments with environmental changes +- Longitudinal comparisons +- User invokes `/autoskillit:exp-lens-validity-threats` or `/autoskillit:make-experiment-diag validity` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-validity-threats/` + +**ALWAYS:** +- Apply Campbell & Stanley's full threat taxonomy — do not skip threats just because they seem unlikely +- For every observed difference, enumerate at least 3 alternative explanations +- Assess mitigation strength honestly — "partially mitigated" is better than false confidence +- Distinguish threats that are ruled out by design from those that remain plausible +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-validity-threats/exp_diag_validity_threats_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-validity-threats/exp_diag_validity_threats_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Temporal Changes (History)** +- Find system, environment, or data changes during the experiment +- Look for: deploy, release, update, change, migration, incident, outage, rollback + +**Instrumentation Changes** +- Find changes to measurement tools or logging during the experiment +- Look for: logging, monitoring, metric, measure, instrument, version, schema + +**Selection & Filtering** +- Find how subjects, samples, or data were selected +- Look for: filter, select, sample, eligibility, inclusion, exclusion, criteria + +**Co-interventions** +- Find other changes running simultaneously with the treatment +- Look for: concurrent, parallel, simultaneous, co-running, other_experiment, a_b_overlap + +**Treatment Diffusion** +- Find ways treatment effects could spread to control groups +- Look for: contamination, diffusion, spillover, shared, cross, control_exposure + +### Step 2: Apply Threat Taxonomy + +Apply Campbell & Stanley's threat taxonomy: plausibility, design mitigation, mitigation strength → build threat matrix. + +### Step 3: Analyze Alternative Explanations + +For every observed difference: list at least 3 alternative explanations, ruling-out evidence, consistent evidence. + +### Step 4: Create the Diagram + +**Direction:** TB. Subgraphs: THREAT SOURCES, DESIGN MITIGATIONS, RESIDUAL THREATS + +### Step 5: Write Output + +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/exp-lens-validity-threats/exp_diag_validity_threats_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Campbell-Stanley Checklist + +Apply to every experiment: +1. History — concurrent events confounding treatment +2. Maturation — natural changes in subjects over time +3. Testing — pre-test sensitization effects +4. Instrumentation — changes in measurement tools +5. Statistical Regression — regression to the mean +6. Selection — non-random group formation +7. Experimental Mortality — differential dropout +8. Selection-Maturation Interaction — groups maturing at different rates +9. Diffusion of Treatments — control group exposed to treatment +10. Co-interventions — simultaneous competing treatments + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-causal-assumptions` +- `/autoskillit:exp-lens-severity-testing` diff --git a/src/autoskillit/skills_extended/exp-lens-variance-stability/SKILL.md b/src/autoskillit/skills_extended/exp-lens-variance-stability/SKILL.md new file mode 100644 index 0000000000..04a18b232c --- /dev/null +++ b/src/autoskillit/skills_extended/exp-lens-variance-stability/SKILL.md @@ -0,0 +1,251 @@ +--- +name: exp-lens-variance-stability +categories: [exp-lens] +activate_deps: [mermaid] +description: Create a variance analysis profile assessing whether signals exceed noise and whether results are stable across random seeds. Stability lens answering "Is the signal larger than the noise?" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Variance Stability Lens - Analyzing signal vs noise...'" + once: true +--- + +# Variance Stability Experimental Design Lens + +**Philosophical Mode:** Stability +**Primary Question:** "Is the signal larger than the noise?" +**Focus:** Run-to-Run Variance, Seed Sensitivity, Nondeterminism Sources, Confidence Intervals, Noise Floor + +## Arguments + +`/autoskillit:exp-lens-variance-stability [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- ML experiments with high variance across seeds +- Systems benchmarks with environmental noise +- Results where small differences are claimed as improvements +- User invokes `/autoskillit:exp-lens-variance-stability` or `/autoskillit:make-experiment-diag variance` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/exp-lens-variance-stability/` + +**ALWAYS:** +- Count the actual number of independent runs — single-run results must be flagged prominently +- Assess whether claimed improvements exceed the observed standard deviation +- Identify all sources of nondeterminism, not just random seeds +- Report when confidence intervals are absent — absence is a finding, not an omission +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/exp-lens-variance-stability/exp_diag_variance_stability_{YYYY-MM-DD_HHMMSS}.md` +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/exp-lens-variance-stability/exp_diag_variance_stability_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1-5; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Launch Parallel Exploration Subagents + +Spawn Explore subagents to investigate: + +**Random Seed Management** +- Find how seeds are set and varied +- Look for: seed, random_state, torch.manual_seed, np.random, set_seed, PYTHONHASHSEED + +**Nondeterminism Sources** +- Find sources of nondeterminism beyond seeds +- Look for: cudnn, benchmark, deterministic, parallel, async, thread, race, order, nondeterministic + +**Multiple Run Protocol** +- Find how many runs are performed per condition +- Look for: n_runs, trials, repeat, replicate, mean, std, confidence, interval, aggregate + +**Variance Reporting** +- Find how variance is reported (if at all) +- Look for: std, stderr, confidence, interval, range, median, quartile, bootstrap, error_bar + +**Signal-to-Noise Assessment** +- Find whether claimed improvements exceed observed variance +- Look for: significant, difference, improvement, margin, effect_size, gap, overlap + +### Step 2: Build Variance Profile + +For each reported result: +1. How many independent runs? +2. What is the standard deviation across runs? +3. Does the claimed improvement exceed the noise floor? +4. Are confidence intervals reported? +5. What sources of nondeterminism exist beyond seeds? + +Build the variance profile. + +### Step 3: Analyze Signal vs Noise + +**CRITICAL — Analyze Signal vs Noise:** +For every claimed improvement: +- Is the improvement magnitude larger than the run-to-run standard deviation? +- Could the ranking of methods change under reruns? +- Are the "best" results cherry-picked from multiple seeds? + +### Step 4: Create the Diagram + +Use the mermaid skill conventions to create a stochasticity diagram with: + +**Direction:** `TB` (nondeterminism sources flow down through aggregation to reported results) + +**Subgraphs:** +- NONDETERMINISM SOURCES +- VARIANCE AGGREGATION +- REPORTED RESULTS + +**Node Styling:** +- `stateNode` class: Nondeterminism sources +- `handler` class: Aggregation methods +- `output` class: Reported results +- `gap` class: Unreported variance or single-run results +- `detector` class: Confidence intervals and statistical tests +- `cli` class: Seed management + +### Step 5: Write Output + +Write the diagram to: `{{AUTOSKILLIT_TEMP}}/exp-lens-variance-stability/exp_diag_variance_stability_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +--- + +## Output Template + +```markdown +# Variance Stability Analysis: {Experiment Name} + +**Lens:** Variance Stability (Stability) +**Question:** Is the signal larger than the noise? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Variance Profile + +| Experiment | N Runs | Mean | Std | CI | Signal > Noise? | +|------------|--------|------|-----|----|-----------------| +| {experiment} | {n} | {mean} | {std} | {CI or "Not reported"} | {Yes/No/Unclear} | + +## Nondeterminism Inventory + +| Source | Type | Controlled? | Impact | +|--------|------|-------------|--------| +| {source} | {seed/hardware/async/etc} | {Yes/No/Partial} | {Low/Medium/High} | + +## Stochasticity Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +graph TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff; + classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000; + classDef integration fill:#c62828,stroke:#ef9a9a,stroke-width:2px,color:#fff; + + subgraph NDSources ["NONDETERMINISM SOURCES"] + direction TB + SEED["Random Seed
    ━━━━━━━━━━
    Controlled via
    seed management"] + HW["Hardware Variance
    ━━━━━━━━━━
    GPU/CPU ordering
    differences"] + ASYNC["Async Operations
    ━━━━━━━━━━
    Thread/process
    race conditions"] + end + + subgraph Aggregation ["VARIANCE AGGREGATION"] + direction TB + MULTI["Multiple Runs
    ━━━━━━━━━━
    N independent
    repetitions"] + CI["Confidence Interval
    ━━━━━━━━━━
    Statistical bounds
    on estimates"] + end + + subgraph Results ["REPORTED RESULTS"] + direction TB + RESULT["Reported Result
    ━━━━━━━━━━
    Mean ± std
    with CI"] + SINGLE["Single-Run Result
    ━━━━━━━━━━
    No variance
    reported"] + end + + SEED --> MULTI + HW --> MULTI + ASYNC --> MULTI + MULTI --> CI + CI --> RESULT + MULTI --> SINGLE + + %% CLASS ASSIGNMENTS %% + class SEED cli; + class HW,ASYNC stateNode; + class MULTI handler; + class CI detector; + class RESULT output; + class SINGLE gap; +``` + +## Seed Sensitivity Assessment + +| Seed | Run Result | Rank Among Methods | +|------|-----------|-------------------| +| {seed} | {result} | {rank} | + +## Reporting Completeness Checklist + +- [ ] Number of runs reported per condition +- [ ] Standard deviation or standard error reported +- [ ] Confidence intervals reported +- [ ] All seeds or seed range disclosed +- [ ] Nondeterminism sources acknowledged + +## Key Findings + +- {Description of whether signals exceed noise and reporting completeness} +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table + +--- + +## Related Skills + +- `/autoskillit:make-experiment-diag` - Parent skill for lens selection +- `/autoskillit:mermaid` - MUST BE LOADED before creating diagram +- `/autoskillit:exp-lens-reproducibility-artifacts` - For environment and artifact reproducibility +- `/autoskillit:exp-lens-error-budget` - For systematic error and bias analysis diff --git a/src/autoskillit/skills_extended/generate-report/SKILL.md b/src/autoskillit/skills_extended/generate-report/SKILL.md new file mode 100644 index 0000000000..9286e1ef95 --- /dev/null +++ b/src/autoskillit/skills_extended/generate-report/SKILL.md @@ -0,0 +1,413 @@ +--- +name: generate-report +categories: [research] +description: Synthesize experiment results into a structured research report in the research/ folder. Supports --inconclusive flag. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: generate-report] Writing research report...'" + once: true +--- + +# Write Report Skill + +Synthesize scope findings, experiment design, and experiment results into a +structured research report. The report is committed to the `research/` directory +in the worktree and becomes the primary deliverable of the research recipe. + +This skill handles both conclusive and inconclusive outcomes — inconclusive +results are valid findings, not failures. + +## When to Use + +- As the reporting step of the `research` recipe (phase 2) +- After `/autoskillit:run-experiment` has produced results (or after retry exhaustion) + +## Arguments + +``` +/autoskillit:generate-report {worktree_path} {results_path} [--inconclusive] +``` + +- `{worktree_path}` — Absolute path to the worktree (required). First path-like + token after the skill name. +- `{results_path}` — Absolute path to the experiment results file (required). + Second path-like token. +- `--inconclusive` — Optional flag indicating experiments were inconclusive + (retry exhaustion or insufficient evidence). When present, the report + emphasizes what was learned and why evidence was insufficient, rather than + framing as a failure. +- `--output-mode {local|pr}` — Optional. When 'local', the report header must include an + issue reference link if `--issue-url` is also provided. +- `--issue-url {url}` — Optional. GitHub issue URL. When output_mode=local and this is + supplied, inject a blockquote reference at the top of report.md. In pr mode, skip — + the PR body handles the issue link. + +## Inputs + +In addition to the arguments above, this skill reads from the worktree: +- `${RESEARCH_DIR}/visualization-plan.md` — figure inventory and `yaml:figure-spec` + blocks produced by `plan-visualization`. Read in Step 2.5 to drive plot generation. +- `${RESEARCH_DIR}/report-plan.md` — section outline mapping figure IDs to report + sections. Read in Step 3 to place figure references correctly. + +## Critical Constraints + +**NEVER:** +- Modify source code files outside the `research/` directory +- Fabricate or embellish results — report exactly what was measured +- Omit the methodology section — reproducibility requires it +- Frame inconclusive results as failures — they are valid findings +- Create the report outside the worktree's `research/` directory + +**ALWAYS:** +- Use `model: "sonnet"` when spawning all subagents via the Task tool +- Write the report to `research/` in the worktree root +- Include experiment scripts inline as fenced code blocks for reproducibility +- Commit the report to the worktree before returning +- Include a "What We Learned" section regardless of outcome +- Link back to the originating GitHub issue if an issue number is available + +## Context Limit Behavior + +When context is exhausted mid-execution, the report may be partially written +but not yet committed to the worktree. The recipe routes to `on_context_limit: test`, +preserving whatever was written. + +**Before emitting structured output tokens:** +1. Run `git -C {worktree_path} status --porcelain` +2. If any files are dirty: `git -C {worktree_path} add -A && git -C {worktree_path} commit -m "chore: commit partial report before context limit"` +3. Only then emit the structured output tokens + +This ensures the partial report is committed and the downstream test step can +evaluate whatever research output was produced. + +## Workflow + +### Step 1 — Gather All Artifacts + +Read all available artifacts from the worktree: +1. Experiment plan: `{{AUTOSKILLIT_TEMP}}/experiment-plan.md` +2. Scope report: `{{AUTOSKILLIT_TEMP}}/scope/` (if available in worktree) +3. Experiment results: `{results_path}` +4. Any raw data files in `{{AUTOSKILLIT_TEMP}}/run-experiment/` +5. Standardized metrics: scan `{{AUTOSKILLIT_TEMP}}/run-experiment/` for + `*_metrics.json` files (e.g., `accuracy_metrics.json`, `parity_metrics.json`). + If present, read them — they will populate the Standardized Metrics Assessment + section of the report. +6. Experiment code: scan the worktree for scripts, fixtures, and tools + added during implementation + +### Step 1.5 — Inject Issue Reference Header (local mode only) + +Parse arguments for `--output-mode` and `--issue-url`. + +If `--output-mode local` AND `--issue-url {url}` is present: +1. Parse the issue number from the URL (last numeric path segment). +2. Prepend this line to the **top** of `report.md`, before the title: + ``` + > This research addresses [Issue #{N}]({url}) + + ``` + (Include a blank line after the blockquote before the title.) + +In pr mode: skip this step entirely — the PR body contains the issue link. + +### Step 2 — Determine Report Type + +Based on the `--inconclusive` flag and the experiment results status: + +**Conclusive (no --inconclusive flag):** +- Full report with definitive findings +- Clear answer to the research question +- Recommendations based on evidence + +**Inconclusive (--inconclusive flag or status = INCONCLUSIVE/FAILED):** +- Read `visualization-plan.md` if it exists. +- For each figure-spec: if `data_source.path` exists and has data, generate + the plot (run Step 2.5 normally for that figure). +- If data is absent: emit the placeholder block instead of the figure: + ``` + > **[Figure {id} not produced]** — experiment concluded inconclusively; + > data required for this figure was not produced. + ``` + Preserve the original `yaml:figure-spec` YAML block in the report for + reproducibility, indented under a `
    ` collapsible. +- Emphasize what was learned despite lack of definitive answer +- Document boundary conditions established +- Clearly state what additional work would produce a conclusive result +- Distinguish between "negative result" (evidence against hypothesis) and + "inconclusive" (insufficient evidence either way) + +### Step 2.5 — Produce Visualizations + +If `${RESEARCH_DIR}/visualization-plan.md` exists: + +1. Read `visualization-plan.md`. If it contains zero figure specs (empty plan), + skip all sub-steps and proceed to Step 3. + +2. Identify the experiment's Docker image. The image tag is `research-{slug}` where + `{slug}` is the experiment directory name. Verify the image exists: + ```bash + docker image inspect "research-{slug}" > /dev/null 2>&1 || \ + (cd "${RESEARCH_DIR}" && docker build --build-arg MAMBA_ENV={slug} -t "research-{slug}" .) + ``` + +3. For each `yaml:figure-spec` block in `visualization-plan.md`: + a. Write a Python plotting script to + `${RESEARCH_DIR}/scripts/fig{N}_{slug}.py` + that reads from `data_source.path` (or scans `results/` and `data/` if + the path does not exist — treat `data_source.path` as a hint). + b. Run the script inside the experiment container (volume-mount research dir): + ```bash + docker run --rm \ + -v "${RESEARCH_DIR}:/workspace" \ + "research-{slug}" \ + bash -c "pip install --quiet matplotlib seaborn plotly kaleido 2>/dev/null; \ + python /workspace/scripts/fig${N}_${slug}.py" + ``` + c. Confirm output exists at `${RESEARCH_DIR}/images/fig-${N}.{png,svg}`. + d. On failure: emit `MISSING: fig-${N} — {error summary}` to stdout and + continue with remaining figures. Do not abort the skill. + +4. Commit scripts and images (if any were produced): + ```bash + git add research/ && git commit -m "Add visualization scripts and figures" + ``` + +### Step 3 — Write Report + +### Domain-Adaptive Section Ordering + +The default section order below suits software engineering and computational +research. Adjust to match domain conventions when the research question +originates from a non-engineering field: + +- **Default (engineering / computational):** Executive Summary → Background and + Research Question → Methodology → Results → Observations → Analysis → + What We Learned → Conclusions → Recommendations +- **Biology / biomedical:** Adapted from IMRaD — Background → Methodology → + Results → Discussion and Future Directions → What We Learned. Use "Discussion + and Future Directions" instead of "Recommendations". For journals that move + Methods to supplementary material (e.g., Nature style), omit the Methodology + section from the main body and note its location. +- **Economics / social science:** Background → Methodology → Results → Analysis → + Discussion and Future Directions → What We Learned. + +**Rules:** +- Executive Summary is always first; Appendices are always last. Exception: for + academic journal submissions (biology, medical, social science) where Executive + Summary is not a standard format, replace it with a structured Abstract at the + document start. +- All mandatory sections (Data Scope Statement, Metrics Provenance Check, Gate + Enforcement, What We Learned) must appear regardless of reordering. +- When reordering, only the section position changes — content requirements are + unchanged. + +Create the report directory and file: +``` +research/YYYY-MM-DD-{slug}/ + report.md # The main research report + scripts/ # Extracted experiment scripts (optional, if complex) +``` + +The `{slug}` is a kebab-case summary of the research topic (max 40 chars). + +The report structure: + +```markdown +# {Research Title} + +> Research report for [Issue #{N}]({issue_url}) — {date} + +## Executive Summary + +### Data Scope Statement (mandatory — include at start of Executive Summary) + +Every report must begin the Executive Summary with a Data Scope Statement: + +> **Data Scope:** All benchmarks were conducted on {comma-separated list of data types +> used, e.g., "synthetic Gaussian blobs (10K–100K points)"}. {Domain target} data was +> {present and used | absent — all results derive from synthetic data | partial — only +> {subset} was available}. + +**Rules:** +- If ALL benchmarks used ONLY synthetic data and the research task was domain-specific: + state this explicitly. Do not claim domain-specific performance improvements derived + from synthetic data without this qualifier. +- If some hypotheses were marked N/A or BLOCKED due to missing data: state which + hypotheses were affected and why. +- Read the experiment plan's `data_manifest` (if available) to determine what data was + planned vs. what was actually used. + +{2-3 paragraph overview: what was investigated, key methodology, headline +finding, and recommendation. Written last, placed first.} + +## Background and Research Question + +{Context: why this investigation was initiated, what decision it informs, +what was known before this experiment.} + +## Methodology + +### Experimental Design +{From the experiment design: hypothesis, variables, controls. Include +enough detail for independent reproduction.} + +### Environment +- **Repository commit:** {output of `git rev-parse HEAD` — the exact commit this experiment ran against} +- **Branch:** {current branch name} +- **Package versions:** {output of the project's package manager — e.g., `pip freeze`, `conda list`, or the contents of lock files (e.g., `requirements.txt`, `environment.yml`). Include ALL relevant dependency versions, not just top-level.} +- **Hardware/OS:** {if relevant to the experiment} +- **Custom environment:** {if a micromamba/conda environment.yml was used, note it and its location} + +### Procedure +{Step-by-step description of what was executed.} + +## Results + +{Present data from the experiment. Use tables, code blocks, or whatever +format best represents the measurements. No interpretation in this +section — just facts.} + +### Figure References + +Reference figures by ID and caption only. NEVER embed images with `![](...)` syntax. +The HTML report rendered by `bundle-local-report` reads `yaml:figure-spec` metadata +and inserts `` tags at the correct sections. Markdown prose uses: +> "Figure 1 shows ..." or "(see Figure 1)" + +### Metrics Provenance Check (mandatory before including any metrics) + +Before including data from any `*_metrics.json` file: + +1. **Check generation timestamp**: The file's modification time must be within the + current experiment's execution window. If the file predates the experiment run, + it is stale. +2. **Check content relevance**: Verify the metrics file's contents relate to the + hypotheses under test. If a metrics file contains data from a different subsystem + or experiment, it is irrelevant. +3. **Disposition:** + - **Current and relevant**: Include normally. + - **Stale**: Disclose in the report: "Note: {filename} predates the current + experiment run and was not regenerated. Excluded from analysis." + - **Irrelevant**: Disclose: "Note: {filename} contains {description of actual + contents} which is unrelated to the hypotheses under test. Excluded." + - **NEVER** silently drop a metrics file. Always disclose the reason for exclusion. + +### Standardized Metrics + +{Include this section when `*_metrics.json` files are present in +`{{AUTOSKILLIT_TEMP}}/run-experiment/`. Omit entirely if no metrics JSON was produced.} + +| Metric | Dimension | Dataset | Value | Threshold | Status | +|--------|-----------|---------|-------|-----------|--------| +| {metric_name} | {Accuracy/Parity} | {dataset} | {value} | {threshold} | ✅ PASS / ❌ FAIL | + +{If any metrics failed: note which solver level or dataset showed the failure +and whether it is within acceptable range for the experiment's scope.} + +## Observations + +{Notable patterns, anomalies, unexpected behaviors discovered during +the experiment.} + +### Gate Enforcement (mandatory for all hypothesis results) + +When reporting on pre-specified hypothesis gates: + +1. **Use the gate threshold from the experiment plan**, not a different hypothesis's + threshold. Each hypothesis has its own pre-specified success criterion — do not + conflate them. +2. **When a gate is NOT met**: State this as a failure. Example: "H6 targeted ≥3× + speedup at n=100K. Measured: 2.04× at n=50K (estimated ~1.95× at n=100K). **FAIL.**" +3. **When recommending GO**: The GO recommendation must reference the specific gate(s) + that were met and their measured values. A GO on H1 (which has a ≥1.5× threshold) + does not satisfy H6 (which has a ≥3× threshold). +4. **NEVER** silently substitute one hypothesis's threshold for another. If H6's gate + is not met, H6 is a FAIL regardless of whether H1's lower threshold was met by the + same measurement. + +## Analysis + +{Interpret the results. Compare against the hypothesis. Explain anomalies. +Connect findings to the original research question. Include statistical +analysis if relevant to the experiment type.} + +## What We Learned + +{Regardless of outcome, document:} +- {Key insight 1} +- {Key insight 2} +- {Boundary conditions established} +- {Methodology learnings for future experiments} + +## Conclusions + +{Direct answer to the research question.} + +## Recommendations + +*For biology and social science domains, use "Discussion and Future Directions" as the section title instead.* + +{Actionable next steps based on findings — what to keep, revert, modify, +or investigate further. Include justification for each recommendation. +In non-engineering domains, frame this section as "Discussion and Future Directions": +interpret findings in the context of existing literature, explain implications, +and propose follow-on studies rather than prescriptive next steps.} + +## Data Availability + +{Optional — include when required by the target journal or domain conventions +(biology, medical, social science). State where datasets, code, and supplementary +materials are available, or explain any access restrictions (e.g., patient data, +proprietary datasets). Omit this section for internal engineering reports.} + +## Appendix: Experiment Scripts + +{Include key experiment scripts as fenced code blocks. These are preserved +for reproducibility even after the worktree is cleaned up.} + +### {script_name.ext} +```{language} +{script content} +``` + +## Appendix: Visualization Scripts + +{Enumerate each script in `${RESEARCH_DIR}/scripts/fig*.py` produced during +Step 2.5. Include the full script as a fenced Python code block. These are +preserved for figure reproducibility even after the worktree is cleaned up.} + +## Appendix: Raw Data + +{If raw data is small enough, include inline. Otherwise, reference the +files committed alongside this report.} +``` + +### Step 4 — Commit and Emit + +1. Create the research directory in the worktree: + `mkdir -p research/YYYY-MM-DD-{slug}/` +2. Write `report.md` to that directory. +3. If experiment scripts are complex (>50 lines), also save them as separate + files in `research/YYYY-MM-DD-{slug}/scripts/`. +4. Commit to the worktree: + ``` + git add research/ + git commit -m "Add research report: {brief title}" + ``` + +After committing, emit the structured output token as the very last line of +your text output: + +> **IMPORTANT:** Emit the structured output tokens as **literal plain text with no +> markdown formatting on the token names**. Do not wrap token names in `**bold**`, +> `*italic*`, or any other markdown. The adjudicator performs a regex match on the +> exact token name — decorators cause match failure. + +``` +report_path = {absolute_path_to_report.md} +``` diff --git a/src/autoskillit/skills_extended/implement-experiment/SKILL.md b/src/autoskillit/skills_extended/implement-experiment/SKILL.md new file mode 100644 index 0000000000..51bbf16e96 --- /dev/null +++ b/src/autoskillit/skills_extended/implement-experiment/SKILL.md @@ -0,0 +1,333 @@ +--- +name: implement-experiment +categories: [research] +description: Deploy experiment artifacts in an isolated git worktree following an approved experiment plan, with per-phase commits. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: implement-experiment] Implementing experiment...'" + once: true +--- + +# Implement Experiment Skill + +Implement an experiment plan in an isolated git worktree. All experiment +artifacts are created inside a single self-contained folder under `research/`. +The worktree is left intact for the orchestrator to run the experiment, test, +and merge separately. + +This skill reads the experiment plan and follows its implementation phases. +The plan specifies the directory layout, what scripts to write, what data to +generate, and what environment to set up. This skill builds all of it. + +## When to Use + +- As the implementation step of the `research` recipe (phase 2) +- After the experiment plan has been approved via GitHub issue + +## Arguments + +``` +/autoskillit:implement-experiment {plan_path} +``` + +`{plan_path}` — Absolute path to the experiment plan file (required). Scan +tokens after the skill name for the first path-like token (starts with `/`, +`./`, or `.autoskillit/`). + +## Critical Constraints + +**NEVER:** +- Implement without first exploring affected systems with subagents +- Implement in the main working directory (always use the worktree) +- Force push or perform destructive git operations +- Merge the worktree branch into any branch +- Delete or remove the worktree +- Run the full test suite — `pytest` with no args or targeting the entire repo + (the orchestrator handles full test execution via test_check) +- Create experiment files outside the planned `research/` subfolder +- Execute `git merge` commands (all branch content must be applied via + `git cherry-pick` or `git checkout -- `) + +**ALWAYS:** +- Create a new worktree from the current branch +- Use subagents to deeply understand the codebase context BEFORE implementing +- Use `model: "sonnet"` when spawning all subagents via the Task tool +- Follow the implementation phases from the experiment plan +- Put all experiment artifacts in one self-contained `research/` subfolder +- Commit per phase with descriptive messages +- Leave the worktree intact when done +- Write `tests/test_{script_name}.py` alongside each experiment script created in Step 4 +- Run `pytest --collect-only` after creating tests to verify discovery before committing + +## Context Limit Behavior + +If this skill hits the Claude context limit mid-execution, the headless session +terminates with `needs_retry=true` in the tool response. The worktree remains +intact on disk with all commits made up to that point. + +The orchestrator should NOT retry this skill — retrying creates a brand-new +worktree, discarding all partial progress. Instead, route to the next step +(run-experiment) which can work with whatever was committed. + +## Workflow + +### Step 0 — Validate Prerequisites + +1. Extract and verify the plan path using **path detection**: scan the tokens + after the skill name for the first one that starts with `/`, `./`, + `{{AUTOSKILLIT_TEMP}}/`, or `.autoskillit/` — that token is the plan path. + Ignore any non-path words that appear before it. If no path-like token is + found, treat the entire argument string as pasted plan content. Verify the + resolved file exists before proceeding. +2. Read the experiment plan. Extract: + - The experiment directory name (`research/YYYY-MM-DD-{slug}/`) + - The planned directory layout + - Implementation phases + - Environment requirements (whether an `environment.yml` is needed) + - What scripts and artifacts to create +3. Check `git status --porcelain` — if dirty, warn user. + +### Step 1 — Create Git Worktree + +```bash +CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD) +WORKTREE_NAME="research-$(date +%Y%m%d-%H%M%S)" +WORKTREE_PATH="../worktrees/${WORKTREE_NAME}" +git worktree add -b "${WORKTREE_NAME}" "${WORKTREE_PATH}" +WORKTREE_PATH="$(cd "${WORKTREE_PATH}" && pwd)" + +# Record the base branch for reliable discovery: +mkdir -p "{{AUTOSKILLIT_TEMP}}/worktrees/${WORKTREE_NAME}" +echo "${CURRENT_BRANCH}" > "{{AUTOSKILLIT_TEMP}}/worktrees/${WORKTREE_NAME}/base-branch" + +# Set upstream tracking if possible: +if ! git fetch origin "${CURRENT_BRANCH}" 2>/dev/null; then + echo "NOTE: Branch '${CURRENT_BRANCH}' has no remote tracking ref on origin." +fi +if ! git -C "${WORKTREE_PATH}" branch --set-upstream-to="origin/${CURRENT_BRANCH}" "${WORKTREE_NAME}" 2>/dev/null; then + echo "NOTE: Could not set upstream tracking for '${WORKTREE_NAME}' → 'origin/${CURRENT_BRANCH}'." +fi +``` + +### Step 1 (cont.) — Emit Structured Tokens Early + +Immediately after the worktree is created, output these tokens so the +execution layer can capture them even if context is exhausted later: + +> **IMPORTANT:** Emit the structured output tokens as **literal plain text with no +> markdown formatting on the token names**. Do not wrap token names in `**bold**`, +> `*italic*`, or any other markdown. The adjudicator performs a regex match on the +> exact token name — decorators cause match failure. + +``` +worktree_path = ${WORKTREE_PATH} +branch_name = ${WORKTREE_NAME} +``` + +### Step 2 — Deep Context Understanding (Subagents) + +Before implementing anything, launch subagents (model: "sonnet") to understand +the codebase context needed for the experiment. The following are **minimum +required** — launch as many additional subagents as needed. + +**Minimum subagents:** + +**Subagent A — Codebase Context:** +> Understand the code areas the experiment will interact with. Identify +> APIs, data structures, functions, and modules that experiment scripts +> will need to reference or call. Report imports, interfaces, and patterns +> the scripts should follow. + +**Subagent B — Compute Environment Requirements:** +> Assess the compute environment needed to execute the experiment. Determine +> what system-level tools, libraries, or runtime capabilities the experiment +> requires. If the experiment plan specifies an environment.yml, examine it — +> identify any non-standard dependencies that need system packages installed +> alongside the micromamba environment. Report what the Dockerfile or +> container setup needs to provide beyond the base micromamba image. + +**Additional subagents (launch as many as needed):** +- Deeper exploration of specific code areas referenced in the plan +- Understanding specific APIs, types, or interfaces the scripts will use +- Any other codebase investigation needed to write correct experiment code + +### Step 3 — Set Up Container Environment + +The research worktree is isolated via Docker. All experiment code runs inside +a container built from the experiment's `environment.yml`. Nothing is installed +on the host. + +**3a — Write the Dockerfile:** + +Locate the `environment.yml` in the planned research directory. The YAML's +`name:` field is the `MAMBA_ENV` slug (e.g., `2026-04-13-my-experiment`). + +Write `${RESEARCH_DIR}/Dockerfile` based on the canonical template at +`src/autoskillit/assets/research/Dockerfile.template` in the project root, +substituting `${MAMBA_ENV}` with the actual environment name from `environment.yml`: + +```dockerfile +FROM mambaorg/micromamba:1.0-bullseye-slim +SHELL ["/bin/bash", "-c"] +ARG MAMBA_ENV="{slug}" + +USER root +RUN apt-get --allow-releaseinfo-change update \ + && apt-get install -y --no-install-recommends procps git curl build-essential \ + && apt-get clean -y && rm -rf /var/lib/apt/lists/* + +RUN curl -sL https://taskfile.dev/install.sh | sh -s -- -b /usr/local/bin + +RUN rm -f /root/.bashrc \ + && echo "source /etc/container.bashrc" >> /etc/bash.bashrc \ + && echo "set +u" > /etc/container.bashrc \ + && echo 'eval "$(micromamba shell hook --shell=bash)"' >> /etc/container.bashrc + +ENV BASH_ENV=/etc/container.bashrc +ENV ENV=/etc/container.bashrc + +COPY {slug}.yaml /opt/research/env/ +RUN micromamba create -f /opt/research/env/{slug}.yaml && micromamba clean -afy +RUN echo "micromamba activate {slug}" >> /etc/container.bashrc +``` + +**3b — Write `${RESEARCH_DIR}/Taskfile.yml`:** + +```yaml +version: '3' +vars: + SLUG: "{slug}" + IMAGE: "research-{{.SLUG}}" + RESEARCH_DIR: + sh: pwd + +tasks: + build-env: + desc: Build Docker image for this experiment + cmds: + - docker build --build-arg MAMBA_ENV={{.SLUG}} -t {{.IMAGE}} . + dir: "{{.RESEARCH_DIR}}" + + run-experiment: + desc: Run experiment inside container (volume-mounts research dir) + cmds: + - docker run --rm -v "{{.RESEARCH_DIR}}:/workspace" {{.IMAGE}} bash -c "cd /workspace && python scripts/run.py" + dir: "{{.RESEARCH_DIR}}" + + test: + desc: Run pytest test suite inside container + cmds: + - docker run --rm -v "{{.RESEARCH_DIR}}:/workspace" {{.IMAGE}} bash -c "cd /workspace && pytest tests/ -v" + dir: "{{.RESEARCH_DIR}}" +``` + +Adjust the `run-experiment` command to match the actual entry-point script from the experiment plan. + +**3c — Build the Docker image:** + +```bash +cd "${RESEARCH_DIR}" +docker build --build-arg MAMBA_ENV={slug} -t "research-{slug}" . +``` + +Verify the build succeeds before proceeding. If the build fails due to missing +system packages, add them to the `apt-get install` layer and rebuild. + +**All commands from this point must run from `${WORKTREE_PATH}`.** Use absolute +paths to avoid CWD drift across Bash tool calls. + +### Step 4 — Implement Phase by Phase + +Follow the implementation phases from the experiment plan. The plan specifies +what to create in each phase. Typical phases include: + +1. **Directory structure and environment** — create the `research/` subfolder + layout. If the plan specifies an `environment.yml`, create it and build + the environment with micromamba. +2. **Data generation** — create data generation scripts, generate datasets, + verify data properties. +3. **Experiment scripts** — create measurement, benchmark, and analysis + scripts. Verify they compile/run. +4. **Dry run** — execute the experiment with minimal inputs to verify the + pipeline works end-to-end. + +For each phase, begin implementation immediately (no announcement): +1. Implement the changes +2. Run any verification the plan specifies +3. Commit with a descriptive message. If the project has pre-commit hooks, + run `pre-commit run --all-files` and stage any auto-fixed files before + each commit. + +**Test creation (required alongside each script phase):** + +When implementing experiment scripts in Phases 2 and 3, also create a corresponding +`tests/test_{script_name}.py` for each script: + +1. Create `{WORKTREE_PATH}/research/{slug}/tests/` and `conftest.py` if not yet present +2. For each script (e.g., `analysis.py`), create `tests/test_analysis.py` covering: + - Data loads without error and has the expected shape/type + - Key output values fall in expected ranges (sanity checks, not exact match) + - At least one test per public function or entry point +3. Run `pytest --collect-only {WORKTREE_PATH}/research/{slug}/tests/` to confirm + pytest can discover all test files. Fix any import errors before committing. + +The plan is the authority on what phases exist and what each phase creates. +Follow it. + +### Step 5 — Copy Experiment Plan into Research Folder + +Copy the experiment plan into the research folder for reference: + +```bash +RESEARCH_DIR=$(ls -d "${WORKTREE_PATH}"/research/*/ 2>/dev/null | head -1) +cp "${PLAN_PATH}" "${RESEARCH_DIR}experiment-plan.md" +git -C "${WORKTREE_PATH}" add research/ && git -C "${WORKTREE_PATH}" commit -m "Add experiment plan to research folder" +``` + +### Step 6 — Pre-commit Checks (Conditional) + +Pre-commit is only relevant when the worktree has a `.pre-commit-config.yaml`. +Research worktrees do not — skip pre-commit for them. + +```bash +if [ -f "${WORKTREE_PATH}/.pre-commit-config.yaml" ]; then + cd "${WORKTREE_PATH}" && pre-commit run --all-files + # Fix any formatting or linting issues, then re-stage and re-commit. +else + echo "No .pre-commit-config.yaml found — skipping pre-commit (research worktree)." +fi +``` + +### Step 7 — Handoff Report + +Output to terminal: +- **Worktree path:** `${WORKTREE_PATH}` +- **Branch name:** `${WORKTREE_NAME}` +- **Base branch:** the branch the worktree was created from +- **Research folder:** the `research/` subfolder created inside the worktree +- **Summary:** list of implemented phases and artifacts created + +Explicitly state: "Worktree left intact for orchestrator to run experiment and test." + +Then emit these structured output tokens: + +> **IMPORTANT:** Emit the structured output tokens as **literal plain text with no +> markdown formatting on the token names**. Do not wrap token names in `**bold**`, +> `*italic*`, or any other markdown. The adjudicator performs a regex match on the +> exact token name — decorators cause match failure. + +``` +worktree_path = ${WORKTREE_PATH} +branch_name = ${WORKTREE_NAME} +``` + +## Error Handling + +- **Worktree creation fails** — check `git worktree list`, suggest `git worktree prune` +- **Environment build fails** — report the error, suggest fixes to environment.yml +- **Script creation fails** — report which phase and why, offer to fix/retry or abort. + Do NOT clean up the worktree. +- **Pre-commit fails** — fix formatting/linting issues and re-commit diff --git a/src/autoskillit/skills_extended/implement-worktree-no-merge/SKILL.md b/src/autoskillit/skills_extended/implement-worktree-no-merge/SKILL.md index e30ad275de..c54865f02c 100644 --- a/src/autoskillit/skills_extended/implement-worktree-no-merge/SKILL.md +++ b/src/autoskillit/skills_extended/implement-worktree-no-merge/SKILL.md @@ -68,7 +68,7 @@ Correct orchestration on `needs_retry=true`: ### Step 0: Validate Prerequisites 1. Extract and verify the plan path using **path detection**: scan the tokens - after the skill name for the first one that starts with `/`, `./`, `.autoskillit/temp/`, + after the skill name for the first one that starts with `/`, `./`, `{{AUTOSKILLIT_TEMP}}/`, or `.autoskillit/` — that token is the plan path. Ignore any non-path words that appear before it (orchestrators sometimes prepend descriptive text such as "the verified plan"). If no path-like token is found, treat the entire @@ -84,7 +84,7 @@ Correct orchestration on `needs_retry=true`: 5. **Multi-Part Plan Detection:** Examine the plan filename. If it contains `_part_` (e.g., `_part_a`, `_part_b`, `_part_1`): - Extract the part identifier (A, B, C… or number) from the suffix. - **SCOPE FENCE — MANDATORY:** Before any exploration or implementation begins, output the following constraint: - > "🚧 SCOPE FENCE ACTIVE: I am implementing PART {X} ONLY. I MUST NOT open, read, or execute any other part files, regardless of what I encounter in .autoskillit/temp/ or any other directory. Sibling part files are out of scope for this entire session." + > "🚧 SCOPE FENCE ACTIVE: I am implementing PART {X} ONLY. I MUST NOT open, read, or execute any other part files, regardless of what I encounter in {{AUTOSKILLIT_TEMP}}/ or any other directory. Sibling part files are out of scope for this entire session." - When launching subagents in Step 2, include this fence instruction explicitly in each subagent prompt so that the subagents do not open, read, or reference sibling part files. ### Step 1: Create Git Worktree @@ -98,8 +98,8 @@ WORKTREE_PATH="$(cd "${WORKTREE_PATH}" && pwd)" # Record the base branch in two ways for reliable discovery by retry-worktree: # 1) Write an explicit file store (works with any Git version, works offline) -mkdir -p ".autoskillit/temp/worktrees/${WORKTREE_NAME}" -echo "${CURRENT_BRANCH}" > ".autoskillit/temp/worktrees/${WORKTREE_NAME}/base-branch" +mkdir -p "{{AUTOSKILLIT_TEMP}}/worktrees/${WORKTREE_NAME}" +echo "${CURRENT_BRANCH}" > "{{AUTOSKILLIT_TEMP}}/worktrees/${WORKTREE_NAME}/base-branch" # 2) Set git upstream tracking (requires remote tracking ref in local fetch cache) if ! git fetch origin "${CURRENT_BRANCH}" 2>/dev/null; then echo "NOTE: Branch '${CURRENT_BRANCH}' has no remote tracking ref on origin." @@ -176,14 +176,12 @@ mcp__code-index__set_project_path(path="${WORKTREE_PATH}") ### Step 4: Implement Phase by Phase -For each phase: -1. Announce phase objective and files to modify -2. Implement changes guided by understanding from Step 2 -3. Run per-phase verification if plan specifies it -4. Commit per phase with descriptive messages. If the project has pre-commit +For each phase, begin implementation immediately (no announcement): +1. Implement changes guided by understanding from Step 2 +2. Run per-phase verification if plan specifies it +3. Commit per phase with descriptive messages. If the project has pre-commit hooks, run `pre-commit run --all-files` and stage any auto-fixed files before each commit. -5. Report phase completion Where practical, delegate test updates to subagents to keep main conversation context lean. diff --git a/src/autoskillit/skills_extended/implement-worktree/SKILL.md b/src/autoskillit/skills_extended/implement-worktree/SKILL.md index 3dbbd07baa..a3ac73cedc 100644 --- a/src/autoskillit/skills_extended/implement-worktree/SKILL.md +++ b/src/autoskillit/skills_extended/implement-worktree/SKILL.md @@ -60,7 +60,7 @@ Correct orchestration on `needs_retry=true`: ### Step 0: Validate Prerequisites 1. Extract and verify the plan path using **path detection**: scan the tokens - after the skill name for the first one that starts with `/`, `./`, `.autoskillit/temp/`, + after the skill name for the first one that starts with `/`, `./`, `{{AUTOSKILLIT_TEMP}}/`, or `.autoskillit/` — that token is the plan path. Ignore any non-path words that appear before it. If no path-like token is found, treat the entire argument string as pasted plan content. Verify the resolved file exists before @@ -75,7 +75,7 @@ Correct orchestration on `needs_retry=true`: 5. **Multi-Part Plan Detection:** Examine the plan filename. If it contains `_part_` (e.g., `_part_a`, `_part_b`, `_part_1`): - Extract the part identifier (A, B, C… or number) from the suffix. - **SCOPE FENCE — MANDATORY:** Before any exploration or implementation begins, output the following constraint: - > "🚧 SCOPE FENCE ACTIVE: I am implementing PART {X} ONLY. I MUST NOT open, read, or execute any other part files, regardless of what I encounter in .autoskillit/temp/ or any other directory. Sibling part files are out of scope for this entire session." + > "🚧 SCOPE FENCE ACTIVE: I am implementing PART {X} ONLY. I MUST NOT open, read, or execute any other part files, regardless of what I encounter in {{AUTOSKILLIT_TEMP}}/ or any other directory. Sibling part files are out of scope for this entire session." - When launching subagents in Step 2, include this fence instruction explicitly in each subagent prompt so that the subagents do not open, read, or reference sibling part files. ### Step 1: Create Git Worktree @@ -86,8 +86,8 @@ WORKTREE_NAME="impl-{plan_name}-$(date +%Y%m%d-%H%M%S)" WORKTREE_PATH="../worktrees/${WORKTREE_NAME}" git worktree add -b "${WORKTREE_NAME}" "${WORKTREE_PATH}" WORKTREE_PATH="$(cd "${WORKTREE_PATH}" && pwd)" -mkdir -p ".autoskillit/temp/worktrees/${WORKTREE_NAME}" -echo "${CURRENT_BRANCH}" > ".autoskillit/temp/worktrees/${WORKTREE_NAME}/base-branch" +mkdir -p "{{AUTOSKILLIT_TEMP}}/worktrees/${WORKTREE_NAME}" +echo "${CURRENT_BRANCH}" > "{{AUTOSKILLIT_TEMP}}/worktrees/${WORKTREE_NAME}/base-branch" ``` ### Step 1.5: Initialize Code Index for Original Project @@ -180,7 +180,7 @@ If tests fail, fix the issue and re-run. ### Step 6: Rebase for Squash-and-Merge ```bash -CURRENT_BRANCH=$(cat ".autoskillit/temp/worktrees/${WORKTREE_NAME}/base-branch") +CURRENT_BRANCH=$(cat "{{AUTOSKILLIT_TEMP}}/worktrees/${WORKTREE_NAME}/base-branch") REMOTE=$(git remote get-url upstream >/dev/null 2>&1 && echo upstream || echo origin) git fetch "$REMOTE" git rebase "$REMOTE/${CURRENT_BRANCH}" @@ -198,7 +198,7 @@ Do not merge until user confirms first! Then emit these structured output tokens on their own lines so recipe capture blocks can extract them: ```bash -CURRENT_BRANCH=$(cat ".autoskillit/temp/worktrees/${WORKTREE_NAME}/base-branch") +CURRENT_BRANCH=$(cat "{{AUTOSKILLIT_TEMP}}/worktrees/${WORKTREE_NAME}/base-branch") ``` > **IMPORTANT:** Emit the structured output tokens as **literal plain text with no diff --git a/src/autoskillit/skills_extended/investigate/SKILL.md b/src/autoskillit/skills_extended/investigate/SKILL.md index 05aba3cc0a..a622b700bd 100644 --- a/src/autoskillit/skills_extended/investigate/SKILL.md +++ b/src/autoskillit/skills_extended/investigate/SKILL.md @@ -50,19 +50,18 @@ tool **before** beginning any analysis. Use the returned `content` field as the - Modify any source code files - Suggest backward compatibility solutions - Suggest fallbacks that hide errors -- Create files outside `.autoskillit/temp/investigate/` directory +- Create files outside `{{AUTOSKILLIT_TEMP}}/investigate/` directory - Choose or accept approaches, solutions, and/or fixes that are chosen simply because they are easier **ALWAYS:** - Use subagents for parallel exploration - Use `model: "sonnet"` when spawning all subagents via the Task tool -- Write findings as a markdown report with unique name to `.autoskillit/temp/investigate/` directory (relative to the current working directory) +- Write findings as a markdown report with unique name to `{{AUTOSKILLIT_TEMP}}/investigate/` directory (relative to the current working directory) - After writing the investigation report, emit the **absolute path** as a structured output - token immediately before `%%ORDER_UP%%`. Resolve the relative `.autoskillit/temp/investigate/...` + token as your final output. Resolve the relative `{{AUTOSKILLIT_TEMP}}/investigate/...` save path to absolute by prepending the full CWD: ``` - investigation_path = /absolute/cwd/.autoskillit/temp/investigate/{filename}.md - %%ORDER_UP%% + investigation_path = /absolute/cwd/{{AUTOSKILLIT_TEMP}}/investigate/{filename}.md ``` This token is MANDATORY — the pipeline cannot proceed without it. - Identify how tests missed the issue (if applicable) @@ -72,7 +71,7 @@ tool **before** beginning any analysis. Use the returned `content` field as the ## Investigation Workflow **Path-existence guard:** Before issuing a `Read` call on a path that is not guaranteed to -exist (e.g., plan file arguments, `.autoskillit/temp/investigate/` reports, external file references), use +exist (e.g., plan file arguments, `{{AUTOSKILLIT_TEMP}}/investigate/` reports, external file references), use `Glob` or `ls` to confirm the path exists first. This prevents ENOENT errors that cascade into sibling parallel-call cancellations. @@ -158,12 +157,71 @@ After subagents complete, consolidate into structured findings: 4. **Data Flow**: How data moves through the system 5. **Test Gap Analysis**: Why tests didn't catch this 6. **Similar Patterns**: How similar issues are handled elsewhere -7. **External Research**: Relevant findings from web search (if applicable) -8. **Recommendations**: Suggested approaches (NOT implementations) +7. **Historical Context**: Whether this root cause has been investigated or fixed before (populated by Step 3.5) +8. **External Research**: Relevant findings from web search (if applicable) +9. **Recommendations**: Suggested approaches (NOT implementations) + +### Step 3.5 — Historical Recurrence Check + +Before writing the report, check whether the root cause identified in Step 3 has been investigated or fixed before. This catches recurring bugs where a prior fix was incomplete, symptom-only, or applied at the wrong layer. Zero overhead for first-occurrence bugs: if nothing matches, skip the analysis subagent and record a single-line result. + +#### Part A: Mine Past Investigation Logs + +Derive the Claude project log directory from the current working directory: + +```bash +PROJECT_PATH=$(pwd) +LOG_DIR="$HOME/.claude/projects/-${PROJECT_PATH//\//-}" +LOG_DIR="${LOG_DIR//--/-}" +``` + +Search for `.jsonl` files containing prior `/autoskillit:investigate` invocations, **excluding subagent log subdirectories** (`*/subagents/*`) so prior subagent conversations are not double-counted: + +```bash +find "$LOG_DIR" -name "*.jsonl" -not -path "*/subagents/*" -print0 | \ + xargs -0 grep -l '/autoskillit:investigate' 2>/dev/null +``` + +For each matching log file, extract the investigation topic, root cause conclusion, and affected components by scanning for keywords `"root cause"`, `"Root Cause"`, `"fix"`, and `"summary"` in assistant messages. Compare against the current investigation's root cause and affected components — overlapping components or error patterns indicate a recurrence. + +#### Part B: Check Git History for Prior Fix Commits + +Using the affected components from Step 3, extract the primary source file paths. Then search bounded recent history (last 100 commits) for commits whose messages signal a prior fix or revert on those files: + +> `{AFFECTED_FILES}` expands to a space-separated list of file paths relative to the repo root (e.g. `src/autoskillit/execution/headless.py tests/execution/test_headless.py`). Pass each path as a separate argument — do not wrap the list in quotes as a single string. + +```bash +git log --oneline -100 --format="%H %s" \ + --grep="fix\|revert\|remove\|replace" -- {AFFECTED_FILES} +``` + +For each matching commit, read the diff to check for symbol-level overlap with the current root cause: + +```bash +git show {HASH} -- {AFFECTED_FILES} +``` + +Cross-reference: if a commit message references the same error type, component name, or function that the current investigation identified as the root cause, treat it as a prior fix for the same or a closely related issue. + +#### Part C: Conditional Analysis (only if history found) + +If Part A or Part B found matches, spawn a single subagent (using `model: "sonnet"` via the Task tool) to: + +- Read the prior fix diffs via `git show {commit_hash}` +- Read any prior investigation report files discovered during log scanning +- Compare the prior fix approach against the current root cause +- Identify what the prior fix missed (incomplete coverage, wrong layer, symptom-only fix, missing regression test) +- Determine whether this represents a recurring pattern that needs architectural remediation + +If neither Part A nor Part B produced matches, skip the subagent entirely and record: **"No prior investigations or fixes found for this root cause."** This guarantees zero overhead for first-occurrence bugs. + +#### Rectify Flag + +When prior fixes are found and the analysis shows the root cause is recurring, explicitly flag: *"This is a recurring pattern — consider running `/autoskillit:rectify` for architectural immunity after resolving the immediate issue."* ### Step 4: Write Report -Write findings to: `.autoskillit/temp/investigate/investigation_{topic}_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Write findings to: `{{AUTOSKILLIT_TEMP}}/investigate/investigation_{topic}_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) Report structure: ```markdown @@ -191,6 +249,15 @@ Report structure: ## Similar Patterns {How similar scenarios are handled elsewhere} +## Historical Context +{If prior fixes found:} +- Prior investigation dates and report paths +- Prior fix commits/PRs with hashes and summaries +- Analysis of why prior fixes were insufficient +- Whether this represents a recurring pattern (flag for /autoskillit:rectify) +{If no prior history:} +No prior investigations or fixes found for this root cause. + ## External Research {Relevant findings from web search - library bugs, known issues, documentation insights} {Include source URLs for reference} diff --git a/src/autoskillit/skills_extended/issue-splitter/SKILL.md b/src/autoskillit/skills_extended/issue-splitter/SKILL.md index ce52a400e1..b40299a40c 100644 --- a/src/autoskillit/skills_extended/issue-splitter/SKILL.md +++ b/src/autoskillit/skills_extended/issue-splitter/SKILL.md @@ -44,7 +44,7 @@ This skill is intentionally lightweight: concern analysis is performed as in-con - Use subagents — concern analysis is in-context LLM reasoning, not subagent delegation - Close the parent issue — it becomes a tracking issue - Apply `batch:N` labels to any GitHub object -- Create files outside `.autoskillit/temp/issue-splitter/` (for any dry-run reports) +- Create files outside `{{AUTOSKILLIT_TEMP}}/issue-splitter/` (for any dry-run reports) **ALWAYS:** - Use `--force` on all `gh label create` calls for idempotency @@ -238,7 +238,7 @@ Output to stdout for `triage-issues` subagent parsing: ## Output Location -Dry-run reports (if any): `.autoskillit/temp/issue-splitter/` +Dry-run reports (if any): `{{AUTOSKILLIT_TEMP}}/issue-splitter/` ## Error Handling diff --git a/src/autoskillit/skills_extended/make-arch-diag/SKILL.md b/src/autoskillit/skills_extended/make-arch-diag/SKILL.md index e0721579f0..52ec34165c 100644 --- a/src/autoskillit/skills_extended/make-arch-diag/SKILL.md +++ b/src/autoskillit/skills_extended/make-arch-diag/SKILL.md @@ -1,6 +1,7 @@ --- name: make-arch-diag categories: [arch-lens] +activate_deps: [arch-lens] description: Generate architecture diagram for a specific component or system. Prompts user to select which area to document, then creates comprehensive mermaid diagrams. hooks: PreToolUse: @@ -29,7 +30,7 @@ Creates comprehensive architecture diagrams for selected components or systems u - Ask user which component/system to diagram - Use the `/autoskillit:mermaid` skill for diagram creation - Include multiple views (data flow, component structure, sequence diagrams) -- Save diagrams to `.autoskillit/temp/make-arch-diag/{component-name}/` (relative to the current working directory) +- Save diagrams to `{{AUTOSKILLIT_TEMP}}/make-arch-diag/{component-name}/` (relative to the current working directory) - Use consistent color coding across all diagrams **NEVER:** @@ -103,6 +104,7 @@ Choose appropriate diagram types: ### Step 5: Create Diagrams Use `/autoskillit:mermaid` skill to create each diagram: +- Using ONLY classDef styles from the mermaid skill (no invented colors) - Follow standard color palette - Include legends - Add clear labels and descriptions @@ -110,7 +112,7 @@ Use `/autoskillit:mermaid` skill to create each diagram: ### Step 6: Write Architecture Description -Create `.autoskillit/temp/make-arch-diag/{component}/architecture.md`: +Create `{{AUTOSKILLIT_TEMP}}/make-arch-diag/{component}/architecture.md`: ```markdown # {Component} Architecture diff --git a/src/autoskillit/skills_extended/make-experiment-diag/SKILL.md b/src/autoskillit/skills_extended/make-experiment-diag/SKILL.md new file mode 100644 index 0000000000..ae0e7d4829 --- /dev/null +++ b/src/autoskillit/skills_extended/make-experiment-diag/SKILL.md @@ -0,0 +1,131 @@ +--- +name: make-experiment-diag +categories: [exp-lens] +activate_deps: [exp-lens] +description: Interactive selection of experimental design lens for visualizing experiment methodology. Routes to the appropriate exp-lens-* skill. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'make-experiment-diag - Selecting experimental design lens...'" + once: true +--- + +# Experimental Design Diagram Selection + +Select the right experimental design lens for your analysis. Each lens asks one primary question about an experiment's design, surfacing assumptions and failure modes specific to that epistemic dimension. + +## When to Use + +- Want to visualize or audit experimental design methodology +- Need to select the right lens for a specific experimental concern +- User says `/autoskillit:make-experiment-diag` +- User wants to examine a specific aspect of an experiment + +## Critical Constraints + +**NEVER:** +- Skip the selection step — always confirm which lens to use +- Modify any source code or experimental artifacts +- Combine multiple lenses in a single invocation + +**ALWAYS:** +- Present the selection table to help the user choose +- Match user description to the most relevant lens +- Load the selected lens skill using the Skill tool +- Follow the loaded skill's instructions exclusively; the delegated skill handles completion + +--- + +## Core Lenses (always recommended) + +| Your experiment involves... | Use this lens | Question it answers | Philosophical Mode | +|-----------------------------|---------------|---------------------|--------------------| +| Unclear or shifting claims | Estimand Clarity | What exactly is the claim? | Evidential | +| Causal attribution without explicit assumptions | Causal Assumptions | What causal assumptions support this design? | Causal-Structural | +| Baseline quality or fairness | Comparator Construction | Is the comparator fair and relevant? | Counterfactual | +| Data preprocessing, splits, or feature pipelines | Pipeline Integrity | Could data handling create optimistic bias? | Integrity | +| Nondeterminism, seed sensitivity, run-to-run noise | Variance & Stability | Is the signal larger than the noise? | Stability | +| Asymmetric tuning, compute, or engineering effort | Fair Comparison | Are alternatives compared symmetrically? | Fairness | +| Reproducing results from artifacts alone | Reproducibility & Artifacts | Could an independent party reproduce this? | Transparency | +| Metric choice, proxy validity, score interpretation | Measurement Validity | Do measurements justify the interpretation? | Psychometric | +| Robustness to preprocessing or modeling choices | Sensitivity & Robustness | Which assumptions are load-bearing? | Robustness | +| Generalization claims beyond the test suite | Benchmark Representativeness | Does this generalize beyond the test bed? | Generalizability | + +## Extended Lenses (enable by experiment class) + +| Your experiment involves... | Use this lens | Question it answers | Philosophical Mode | +|-----------------------------|---------------|---------------------|--------------------| +| Shared resources, network effects, spillovers | Unit & Interference | What is the unit, and can treatments spill over? | Causal-Structural | +| Power, multiplicity, sequential monitoring | Error Budget | Are error risks sized and controlled? | Statistical | +| Theory claims needing adversarial stress | Severity Testing | Would this design have caught the error? | Falsificationist | +| Assignment mechanism, blocking, stratification | Randomization & Blocking | Where does comparability come from? | Design-Structural | +| Confounds, history effects, co-interventions | Validity Threats | What alternative explanations survive? | Adversarial | +| Multi-step exploration, adaptive allocation | Iterative Learning | How does this maximize learning per cost? | Decision-Theoretic | +| Mixing discovery and confirmation in one study | Exploratory vs Confirmatory | Is this discovery or test? | Boundary | +| Deployment risk, fairness, stakeholder harm | Governance & Risk | What risks arise from acting on this result? | Governance | + +--- + +## Workflow + +### Step 1: Prompt User + +Ask the user: + +> What aspect of your experimental design would you like to examine? + +Example prompts: +- "I want to check if my causal claims are well-supported" +- "I need to verify my data pipeline doesn't leak" +- "Are my baselines fair comparisons?" +- "Could someone reproduce my experiment?" +- "Is my benchmark representative enough?" + +### Step 2: Match to Lens + +Based on the user's description, match to the most appropriate lens using the selection tables above. If ambiguous, present the top 2-3 candidates and ask the user to choose. + +### Step 3: Load the Selected Lens + +Use the Skill tool to load the selected `/autoskillit:exp-lens-{slug}` skill. + +If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with the exp-lens analysis. Abort this step and inform the user that the lens skill is unavailable. + +### Step 4: Execute the Loaded Skill + +The loaded lens skill takes over and runs its full analysis workflow. + +--- + +## Alias Table + +| Alias | Lens | +|-------|------| +| estimand | exp-lens-estimand-clarity | +| causal | exp-lens-causal-assumptions | +| comparator | exp-lens-comparator-construction | +| pipeline | exp-lens-pipeline-integrity | +| variance | exp-lens-variance-stability | +| fairness | exp-lens-fair-comparison | +| reproducibility | exp-lens-reproducibility-artifacts | +| measurement | exp-lens-measurement-validity | +| sensitivity | exp-lens-sensitivity-robustness | +| benchmark | exp-lens-benchmark-representativeness | +| unit | exp-lens-unit-interference | +| error | exp-lens-error-budget | +| severity | exp-lens-severity-testing | +| randomization | exp-lens-randomization-blocking | +| validity | exp-lens-validity-threats | +| iterative | exp-lens-iterative-learning | +| exploratory | exp-lens-exploratory-confirmatory | +| governance | exp-lens-governance-risk | + +--- + +## Related Skills + +- `/autoskillit:mermaid` - Shared diagram styling (loaded by individual lenses) +- `/autoskillit:make-arch-diag` - Software architecture lens counterpart +- `/autoskillit:verify-diag` - Verify diagram accuracy against codebase diff --git a/src/autoskillit/skills_extended/make-groups/SKILL.md b/src/autoskillit/skills_extended/make-groups/SKILL.md index 519d51b2bd..3a07de0003 100644 --- a/src/autoskillit/skills_extended/make-groups/SKILL.md +++ b/src/autoskillit/skills_extended/make-groups/SKILL.md @@ -53,7 +53,7 @@ tool **before** beginning any analysis. Use the returned `content` field as the **NEVER:** - Modify any source code files -- Create files outside `.autoskillit/temp/make-groups/` directory +- Create files outside `{{AUTOSKILLIT_TEMP}}/make-groups/` directory - Drop, split, or rewrite requirements — reference them by original ID - Create groups that cannot be independently planned - Include implementation steps or technical approach in the group descriptions @@ -64,15 +64,14 @@ tool **before** beginning any analysis. Use the returned `content` field as the - Include every requirement from the source document in exactly one group - Assign each group a sequential suffix: groupA, groupB, ... groupZ - State dependencies between groups explicitly -- Write to `.autoskillit/temp/make-groups/` directory (relative to the current working directory) +- Write to `{{AUTOSKILLIT_TEMP}}/make-groups/` directory (relative to the current working directory) - After writing the groups file and manifest, emit the **absolute paths** as structured output - tokens immediately before `%%ORDER_UP%%`. Resolve the relative `.autoskillit/temp/make-groups/...` + tokens as your final output. Resolve the relative `{{AUTOSKILLIT_TEMP}}/make-groups/...` save paths to absolute by prepending the full CWD: ``` - groups_path = /absolute/cwd/.autoskillit/temp/make-groups/{groups_filename}.md - manifest_path = /absolute/cwd/.autoskillit/temp/make-groups/{manifest_filename}.json - group_files = /absolute/cwd/.autoskillit/temp/make-groups/{groups_filename}.md - %%ORDER_UP%% + groups_path = /absolute/cwd/{{AUTOSKILLIT_TEMP}}/make-groups/{groups_filename}.md + manifest_path = /absolute/cwd/{{AUTOSKILLIT_TEMP}}/make-groups/{manifest_filename}.json + group_files = /absolute/cwd/{{AUTOSKILLIT_TEMP}}/make-groups/{groups_filename}.md ``` These tokens are MANDATORY — the pipeline cannot proceed without them. @@ -130,7 +129,7 @@ Sort groups so that each group's dependencies are satisfied by earlier groups. D ### Step 5: Write the Groups Documents -Produce three outputs in `.autoskillit/temp/make-groups/`: +Produce three outputs in `{{AUTOSKILLIT_TEMP}}/make-groups/`: **5a. Index file (consolidated):** `groups_{topic}_{YYYY-MM-DD_HHMMSS}.md` @@ -274,7 +273,7 @@ orchestrating recipe). List every per-group file in implementation order. ## Output Location ``` -.autoskillit/temp/make-groups/ +{{AUTOSKILLIT_TEMP}}/make-groups/ ├── groups_{topic}_{ts}.md # Consolidated index (all groups) ├── manifest_{topic}_{ts}.json # Machine-readable manifest ├── groupA_{topic}_{ts}.md # Individual per-group file diff --git a/src/autoskillit/skills_extended/make-plan/SKILL.md b/src/autoskillit/skills_extended/make-plan/SKILL.md index 4607c9bffc..824a6b2925 100644 --- a/src/autoskillit/skills_extended/make-plan/SKILL.md +++ b/src/autoskillit/skills_extended/make-plan/SKILL.md @@ -1,5 +1,6 @@ --- name: make-plan +activate_deps: [arch-lens] description: Create implementation plans through deep codebase understanding. Use when user asks to create, devise, or write a plan. Leverages subagents to explore approaches, understand systems, and design aligned solutions. hooks: PreToolUse: @@ -129,7 +130,7 @@ call is mandatory at the start of every headless session that uses code-index to **5b. Write your lens selection rationale to a file using the Write tool:** -- **Path:** `.autoskillit/temp/make-plan/arch_lens_selection_{YYYY-MM-DD_HHMMSS}.md` +- **Path:** `{{AUTOSKILLIT_TEMP}}/make-plan/arch_lens_selection_{YYYY-MM-DD_HHMMSS}.md` - **Content:** Which lens was selected and why (1-2 sentences of rationale). **5c. MANDATORY: LOAD the appropriate arch-lens skill using the Skill tool:** @@ -150,6 +151,8 @@ call is mandatory at the start of every headless session that uses code-index to | State Lifecycle | `/autoskillit:arch-lens-state-lifecycle` | | Deployment | `/autoskillit:arch-lens-deployment` | +If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, proceed without the architectural diagram. + **5d. Create the diagram following the loaded skill's instructions:** - Focus on the PROPOSED changes (use `newComponent` class for new elements) - Show how new components integrate with existing architecture @@ -206,7 +209,7 @@ Before writing the final plan, verify: ## Critical Constraints -**NEVER use EnterPlanMode.** This skill IS the planning process. Execute the planning steps directly — explore with subagents, design the approach, write the plan file to `.autoskillit/temp/make-plan/` (relative to the current working directory). Do not enter plan mode, do not call ExitPlanMode. Just do the work and deliver the plan. +**NEVER use EnterPlanMode.** This skill IS the planning process. Execute the planning steps directly — explore with subagents, design the approach, write the plan file to `{{AUTOSKILLIT_TEMP}}/make-plan/` (relative to the current working directory). Do not enter plan mode, do not call ExitPlanMode. Just do the work and deliver the plan. **NEVER include:** - Multiple alternative approaches (recommend ONE only) @@ -220,18 +223,17 @@ Before writing the final plan, verify: - Change any code - Choose an approach because it's easier - Reject an approach because it's harder -- Create files outside `.autoskillit/temp/make-plan/` directory +- Create files outside `{{AUTOSKILLIT_TEMP}}/make-plan/` directory - **Use `git merge` in implementation plans.** When a plan needs to bring in changes from another branch, use `git cherry-pick ` for individual commits or `git checkout -- ` for specific files. `merge_worktree` requires linear commit history — merge commits cannot be rebased and will cause `WORKTREE_INTACT_MERGE_COMMITS_DETECTED` failure. See "Conflict-Resolution Plan Requirements" section for full guidance. **ALWAYS:** -- Write to `.autoskillit/temp/make-plan/` directory (relative to the current working directory) +- Write to `{{AUTOSKILLIT_TEMP}}/make-plan/` directory (relative to the current working directory) - After writing the plan file, emit the **absolute path** as a structured output token - immediately before `%%ORDER_UP%%`. The save path is relative (`.autoskillit/temp/make-plan/...`) but + as your final output. The save path is relative (`{{AUTOSKILLIT_TEMP}}/make-plan/...`) but the token **must** use the absolute path (prepend the full CWD): ``` - plan_path = /absolute/cwd/.autoskillit/temp/make-plan/{filename}.md - plan_parts = /absolute/cwd/.autoskillit/temp/make-plan/{filename}.md - %%ORDER_UP%% + plan_path = /absolute/cwd/{{AUTOSKILLIT_TEMP}}/make-plan/{filename}.md + plan_parts = /absolute/cwd/{{AUTOSKILLIT_TEMP}}/make-plan/{filename}.md ``` This token is MANDATORY — the pipeline cannot capture the output without it. - Use `model: "sonnet"` when spawning all subagents via the Task tool @@ -250,7 +252,7 @@ If the plan exceeds 500 lines, split it into multiple files (`_part_a`, `_part_b - The title of each part file MUST include `— PART A ONLY` (or B, C, etc.) so scope is immediately visible. - Each part file MUST open with the scope warning block shown in the multi-part template below. -Save the plan to: `.autoskillit/temp/make-plan/{task_name}_plan_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Save the plan to: `{{AUTOSKILLIT_TEMP}}/make-plan/{task_name}_plan_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) **Structured output:** After saving the file(s), emit the following lines so pipeline orchestrators can capture both fields: diff --git a/src/autoskillit/skills_extended/make-req/SKILL.md b/src/autoskillit/skills_extended/make-req/SKILL.md index 3d34d6d267..0f9c3c8927 100644 --- a/src/autoskillit/skills_extended/make-req/SKILL.md +++ b/src/autoskillit/skills_extended/make-req/SKILL.md @@ -31,7 +31,7 @@ Decompose a task, plan, roadmap, or feature description into a structured set of **NEVER:** - Modify any source code files -- Create files outside `.autoskillit/temp/make-req/` directory +- Create files outside `{{AUTOSKILLIT_TEMP}}/make-req/` directory - Prescribe implementation approaches or libraries in requirements - Include implementation steps disguised as requirements ("Refactor X to use Y" is an instruction, not a requirement) - Write requirements that can only be verified by reading source code @@ -41,7 +41,7 @@ Decompose a task, plan, roadmap, or feature description into a structured set of - Group requirements by what would be implemented together - Provide background and context for each group - State requirements as verifiable conditions -- Write to `.autoskillit/temp/make-req/` directory (relative to the current working directory) +- Write to `{{AUTOSKILLIT_TEMP}}/make-req/` directory (relative to the current working directory) ## Workflow @@ -90,7 +90,7 @@ Keep context factual. Do not suggest solutions. ### Step 5: Write the Requirements Document -Save to: `.autoskillit/temp/make-req/requirements_{topic}_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Save to: `{{AUTOSKILLIT_TEMP}}/make-req/requirements_{topic}_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) ```markdown # Requirements: {Topic} diff --git a/src/autoskillit/skills_extended/merge-pr/SKILL.md b/src/autoskillit/skills_extended/merge-pr/SKILL.md index 473b385f93..53fb9038e8 100644 --- a/src/autoskillit/skills_extended/merge-pr/SKILL.md +++ b/src/autoskillit/skills_extended/merge-pr/SKILL.md @@ -38,7 +38,7 @@ conflicts from earlier merges in the queue. - Use `git merge` to merge the PR into the integration branch — always use `gh pr merge --squash --auto` (when `autoMergeAllowed=true`) or `gh pr merge --squash` (when `autoMergeAllowed=false`) - Close or comment on the PR - Leave the git working tree in a dirty state -- Create files outside `.autoskillit/temp/merge-prs/` directory +- Create files outside `{{AUTOSKILLIT_TEMP}}/merge-prs/` directory **ALWAYS:** - Run `git status` before any operation to verify clean state @@ -279,7 +279,7 @@ Extract the `## Requirements` section if present — set `requirements_section = Compute timestamp: `YYYY-MM-DD_HHMMSS`. -Write `.autoskillit/temp/merge-prs/conflict_pr{pr_number}_plan_{ts}.md`: +Write `{{AUTOSKILLIT_TEMP}}/merge-prs/conflict_pr{pr_number}_plan_{ts}.md`: ```markdown # Conflict Resolution Plan: PR #{pr_number} — "{pr_title}" @@ -401,7 +401,7 @@ Print a JSON result block to stdout for recipe capture: "pr_number": 47, "pr_branch": "feature/db-refactor", "pr_title": "Refactor database layer", - "conflict_report_path": ".autoskillit/temp/merge-prs/conflict_pr47_plan_YYYY-MM-DD_HHMMSS.md" + "conflict_report_path": "{{AUTOSKILLIT_TEMP}}/merge-prs/conflict_pr47_plan_YYYY-MM-DD_HHMMSS.md" } ``` @@ -420,7 +420,7 @@ with `conflict_report_path` set. The pipeline then routes to make-plan → imple "pr_number": 47, "pr_branch": "feature/stale-branch", "pr_title": "Feature from stale branch", - "conflict_report_path": ".autoskillit/temp/merge-prs/conflict_pr47_plan_YYYY-MM-DD_HHMMSS.md" + "conflict_report_path": "{{AUTOSKILLIT_TEMP}}/merge-prs/conflict_pr47_plan_YYYY-MM-DD_HHMMSS.md" } ``` @@ -520,7 +520,7 @@ written. Omit the line entirely on a successful direct merge or when `escalation ## Output Location ``` -.autoskillit/temp/merge-prs/ +{{AUTOSKILLIT_TEMP}}/merge-prs/ └── conflict_pr{N}_plan_{ts}.md (written only when needs_plan=true) ``` diff --git a/src/autoskillit/skills_extended/migrate-recipes/SKILL.md b/src/autoskillit/skills_extended/migrate-recipes/SKILL.md index 0a5ecdfc3c..48413457ec 100644 --- a/src/autoskillit/skills_extended/migrate-recipes/SKILL.md +++ b/src/autoskillit/skills_extended/migrate-recipes/SKILL.md @@ -1,5 +1,6 @@ --- name: migrate-recipes +activate_deps: [write-recipe] description: Apply versioned migration notes to an AutoSkillit recipe. Use when user confirms migration, called by agent or autoskillit migrate CLI, or invoked directly. hooks: PreToolUse: @@ -37,7 +38,7 @@ The orchestrator provides all context in the prompt: - Declare success if validation fails after all retry attempts **ALWAYS:** -- Save migrated scripts to .autoskillit/temp/migrations/{script_name}.yaml for review +- Save migrated scripts to {{AUTOSKILLIT_TEMP}}/migrations/{script_name}.yaml for review - Validate via validate_recipe before declaring success - Preserve all existing script fields not targeted by migration changes - Output a human-readable diff summary of changes applied @@ -51,12 +52,13 @@ The orchestrator provides all context in the prompt: - `missing_field`: The field that should be added if absent 3. If changes are needed, use `/autoskillit:write-recipe` in edit mode: - Load the skill: invoke `/autoskillit:write-recipe` via the Skill tool + - If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, skip the recipe update and log a warning; proceed with remaining validation steps. - Provide the current YAML content - Describe all needed changes with the `instruction` text and before/after examples 4. Validate the result with `validate_recipe` 5. On validation failure, retry up to 3 times with error feedback 6. Ensure `autoskillit_version` is set to the `target_version` -7. Save the migrated script to `.autoskillit/temp/migrations/{script_name}.yaml` +7. Save the migrated script to `{{AUTOSKILLIT_TEMP}}/migrations/{script_name}.yaml` 8. Output a summary of changes applied ## Error Handling diff --git a/src/autoskillit/skills_extended/open-integration-pr/SKILL.md b/src/autoskillit/skills_extended/open-integration-pr/SKILL.md index f4bb7d082e..0c3292ce95 100644 --- a/src/autoskillit/skills_extended/open-integration-pr/SKILL.md +++ b/src/autoskillit/skills_extended/open-integration-pr/SKILL.md @@ -1,6 +1,7 @@ --- name: open-integration-pr categories: [github] +activate_deps: [arch-lens] description: > Create an integration PR for the merge-prs. Reads pr_order_file JSON, generates a rich PR body with per-PR details, arch-lens diagrams, and carried-forward Closes #N @@ -45,7 +46,7 @@ PR, and output `pr_url=`. ## Critical Constraints **NEVER:** -- Create files outside `.autoskillit/temp/open-integration-pr/` (except the temp body file for `gh pr create --body-file`) +- Create files outside `{{AUTOSKILLIT_TEMP}}/open-integration-pr/` (except the temp body file for `gh pr create --body-file`) - Modify any source code - Fail the pipeline if `gh` is unavailable or not authenticated — output `pr_url=` (empty) and exit successfully - Close original PRs before the integration PR is successfully created @@ -208,15 +209,9 @@ lens guard. For each selected lens, follow this exact sequence: -**CRITICAL:** Do NOT output any prose status text between lens iterations. -After completing all sub-steps for one lens (including mermaid extraction and -validation), immediately begin sub-step 1 (Write the PR context file) for the -next lens. Progress announcements like "Diagram generated. Now calling X:" -create end_turn windows that cause stochastic session termination. - **1. Write the PR context to a file using the Write tool:** -- **Path:** `.autoskillit/temp/open-integration-pr/pr_arch_lens_context_{YYYY-MM-DD_HHMMSS}.md` +- **Path:** `{{AUTOSKILLIT_TEMP}}/open-integration-pr/pr_arch_lens_context_{YYYY-MM-DD_HHMMSS}.md` - **Content:** The following PR context block, with placeholders filled in: ```markdown @@ -241,9 +236,15 @@ This diagram is for a Pull Request. Focus the diagram on the areas of the codeba **2. Immediately call the Skill tool to load the arch-lens skill** (e.g., `/autoskillit:arch-lens-module-dependency`). The loaded skill will read the PR context file written in step 1 above. +**If the Skill tool returns an error containing "disable-model-invocation" or "cannot be used", +do NOT write a diagram freehand. Discard this lens iteration silently. If ALL arch-lens +invocations fail this way, set `validated_diagrams = []` (the Architecture Impact section is +omitted per Step 7 behavior).** + **3. Follow the loaded skill's instructions** to explore the codebase and generate the diagram. +Using ONLY classDef styles from the mermaid skill (no invented colors). -The arch-lens skills write their output to `.autoskillit/temp/arch-lens-{lens-name}/` (relative to the current working directory). After each skill +The arch-lens skills write their output to `{{AUTOSKILLIT_TEMP}}/arch-lens-{lens-name}/` (relative to the current working directory). After each skill runs, read the generated markdown file and extract the mermaid code block(s). After extracting the mermaid block, inspect its content for `★` or `●` characters: @@ -252,7 +253,7 @@ After extracting the mermaid block, inspect its content for `★` or `●` chara ### Step 7: Compose PR Body -Write to `.autoskillit/temp/open-integration-pr/pr_body_{timestamp}.md`. (relative to the current working directory) +Write to `{{AUTOSKILLIT_TEMP}}/open-integration-pr/pr_body_{timestamp}.md`. (relative to the current working directory) ```markdown ## Integration Summary @@ -324,7 +325,7 @@ gh pr create \ --base {base_branch} \ --head {integration_branch} \ --title "Integration: collapsed PRs #{numbers} into {base_branch}" \ - --body-file .autoskillit/temp/open-integration-pr/pr_body_{timestamp}.md + --body-file {{AUTOSKILLIT_TEMP}}/open-integration-pr/pr_body_{timestamp}.md ``` `{numbers}` = comma-separated PR numbers (e.g., `#42, #47, #51`). diff --git a/src/autoskillit/skills_extended/open-pr/SKILL.md b/src/autoskillit/skills_extended/open-pr/SKILL.md deleted file mode 100644 index 9f1cde1121..0000000000 --- a/src/autoskillit/skills_extended/open-pr/SKILL.md +++ /dev/null @@ -1,368 +0,0 @@ ---- -name: open-pr -categories: [github] -description: Create a GitHub PR for a completed implementation, with auto-selected arch-lens - diagrams embedded in the PR body. Use after pipeline implementation when open_pr mode is - enabled. -hooks: - PreToolUse: - - matcher: "*" - hooks: - - type: command - command: "echo '[SKILL: open-pr] Opening pull request...'" - once: true ---- - -# Open PR - -Read a completed plan, analyze changed files, generate architecture diagrams using the most -relevant arch-lens lenses, and open a GitHub Pull Request. - -## Arguments - -`/autoskillit:open-pr {plan_paths} {feature_branch} {base_branch} [closing_issue] [conflict_report_path]` - -- **plan_paths** — Comma-separated list of absolute paths to implementation plan - markdown files. Single path for non-groups runs; multiple comma-separated paths - for multi-group runs. -- **feature_branch** — Branch containing all merged implementation changes -- **base_branch** — Branch to open the PR against (e.g., "main") -- **closing_issue** (optional) — GitHub issue number to close (e.g., "99"). When provided, - inserts `Closes #closing_issue` into the PR body so GitHub auto-closes the issue on merge. -- **conflict_report_path** (optional) — Absolute path to a single conflict resolution report - from `resolve-merge-conflicts`. When provided and non-empty, embed a "Conflict Resolution - Decisions" section in the PR body. Accepts exactly one path (not comma-separated); the - implementation pipeline passes only one path per single-branch run. - -## When to Use - -- Called by `implementation` when `open_pr=true`, after all groups/parts are merged -- Can be invoked standalone after any implementation that used a feature branch - -## Critical Constraints - -**NEVER:** -- Create files outside `.autoskillit/temp/open-pr/` (except temp files used for `gh pr create --body-file`) -- Fail the pipeline if `gh` is not available or not authenticated — output `pr_url=` (empty) and exit successfully -- Modify any source code - -**ALWAYS:** -- Check `gh auth status` before attempting GitHub operations -- ALWAYS assume the feature branch is already on the remote (the recipe pushes before invoking this skill) -- Output `pr_url=` on the last output line (empty string if GitHub unavailable) -- Select 1–3 arch-lens lenses based on relevance — only include a lens if the changed files map to that lens's concern - -## Workflow - -**Precondition:** The feature branch is already published to the remote by the `push_to_remote` recipe step that precedes this skill invocation. Do NOT push the branch yourself. - -### Step 0: Stable Branch Guard - -Parse the positional arguments: -- arg[1] = plan_paths -- arg[2] = feature_branch (the branch being PRed) -- arg[3] = base_branch (PR target) - -If base_branch == "stable" AND feature_branch != "main": - Print to stderr: - ERROR: PRs targeting 'stable' are only allowed from 'main'. - Source branch '$feature_branch' is not 'main'. - Stable branch policy: only integration PRs from main are permitted. - Tip: Open a PR to 'integration' first, then promote via the integration pipeline. - Exit with code 1. - -### Step 1: Parse Arguments - -Parse three positional arguments: `plan_paths`, `feature_branch`, `base_branch`. -Parse the optional fourth positional argument `closing_issue` (may be absent or empty string). -Parse the optional fifth positional argument `conflict_report_path` (may be absent or empty string). -Split `plan_paths` by comma to get a list of plan file paths. - -### Step 1b: Fetch Requirements from Closing Issue - -- If `closing_issue` is absent or empty string: skip — set `requirements_section = ""`. -- Fetch issue body: - ```bash - gh issue view {closing_issue} --json body -q .body - ``` -- Extract the `## Requirements` section: - `requirements_section` = everything from `## Requirements` to the next `## ` heading or end of body, whichever comes first. -- If no `## Requirements` section found: set `requirements_section = ""`. -- This step is skipped gracefully if `gh` is unavailable — `requirements_section` remains `""`. - -### Step 2: Extract PR Title from Plan - -Read all plan files. For each, extract the first `# ` heading line, strip the `# ` prefix, -and strip any trailing `— PART [A-Z] ONLY` suffix (e.g., `— PART A ONLY`, `— PART B ONLY`). -This suffix is a plan-level scope marker that must not appear in PR titles. - -- **Single plan:** Use the heading directly as `{task_title}` (current behavior). -- **Multiple plans:** Spawn a subagent (Task tool, model: sonnet) with all extracted - headings. Instruct it to synthesize a single concise PR title (under 70 characters) - that captures the overall scope. The title should NOT enumerate every group — it - should describe the aggregate change. - -**PR Title Prefix (derived from run_name):** - -If a `run_name` positional argument is provided, apply a prefix to the PR title: - -- `run_name` starts with `"feature"` → prepend `[FEATURE] ` to the PR title -- `run_name` starts with `"fix"` → prepend `[FIX] ` to the PR title -- Any other `run_name` → no prefix (existing behavior preserved) - -This convention is set by `/autoskillit:process-issues` when it passes -`run_name="feature"` for `recipe:implementation` issues and `run_name="fix"` -for `recipe:remediation` issues. Direct recipe invocations using `run_name="impl"` -(the default) are unaffected. - -```bash -BASE_TITLE="$(head -1 {plan_path} | sed 's/^# //' | LC_ALL=en_US.UTF-8 sed 's/ *— *PART [A-Z] ONLY$//')" -case "$RUN_NAME" in - feature*) TITLE="[FEATURE] $BASE_TITLE" ;; - fix*) TITLE="[FIX] $BASE_TITLE" ;; - *) TITLE="$BASE_TITLE" ;; -esac -gh pr create --title "$TITLE" ... -``` - -### Step 2c: Load Conflict Resolution Report - -- If `conflict_report_path` is absent or empty string: skip — set `conflict_resolution_table = ""`. -- Read the file at `conflict_report_path`. -- Extract the `## Per-File Resolution Decisions` table (all lines from the `| File |` header - through the last table row). -- Store as `conflict_resolution_table`. - -Skip gracefully if the path does not exist — `conflict_resolution_table` remains `""`. - -### Step 3: Get Changed Files - -Run: -```bash -git diff --name-only {base_branch}..{feature_branch} -``` - -Collect the list of changed file paths. If the command fails or returns empty, proceed with -an empty file list (the PR body will note that no diff was available). - -Then classify changed files by status: - -```bash -# Files added (new) -git diff --diff-filter=A --name-only {base_branch}..{feature_branch} -``` - -```bash -# Files modified -git diff --diff-filter=M --name-only {base_branch}..{feature_branch} -``` - -Store these as two separate lists: `new_files` (added) and `modified_files`. The existing -`changed_files` list (all files) is retained for lens selection in Step 4. - -### Step 4: Select Arch-Lens Lenses - -Spawn a subagent (Task tool, model: sonnet) with the list of changed file paths and the -following lens menu: - -``` -c4-container, concurrency, data-lineage, deployment, development, -error-resilience, module-dependency, operational, process-flow, -repository-access, scenarios, security, state-lifecycle -``` - -Instruct the subagent to return 1–3 lens names. Only include a lens if at least one changed file maps to that lens's concern — if no files clearly map to a given lens, omit it. Choose as few as are genuinely relevant; more is not better. - -**Development lens guard:** The `development` lens must ONLY be selected if at least one changed file matches a build/test configuration pattern: `pyproject.toml`, `Taskfile*`, `conftest.py`, `.github/workflows/*`, `Makefile`, `setup.cfg`, `setup.py`, `tox.ini`, `noxfile.py`, or files under a `ci/` directory. If no changed file matches these patterns, do NOT select the `development` lens regardless of other criteria. - -Selection criteria: -- `module-dependency` → changes span multiple packages or add new dependencies -- `process-flow` → changes affect workflow routing, state transitions, or control flow -- `development` → changes affect build config or quality gates (pyproject.toml, Taskfile*, conftest.py, CI configs) — NOT selected for ordinary test file changes -- `operational` → changes affect CLI, config, or observability -- `c4-container` → changes add new services, tools, or integrations -- `security` → changes affect trust boundaries or validation layers -- `repository-access` → changes affect data access or repository patterns -- `state-lifecycle` → changes affect field contracts or resume safety - -### Step 5: Generate Arch-Lens Diagrams - -For each selected lens, follow this exact sequence: - -**CRITICAL:** Do NOT output any prose status text between lens iterations. -After completing all sub-steps for one lens (including mermaid extraction and -validation), immediately begin sub-step 1 (Write the PR context file) for the -next lens. Progress announcements like "Diagram generated. Now calling X:" -create end_turn windows that cause stochastic session termination. - -**1. Write the PR context to a file using the Write tool:** - -- **Path:** `.autoskillit/temp/open-pr/pr_arch_lens_context_{YYYY-MM-DD_HHMMSS}.md` -- **Content:** The following PR context block, with placeholders filled in: - -```markdown -# PR Context — Changed Files - -This diagram is for a Pull Request. Focus the diagram on the areas of the codebase affected by these changes. Do not create a generic whole-project diagram. - -## New files (use ★ prefix on these nodes): -{list of new_files from Step 3, or "None"} - -## Modified files (use ● prefix on these nodes): -{list of modified_files from Step 3, or "None"} - -## Instructions: -- Focus exploration and the diagram on the architectural areas these files belong to -- Use `★` prefix on nodes representing new files/components -- Use `●` prefix on nodes representing modified files/components -- Leave unchanged components unmarked (include them only if needed for context/connectivity) -- The diagram should help PR reviewers understand the architectural impact of these specific changes -``` - -**2. Immediately call the Skill tool to load the arch-lens skill** (e.g., `/autoskillit:arch-lens-module-dependency`). -The loaded skill will read the PR context file written in step 1 above. - -**3. Follow the loaded skill's instructions** to explore the codebase and generate the diagram. - -The arch-lens skills write their output to `.autoskillit/temp/arch-lens-{lens-name}/` (relative to the current working directory). After each skill -runs, read the generated markdown file and extract the mermaid code block(s). - -After extracting the mermaid block, inspect its content for `★` or `●` characters: -- If the block contains at least one `★` or `●` → add it to `validated_diagrams`. -- If the block contains neither → discard this diagram; do not add it to the list. - -This ensures the PR body only includes diagrams where at least one component was -visibly modified or created by the PR. - -### Step 6: Compose PR Body - -After generating all diagrams, check `validated_diagrams`: -- If `validated_diagrams` is non-empty → include the `## Architecture Impact` section - as described below, embedding only the validated mermaid blocks. -- If `validated_diagrams` is empty → omit the `## Architecture Impact` section entirely. - Do not include a placeholder or note in the PR body. - -Write the PR body to `.autoskillit/temp/open-pr/pr_body_{timestamp}.md`. (relative to the current working directory) - -Read `## Summary` from each plan file. - -#### Single plan (one path): - -```markdown -## Summary - -{First paragraph of the plan's ## Summary section, or first 5 lines after the heading} - -{If extracted: include the requirements section from the closing issue} -## Requirements - -{requirements_section from closing issue} - -{If conflict_resolution_table is non-empty:} -## Conflict Resolution Decisions - -The following files had merge conflicts that were automatically resolved. - -{conflict_resolution_table} - -{## Architecture Impact — conditional: include only if validated_diagrams is non-empty} -## Architecture Impact - -{For each validated lens diagram: embed the mermaid block with a heading for the lens name} - -### {Lens Name} Diagram - -` ` `mermaid -{diagram content} -` ` ` - -{If closing_issue is provided and non-empty:} -Closes #{closing_issue} - -## Implementation Plan - -Plan file: `{plan_path}` - -🤖 Generated with [Claude Code](https://claude.com/claude-code) via AutoSkillit -``` - -#### Multiple plans (comma-separated paths): - -```markdown -## Summary - -{Synthesized overall summary — 2-3 sentences covering the aggregate change. - Use a sonnet subagent to produce this from all individual summaries.} - -
    -Individual Group Plans - -### Group 1: {heading from plan 1} -{Summary from plan 1} - -### Group 2: {heading from plan 2} -{Summary from plan 2} - -
    - -{If extracted: include the requirements section from the closing issue} -## Requirements - -{requirements_section from closing issue} - -{If conflict_resolution_table is non-empty:} -## Conflict Resolution Decisions - -The following files had merge conflicts that were automatically resolved. - -{conflict_resolution_table} - -{## Architecture Impact — conditional: include only if validated_diagrams is non-empty} -## Architecture Impact - -{Same as single plan — validated lens diagrams are based on full diff, not plan count} - -### {Lens Name} Diagram - -` ` `mermaid -{diagram content} -` ` ` - -{If closing_issue is provided and non-empty:} -Closes #{closing_issue} - -## Implementation Plan - -Plan files: -- `{plan_path_1}` -- `{plan_path_2}` - -🤖 Generated with [Claude Code](https://claude.com/claude-code) via AutoSkillit -``` - -### Step 7: Check GitHub Availability - -Run `gh auth status 2>/dev/null`. If exit code is non-zero: -- Log "GitHub CLI not available or not authenticated — skipping PR creation" -- Output: `pr_url=` -- Exit successfully - -### Step 8: Create Pull Request - -```bash -gh pr create \ - --base {base_branch} \ - --head {feature_branch} \ - --title "{task_title}" \ - --body-file .autoskillit/temp/open-pr/pr_body_{timestamp}.md -``` - -Capture the PR URL from stdout. - -Output: `pr_url={url}` - -## Output - -- Always: `pr_url=` (empty string when GitHub unavailable) -- PR body written to: `.autoskillit/temp/open-pr/pr_body_{timestamp}.md` -- Token usage summary: appended automatically to the PR body by the `token_summary_appender.py` PostToolUse hook after this skill's result is returned \ No newline at end of file diff --git a/src/autoskillit/skills_extended/pipeline-summary/SKILL.md b/src/autoskillit/skills_extended/pipeline-summary/SKILL.md index ea0b36203c..9b1598fd64 100644 --- a/src/autoskillit/skills_extended/pipeline-summary/SKILL.md +++ b/src/autoskillit/skills_extended/pipeline-summary/SKILL.md @@ -138,7 +138,7 @@ If push fails (no remote, network issue), log the error and exit successfully. ### Step 6: Create GitHub Issue Write the issue body to a temp file, then: ```bash -TEMP_ISSUE_BODY=".autoskillit/temp/pipeline-summary/issue_body_$(date +%Y%m%d-%H%M%S).md" +TEMP_ISSUE_BODY="{{AUTOSKILLIT_TEMP}}/pipeline-summary/issue_body_$(date +%Y%m%d-%H%M%S).md" mkdir -p "$(dirname "${TEMP_ISSUE_BODY}")" # [write the issue body content to ${TEMP_ISSUE_BODY} here] gh issue create \ @@ -153,7 +153,7 @@ Output: `issue_url={url}` ### Step 7: Create Pull Request Write the PR body to a temp file (reference the issue), then: ```bash -TEMP_PR_BODY=".autoskillit/temp/pipeline-summary/pr_body_$(date +%Y%m%d-%H%M%S).md" +TEMP_PR_BODY="{{AUTOSKILLIT_TEMP}}/pipeline-summary/pr_body_$(date +%Y%m%d-%H%M%S).md" mkdir -p "$(dirname "${TEMP_PR_BODY}")" # [write the PR body content to ${TEMP_PR_BODY} here] gh pr create \ @@ -182,7 +182,7 @@ Output: `pr_url={url}` For recipe authors who want to include token/timing data in the PR body: 1. Call the `get_token_summary` MCP tool to retrieve current pipeline token data. -2. Write the JSON result to `.autoskillit/temp/token_summary_{timestamp}.json` using a `run_python` step. (relative to the current working directory) +2. Write the JSON result to `{{AUTOSKILLIT_TEMP}}/token_summary_{timestamp}.json` using a `run_python` step. (relative to the current working directory) The `run_python` step executes in the MCP server process and has access to the live `ToolContext` via the server context; call `ctx.token_log.get_report()` and `ctx.token_log.compute_total()`, then write `{"steps": ..., "total": ...}` as JSON. diff --git a/src/autoskillit/skills_extended/plan-experiment/SKILL.md b/src/autoskillit/skills_extended/plan-experiment/SKILL.md new file mode 100644 index 0000000000..832e4b335e --- /dev/null +++ b/src/autoskillit/skills_extended/plan-experiment/SKILL.md @@ -0,0 +1,478 @@ +--- +name: plan-experiment +categories: [research] +description: Convert a scope report into a structured experiment plan with hypothesis, variables, phases, and success criteria. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: plan-experiment] Planning experiment...'" + once: true +--- + +# Plan Experiment Skill + +Transform a scope report into an experiment plan. The output is both a research +design AND an implementation plan — it describes what is being tested, how to +build the experiment infrastructure, and what to run. The plan is posted as a +GitHub issue for human review before any compute is spent. + +The plan must be specific and actionable: an implementer should be able to read +it and know exactly what files to create, what environment to set up, what +commands to run, and what results to collect. Everything is planned to live in +one self-contained folder under `research/`. + +## When to Use + +- As the second step of the `research` recipe (phase 1) +- When you have a scope report and need to plan an experiment + +## Arguments + +/autoskillit:plan-experiment {scope_report_path} [{revision_guidance}] + +`{scope_report_path}` — Absolute path to the scope report produced by `/autoskillit:scope` +(required). Scan tokens after the skill name for the first path-like token +(starts with `/`, `./`, or `.autoskillit/`). + +`{revision_guidance}` — Optional. Absolute path to revision guidance produced by +`/autoskillit:review-design` when verdict=REVISE. Scan for the second path-like token. +When absent or empty (first pass), proceed normally. When present, read it and +incorporate the feedback before writing the plan. + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Create files outside `{{AUTOSKILLIT_TEMP}}/plan-experiment/` directory +- Write implementation code — this skill produces a plan only +- Skip the threats-to-validity section +- Leave success criteria vague — every criterion must be measurable +- Omit the environment assessment — always explicitly state whether a custom + environment is needed or not, and why +- Omit YAML frontmatter unless a V1–V4 ERROR is triggered — every plan must have frontmatter +- Write frontmatter after the `# Experiment Plan:` heading — it always goes BEFORE + +**ALWAYS:** +- Use `model: "sonnet"` when spawning all subagents via the Task tool +- Write output to `{{AUTOSKILLIT_TEMP}}/plan-experiment/` directory +- State hypotheses as falsifiable claims with measurable outcomes +- Define metrics before describing the method +- Reference specific files, functions, and test fixtures from the scope report +- Plan all artifacts into one self-contained `research/YYYY-MM-DD-{slug}/` folder +- Include implementation phases that an implementer can follow step by step +- Write YAML frontmatter between --- delimiters BEFORE the # Experiment Plan: heading +- Apply all 9 validation rules before writing the frontmatter block +- Log V1–V4, V9 ERRORs in a ## Frontmatter Validation Errors section instead of writing frontmatter +- Log V5–V8 WARNINGs as # WARNING: ... YAML comments on the relevant field lines + +## Workflow + +### Step 1 — Read Scope and Revision Guidance + +Detect and read inputs: +1. Read the scope report at `{scope_report_path}`. Extract: + - The research question + - Known/unknown matrix + - Proposed investigation directions + - Success criteria hints + - External research findings +2. If a second path-like token is present and resolves to an existing file, read + `{revision_guidance}`. Extract all revision instructions — these take priority over + your initial analysis in Step 2. Note which sections of the plan need rework. + When absent or empty, skip this sub-step and proceed normally (first pass). + +### Step 2 — Explore Feasibility + +Launch subagents (model: "sonnet") to assess feasibility. The following are +**minimum required** — launch as many additional subagents as needed to fill +information gaps and produce the best possible experiment plan. + +**Minimum subagents:** + +**Subagent A — Measurement Feasibility:** +> Search the project for any existing metrics infrastructure — files that define +> canonical metric names, measurement dimensions, quality thresholds, or +> standardized assessment tooling (e.g., files named `metrics.*`, `benchmark.*`, +> `evaluation.*`, or any assessment/scoring module). If no dedicated metrics +> infrastructure exists, treat all dependent variables as "NEW". +> Cross-reference against the scope report's Metric Context section if present; +> if absent, proceed without it and note the gap. +> For each dependent variable in the research question: verify it has an existing +> measurement mechanism, or flag it as "NEW" requiring formula, unit, and +> threshold definition. Report what measurement infrastructure already exists +> vs. what needs to be built. + +**Subagent B — Data & Input Feasibility:** +> Assess what data the experiment needs to operate on. Can it be generated +> synthetically? Does it need to be constructed with specific properties? +> Are there existing datasets or fixtures that can be reused? What +> generators or construction scripts would need to be written? +> +> **Research Task Directive Compliance:** When the research task directive or issue +> specifies using particular data (e.g., "use MERFISH data", "benchmark on real-world +> datasets"), the Data Manifest MUST include acquisition steps for that data. The plan +> must NOT assume the data will already be present — especially in worktrees where +> gitignored directories are empty. If the directive specifies data that requires +> download or generation, include the exact commands in the `acquisition` field. + +**Subagent C — Environment Assessment:** +> Determine whether the experiment can run with the project's existing +> toolchain, or whether it requires additional tools, libraries, or +> runtimes. If external tools are needed, research the correct package +> names and versions for a micromamba/conda environment.yml. + +**Additional subagents (launch as many as needed):** +- Web searches for relevant tools, libraries, measurement techniques, + established methodologies, or documentation for specific technologies +- Deeper exploration of specific code areas +- Research into how similar experiments have been designed elsewhere +- Investigation of specific technical constraints or requirements +- Any other research that improves the experiment plan + +### Step 3 — Write Experiment Plan + +Produce a structured experiment plan. The plan has two halves: the **research +design** (what and why) and the **implementation plan** (how to build it). + +Choose a date-stamped slug for the experiment folder: +`research/YYYY-MM-DD-{slug}/` where `{slug}` is a kebab-case summary of the +research topic (max 40 chars). + +```markdown +# Experiment Plan: {title} + +## Motivation +{Why this experiment matters. What decision will its results inform?} + +## Hypothesis + +**Null hypothesis (H0):** {The default assumption — no effect, no difference} +**Alternative hypothesis (H1):** {The claim being tested — stated with a +measurable outcome} + +## Independent Variables +{What is being varied} + +| Variable | Values | Rationale | +|----------|--------|-----------| +| {var1} | {value_a, value_b} | {why these values} | + +## Dependent Variables (Metrics) +{What is being measured} + +| Metric | Unit | Collection Method | Canonical Name | +|--------|------|-------------------|----------------| +| {metric1} | {unit} | {how collected} | {canonical name in evaluation framework, or "NEW"} | + +Canonical names must match entries in the project's evaluation framework (if one +exists). For any metric marked "NEW", include: formula, unit, threshold value, and +a note that it must be registered in whatever evaluation catalog the project uses +before the experiment is finalized. + +## Controlled Variables +{What is held constant and how} + +| Variable | Fixed Value | Rationale | +|----------|-------------|-----------| +| {var1} | {value} | {why fixed} | + +## Inputs and Data + +{What data the experiment operates on. The inputs determine what the +experiment can prove.} + +- {What datasets are needed — existing, synthetic, or constructed?} +- {How will datasets be generated or obtained?} +- {What properties must the data have to be a valid test of the hypothesis?} +- {What range and diversity of inputs avoids narrow conclusions?} + +| Dataset | Source | Properties | Purpose | +|---------|--------|------------|---------| +| {dataset1} | {generated/existing/external} | {key characteristics} | {what it tests} | + +## Experiment Directory Layout + +All experiment artifacts live in one self-contained folder: + +``` +research/YYYY-MM-DD-{slug}/ +├── Dockerfile # Docker image spec — builds from environment.yml +├── Taskfile.yml # build-env, run-experiment, test tasks +├── environment.yml # Micromamba/conda env (required) +├── scripts/ +│ ├── {script_1} # {description} +│ └── ... +├── tests/ # Test suite for experiment scripts +│ ├── conftest.py +│ └── test_{script_1}.py +├── data/ +├── results/ +└── report.md +``` + +{Describe each planned file and its purpose.} + +## Environment + +{Explicitly state one of:} + +**Option A — No custom environment needed:** +{The project's existing toolchain is sufficient because {reason}. No +environment.yml will be created.} +Verify that `pytest` is available in the existing toolchain (`pytest --version`). If not, note that test_check requires pytest to pass. + +**Option B — Custom environment required (standard for research experiments):** +{The experiment requires {tools/libraries} not available in the project toolchain. +An environment.yml will be created. The implement-experiment skill builds a Docker +image from this YAML — all experiment code runs inside the container. Nothing is +installed on the host.} + +```yaml +name: {experiment-slug} +channels: + - conda-forge +dependencies: + - {package1}={version} + - {package2}={version} + - pytest # Required: enables test_check to discover and run experiment tests +``` + +{Rationale for each dependency.} + +## Implementation Phases + +### Phase 1: Directory Structure and Environment +- Create `research/YYYY-MM-DD-{slug}/` and subdirectories +- Create `environment.yml` (if needed) and build the environment +- Verify environment is functional + +### Phase 2: Data Generation +- Create data generation scripts in `scripts/` +- Generate datasets into `data/` +- Verify data has the required properties + +### Phase 3: Experiment Scripts +- Create measurement/benchmark scripts in `scripts/` +- Create any analysis or post-processing scripts +- Verify scripts run correctly with small inputs + +### Phase 4: Dry Run +- Execute the full experiment procedure with minimal inputs +- Verify metrics are collected correctly +- Confirm end-to-end pipeline works before committing to full runs + +### Phase 5: Test Infrastructure +- Create `tests/` directory and `tests/conftest.py` with shared fixtures +- For each experiment script in `scripts/`, create a corresponding `tests/test_{script_name}.py` +- Tests must cover: data loading without error, output shape/type validation, key metric + value sanity checks (e.g., result is non-empty, values are in expected range) +- Run `pytest --collect-only` in the research directory to verify test discovery +- Commit the test suite + +{Adapt phases as needed — not all experiments require all phases. Add or +remove phases to match the specific experiment. Each phase should list the +specific files to create and commands to run.} + +## Execution Protocol + +{Step-by-step procedure for running the actual experiment after +implementation is complete. Be specific about what commands to run, +what data to collect, and in what order.} + +## Analysis Plan +{How to interpret the results. Include statistical analysis if relevant +to the experiment type — not all experiments require it. Describe what +patterns or outcomes would support or refute the hypothesis.} + +## Success Criteria +{Explicit, measurable conditions that answer the research question} + +- **Conclusive positive:** {specific condition that supports H1} +- **Conclusive negative:** {specific condition that supports H0} +- **Inconclusive:** {conditions under which no conclusion can be drawn} + +## Threats to Validity + +### Internal +{Confounds that could invalidate results within this experiment} + +### External +{Limits on generalizability beyond the test conditions} + +## Estimated Resource Requirements +{Approximate compute time, disk space, dependencies needed} +``` + +### Step 3a — Extract YAML Frontmatter + +After writing the prose plan, extract structured metadata and write the +complete experiment plan file with YAML frontmatter prepended before the +`# Experiment Plan:` heading. The final file layout is: + +``` +--- +experiment_type: {one of: benchmark, configuration_study, causal_inference, robustness_audit, exploratory} + +estimand: + treatment: "{the intervention}" # RECOMMENDED; required when causal_inference + outcome: "{the measured effect}" + population: "{scope of units}" + contrast: "{A vs B vs C}" # REQUIRED for causal_inference + +hypothesis_h0: "{null hypothesis with measurable threshold}" # REQUIRED +hypothesis_h1: "{alt hypothesis with measurable threshold}" # REQUIRED + +metrics: # REQUIRED, min 1 + - name: "{metric_name}" + unit: "{unit}" + canonical_name: "{canonical name from evaluation framework, or NEW}" + collection_method: "{exact command or code path}" + threshold: "{success threshold}" + direction: "higher_is_better" # higher_is_better | lower_is_better | target_value + primary: true # mark exactly one when len(metrics) >= 2 + +baselines: # REQUIRED for benchmark/causal_inference + - name: "{comparator name}" + version: "{package==version or git SHA}" + tuning_budget: "{what tuning was done, or 'default'}" + +statistical_plan: # REQUIRED unless exploratory + test: "{primary statistical test}" + alpha: 0.05 + power_target: 0.80 + correction_method: "Holm-Bonferroni" # null | Bonferroni | Holm-Bonferroni | BH + sample_size_justification: "{why N is sufficient}" + min_detectable_effect: "{MDE in metric units}" + +environment: # REQUIRED + type: "custom" # standard | custom + spec_path: "research/{slug}/environment.yml" # required when type=custom + +success_criteria: # REQUIRED + conclusive_positive: "{conditions supporting H1, referencing metrics}" + conclusive_negative: "{conditions supporting H0}" + inconclusive: "{conditions where no conclusion can be drawn}" + +data_manifest: # REQUIRED — one entry per hypothesis (or shared) + - hypothesis: [H1, H2] # which hypotheses consume this data + source_type: synthetic # synthetic | fixture | external | gitignored + description: "Gaussian blobs, 10K-100K points" + acquisition: "generate in-script via sklearn.datasets" + location: null # null for in-script generation + verification: "non-empty ndarray with shape[0] >= 1000" + # - hypothesis: [H5] + # source_type: external + # description: "MERFISH spatial transcriptomics subset" + # acquisition: "python tests/visual_eval/generate_merfish_subset.py --n 100000" + # location: "temp/merfish_100k/" + # verification: "directory exists with >= 1 .parquet file, total size > 10MB" + # depends_on: "python tests/visual_eval/download_merfish.py" + +experiment_slug: "{YYYY-MM-DD-slug}" # optional, derived from directory layout +--- + +# Experiment Plan: {title} +...prose sections unchanged... +``` + +Use this prose section ↔ frontmatter mapping to extract fields: + +| Prose Section | Frontmatter Field(s) | +|---------------|---------------------| +| `## Hypothesis` (H0/H1 bold labels) | `hypothesis_h0`, `hypothesis_h1`, `estimand` | +| `## Independent Variables` table | `estimand.contrast`, `baselines[]` | +| `## Dependent Variables (Metrics)` table | `metrics[]` | +| `## Environment` | `environment` | +| `## Analysis Plan` | `statistical_plan` | +| `## Success Criteria` | `success_criteria` | +| `## Experiment Directory Layout` | `experiment_slug` | +| `## Inputs and Data` | `data_manifest[]` | + +### data_manifest (required) + +A list of data source entries, one per hypothesis (or shared across hypotheses). Each entry: + +**Field definitions:** +| Field | Required | Description | +|-------|----------|-------------| +| `hypothesis` | yes | List of hypothesis IDs that consume this data | +| `source_type` | yes | One of: `synthetic`, `fixture`, `external`, `gitignored` | +| `description` | yes | Human-readable description of the data | +| `acquisition` | yes | Exact command or method to produce/retrieve the data | +| `location` | no | Filesystem path where data will reside (null for in-script) | +| `verification` | yes | How to confirm the data is present and valid | +| `depends_on` | no | Prerequisite acquisition step (e.g., download before subset) | + +Apply these validation rules in order before writing the frontmatter: + +``` +V1: benchmark/causal_inference → len(baselines) >= 1 AND each baseline.version not empty + ERROR: "Benchmark/causal_inference experiments require at least one named baseline with a version" + +V2: causal_inference → estimand.contrast is not null + ERROR: "causal_inference requires estimand with treatment, outcome, and contrast fields" + +V3: !exploratory → statistical_plan present AND test not null + ERROR: "Non-exploratory experiments require a statistical_plan; use {test: 'none'} to waive" + +V4: environment.type=custom → spec_path not null + ERROR: "Custom environment requires spec_path pointing to environment.yml" + +V5: len(metrics) >= 2 → exactly one metric has primary: true + WARNING: "Multiple metrics but no primary designated; H1 threshold ambiguous" + +V6: any metric.canonical_name = "NEW" + WARNING: "Plan includes NEW metrics not yet in any registered evaluation framework" + +V7: hypothesis_h1 has no numeric threshold + WARNING: "H1 should include a measurable numeric threshold" + +V8: success_criteria.conclusive_positive should reference at least one metric.name + WARNING: "Success criteria does not reference any declared metric" + +V9: data_manifest completeness + ERROR if: + - Any hypothesis referenced in `success_criteria` has no entry in `data_manifest` + - Any entry with `source_type: external` or `source_type: gitignored` lacks a non-null `location` + - Any entry with `source_type: external` lacks a `depends_on` or explicit download command in `acquisition` + ERROR: "Data Manifest incomplete: {specific missing field or hypothesis}" +``` + +- ERRORs (V1–V4, V9): Stop frontmatter generation, append the error message to the plan + prose under a `## Frontmatter Validation Errors` section, and save the plan WITHOUT + a frontmatter block. Emit the `experiment_plan` token as usual. +- WARNINGs (V5–V8): Continue; log each as a `# WARNING: ...` YAML comment on the + relevant field line. + +Field requirements by experiment type: + +| Field | benchmark | config_study | causal_inference | robustness_audit | exploratory | +|-------|-----------|-------------|-----------------|-----------------|-------------| +| experiment_type | required | required | required | required | required | +| estimand | recommended | recommended | **required** | recommended | optional | +| hypothesis_h0/h1 | required | required | required | required | required | +| metrics | required | required | required | required | required | +| baselines | **required** | optional | **required** | optional | optional | +| statistical_plan | required | required | required | required | **waived** | +| environment | required | required | required | required | required | +| success_criteria | required | required | required | required | required | +| data_manifest | required | required | required | required | required | + +### Step 4 — Write Output + +Save the experiment plan to: +`{{AUTOSKILLIT_TEMP}}/plan-experiment/experiment_plan_{topic}_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +After saving, emit the structured output token as the very last line of your +text output: + +> **IMPORTANT:** Emit the structured output tokens as **literal plain text with no +> markdown formatting on the token names**. Do not wrap token names in `**bold**`, +> `*italic*`, or any other markdown. The adjudicator performs a regex match on the +> exact token name — decorators cause match failure. + +``` +experiment_plan = {absolute_path_to_experiment_plan} +``` diff --git a/src/autoskillit/skills_extended/plan-visualization/SKILL.md b/src/autoskillit/skills_extended/plan-visualization/SKILL.md new file mode 100644 index 0000000000..03f3ca7ea6 --- /dev/null +++ b/src/autoskillit/skills_extended/plan-visualization/SKILL.md @@ -0,0 +1,223 @@ +--- +name: plan-visualization +categories: [research, vis-lens] +description: > + Orchestrates 2–4 vis-lens skills in parallel to produce a figure inventory + (visualization-plan.md) and a report-placement outline (report-plan.md). + Runs after design review GO, before worktree creation. +--- + +# Plan Visualization Skill + +Reads the finalized experiment plan, selects 2–4 vis-lens skills via three-tier +logic, runs them in parallel, resolves conflicts across their `yaml:figure-spec` +outputs, and synthesizes a complete visualization plan. + +## When to Use + +- As the `plan_visualization` step of the `research` recipe, after `review_design` + GO and before `create_worktree` + +## Arguments + +``` +/autoskillit:plan-visualization {source_dir} {experiment_plan_path} {scope_report_path} +``` + +- `{source_dir}` — Absolute path to the source repo (the CWD before worktree creation) +- `{experiment_plan_path}` — Absolute path to the finalized experiment plan markdown +- `{scope_report_path}` — Absolute path to the scope report (may be empty string if absent) + +## Critical Constraints + +**NEVER:** +- Select fewer than 2 or more than 4 lenses +- Skip vis-lens-always-on (it is always Tier A) +- Run vis-lens calls across multiple assistant messages — all selected lens calls must + appear in a SINGLE assistant message to execute in parallel +- Write outputs outside `{{AUTOSKILLIT_TEMP}}/plan-visualization/` + +**ALWAYS:** +- Use `model: "sonnet"` when spawning all subagents via the Task tool +- Write a vis-lens context file for each selected lens before invoking it +- Log every conflict resolution decision in the Conflict Resolution Log table +- Emit `visualization_plan_path` and `report_plan_path` tokens as your final output + +## Workflow + +### Step 0 — Parse Arguments + +Extract `source_dir`, `experiment_plan_path`, and `scope_report_path` from arguments. +Read the experiment plan at `experiment_plan_path`. + +Extract the following fields (use sensible defaults if absent): +- `experiment_type` — string (e.g., "benchmark", "ablation", "correlation") +- `training_curves` — boolean (default: false) +- `num_DVs` — integer count of dependent variables (default: 1) +- `comparative` — boolean (true if multiple conditions compared head-to-head) +- `DV_types` — list of DV type strings (e.g., ["accuracy", "temporal", "latency"]) +- `num_conditions` — integer count of experimental conditions (default: 1) +- `target_domain` — string (e.g., "nlp", "cv", "rl", "general") + +### Step 1 — Three-Tier Lens Selection + +Build `selected_lenses` (list of 2–4 vis-lens skill slugs): + +**Tier A (always selected, mandatory):** +- `vis-lens-always-on` + +**Tier B (select 1–2 based on experiment_type and override rules):** + +Override rules (checked first, in priority order): +1. If `training_curves == true` → include `vis-lens-temporal` +2. If `num_DVs >= 6 AND comparative == true` → include `vis-lens-multi-compare` +3. If `DV_types` contains `"temporal"` → include `vis-lens-temporal` (if not already) +4. If `num_conditions >= 8` → include `vis-lens-multi-compare` (if not already) + +Experiment-type table (use when no override fires or to fill second Tier-B slot): +| experiment_type | Primary lens | Secondary lens (optional) | +|---|---|---| +| benchmark | vis-lens-chart-select | vis-lens-uncertainty | +| ablation | vis-lens-multi-compare | vis-lens-chart-select | +| correlation | vis-lens-chart-select | vis-lens-figure-table | +| regression | vis-lens-temporal | vis-lens-uncertainty | +| classification | vis-lens-chart-select | vis-lens-uncertainty | +| (default) | vis-lens-chart-select | — | + +Cap Tier B at 2 lenses total (overrides count toward this cap). + +**Tier C (0–1 based on target_domain):** +| target_domain | Lens | +|---|---| +| nlp | vis-lens-domain-norms | +| cv | vis-lens-domain-norms | +| rl | vis-lens-temporal | +| (others / general) | — (skip Tier C) | + +Only add Tier C lens if it is not already in Tier A or Tier B. + +**Enforcement:** Total must be 2–4. If total < 2, add `vis-lens-chart-select`. If total +> 4, drop the last Tier C lens, then last Tier B secondary. + +### Step 2 — Write Vis-Lens Context Files + +For each lens in `selected_lenses`, write a context file: + +Path: `{{AUTOSKILLIT_TEMP}}/plan-visualization/vis_ctx_{slug}_{YYYY-MM-DD_HHMMSS}.md` + +Template for each context file: +``` +# Vis-Lens Context: {slug} + +## Experiment Summary +{1–3 sentence description of the experiment from the plan} + +## Data Shape +- Dependent Variables ({num_DVs} total): {DV names and types} +- Independent Variables: {IV names, levels, and ranges} +- Conditions: {num_conditions} conditions +- Replication: {n_seeds or n_trials if available} + +## DV Specification +{For each DV: name, type (continuous/discrete/temporal), unit, expected range} + +## IV Specification +{For each IV: name, type, levels (for categorical) or range (for continuous)} + +## Comparison Structure +- Comparative: {true/false} +- Head-to-head pairs: {list if applicable} +- Factorial interactions: {list if applicable} + +## Expected Data Outputs +{List the files or data structures the experiment will produce, from the plan's +data_manifest or results/ section if available} +``` + +### Step 3 — Run Vis-Lens Skills in Parallel + +In a **single assistant message**, invoke all `selected_lenses` as slash commands: + +``` +/autoskillit:vis-lens-{slug1} {source_dir} {vis_ctx_path_for_slug1} +/autoskillit:vis-lens-{slug2} {source_dir} {vis_ctx_path_for_slug2} +... +``` + +Wait for all lens outputs. Read each lens's output file (the `yaml:figure-spec` blocks +within each lens's output markdown). + +**Empty plan handling:** If `vis-lens-always-on` returns `SKIP: no_figures_needed`, +record zero figures and proceed to Step 4 with an empty figure list. + +### Step 4 — Resolve Conflicts + +For each figure-spec block where two lenses disagree on chart type, color encoding, +or layout, apply the conflict resolution hierarchy: + +``` +accessibility > anti-pattern > domain-norms > chart-select +``` + +Resolution rules: +- `accessibility` (from `vis-lens-always-on` or `vis-lens-color-access`) wins over all +- `anti-pattern` findings (from `vis-lens-antipattern` or always-on pass 1) override + chart-select and domain-norms recommendations +- `domain-norms` (from `vis-lens-domain-norms`) overrides `chart-select` +- `chart-select` (from `vis-lens-chart-select`) is the lowest priority + +Every resolution must be logged as a row in the Conflict Resolution Log table. + +### Step 5 — Write visualization-plan.md + +Path: `{{AUTOSKILLIT_TEMP}}/plan-visualization/visualization-plan.md` + +Content structure: +```markdown +# Visualization Plan + +## Figure Inventory + +| Fig ID | Title | Lens Source | Chart Type | Data Source | Priority | +|--------|-------|-------------|------------|-------------|----------| +| fig-1 | ... | ... | ... | ... | P0/P1/P2 | + +## Figure Specifications + +{For each figure: paste the yaml:figure-spec block from the winning lens} + +## Code Allocation Hints + +{For each figure: note which module/file the plotting script should live in, +e.g., `research/{slug}/scripts/fig1_training_curves.py`} + +## Conflict Resolution Log + +| Fig ID | Dimension | Lens A | Lens A Rec | Lens B | Lens B Rec | Winner | Reason | +|--------|-----------|--------|------------|--------|------------|--------|--------| +``` + +### Step 6 — Write report-plan.md + +Path: `{{AUTOSKILLIT_TEMP}}/plan-visualization/report-plan.md` + +Content structure: +```markdown +# Report Plan + +## Section Outline + +| Report Section | Figure IDs | Notes | +|---|---|---| +| Executive Summary | — | no figures in summary | +| Results | fig-1, fig-2 | ... | +| Analysis | fig-3 | ... | +| Appendix | all | full captions | +``` + +### Step 7 — Emit Structured Tokens + +``` +visualization_plan_path = {absolute_path_to_visualization-plan.md} +report_plan_path = {absolute_path_to_report-plan.md} +``` diff --git a/src/autoskillit/skills_extended/prepare-issue/SKILL.md b/src/autoskillit/skills_extended/prepare-issue/SKILL.md index 38a16d3665..340d78c8b5 100644 --- a/src/autoskillit/skills_extended/prepare-issue/SKILL.md +++ b/src/autoskillit/skills_extended/prepare-issue/SKILL.md @@ -136,9 +136,12 @@ Your choice [C]: 3. If **edit**: ```bash # Fetch current body and append new context using a temp file to avoid shell injection - gh issue view {selected_number} --json body -q .body > /tmp/issue_edit_body.txt - printf '\n## Additional Context\n\n%s' "{description}" >> /tmp/issue_edit_body.txt - gh issue edit {selected_number} --body-file /tmp/issue_edit_body.txt + ts=$(date +%Y-%m-%d_%H%M%S) + EDIT_BODY_FILE="{{AUTOSKILLIT_TEMP}}/prepare-issue/edit_body_${ts}.md" + mkdir -p "{{AUTOSKILLIT_TEMP}}/prepare-issue" + gh issue view {selected_number} --json body -q .body > "${EDIT_BODY_FILE}" + printf '\n## Additional Context\n\n%s' "{description}" >> "${EDIT_BODY_FILE}" + gh issue edit {selected_number} --body-file "${EDIT_BODY_FILE}" ``` 4. Set `issue_number = selected_number` (no new issue will be created). 5. Fetch the updated issue for triage: @@ -179,25 +182,53 @@ provided (adopting an existing issue) or when `--dry-run` is active. **Validated audit report input (`is_validated_report = true`):** -1. Read the full report from `report_path` (or use `description` directly if the content - was provided inline rather than as a file path). -2. Derive the issue title from the report's H1 heading: strip the leading `# ` and use - the result verbatim (e.g. `Validated Audit Report — arch (2026-03-28)`). -3. Construct the issue body by applying all of the following transforms: - - **Remove** the `validated: true` front matter line and any immediately following - blank lines. - - **Remove** any line that begins with `**Original report:**` (it contains an artifact - file path the implementer cannot access). - - **Remove** any line that contains the substring `contested_findings_` - (this matches the contested-findings reference line regardless of surrounding formatting). - - **Remove** `| **Contested:** {N}` from the `**Findings processed:**` summary line (if - present; skip this rule if the Contested column is absent); keep only the Valid and - Exception Warranted counts. - - **Keep** everything else: the H1 title, the `## Validation Status` table, - the `## Validated Findings` section, and the `## Findings with Exceptions` section. -4. The resulting body must contain **only** actionable content — validated findings with - full detail (file:line, verdict, severity, exception notes). No artifact paths. No - contested findings content of any kind. +1. Derive the issue title from the validated report's H1 heading: strip the leading `# ` + and use the result verbatim. +2. Apply all strip transforms in a single deterministic shell pipeline: + + ```bash + ts=$(date +%Y-%m-%d_%H%M%S) + ISSUE_BODY_FILE="{{AUTOSKILLIT_TEMP}}/prepare-issue/issue_body_${ts}.md" + mkdir -p "{{AUTOSKILLIT_TEMP}}/prepare-issue" + + grep -v 'validated: true' "$report_path" \ + | grep -v '\.autoskillit/' \ + | grep -v 'contested_findings_' \ + | grep -v '| CONTESTED |' \ + | grep -v '| VALID BUT EXCEPTION WARRANTED |' \ + | sed 's/ | \*\*Contested:\*\* [0-9][0-9]*//' \ + | sed 's/ | \*\*Exception warranted:\*\* [0-9][0-9]*//' \ + > "${ISSUE_BODY_FILE}" || { echo 'ERROR: failed to process report_path'; exit 1; } + + # Strip the ## Findings with Exceptions section entirely: + awk '/^## Findings with Exceptions/{skip=1} skip && /^---/{skip=0; next} !skip' \ + "${ISSUE_BODY_FILE}" > "${ISSUE_BODY_FILE}.tmp" \ + && mv "${ISSUE_BODY_FILE}.tmp" "${ISSUE_BODY_FILE}" + ``` + + **What each transform removes:** + - `validated: true` — YAML front-matter sentinel (not content) + - `.autoskillit/` lines — all artifact paths (`**Original report:**` and any future variants) + - `contested_findings_` lines — footer reference to the excluded-findings file + - `| CONTESTED |` rows — CONTESTED verdict rows from `## Validation Status` table + - `| VALID BUT EXCEPTION WARRANTED |` rows — exception verdict rows from `## Validation Status` + - `| **Contested:** N` and `| **Exception warranted:** N` — count segments from the + `**Findings processed:**` summary line; leaves `**Findings processed:** {total} | **Valid:** {N}` + - `## Findings with Exceptions` through next `---` — the entire exception-findings section + +3. Call `gh issue create` using the temp file: + + ```bash + gh issue create \ + --title "{title}" \ + --body-file "${ISSUE_BODY_FILE}" + ``` + + Capture the returned issue URL and extract the issue number from it. + +The resulting body contains **only** actionable, VALID findings: the H1 title, the +`## Validation Status` table (VALID rows only), and the `## Validated Findings` section. +No artifact paths, no contested content, no exception-warranted content. **Standard input (`is_validated_report = false`):** @@ -268,18 +299,19 @@ If route is `recipe:implementation`: `gh issue edit`. Set `requirements_generated: true`, `requirements_appended: false`. 7. Otherwise, append the Requirements section: ```bash - gh issue edit {N} --body "$(gh issue view {N} --json body -q .body) - -## Requirements - -### {Group Name} + ts=$(date +%Y-%m-%d_%H%M%S) + EDIT_BODY_FILE="{{AUTOSKILLIT_TEMP}}/prepare-issue/edit_body_${ts}.md" + REQUIREMENTS_FILE="{{AUTOSKILLIT_TEMP}}/prepare-issue/requirements_${ts}.md" + mkdir -p "{{AUTOSKILLIT_TEMP}}/prepare-issue" -- **REQ-{GRP}-001:** ... -- **REQ-{GRP}-002:** ... + # Fetch current issue body to temp file (avoids shell interpolation): + gh issue view {N} --json body -q .body > "${EDIT_BODY_FILE}" -### {Group 2 Name} + # Populate ${REQUIREMENTS_FILE} with the generated requirements content, then: + printf '\n\n## Requirements\n\n' >> "${EDIT_BODY_FILE}" + cat "${REQUIREMENTS_FILE}" >> "${EDIT_BODY_FILE}" -- **REQ-{GRP2}-001:** ..." + gh issue edit {N} --body-file "${EDIT_BODY_FILE}" ``` 8. If the issue is too vague for clean requirement extraction (no clear goal, contradictory claims, or entirely implementation-prescriptive): do not force it. @@ -336,6 +368,11 @@ gh issue edit {issue_number} --add-label "{issue_type}" - Proceed past Step 2 (Auth) if `gh auth status` fails - Create a GitHub issue without displaying the draft and receiving explicit Y confirmation (unless `--issue N` or `--dry-run` is active) +- Use `--body` inline for the validated-report `gh issue create` — always write the + stripped body to `{{AUTOSKILLIT_TEMP}}/prepare-issue/issue_body_{timestamp}.md` and + pass `--body-file` (prevents LLM paraphrase, shell truncation, and special-character injection) +- Use `--body` shell substitution (`--body "$(...)`) for `gh issue edit` — always write to + `{{AUTOSKILLIT_TEMP}}/prepare-issue/req_body_{timestamp}.md` and use `--body-file` **ALWAYS:** - Confirm repo access with `gh repo view` before any issue operations diff --git a/src/autoskillit/skills_extended/prepare-pr/SKILL.md b/src/autoskillit/skills_extended/prepare-pr/SKILL.md new file mode 100644 index 0000000000..6ee1c43dd0 --- /dev/null +++ b/src/autoskillit/skills_extended/prepare-pr/SKILL.md @@ -0,0 +1,239 @@ +--- +name: prepare-pr +categories: [github] +description: > + Reads plan(s), runs git diff, classifies changed files, selects 1–3 arch-lens slugs, + writes one context file per lens, and writes a PR prep file. Does NOT invoke arch-lens + skills. Part 1 of 3 in the decomposed PR flow. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: prepare-pr] Preparing PR metadata and arch-lens context...'" + once: true +--- + +# Prepare PR + +Read plan(s), analyze changed files, select relevant arch-lens slugs, write one PR context +file per lens, and write a PR prep file for downstream use by `compose-pr`. + +This skill Does NOT invoke arch-lens skills or any other sub-skills. It is Part 1 of 3 +in the decomposed PR flow (prepare → run_arch_lenses → compose). + +## Arguments + +`/autoskillit:prepare-pr {plan_paths} {run_name} {base_branch} [closing_issue] [conflict_report_path]` + +- **plan_paths** — Comma-separated absolute paths to implementation plan markdown files +- **run_name** — Branch name prefix (e.g. `impl`, `feature/123`, `fix/653`); determines + `[FEATURE]`/`[FIX]` prefix +- **base_branch** — PR target branch +- **closing_issue** (optional) — GitHub issue number for requirements fetch + `Closes #N` +- **conflict_report_path** (optional) — Absolute path to conflict resolution report + +## Critical Constraints + +**NEVER:** +- Invoke arch-lens skills or any other sub-skills +- Create files outside `{{AUTOSKILLIT_TEMP}}/prepare-pr/` +- Fail if closing_issue is absent or gh is unavailable — degrade gracefully + +**ALWAYS:** +- Emit all three output tokens (`prep_path`, `selected_lenses`, `lens_context_paths`) +- Classify changed files as new (★) vs modified (●) + +## Context Limit Behavior + +When context is exhausted mid-execution, prep files may be partially written. +The recipe routes to `on_context_limit` (typically `release_issue_failure`), +abandoning the PR preparation. + +**Before emitting structured output tokens:** +1. If prep files were not fully written, emit `prep_path = ` (empty) as a fallback +2. Emit whatever was completed; the orchestrator handles the context-limit route + +## Workflow + +### Step 0: Parse Arguments and Initialize + +Parse positional arguments: +- arg[1] = `plan_paths` (comma-separated) +- arg[2] = `run_name` +- arg[3] = `base_branch` +- arg[4] = `closing_issue` (optional — may be absent or empty string) +- arg[5] = `conflict_report_path` (optional — may be absent or empty string) + +Derive `feature_branch` (`git rev-parse --abbrev-ref HEAD`). +Create temp dir (relative to the current working directory): +```bash +mkdir -p {{AUTOSKILLIT_TEMP}}/prepare-pr/ +FEATURE_BRANCH=$(git rev-parse --abbrev-ref HEAD) +ts=$(date +%Y-%m-%d_%H%M%S) +CLOSING_ISSUE="${4:-}" +``` +Generate timestamp `ts` from the bash block above. + +### Step 1: Fetch Requirements from Closing Issue + +- If `closing_issue` is absent or empty string: skip — set `requirements_section = ""`. +- Fetch issue body: + ```bash + gh issue view $CLOSING_ISSUE --json body -q .body + ``` +- Extract the `## Requirements` section: everything from `## Requirements` to the next + `## ` heading or end of body, whichever comes first. +- If no `## Requirements` section found: set `requirements_section = ""`. +- Skip gracefully if `gh` is unavailable — `requirements_section` remains `""`. + +### Step 2: Extract PR Title from Plans + +Read all plan files. For each, extract the first `# ` heading line, strip the `# ` prefix, +and strip any trailing `— PART [A-Z] ONLY` suffix. + +- **Single plan:** Use the heading directly as `task_title`. +- **Multiple plans:** Spawn a subagent (Task tool, model: sonnet) with all extracted + headings. Instruct it to synthesize a single concise PR title (under 70 characters). + +**PR Title Prefix (derived from run_name):** + +```bash +case "$RUN_NAME" in + feature*) TITLE="[FEATURE] $BASE_TITLE" ;; + fix*) TITLE="[FIX] $BASE_TITLE" ;; + *) TITLE="$BASE_TITLE" ;; +esac +``` + +### Step 3: Load Conflict Resolution Report + +- If `conflict_report_path` is absent or empty: skip — `conflict_resolution_table = ""`. +- Read the file at `conflict_report_path`. +- Extract the `## Per-File Resolution Decisions` table. +- Skip gracefully if the file does not exist. + +### Step 4: Classify Changed Files + +Run git diff to classify changed files: + +```bash +git diff --name-only $BASE_BRANCH..$FEATURE_BRANCH +git diff --diff-filter=A --name-only $BASE_BRANCH..$FEATURE_BRANCH # new_files +git diff --diff-filter=M --name-only $BASE_BRANCH..$FEATURE_BRANCH # modified_files +``` + +Store as separate lists: `new_files` (added, ★) and `modified_files` (modified, ●). + +### Step 5: Select Arch-Lens Slugs + +Spawn a subagent (Task tool, model: sonnet) with the list of changed file paths and the +following lens menu: + +``` +c4-container, concurrency, data-lineage, deployment, development, +error-resilience, module-dependency, operational, process-flow, +repository-access, scenarios, security, state-lifecycle +``` + +Instruct the subagent to return 1–3 lens slugs. Only include a lens if at least one +changed file maps to that lens's concern. + +**Development lens guard:** The `development` lens must ONLY be selected if at least one +changed file matches a build/test configuration pattern: `pyproject.toml`, `Taskfile*`, +`conftest.py`, `.github/workflows/*`, `Makefile`, `setup.cfg`, `setup.py`, `tox.ini`, +`noxfile.py`, or files under a `ci/` directory. If no changed file matches these patterns, +do NOT select the `development` lens regardless of other criteria. + +Output: comma-separated slug list → `selected_lens_slugs`. + +### Step 6: Write Context Files per Lens + +For each selected slug, write one context file to +`{{AUTOSKILLIT_TEMP}}/prepare-pr/pr_arch_lens_context_{slug}_{ts}.md`: + +```markdown +# PR Context — Changed Files + +This diagram is for a Pull Request. Focus the diagram on the areas of the codebase +affected by these changes. Do not produce a generic whole-project view. + +## New files (use ★ prefix on these nodes): +{list of new_files, or "None"} + +## Modified files (use ● prefix on these nodes): +{list of modified_files, or "None"} + +## Instructions: +- Focus exploration and the diagram on the architectural areas these files belong to +- Use ★ prefix on nodes representing new files/components +- Use ● prefix on nodes representing modified files/components +- Leave unchanged components unmarked (include only if needed for context/connectivity) +- The diagram should help PR reviewers understand the architectural impact +``` + +Record absolute paths in `lens_context_paths` list (comma-separated). + +### Step 7: Read Plan Summaries + +Read `## Summary` from each plan file. Store plan summaries for the prep file. + +### Step 8: Write PR Prep File + +Write PR prep file to `{{AUTOSKILLIT_TEMP}}/prepare-pr/pr_prep_{ts}.md`: + +```markdown +# PR Prep: {task_title} + +## Metadata + +- feature_branch: {feature_branch} +- base_branch: {base_branch} +- closing_issue: {issue_number or ""} +- plan_paths: {comma-separated} + +## Title + +{task_title} + +## Plan Summary + +{for single plan: ## Summary section content} +{for multiple plans: individual summaries with group headings} + +## Requirements + +{requirements_section or ""} + +## Conflict Resolution Table + +{conflict_resolution_table or ""} + +## Changed Files + +### New (★): +{new_files list or "None"} + +### Modified (●): +{modified_files list or "None"} + +## Selected Lenses + +{comma-separated slugs} + +## Lens Context Paths + +{comma-separated absolute paths} +``` + +## Output + +Emit these structured output tokens (literal plain text, no markdown decoration). +All output paths are absolute (resolve `{{AUTOSKILLIT_TEMP}}/prepare-pr/` relative to +the current working directory using `$(pwd)`): + +``` +prep_path = /absolute/path/{{AUTOSKILLIT_TEMP}}/prepare-pr/pr_prep_{ts}.md +selected_lenses = module-dependency,process-flow +lens_context_paths = /abs/ctx_module-dependency_{ts}.md,/abs/ctx_process-flow_{ts}.md +``` diff --git a/src/autoskillit/skills_extended/prepare-research-pr/SKILL.md b/src/autoskillit/skills_extended/prepare-research-pr/SKILL.md new file mode 100644 index 0000000000..d74a4354b4 --- /dev/null +++ b/src/autoskillit/skills_extended/prepare-research-pr/SKILL.md @@ -0,0 +1,247 @@ +--- +name: prepare-research-pr +categories: [research] +description: > + Reads a research report and experiment plan, synthesizes a recommendation, + selects 1-2 exp-lens lenses, writes a context file per lens, and writes a + PR prep file. Does NOT open a PR. Part 1 of 3 in the decomposed research-PR flow. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: prepare-research-pr] Preparing research PR metadata...'" + once: true +--- + +# Prepare Research PR + +Reads a completed experiment report and plan, synthesizes a directional +recommendation, selects 1-2 exp-lens lenses, writes a context file per lens, +and writes a PR prep file for downstream use by `compose-research-pr`. +Does NOT invoke any exp-lens skills or create a PR. + +## Arguments + +`/autoskillit:prepare-research-pr {report_path} {experiment_plan_path} {worktree_path} {base_branch}` + +- **report_path** — Absolute path to `research/{slug}/README.md` (post-rename by `commit_research_artifacts`) +- **experiment_plan_path** — Absolute path to the experiment plan (from `${{ context.experiment_plan }}`) +- **worktree_path** — Worktree root directory +- **base_branch** — PR target branch + +## Critical Constraints + +**NEVER:** +- Invoke exp-lens skills — they are run in separate sessions by the recipe orchestrator +- Create files outside `{{AUTOSKILLIT_TEMP}}/prepare-research-pr/` (relative to the current working directory) +- Fail silently — always emit all three output tokens as your final output + +**ALWAYS:** +- Use Agent subagents (not slash commands) for reading and synthesis +- Emit `prep_path`, `selected_lenses`, and `lens_context_paths` as your final output +- Write all output paths as absolute paths + +## Lens Selection Table + +| experiment_type | Primary Lens | Secondary Lens (optional) | +|---|---|---| +| benchmark | exp-lens-fair-comparison | exp-lens-estimand-clarity | +| configuration_study | exp-lens-iterative-learning | exp-lens-sensitivity-robustness | +| causal_inference | exp-lens-causal-assumptions | exp-lens-estimand-clarity | +| robustness_audit | exp-lens-severity-testing | exp-lens-validity-threats | +| exploratory | exp-lens-estimand-clarity | exp-lens-exploratory-confirmatory | + +## Experiment Status Badges + +- `CONCLUSIVE_POSITIVE` — hypothesis supported; results meet success criteria +- `CONCLUSIVE_NEGATIVE` — hypothesis refuted; results clearly below threshold +- `INCONCLUSIVE` — results ambiguous; insufficient signal or mixed evidence +- `FAILED` — experiment could not be completed; results invalid + +--- + +## Workflow + +### Step 0: Parse arguments and create temp dir + +Parse positional args: +- arg[1] = report_path +- arg[2] = experiment_plan_path +- arg[3] = worktree_path +- arg[4] = base_branch + +Derive `feature_branch`: + + FEATURE_BRANCH=$(git -C "{worktree_path}" rev-parse --abbrev-ref HEAD) + +Create temp directory: + + mkdir -p {{AUTOSKILLIT_TEMP}}/prepare-research-pr/ + +Generate a timestamp `ts` (format: `YYYY-MM-DD_HHMMSS`) for unique file naming. + +### Step 1: Read report via Agent subagent + +Spawn an **Explore** subagent to read `{report_path}` and extract: +- Executive summary +- Conclusions +- Recommendations +- Results section (findings table, key metrics) +- Experiment status badge (CONCLUSIVE_POSITIVE / CONCLUSIVE_NEGATIVE / INCONCLUSIVE / FAILED) +- Title from the first H1 heading or `title:` field + +Store extracted content as `report_content`. + +### Step 2: Read experiment plan via Agent subagent + +Spawn an **Explore** subagent to read `{experiment_plan_path}` and extract: +- `experiment_type` (benchmark / configuration_study / causal_inference / robustness_audit / exploratory) +- H0 (null hypothesis) +- H1 (alternative hypothesis) +- Independent Variables (IV) table +- Dependent Variables / Metrics (DV) table +- Controlled Variables list +- Success Criteria +- Methodology section + +Store extracted content as `plan_content`. + +### Step 3: Synthesize recommendation via sonnet subagent + +Spawn a **sonnet** subagent with the report's Conclusions, Recommendations, and +experiment status. Produce a 1-3 sentence directional recommendation (inverted pyramid — +most important finding first). Store as `recommendation`. + +### Step 4: Select lenses via sonnet subagent + +Spawn a **sonnet** subagent with `experiment_type` and the plan's IV/DV structure. +Select 1-2 exp-lens slugs using the Lens Selection Table above. + +Output: a list of 1-2 slugs, e.g. `["fair-comparison", "estimand-clarity"]`. +Store as `selected_lens_slugs`. + +### Step 5: Write one context file per lens + +For each slug in `selected_lens_slugs`, write a context file to: + + {{AUTOSKILLIT_TEMP}}/prepare-research-pr/exp_lens_context_{slug}_{ts}.md + +The context file must contain (enough for the lens to build its diagram without +reading the entire CWD): + +```markdown +# Experiment Context: {slug} Lens + +## Hypotheses + +| | Hypothesis | +|---|---| +| H0 | {null hypothesis} | +| H1 | {alternative hypothesis} | + +## Independent Variables + +| Variable | Values / Levels | Role | +|----------|-----------------|------| +{rows from plan's IV table} + +## Dependent Variables / Metrics + +| Metric | Unit | Threshold | +|--------|------|-----------| +{rows from plan's DV table} + +## Controlled Variables + +{list from plan} + +## Success Criteria + +{from plan} + +## Experiment Type + +{experiment_type} +``` + +Record the absolute paths in `lens_context_paths` list (same order as slugs). + +### Step 6: Build results summary + +From the report's Results section, construct: +- Findings table (Finding / Result / Confidence) +- Experiment status badge +- Key metrics (if standardized metrics referenced in the report, include inline) + +Store as `results_summary` (plain text, will be embedded in prep file). + +### Step 7: Write PR prep file + +Write to `{{AUTOSKILLIT_TEMP}}/prepare-research-pr/pr_prep_{ts}.md`: + +```markdown +# PR Prep: {title from report} + +## Metadata + +- report_path: {absolute path} +- experiment_plan_path: {absolute path} +- feature_branch: {branch} +- base_branch: {branch} +- experiment_type: {type} +- status_badge: {CONCLUSIVE_POSITIVE | CONCLUSIVE_NEGATIVE | INCONCLUSIVE | FAILED} + +## Recommendation + +{recommendation from Step 3} + +## Results Summary + +{results_summary from Step 6} + +## Hypothesis Table + +| | Hypothesis | +|---|---| +| H0 | {H0} | +| H1 | {H1} | + +## Metrics Table + +| Metric | Unit | Threshold | +|--------|------|-----------| +{DV rows} + +## Methodology + +{condensed from plan's Methodology section} + +## Selected Lenses + +{comma-separated slugs} + +## Lens Context Paths + +{comma-separated absolute paths} +``` + +Store the absolute path as `prep_file_path`. + +--- + +## Output + +Emit these tokens as **literal plain text** (no markdown formatting on the token names) +as your final output: + +``` +prep_path = /absolute/path/{{AUTOSKILLIT_TEMP}}/prepare-research-pr/pr_prep_{ts}.md +selected_lenses = fair-comparison,estimand-clarity +lens_context_paths = /abs/ctx_fair-comparison_{ts}.md,/abs/ctx_estimand-clarity_{ts}.md +``` + +Where: +- `selected_lenses` is a comma-separated list of lens slugs (no spaces) +- `lens_context_paths` is a comma-separated list of absolute context file paths in the + same order as `selected_lenses` diff --git a/src/autoskillit/skills_extended/process-issues/SKILL.md b/src/autoskillit/skills_extended/process-issues/SKILL.md index b357c9898d..c45e37594e 100644 --- a/src/autoskillit/skills_extended/process-issues/SKILL.md +++ b/src/autoskillit/skills_extended/process-issues/SKILL.md @@ -19,14 +19,14 @@ issues upfront, load recipe, execute session, collect result, report. ## When to Use -- After `/autoskillit:triage-issues` has produced a manifest in `.autoskillit/temp/triage-issues/` +- After `/autoskillit:triage-issues` has produced a manifest in `{{AUTOSKILLIT_TEMP}}/triage-issues/` - User says "process issues", "run issues", "execute pipeline for issues" - When a triage manifest exists and batched issues need implementation sessions launched ## Critical Constraints **NEVER:** -- Create files outside `.autoskillit/temp/process-issues/` directory +- Create files outside `{{AUTOSKILLIT_TEMP}}/process-issues/` directory - Apply `batch:N` labels to GitHub issues (batch assignments are internal — they live only in the manifest JSON, not on GitHub objects) - Modify any source code files @@ -37,7 +37,7 @@ issues upfront, load recipe, execute session, collect result, report. - Process batches in ascending order: batch 1 before batch 2 before batch 3 - Use `load_recipe` to execute the recipe for each issue - Emit `---process-issues-result---` result block on completion (success or failure) -- Write the summary report to `.autoskillit/temp/process-issues/` (relative to the current working directory) +- Write the summary report to `{{AUTOSKILLIT_TEMP}}/process-issues/` (relative to the current working directory) - Use `model: "sonnet"` when spawning subagents via the Task tool - Use `gh` CLI for all GitHub operations (not raw API calls) - Include `--force` in all `gh label create` calls @@ -69,7 +69,7 @@ Parse arguments: 1. If a positional path argument was given, use it directly. 2. Otherwise, auto-discover the most recently modified manifest: ```bash - ls -t .autoskillit/temp/triage-issues/triage_manifest_*.json 2>/dev/null | head -1 + ls -t {{AUTOSKILLIT_TEMP}}/triage-issues/triage_manifest_*.json 2>/dev/null | head -1 ``` 3. If no manifest is found, abort: > "No triage manifest found. Run `/autoskillit:triage-issues` first, @@ -162,10 +162,6 @@ After this phase: For each batch in **ascending order** (batch 1, then batch 2, etc.): -**CRITICAL:** Do NOT output any prose status text between batches. After -completing one batch (all issues processed, optional merge cycle done), -immediately begin the batch header (3a) for the next batch. - - If `--batch N` was given, skip all batches with a different number. **3a. Log batch header:** @@ -178,11 +174,6 @@ Processing X issues: **3b. For each issue in the batch (process sequentially):** -**CRITICAL:** Do NOT output any prose status text between issues. After -completing one issue's processing (step 6), immediately begin step 1 -(check pre_claimed_urls) for the next issue. Inter-issue announcements -create end_turn windows that cause stochastic session termination. - 1. **Check pre_claimed_urls:** If `issue_url` is NOT in `pre_claimed_urls` → skip (excluded by upfront claim phase — another session holds it). @@ -260,21 +251,38 @@ run_skill("/autoskillit:analyze-prs {base_branch}") Parse the `pr_order_file` from the skill output. For each PR in the recommended merge order: -**CRITICAL:** Do NOT output any prose status text between PRs. After one -merge-pr completes, immediately call run_skill for the next PR. - ``` run_skill("/autoskillit:merge-pr {pr_number} {complexity}") ``` Log merge results and proceed to the next batch. +**3d. Batch Clone Cleanup (always, after all batches complete):** + +After all batches finish (whether or not `--merge-batch` was used), call: + +``` +batch_cleanup_clones() +``` + +This reads the shared registry at `{{AUTOSKILLIT_TEMP}}/clone-cleanup-registry.json`, +deletes all clones registered with `status=success` by the **current kitchen** (their +pipelines completed cleanly), and leaves all `status=error` clones on disk for investigation. + +The call is scoped to the current kitchen's entries by default — entries registered by other +parallel orchestrator sessions are not touched. + +**Operator escape hatch (recovery only):** `batch_cleanup_clones(all_owners="true")` ignores +owner scoping and deletes all success-status entries, including legacy orphan entries from +registries created before the owner field was introduced. Do not use this on the normal happy +path — it is intended for manual recovery of stale registry files only. + ### Step 4: Write Summary Report Compute timestamp: `YYYY-MM-DD_HHMMSS`. -Create `.autoskillit/temp/process-issues/` if it does not exist. +Create `{{AUTOSKILLIT_TEMP}}/process-issues/` if it does not exist. -Write `.autoskillit/temp/process-issues/process_report_{ts}.md`: +Write `{{AUTOSKILLIT_TEMP}}/process-issues/process_report_{ts}.md`: ```markdown # Process Issues Report — {ts} @@ -313,7 +321,7 @@ Print the structured result for pipeline capture: ``` ---process-issues-result--- { - "report_path": ".autoskillit/temp/process-issues/process_report_{ts}.md", + "report_path": "{{AUTOSKILLIT_TEMP}}/process-issues/process_report_{ts}.md", "total_issues": N, "successes": X, "failures": Y, @@ -330,7 +338,7 @@ Print the structured result for pipeline capture: ## Output Location ``` -.autoskillit/temp/process-issues/ +{{AUTOSKILLIT_TEMP}}/process-issues/ process_report_{ts}.md # Human-readable summary (created per run) ``` diff --git a/src/autoskillit/skills_extended/rectify/SKILL.md b/src/autoskillit/skills_extended/rectify/SKILL.md index 28996b4150..09d42bdc69 100644 --- a/src/autoskillit/skills_extended/rectify/SKILL.md +++ b/src/autoskillit/skills_extended/rectify/SKILL.md @@ -1,5 +1,6 @@ --- name: rectify +activate_deps: [arch-lens] description: Deep investigation of test gaps and architectural weaknesses following an investigation, then devise a plan for architectural immunity rather than direct fixes. Use when user says "rectify", "rectify this", or wants to address root architectural causes after an investigation. hooks: PreToolUse: @@ -36,7 +37,7 @@ Do not change any code. - Modify any source code files - Propose bandaid fixes, fallbacks, or direct-only fixes - Suggest backward compatibility shims -- Create files outside `.autoskillit/temp/rectify/` directory +- Create files outside `{{AUTOSKILLIT_TEMP}}/rectify/` directory **ALWAYS:** - Use subagents for parallel exploration @@ -44,14 +45,13 @@ Do not change any code. - Focus on architectural immunity over direct fixes - Identify how tests missed the issue and similar/related bugs - Map the components and their connections thoroughly -- Write the plan as markdown to `.autoskillit/temp/rectify/` directory (relative to the current working directory) +- Write the plan as markdown to `{{AUTOSKILLIT_TEMP}}/rectify/` directory (relative to the current working directory) - After writing the plan file, emit the **absolute path** as a structured output token - immediately before `%%ORDER_UP%%`. The save path is relative (`.autoskillit/temp/rectify/...`) but + as your final output. The save path is relative (`{{AUTOSKILLIT_TEMP}}/rectify/...`) but the token **must** use the absolute path (prepend the full CWD): ``` - plan_path = /absolute/cwd/.autoskillit/temp/rectify/{filename}.md - plan_parts = /absolute/cwd/.autoskillit/temp/rectify/{filename}.md - %%ORDER_UP%% + plan_path = /absolute/cwd/{{AUTOSKILLIT_TEMP}}/rectify/{filename}.md + plan_parts = /absolute/cwd/{{AUTOSKILLIT_TEMP}}/rectify/{filename}.md ``` This token is MANDATORY — the pipeline cannot capture the output without it. - The solution must solve more than just the immediate issue @@ -60,14 +60,14 @@ Do not change any code. ### Step 1: Identify the Investigation Context -Locate the most recent investigation report in `.autoskillit/temp/investigate/` or from conversation context. Extract: +Locate the most recent investigation report in `{{AUTOSKILLIT_TEMP}}/investigate/` or from conversation context. Extract: - The root cause identified - Affected components - Test gaps noted - Any recommendations made **Path-existence guard:** Before issuing a `Read` call on a path that is not guaranteed to -exist (e.g., plan file arguments, `.autoskillit/temp/investigate/` reports, external file references), use +exist (e.g., plan file arguments, `{{AUTOSKILLIT_TEMP}}/investigate/` reports, external file references), use `Glob` or `ls` to confirm the path exists first. This prevents ENOENT errors that cascade into sibling parallel-call cancellations. @@ -152,7 +152,7 @@ After finalizing the plan, determine which architecture lens best illustrates th **4b. Write your lens selection rationale to a file using the Write tool:** -- **Path:** `.autoskillit/temp/rectify/arch_lens_selection_{YYYY-MM-DD_HHMMSS}.md` +- **Path:** `{{AUTOSKILLIT_TEMP}}/rectify/arch_lens_selection_{YYYY-MM-DD_HHMMSS}.md` - **Content:** Which lens was selected and why (1-2 sentences of rationale). **4c. MANDATORY: LOAD the appropriate arch-lens skill using the Skill tool:** @@ -173,6 +173,8 @@ After finalizing the plan, determine which architecture lens best illustrates th | State Lifecycle | `/autoskillit:arch-lens-state-lifecycle` | | Deployment | `/autoskillit:arch-lens-deployment` | +If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, skip the diagram step and proceed without the architectural diagram. + **4d. Create the diagram following the loaded skill's instructions:** - Focus on the PROPOSED changes (use `newComponent` class for new elements) - Show how new components integrate with existing architecture @@ -204,7 +206,7 @@ If the plan exceeds 500 lines, split it into multiple files (`_part_a`, `_part_b - The title of each part file MUST include `— PART A ONLY` (or B, C, etc.). - Each part file MUST open with: `> **PART {X} ONLY. Do not implement any other part. Other parts are separate tasks requiring explicit authorization.**` -Save the plan to: `.autoskillit/temp/rectify/rectify_{topic}_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Save the plan to: `{{AUTOSKILLIT_TEMP}}/rectify/rectify_{topic}_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) **Structured output:** After saving the file(s), emit the following lines so pipeline orchestrators can capture both fields: diff --git a/src/autoskillit/skills_extended/resolve-claims-review/SKILL.md b/src/autoskillit/skills_extended/resolve-claims-review/SKILL.md new file mode 100644 index 0000000000..080f988b2d --- /dev/null +++ b/src/autoskillit/skills_extended/resolve-claims-review/SKILL.md @@ -0,0 +1,508 @@ +--- +name: resolve-claims-review +categories: [research] +description: > + Fetch claim findings from audit-claims, run citation-aware intent validation + (ACCEPT/REJECT/DISCUSS), apply targeted citation fixes, escalate findings + requiring experiment reruns, and post inline replies. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: resolve-claims-review] Resolving claim review findings...'" + once: true +--- + +# Resolve Claims Review Skill + +Apply `changes_requested` claim findings from a research PR to the research +worktree. Reads open review threads from `audit-claims`, runs citation-aware +intent validation, applies targeted citation fixes by fix-strategy taxonomy, +escalates unrerunnable findings, resolves addressed threads, and posts inline +replies so a follow-up push closes the review cycle. + +## Arguments + +`/autoskillit:resolve-claims-review {worktree_path} {base_branch}` + +- **worktree_path** — Absolute path to the research worktree +- **base_branch** — Target branch for the PR + +## When to Use + +Called by the research recipe when `audit_claims` routes `changes_requested` via +`route_claims_resolve`. Bounded by `retries: 2` — on exhaustion routes to +`merge_escalations`. + +## Critical Constraints + +**NEVER:** +- Merge or push the branch — the recipe's `re_push_research` step handles push +- Dismiss review threads without addressing the underlying comment +- Create files outside `{{AUTOSKILLIT_TEMP}}/resolve-claims-review/` +- Exceed 3 fix-and-retry iterations +- Delete or discard the working directory on failure +- Modify tests to suppress failures introduced by reviewer fixes +- Use file-path-segment grouping — claim comments are grouped by **dimension**, not by file path + +**ALWAYS:** +- Find the PR by feature branch at invocation time (not a hardcoded number) +- Commit all fixes before returning control to the orchestrator +- Run intent validation BEFORE making any code changes +- Gracefully degrade (exit 0, report skip) if `gh` is unavailable or no PR is found +- Report a structured summary including escalation count + +## Configuration + +The skill reads the `claims_review` namespace from `.autoskillit/config.yaml`: + +```yaml +claims_review: + validation_command: null # command to validate research artifacts after fixes; null = skip validation + validation_timeout: 120 # seconds before treating validation as a failure +``` + +This namespace is not in `defaults.yaml` (it has no global default value); if absent, the +skill uses the in-code defaults shown above. + +## Workflow + +Read `claims_review.validation_command` (default: `null`) and +`claims_review.validation_timeout` (default: `120`) from `.autoskillit/config.yaml`. + +### Step 0: Validate Arguments + +Parse two positional arguments: `worktree_path` and `base_branch`. + +Derive `feature_branch` via: +```bash +feature_branch=$(git -C "$worktree_path" rev-parse --abbrev-ref HEAD 2>/dev/null || echo "") +if [ -z "$feature_branch" ]; then + echo "Error: could not determine feature_branch from '$worktree_path'" >&2 + exit 1 +fi +``` + +Read config: +```python +import yaml, pathlib +cfg = yaml.safe_load(pathlib.Path(".autoskillit/config.yaml").read_text()) if pathlib.Path(".autoskillit/config.yaml").exists() else {} +cr_cfg = cfg.get("claims_review", {}) +validation_command = cr_cfg.get("validation_command", None) +validation_timeout = cr_cfg.get("validation_timeout", 120) +``` + +If either positional arg is missing, abort with: +`"Usage: /autoskillit:resolve-claims-review "` + +### Step 0.5 — Code-Index Initialization (required before any code-index tool call) + +Call `set_project_path` with the repo root where this skill was invoked (not a worktree path): + +``` +mcp__code-index__set_project_path(path="{PROJECT_ROOT}") +``` + +Code-index tools require **project-relative paths**. Always use paths like: + + src/mypackage/core/module.py + +NOT absolute paths like: + + /path/to/project/src/mypackage/core/module.py + +Agents launched via `run_skill` inherit no code-index state from the parent session — this +call is mandatory at the start of every headless session that uses code-index tools. + +### Step 1: Find the Open PR + +```bash +PR_LIST_OUTPUT=$(gh pr list --head "$feature_branch" --base "$base_branch" \ + --json number,url -q '.[0] | "\(.number) \(.url)"' 2>/dev/null || echo "") +PR_NUMBER=$(echo "$PR_LIST_OUTPUT" | awk '{print $1}') +PR_URL=$(echo "$PR_LIST_OUTPUT" | awk '{print $2}') + +# Graceful degradation: .[0] returns null when no PR matches; PR_NUMBER will be empty +if [ -z "$PR_NUMBER" ] || [ "$PR_NUMBER" = "null" ]; then + echo "No PR found or gh unavailable — skipping claims review resolution" + exit 0 +fi +``` + +Get owner/repo: +```bash +gh repo view --json nameWithOwner -q .nameWithOwner +``` + +If `gh` is unavailable or not authenticated, or no PR is found: +- Log "No PR found or gh unavailable — skipping claims review resolution" +- Exit 0 (graceful degradation — do not fail the pipeline) + +### Step 2: Fetch Review Comments + +Fetch inline comments (anchored to specific file lines): +```bash +gh api repos/{owner}/{repo}/pulls/{number}/comments --paginate +``` + +Fetch top-level review bodies (summary reviews): +```bash +gh api repos/{owner}/{repo}/pulls/{number}/reviews --paginate +``` + +Fetch review thread node IDs using cursor-based pagination to handle PRs with more than +100 threads: + +```bash +gh api graphql \ + -f query='query($owner:String!,$repo:String!,$number:Int!,$after:String){repository(owner:$owner,name:$repo){pullRequest(number:$number){reviewThreads(first:100,after:$after){pageInfo{hasNextPage endCursor}nodes{id isResolved comments(first:1){nodes{databaseId}}}}}}}' \ + -F owner="$owner" \ + -F repo="$repo" \ + -F number=$number \ + -F after="" +``` + +Build `comment_id_to_thread_id: dict[int, str]` map. Skip threads where `isResolved` +is already `true`. + +If the GraphQL call fails, log a warning and set `comment_id_to_thread_id = {}`. +Thread resolution will be silently skipped in Step 6. + +Save to: +- `{{AUTOSKILLIT_TEMP}}/resolve-claims-review/inline_comments_{pr}.json` +- `{{AUTOSKILLIT_TEMP}}/resolve-claims-review/reviews_{pr}.json` +- `{{AUTOSKILLIT_TEMP}}/resolve-claims-review/threads_{pr}.json` + +### Step 3: Parse, Classify, and Dimension-Group + +From **inline comments**, extract per comment: +- `path` — file path relative to repo root +- `line` — the line being commented on +- `body` — the reviewer's message +- `diff_hunk` — surrounding context +- `id` — the comment's REST database ID +- `thread_node_id` — look up `comment_id_to_thread_id.get(id)` + +**Classify each finding by severity** (same as resolve-review): +- `critical` — body contains: "must", "critical", "security", "data loss", "wrong", + "broken", "incorrect", "bug", "error", "never" +- `warning` — body contains: "should", "consider", "recommend", "prefer", "suggest", + "missing", "lacks" +- `info` — body contains: "nit", "optional", "minor", "style", "cosmetic", "could" + +Include `critical` and `warning` only. Skip `info` findings. + +**Dimension extraction** — comments posted by `audit-claims` have format +`[severity] dimension: message`. Extract the dimension label using: + +```python +import re +DIMENSION_PATTERN = re.compile(r'^\[(?:critical|warning|info)\]\s+(\S+):\s+') +``` + +Apply `DIMENSION_PATTERN` to each comment body to extract the dimension label. + +**Dimension group mapping:** + +| Comment dimension | Group key | +|---|---| +| `external` | `citations` | +| `methodological` | `methodology` | +| `comparative` | `comparisons` | +| (unparseable / no match) | `unknown` | + +Note: `experimental` findings never appear — they are self-evidencing and generate no +findings in `audit-claims`. + +Save `dimension_groups_{pr}.json` with findings keyed by group. + +### Step 3.5: Intent Validation (Parallel Sub-Agents — BEFORE any code changes) + +Before applying any fix, validate every critical and warning finding against the actual +codebase and git history. This analysis phase runs entirely before code changes are made. + +**Dimension grouping:** Group findings by their extracted dimension group key +(`citations`, `methodology`, `comparisons`, `unknown`). +This is dimension-based grouping, NOT file-path grouping. + +Launch one parallel subagent (Task tool, `model: "sonnet"`) per non-empty dimension +group. Each subagent receives: +- Its list of findings (path, line, body, diff_hunk, dimension) +- Instructions to read the actual content at each flagged line (±30 lines context) +- Instructions to classify each as `ACCEPT`, `REJECT`, or `DISCUSS` with: + - `verdict` — the classification + - `evidence` — specific references (line numbers, section names, citation markers) + - `category` (REJECT only): one of `claim_is_supported`, `citation_not_required`, + `experimental_claim_misclassified`, `out_of_scope`, `stale_comment` + - `fix_strategy` (ACCEPT only): one of `add_citation`, `qualify_claim`, `remove_claim`, + `rerun_required` (escalated), `design_flaw` (escalated) + - `escalate`: `true` if `fix_strategy` is `rerun_required` or `design_flaw` + - `dimension` — the extracted dimension label + +**REJECT category guidance:** +- `claim_is_supported` — evidence for the claim exists in the diff but subagent missed it +- `citation_not_required` — claim is general knowledge not requiring citation +- `experimental_claim_misclassified` — claim is self-evidencing (derived from experiment data) +- `out_of_scope` — comment addresses content outside this PR +- `stale_comment` — comment refers to text no longer present + +**fix_strategy guidance (ACCEPT only):** +- `add_citation` — add a missing reference in the report document +- `qualify_claim` — add hedging language ("in our experiments", "preliminary evidence suggests") +- `remove_claim` — delete an unsupported claim with no path to citation +- `rerun_required` — fix requires re-running experiment to generate supporting data +- `design_flaw` — fundamental scope/methodology issue; cannot fix with citation alone + +**Protocol deviation rule (`rerun_required`):** +When a claim depends on experimental results, and the experiment plan specifies a +replication count, sample size, or other methodological parameter that the actual +execution did not follow, classify as `rerun_required` if the deviation materially +undermines the evidence supporting the claim. Qualifying the claim with hedging +language (`qualify_claim`) does not constitute remediation when the underlying data +is statistically invalid — the claim needs new supporting data, not softer language. + +Exception — justified deviations: If the research report provides a substantive +rationale for why the conclusions remain valid despite the methodological difference, +and that rationale withstands scrutiny, then `qualify_claim` or `remove_claim` may +be appropriate. The key test is: **does this deviation materially undermine the +evidence cited in support of the claim?** + +**Invalid statistics rule (`rerun_required`):** +When a finding identifies confidence intervals, p-values, or significance claims +cited as evidence for a claim, and those statistics are computed from the wrong unit +of analysis (e.g., within-run iterations treated as independent replicates), classify +as `rerun_required` if the invalid statistics remain in the report. Classification +as `remove_claim` applies if the claim and its invalid statistical evidence are both +fully removed. Classification as `qualify_claim` applies only if the statistical +artifacts are fully removed and the claim is restated without statistical backing. + +**Fallback:** If a subagent fails or times out, discard any partial output from that +subagent (partial JSON must not be used — using partial output risks silently demoting +ACCEPT findings to DISCUSS without surfacing the data loss). Classify all comments in the +failed group as `DISCUSS` and log the failure with the error message, domain group name, +and affected comment IDs. + +Merge results into `classification_map: dict[comment_id, verdict_entry]`. +Save `classification_map_{pr}.json`. + +Write analysis report to `{{AUTOSKILLIT_TEMP}}/resolve-claims-review/analysis_{pr}_{ts}.md` +with banner (BEFORE any code changes): +``` +Analysis complete (BEFORE any code changes) +ACCEPT: N | REJECT: N | DISCUSS: N + (add_citation: N, qualify_claim: N, remove_claim: N, rerun_required: N ESCALATED, design_flaw: N ESCALATED) +``` + +Track `accept_count`, `reject_count`, `discuss_count`, and per-strategy counts. + +### Step 4: Apply Fixes + +Initialize before processing: +```python +addressed_thread_ids: list[str] = [] +escalation_records: list = [] +``` + +**Processing order** within ACCEPT findings (critical before warning within each tier): +1. `add_citation` — add reference entries or inline citations +2. `qualify_claim` — add qualifying language +3. `remove_claim` — delete unsupported assertions + +For each ACCEPT finding, route by `fix_strategy`: + +**`rerun_required` or `design_flaw` → ESCALATE:** +1. Append to `escalation_records` with full finding details and `strategy` field +2. Do NOT add to `addressed_thread_ids` +3. Continue processing — escalation does not change the exit code (exit code remains 0) + +**`add_citation` / `qualify_claim` / `remove_claim` → apply edit → commit:** +```bash +git -C "$worktree_path" add {file} +# If pre-commit hooks exist: +pre-commit run --files {file} && git -C "$worktree_path" add {file} +git -C "$worktree_path" commit -m "fix(claims-review): {description} [{dimension}]" +``` +Append `thread_node_id` to `addressed_thread_ids` (if not `None`). + +**Classification gate — REJECT/DISCUSS bypass:** +- No code changes; record skip +- Do NOT add to `addressed_thread_ids` + +### Step 5: Run Validation Command (max 3 iterations) + +```python +if validation_command is None: + # Skip validation step entirely — null validation_command means skip + validation_status = "SKIPPED" +else: + # Run with retry logic (max 3 iterations) + # Timeout expiration is treated as failure and counts toward the iteration limit. + for iteration in range(1, 4): + result = run(validation_command, timeout=validation_timeout) + # returncode non-zero OR timeout (TimeoutExpired) both count as failure. + if result.returncode == 0: + validation_status = "PASS" + break + if iteration >= 3: + validation_status = "FAIL" + # Report failure, leave working directory intact, exit non-zero + exit(1) + # Analyze failures, revert/adjust problematic commit, retry +``` + +When `validation_command` is `null`, skip validation — do not run any command. +When configured, enforce max 3 iteration retry loop before exiting non-zero. + +### Step 6: Resolve Addressed Review Threads + +For each `thread_id` in `addressed_thread_ids`: + +```bash +gh api graphql \ + -f query='mutation($threadId:ID!){resolveReviewThread(input:{threadId:$threadId}){thread{isResolved}}}' \ + -f threadId="$thread_id" +``` + +- Success (`isResolved: true`): increment `resolved_count` +- Failure: log warning `"Warning: could not resolve thread {thread_id}: {error}"`, + continue. Do not modify exit code. + +Track `resolved_count` and `resolve_failed_count`. Thread resolution failure must never +cause exit non-zero. + +### Step 6.5: Post Inline Replies + +For every analyzed comment (critical + warning), post one reply using the reply API. + +**Reply templates:** + +``` +ACCEPT (applied): "Addressed in {sha}: {evidence}" +ACCEPT (skipped): "Investigated but could not apply: {reason}" +REJECT: "Investigated — {category}. {evidence}" +DISCUSS: "Valid observation — flagged for human judgment. {evidence}" +ESCALATION (rerun): "[ESCALATION] Requires re-running experiment. {message}" +ESCALATION (design): "[ESCALATION] Fundamental design issue. {message}" +``` + +API endpoint: +```bash +gh api repos/{owner}/{repo}/pulls/{pr_number}/comments/{comment_id}/replies \ + --method POST --field body="..." +``` + +Track `reply_posted_count` and `reply_failed_count`. Best-effort — failure to post +any reply must not affect exit code. + +### Step 6.6: Persist Reject Patterns + +Save all REJECT-classified comments to: +`{{AUTOSKILLIT_TEMP}}/resolve-claims-review/reject_patterns_{pr}_{ts}.json` + +Schema: +```json +{ + "comment_id": 123, + "path": "research/report.md", + "line": 42, + "body": "...", + "evidence": "...", + "category": "citation_not_required", + "dimension": "external", + "pr_number": 99, + "feature_branch": "..." +} +``` + +Save escalation records to: +`{{AUTOSKILLIT_TEMP}}/resolve-claims-review/escalation_records_{pr}.json` + +Each escalation record must include a `"strategy"` field set to the `fix_strategy` value +(either `"rerun_required"` or `"design_flaw"`). This field is read by the structured +output determination logic. + +### Step 7: Report + +Print structured summary: +``` +resolve-claims-review complete +PR: #{pr_number} ({feature_branch} → {base_branch}) +Findings fetched: {total} + - critical: {n}, warning: {n}, info: {n} (skipped) +Intent validation: + - ACCEPT: {n} (add_citation: {n}, qualify_claim: {n}, remove_claim: {n}, + rerun_required: {n} ESCALATED, design_flaw: {n} ESCALATED) + - REJECT: {n} + - DISCUSS: {n} +Fixes applied: {n} +Escalations: {n} +Validation: {SKIPPED | PASS | FAIL} +Threads resolved: {n}/{total} +Inline replies: {reply_posted_count} posted / {reply_failed_count} failed +Status: PASS +``` + +Save full report to `{{AUTOSKILLIT_TEMP}}/resolve-claims-review/report_{pr}_{ts}.md`. + +Exit 0. + +## Temp File Layout + +``` +{{AUTOSKILLIT_TEMP}}/resolve-claims-review/ +├── inline_comments_{pr}.json +├── reviews_{pr}.json +├── threads_{pr}.json +├── dimension_groups_{pr}.json +├── classification_map_{pr}.json +├── escalation_records_{pr}.json +├── analysis_{pr}_{ts}.md (written BEFORE code changes) +├── reject_patterns_{pr}_{ts}.json +└── report_{pr}_{ts}.md +``` + +## Structured Output + +After completing all thread processing (addressed + escalated), emit structured +output tokens: + +**Verdict decision:** +- If fixes were applied (`Fixes applied: N` where N >= 1): `verdict = real_fix` +- If no fixes were needed (all findings already addressed): `verdict = already_green` + +``` +needs_rerun = {true|false} +verdict = {real_fix|already_green} +fixes_applied = {N} +``` + +- **`needs_rerun = true`**: At least one finding was classified as `rerun_required` in + the escalation records. This includes: (a) fixes requiring re-running the experiment + to generate supporting data, (b) protocol deviations where the experiment execution + diverged from the plan in ways that materially undermine the report's claims, or + (c) invalid statistical analyses (e.g., CIs from the wrong unit of analysis) that + remain cited as evidence for claims. +- **`needs_rerun = false`**: No `rerun_required` escalations exist. May still have + `design_flaw` escalations (these are informational and do not require re-running). + +**Determination logic:** After writing `escalation_records_{pr}.json`, check whether any +entry has `"strategy": "rerun_required"`. If yes → `true`. If no entries or all entries +are `design_flaw` → `false`. + +`needs_rerun` is mandatory. The recipe captures it as `claims_needs_rerun` to route via +`merge_escalations`. + +## Output + +Emit the structured output tokens as the very last lines as your final output: + +> **IMPORTANT:** Emit the tokens as **literal plain text with no code fences, no markdown formatting**. The recipe capture system reads raw stdout. + +``` +needs_rerun = {true|false} +verdict = {real_fix|already_green} +fixes_applied = {N} +``` + +Summary: `{{AUTOSKILLIT_TEMP}}/resolve-claims-review/report_{pr}_{ts}.md` (relative to the current working directory) diff --git a/src/autoskillit/skills_extended/resolve-design-review/SKILL.md b/src/autoskillit/skills_extended/resolve-design-review/SKILL.md new file mode 100644 index 0000000000..ebdfb8ca9c --- /dev/null +++ b/src/autoskillit/skills_extended/resolve-design-review/SKILL.md @@ -0,0 +1,192 @@ +--- +name: resolve-design-review +categories: [research] +description: > + Triage STOP verdict findings from review-design, classifying each as + ADDRESSABLE/STRUCTURAL/DISCUSS using parallel subagents. If any are ADDRESSABLE + or DISCUSS, generate revision_guidance and emit resolution=revised. If all are + STRUCTURAL, emit resolution=failed for terminal stop. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: resolve-design-review] Triaging design review STOP findings...'" + once: true +--- + +# Resolve Design Review Skill + +Triage STOP verdict findings from `review-design`, perform feasibility +analysis to classify each finding as ADDRESSABLE/STRUCTURAL/DISCUSS using +parallel feasibility-validation subagents, generate revision guidance for +addressable findings, and emit routing token to feed back into the revision +loop or halt. + +## Arguments + +`/autoskillit:resolve-design-review [prior_revision_guidance_path]` + +## When to Use + +Called by the research recipe via run_skill when review_design emits verdict=STOP. +MCP-only — not user-invocable directly. + +## Critical Constraints + +**NEVER:** +- Create files outside `{{AUTOSKILLIT_TEMP}}/resolve-design-review/` +- Modify the evaluation dashboard, experiment plan, or any source file +- Apply fixes — this skill triages fixability only + +**ALWAYS:** +- Exit 0 in all cases — resolution=revised and resolution=failed are both normal outcomes +- Emit revision_guidance ONLY when resolution=revised +- Use model: "sonnet" for all subagents + +## Context Limit Behavior + +When context is exhausted mid-execution, temp files may be partially written and +output tokens may not yet be emitted. The recipe routes to `on_context_limit`, +abandoning the partial triage. + +**Before emitting structured output tokens:** +1. If analysis was not completed, emit `resolution = failed` as a safe fallback +2. The orchestrator handles the context-limit route based on the emitted verdict + +## Workflow + +### Step 0: Validate Arguments and Parse Dashboard + +1. Create `{{AUTOSKILLIT_TEMP}}/resolve-design-review/` if absent +2. Parse two positional path arguments: `evaluation_dashboard_path`, `experiment_plan_path` + - If missing: print `"Error: missing required argument(s) — expected "`, then emit `resolution=failed`, exit 0 + - If file not found: print `"Error: file not found — {missing_path}"`, then emit `resolution=failed`, exit 0 +3. Parse optional third argument: `prior_revision_guidance_path` + - If present and file exists: read prior revision guidance for theme comparison + - If absent or file not found: skip diminishing-return detection (first-round behavior) +4. Parse stop-trigger findings from the evaluation dashboard: + - Locate machine-readable YAML block (`# --- review-design machine summary ---`) + - Extract critical findings from L1 dimensions (estimand_clarity, hypothesis_falsifiability) + - Extract red_team critical findings + - If no findings parseable: treat all as DISCUSS → emit resolution=revised with generic guidance; add a `> **Warning:** dashboard could not be parsed — falling back to generic guidance` annotation at the top of the revision_guidance file so the parse failure is visible in pipeline logs + +### Step 1: Feasibility Validation (Parallel Subagents — BEFORE any guidance is written) + +This is the analysis phase. It runs entirely before any guidance is generated. + +Group findings; launch one parallel Task subagent per finding (model: "sonnet"). +Each subagent receives: finding metadata + full plan text. +Each subagent classifies the finding as: + +- **ADDRESSABLE** — concrete methodological flaw with a mechanical fix + (fix is well-defined, e.g., "set --iterations >= 3 at all n values") +- **STRUCTURAL** — fundamental unfixability: research question not answerable + with this design regardless of revision +- **DISCUSS** — valid design question requiring human judgment; fix is not mechanical + +Each subagent returns: +```json +{ + "verdict": "ADDRESSABLE|STRUCTURAL|DISCUSS", + "evidence": "specific references from plan text", + "fix_sketch": "brief concrete fix description (ADDRESSABLE only)" +} +``` + +Fallback: failed/timed-out subagent → classify finding as DISCUSS (safe, routes to revision). + +Write analysis report to `{{AUTOSKILLIT_TEMP}}/resolve-design-review/analysis_{slug}_{ts}.md` +BEFORE any guidance is generated. Report must include summary banner: +``` +Triage complete (BEFORE any guidance written) +ADDRESSABLE: N | STRUCTURAL: N | DISCUSS: N +``` + +### Step 1.5: Diminishing-Return Detection (only when prior_revision_guidance_path provided) + +When prior revision guidance is available, compare the current ADDRESSABLE findings +against the themes in the prior round's revision guidance to detect goalposts-moving. + +A finding is **goalposts-moving** when: +- The prior guidance addressed a specific concern at scope X (e.g., "add n=100K") +- The current finding raises the same concern at scope X+1 (e.g., "n=100K doesn't prove n=250K") +- The pattern is: the plan improved to satisfy the prior concern, but the reviewer + raised the bar on the same theme + +Detection heuristic — launch one subagent (model: "sonnet") per ADDRESSABLE finding. +Each subagent receives: current finding + all prior guidance entries. It returns: + +```json +{ + "goalposts_moving": true|false, + "prior_theme_match": "the specific prior guidance entry this finding escalates", + "escalation_pattern": "brief description of how the bar was raised" +} +``` + +When `goalposts_moving: true`, reclassify the finding from ADDRESSABLE to STRUCTURAL +with annotation: `"reclassified: goalposts-moving (prior theme: {prior_theme_match})"`. +This ensures the fix-and-review cycle terminates for concerns that are not converging. + +Fallback: if no prior_revision_guidance_path is provided, skip this step entirely +(preserves current first-round behavior unchanged). + +### Step 2: Apply Resolution Logic + +``` +resolution = "revised" when ANY finding is ADDRESSABLE or DISCUSS +resolution = "failed" only when ALL findings are STRUCTURAL +``` + +### Step 3: Write Revision Guidance (only when resolution = revised) + +Write `revision_guidance_{slug}_{ts}.md` to `{{AUTOSKILLIT_TEMP}}/resolve-design-review/` + +Sections: +1. **Required Fixes** — ADDRESSABLE findings with fix_sketch from subagent +2. **Design Questions for Human Review** — DISCUSS findings flagged for human awareness +3. **Structural Findings (for context)** — STRUCTURAL findings listed (if any) + +### Step 4: Report and Emit Structured Output Tokens + +Print summary: +``` +resolve-design-review complete +Stop triggers triaged: {total} + ADDRESSABLE: {n} + STRUCTURAL: {n} + DISCUSS: {n} +Resolution: {revised|failed} +``` + +IMPORTANT: Emit the structured output tokens as **literal plain text with no +markdown formatting on the token names**. Do not wrap token names in `**bold**`, +`*italic*`, or any other markdown. The adjudicator performs a regex match on the +exact token name — decorators cause match failure. + +When resolution = revised, emit as your final output: + +``` +resolution = revised +revision_guidance = /absolute/path/{{AUTOSKILLIT_TEMP}}/resolve-design-review/revision_guidance_{slug}_{ts}.md +``` + +When resolution = failed, emit as your final output: + +``` +resolution = failed +``` + +`revision_guidance` is ONLY emitted when resolution = revised. + +## Output + +All output files are written to `{{AUTOSKILLIT_TEMP}}/resolve-design-review/` relative to +the current working directory. + +``` +{{AUTOSKILLIT_TEMP}}/resolve-design-review/ +├── analysis_{slug}_{ts}.md (always written — before any guidance) +└── revision_guidance_{slug}_{ts}.md (revised path only) +``` diff --git a/src/autoskillit/skills_extended/resolve-failures/SKILL.md b/src/autoskillit/skills_extended/resolve-failures/SKILL.md index 63437e32ce..efc3e77b42 100644 --- a/src/autoskillit/skills_extended/resolve-failures/SKILL.md +++ b/src/autoskillit/skills_extended/resolve-failures/SKILL.md @@ -16,10 +16,13 @@ Fix test failures in a worktree implemented by `/autoskillit:implement-worktree- ## When to Use +- MCP orchestrator calls this via `run_skill` after `ci_watch` reports a CI failure - MCP orchestrator calls this via `run_skill` after `test_check` returns FAIL - MCP orchestrator calls this via `run_skill` when `merge_worktree` returns `dirty_tree` -- Takes three positional arguments: `{worktree_path} {plan_path} {base_branch}` +- Takes three required positional arguments: `{worktree_path} {plan_path} {base_branch}` +- Optional trailing args (passed by recipe): `{ci_conclusion} {ci_failed_jobs} {diagnosis_path}` - Remediates test failures only — the orchestrator is responsible for calling `merge_worktree` after verify passes. +- Emits a typed `verdict` output token so the recipe can route correctly (never silently re-pushes). ## Critical Constraints @@ -31,31 +34,61 @@ Fix test failures in a worktree implemented by `/autoskillit:implement-worktree- - Exceed 3 fix-and-retest iterations - Delete the worktree if tests still fail after max attempts - Modify the plan file -- Create files outside `.autoskillit/temp/resolve-failures/` directory +- Create files outside `{{AUTOSKILLIT_TEMP}}/resolve-failures/` directory +- Report `fixes_applied=0` when CI has identified a specific failing test **ALWAYS:** - Read the plan first to understand implementation intent - Commit each fix iteration separately with descriptive messages - Report iteration count and what was fixed - Leave worktree intact on failure for manual inspection +- Treat CI as the source of truth: "passes locally" is not a resolution + +## Context Limit Behavior + +When context is exhausted mid-execution, edits may be on disk but not committed. +The recipe routes to `on_context_limit` (typically `test`), bypassing the normal +commit protocol in Step 3. + +**Before every test run and before emitting structured output tokens:** +1. Run `git -C {worktree_path} status --porcelain` +2. If any files are dirty: `git -C {worktree_path} add -A && git -C {worktree_path} commit -m "fix: commit pending changes before context limit"` +3. Only then proceed with the test or structured output + +This ensures that even if context exhaustion interrupts the fix loop, all applied +edits are committed and the downstream merge gate receives a clean worktree. ## Workflow Read the configured test command from `.autoskillit/config.yaml` (key: `test_check.command`). Use this command wherever `{test_command}` appears in these instructions. If no config exists, use the `test_check` MCP tool (which resolves the command from the project's config automatically). ### Step 0: Validate Arguments -1. Parse three positional args using **path detection**: scan all tokens after - the skill name for those starting with `/`, `./`, or `.autoskillit/`. The - first path-like token is `worktree_path`; the second is `plan_path`. The - `base_branch` is the remaining non-path token. Ignore any non-path tokens - that appear before the path arguments. If fewer than two path-like tokens - are found, abort with a clear error and the correct format: +1. Parse positional args using **path detection**: scan all tokens after the + skill name. + + ``` + Positional args (in order): + 1. worktree_path — path-like token (starts with /, ./, or .autoskillit/) + 2. plan_path — path-like token + 3. base_branch — non-path token + 4. ci_conclusion — optional: "failure", "success", or absent/"-" + 5. ci_failed_jobs — optional: JSON array of job names or absent/"-" + 6. diagnosis_path — optional: path-like token to the diagnose-ci report or absent/"-" + ``` + + Scanning rules: use path-detection (find path-like tokens for positions 1, 2, + and 6); pick up remaining non-path non-`"-"` tokens for `base_branch`, + `ci_conclusion`, and `ci_failed_jobs`. The last path-like token after + `plan_path` that ends with `.md` → `diagnosis_path`. Ignore any non-path + tokens that appear before the path arguments. If fewer than two path-like + tokens are found, abort with a clear error and the correct format: `/autoskillit:resolve-failures ` 2. Verify worktree exists and is a valid git worktree 3. Verify plan file exists and is readable +4. If `diagnosis_path` is provided and exists, note it for Step 2a below **Path-existence guard:** Before issuing a `Read` call on a path that is not guaranteed to - exist (e.g., plan file arguments, `.autoskillit/temp/investigate/` reports, external file references), use + exist (e.g., plan file arguments, `{{AUTOSKILLIT_TEMP}}/investigate/` reports, external file references), use `Glob` or `ls` to confirm the path exists first. This prevents ENOENT errors that cascade into sibling parallel-call cancellations. 4. Check for development environment in worktree, recreate if missing. Use the project's configured `worktree_setup.command`, or: `cd "${worktree_path}" && task install-worktree` @@ -111,30 +144,144 @@ affect git operations, which always use `git -C {worktree_path}` explicitly. 2. Run `git log --oneline $(git merge-base HEAD origin/{base_branch})..HEAD` 3. Run `git diff --stat $(git merge-base HEAD origin/{base_branch})..HEAD` +### Step 2a: Read CI Context + +If `diagnosis_path` was provided and the file exists: +1. Open `diagnosis_path` and read its content +2. Find the "Structured Output" section or scan for the line matching `failure_subtype = {value}` +3. Extract the `failure_subtype` value (e.g., `flaky`, `deterministic`, `timing_race`, etc.) +4. Store as `{failure_subtype}` for use in Step 2d + +If `diagnosis_path` is absent or the file does not exist: +- Set `{failure_subtype} = unknown` + +### Step 2b: Reproduce CI Pre-Test Steps + +Check if the project has artifact generation steps that CI runs before tests: +1. Read `.github/workflows/tests.yml` (or the CI workflow file) if it exists +2. Identify pre-test steps (e.g., `generate_hooks_json`, `recipes render`, code generation) +3. Run equivalent generation commands locally in the worktree before executing the test suite + +This ensures local test results match CI behavior. Skip if no pre-test generation steps exist. + ### Step 2: Run Tests -1. Run `cd {worktree_path} && {test_command}` -2. If tests pass: go to Step 4 (Report Success) -3. If tests fail: go to Step 3 (Fix Loop) +1. Run tests using the `test_check` MCP tool — not via Bash or `run_cmd`: + ``` + test_check(worktree_path="{worktree_path}") + ``` + When test suites take 5–7 minutes, the Bash tool auto-backgrounds the command + and the LLM enters a polling cascade of 20+ API calls to detect completion. + `test_check` blocks synchronously and returns `passed: true/false` in a single call. +2. Record the result as `{local_result}`: PASS (`passed: true`) or FAIL (`passed: false`) + +### Step 2d: Verdict Decision Tree + +Using `{local_result}` from Step 2 and `{failure_subtype}` from Step 2a, determine `{verdict}`: + +| Local result | `failure_subtype` | Verdict | +|---|---|---| +| FAIL → (fix applied in Step 3) → PASS | any | `real_fix` | +| FAIL → (no fix possible after 3 iterations) | any | proceed to Step 5 | +| PASS | `flaky` or `timing_race` | `flake_suspected` | +| PASS | `deterministic` | `ci_only_failure` | +| PASS | `fixture` or `import` | `ci_only_failure` | +| PASS | `env` or `unknown` | `ci_only_failure` (conservative) | + +**Note on `already_green`:** This verdict is reserved for the `pre_resolve_rebase` +re-entry path — when a sibling pipeline's fix has already landed on integration and +the worktree was rebased before this skill ran. In that case, the orchestrator's +`pre_resolve_rebase` step has already pulled the fix; the re-run of diagnose-ci + +resolve-failures will now emit `real_fix` or another verdict. `already_green` is +not emitted by this skill's primary workflow. + +If local tests PASS (no fix needed): go to Step 2.5 (Validate CI Resolution) before +proceeding to Step 4 — the CI-truth gate may redirect to Step 3 for flakiness +investigation even when local tests pass. + +If local tests FAIL: enter Step 3. + +### Step 2.5: Validate CI Resolution + +Tests passed locally. Before reporting success, check whether the skill was invoked +in response to a CI failure. + +**CI is the source of truth.** A local pass does not resolve a CI failure — it means +the failure could not be reproduced locally, which is a flaky-test signal. + +1. If `diagnosis_path` is absent (or "-"), or `ci_conclusion` is absent (or is not + "failure"): proceed to Step 4 (no active CI failure context to enforce). + +2. If `diagnosis_path` is present AND `ci_conclusion == "failure"`: + a. Read the diagnosis file at `diagnosis_path` + b. Extract the failing test name(s) from the "## Log Excerpt" or the failure_type + classification in the diagnosis + c. If `failure_type == "test"` (one or more named test failures identified): + - Do **NOT** proceed to Step 4 + - Log: "CI failure on [test name] — local pass is not a resolution (flaky test + signal). Entering fix loop to investigate and stabilize." + - Proceed to **Step 3 (Fix Loop)** to investigate the non-determinism, timing + dependencies, or race conditions that caused the test to pass locally but fail + in CI. Apply a stabilizing fix (e.g., increase timeouts, remove timing + dependencies, add retry guards, fix resource cleanup). + d. If `failure_type` is not "test" (e.g., "lint", "build") and tests pass locally: + - Proceed to Step 4 — local pass resolves non-test CI failures (lint/build + failures are deterministic; they don't pass locally while failing remotely). ### Step 3: Fix Loop (max 3 iterations) 1. Analyze test failures against the plan to understand root cause 2. Apply targeted fixes -3. If the project has pre-commit hooks, run `pre-commit run --all-files` and - stage any auto-fixed files before committing. Commit each fix: `fix: {what was wrong and why}` -4. Re-run: `cd {worktree_path} && {test_command}` -5. Green → Step 4; Red and < 3 iterations → repeat; Red and >= 3 → Step 5 +3. Commit ALL modified files (not just intentionally changed ones): + a. If the project has pre-commit hooks, run `pre-commit run --all-files` first + b. Run `git -C {worktree_path} status --porcelain` to capture the full set of modified files, including any auto-fixed by hooks + c. Stage and commit: `git -C {worktree_path} add -A && git -C {worktree_path} commit -m "fix: {what was wrong and why}"` + d. Run `git -C {worktree_path} status --porcelain` again to verify the tree is clean; if any files remain dirty, stage and commit them too +4. Write a fix log entry to `{{AUTOSKILLIT_TEMP}}/resolve-failures/` (relative to + the current working directory) to satisfy the write_behavior contract + (generates an Edit/Write call that proves work was done): + - Path: `{{AUTOSKILLIT_TEMP}}/resolve-failures/fix_log_{iteration}_{ts}.md` + - Content: iteration number, files changed, commit SHA, brief description +5. Re-run tests using the `test_check` MCP tool: + ``` + test_check(worktree_path="{worktree_path}") + ``` + Do NOT re-run via Bash — see Step 2 rationale. + After receiving the result, extract and retain ONLY: + - Total pass/fail counts (e.g., "12 failed, 240 passed") + - The names of all failing tests + - The specific error message for each failure (first 10–15 lines) + Discard the full pytest stdout — do not retain progress dots, install-worktree + output, or timing lines. These accumulate across iterations and inflate context. +6. Green → Step 4 (with `verdict = real_fix`); Red and < 3 iterations → repeat; Red and >= 3 → Step 5 + +### Step 4: Report + +Tests are green. Report and exit — do NOT merge. -### Step 4: Report Success +Output to terminal: +- Summary of what was fixed (or reason no fix was applied) +- Verdict: `{verdict}` +- Worktree path (left intact for orchestrator's gate) -Tests are green. Report success and exit — do NOT merge. +Then emit the structured output tokens on their own lines so the pipeline's +`on_result:` verdict routing and `write_behavior: conditional` contract can evaluate them: -Output to terminal: -- Total fix iterations performed (may be 0 if tests were already passing on re-run) -- Summary of what was fixed (or "no changes needed") -- Worktree path (left intact for orchestrator's merge gate) +> **IMPORTANT:** Emit the tokens as **literal plain text with no markdown +> formatting**. The gate performs a regex match — decorators cause match failure. + +``` +verdict = {verdict} +fixes_applied = {N} +``` + +Where: +- `{verdict}` is one of: `real_fix`, `flake_suspected`, `ci_only_failure` +- `{N}` is the number of fix iterations performed (0 for non-real_fix verdicts, ≥1 for `real_fix`) -Return control to the orchestrator. The `merge_worktree` MCP tool will be -called by the recipe pipeline, not by this skill. +Return control to the orchestrator. The recipe's `on_result:` routing dispatches +on `verdict`: +- `real_fix` → `re_push` (fix landed, push to remote) +- `flake_suspected` → `release_issue_failure` (human escalation) +- `ci_only_failure` → `release_issue_failure` (human escalation) ### Step 5: Report Failure - Total fix iterations attempted diff --git a/src/autoskillit/skills_extended/resolve-merge-conflicts/SKILL.md b/src/autoskillit/skills_extended/resolve-merge-conflicts/SKILL.md index 522940857c..40bea5766b 100644 --- a/src/autoskillit/skills_extended/resolve-merge-conflicts/SKILL.md +++ b/src/autoskillit/skills_extended/resolve-merge-conflicts/SKILL.md @@ -19,7 +19,7 @@ hooks: ## Arguments (positional) - `{worktree_path}` — absolute path to the existing worktree (must exist; rebase was aborted cleanly) -- `{plan_path}` — absolute path to the implementation plan (`.autoskillit/temp/make-plan/…_plan_….md`, relative to the current working directory) +- `{plan_path}` — absolute path to the implementation plan (`{{AUTOSKILLIT_TEMP}}/make-plan/…_plan_….md`, relative to the current working directory) - `{base_branch}` — the integration branch to rebase onto (e.g. `integration/run-N`) ## Critical Constraints @@ -37,7 +37,7 @@ hooks: - Emit `worktree_path=` and `branch_name=` on successful resolution - Run `pre-commit run --all-files` after a successful rebase before emitting output tokens - Validate all three positional arguments before touching git state -- Write `conflict_resolution_report_*.md` to `.autoskillit/temp/resolve-merge-conflicts/` and emit `conflict_report_path=` after successful conflict resolution +- Write `conflict_resolution_report_*.md` to `{{AUTOSKILLIT_TEMP}}/resolve-merge-conflicts/` and emit `conflict_report_path=` after successful conflict resolution ## When to Use @@ -107,7 +107,7 @@ git -C {worktree_path} rebase $REMOTE/{base_branch} ``` **On success (clean rebase):** The integration branch advanced in a non-conflicting way -since the last attempt. Proceed directly to Step 7 — emit output tokens and exit. +since the last attempt. Proceed to Step 5a for manifest validation before emitting output tokens. **On conflict:** Proceed to Step 3. @@ -255,17 +255,122 @@ re-run `pre-commit run --all-files` to confirm clean. which already ran and passed before `merge_to_integration` was first attempted. Running tests here would be redundant and is explicitly prohibited. +### Step 5a — Language-aware manifest validation + +After `pre-commit run --all-files` succeeds, detect the project language and run a fast +manifest validity check. This catches semantically broken merges (e.g., duplicate +dependency keys in Cargo.toml) that produce no conflict markers and are not caught +by pre-commit hooks. + +**Detection and validation commands (run the first matching check):** + +| Detected by | Command | +|-------------|---------| +| `Cargo.toml` present | `cargo metadata --no-deps --format-version 1 >/dev/null` | +| `package.json` present | `node -e "JSON.parse(require('fs').readFileSync('package.json'))"` | +| `uv.lock` present | `uv lock --check` | +| `pyproject.toml` present (no uv.lock) | `python3 -c "import tomllib; tomllib.load(open('pyproject.toml','rb'))"` | + +Run in the worktree root: + +```bash +cd {worktree_path} +``` + +If **no manifest files are detected**: skip this step and proceed to Step 5b. + +If the check **fails**: do NOT attempt to fix the manifest. The rebase produced a +semantically invalid result. Escalate immediately: + +```bash +git -C {worktree_path} rebase --abort +``` + +``` +escalation_required = true +escalation_reason = Post-rebase manifest validation failed: . The rebase produced a semantically invalid manifest (e.g., duplicate dependency key). Manual inspection required. +``` + +If the check **passes**: proceed to Step 5b. + +### Step 5b — Duplicate key scan in cleanly-merged structured files + +Scan manifest files for duplicate keys. Both branches may have independently added +the same dependency entry; git merges these without conflict markers but the result +is semantically invalid. + +**Files to scan** (if present in `{worktree_path}`): +- `Cargo.toml` — scan `[dependencies]`, `[dev-dependencies]`, `[build-dependencies]` sections +- `pyproject.toml` — scan `[project.dependencies]`, `[tool.uv.dev-dependencies]` +- `package.json` — scan all top-level keys + +**TOML duplicate detection** (for each TOML manifest file): + +```bash +python3 -c " +import re, sys +text = open(sys.argv[1]).read() +in_dep_section = False +counts = {} +for line in text.splitlines(): + if re.match(r'^\s*\[(dependencies|dev-dependencies|build-dependencies)\]', line): + in_dep_section = True + continue + if re.match(r'^\s*\[', line): + in_dep_section = False + if in_dep_section: + m = re.match(r'^\s*([a-zA-Z0-9_-]+)\s*[=\.]', line) + if m: + k = m.group(1) + counts[k] = counts.get(k, 0) + 1 +dups = {k: v for k, v in counts.items() if v > 1} +if dups: + print('DUPLICATE_KEYS:', dups) + sys.exit(1) +" Cargo.toml +``` + +**JSON duplicate detection** (for `package.json`): + +```bash +python3 -c " +import json, sys +class _Dup(Exception): pass +def check(pairs): + seen = {} + for k, v in pairs: + if k in seen: + raise _Dup(f'duplicate key: {k!r}') + seen[k] = v + return seen +json.loads(open('package.json').read(), object_pairs_hook=check) +" 2>&1 +``` + +**If duplicates are found**: escalate immediately: + +```bash +git -C {worktree_path} rebase --abort +``` + +``` +escalation_required = true +escalation_reason = Duplicate key detected in : key '' appears multiple times in section '[
    ]'. This is a semantically invalid clean merge — both branches independently added the same dependency. +``` + +**If no duplicates are found** (or no manifest files are present): proceed to Step 6. + ### Step 6 — Write Conflict Resolution Report Create the directory and write the conflict resolution report: ```bash -mkdir -p {worktree_path}/.autoskillit/temp/resolve-merge-conflicts +mkdir -p {worktree_path}/{{AUTOSKILLIT_TEMP}}/resolve-merge-conflicts ``` Write the report to: ``` -{worktree_path}/.autoskillit/temp/resolve-merge-conflicts/conflict_resolution_report_{YYYY-MM-DD_HHMMSS}.md +{worktree_path}/{{AUTOSKILLIT_TEMP}}/resolve-merge-conflicts/conflict_resolution_report_{YYYY-MM-DD_HHMMSS}.md ``` Report format: diff --git a/src/autoskillit/skills_extended/resolve-research-review/SKILL.md b/src/autoskillit/skills_extended/resolve-research-review/SKILL.md new file mode 100644 index 0000000000..3075a08375 --- /dev/null +++ b/src/autoskillit/skills_extended/resolve-research-review/SKILL.md @@ -0,0 +1,465 @@ +--- +name: resolve-research-review +categories: [research] +description: > + Fetch PR review comments from review-research-pr, run research-aware intent + validation (ACCEPT/REJECT/DISCUSS), apply targeted fixes, escalate unrerunnable + findings, and post inline replies. Exit 0 drives recipe re_push_research; exit + non-zero halts the cycle. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: resolve-research-review] Resolving research review comments...'" + once: true +--- + +# Resolve Research Review Skill + +Apply `changes_requested` review comments from a research PR to the research +worktree. Reads open review threads, runs research-aware intent validation, applies +targeted fixes by fix-strategy taxonomy, escalates unrerunnable findings, resolves +addressed threads, and posts inline replies so a follow-up push closes the review cycle. + +## Arguments + +`/autoskillit:resolve-research-review {worktree_path} {base_branch}` + +- **worktree_path** — Absolute path to the research worktree +- **base_branch** — Target branch for the PR + +## When to Use + +Called by the research recipe when `review_research_pr` routes `changes_requested`. +Bounded by `retries: 2` — on exhaustion routes to `research_complete`. + +## Critical Constraints + +**NEVER:** +- Merge or push the branch — the recipe's `re_push_research` step handles push +- Dismiss review threads without addressing the underlying comment +- Create files outside `{{AUTOSKILLIT_TEMP}}/resolve-research-review/` +- Exceed 3 fix-and-retry iterations +- Delete or discard the working directory on failure +- Modify tests to suppress failures introduced by reviewer fixes +- Use file-path-segment grouping — research comments are grouped by **dimension**, not by file path + +**ALWAYS:** +- Find the PR by feature branch at invocation time (not a hardcoded number) +- Commit all fixes before returning control to the orchestrator +- Run intent validation BEFORE making any code changes +- Gracefully degrade (exit 0, report skip) if `gh` is unavailable or no PR is found +- Report a structured summary including escalation count + +## Workflow + +Read `research_review.validation_command` (default: `null`) and +`research_review.validation_timeout` (default: `120`) from `.autoskillit/config.yaml`. + +### Step 0: Validate Arguments + +Parse two positional arguments: `worktree_path` and `base_branch`. + +Derive `feature_branch` via: +```bash +feature_branch=$(git -C "$worktree_path" rev-parse --abbrev-ref HEAD) +``` + +Read config: +```python +import yaml, pathlib +cfg = yaml.safe_load(pathlib.Path(".autoskillit/config.yaml").read_text()) if pathlib.Path(".autoskillit/config.yaml").exists() else {} +rr_cfg = cfg.get("research_review", {}) +validation_command = rr_cfg.get("validation_command", None) +validation_timeout = rr_cfg.get("validation_timeout", 120) +``` + +If either positional arg is missing, abort with: +`"Usage: /autoskillit:resolve-research-review "` + +### Step 1: Find the Open PR + +```bash +PR_LIST_OUTPUT=$(gh pr list --head "$feature_branch" --base "$base_branch" \ + --json number,url -q '.[0] | "\(.number) \(.url)"') +PR_NUMBER=$(echo "$PR_LIST_OUTPUT" | awk '{print $1}') +PR_URL=$(echo "$PR_LIST_OUTPUT" | awk '{print $2}') +``` + +Get owner/repo: +```bash +gh repo view --json nameWithOwner -q .nameWithOwner +``` + +If `gh` is unavailable or not authenticated, or no PR is found: +- Log "No PR found or gh unavailable — skipping review resolution" +- Exit 0 (graceful degradation — do not fail the pipeline) + +### Step 2: Fetch Review Comments + +Fetch inline comments (anchored to specific file lines): +```bash +gh api repos/{owner}/{repo}/pulls/{number}/comments --paginate +``` + +Fetch top-level review bodies (summary reviews): +```bash +gh api repos/{owner}/{repo}/pulls/{number}/reviews --paginate +``` + +Fetch review thread node IDs using cursor-based pagination to handle PRs with more than +100 threads: + +```bash +# Fetch all pages; repeat with after=$endCursor while hasNextPage is true +gh api graphql \ + -f query='query($owner:String!,$repo:String!,$number:Int!,$after:String){repository(owner:$owner,name:$repo){pullRequest(number:$number){reviewThreads(first:100,after:$after){pageInfo{hasNextPage endCursor}nodes{id isResolved comments(first:1){nodes{databaseId}}}}}}}' \ + -F owner="$owner" \ + -F repo="$repo" \ + -F number=$number \ + -F after="" +``` + +Build `comment_id_to_thread_id: dict[int, str]` map. Skip threads where `isResolved` +is already `true`. + +If the GraphQL call fails, log a warning and set `comment_id_to_thread_id = {}`. +Thread resolution will be silently skipped in Step 6. + +Save to: +- `{{AUTOSKILLIT_TEMP}}/resolve-research-review/inline_comments_{pr}.json` +- `{{AUTOSKILLIT_TEMP}}/resolve-research-review/reviews_{pr}.json` +- `{{AUTOSKILLIT_TEMP}}/resolve-research-review/threads_{pr}.json` + +### Step 3: Parse, Classify, and Dimension-Group + +From **inline comments**, extract per comment: +- `path` — file path relative to repo root +- `line` — the line being commented on +- `body` — the reviewer's message +- `diff_hunk` — surrounding context +- `id` — the comment's REST database ID +- `thread_node_id` — look up `comment_id_to_thread_id.get(id)` + +**Classify each finding by severity** (same as resolve-review): +- `critical` — body contains: "must", "critical", "security", "data loss", "wrong", + "broken", "incorrect", "bug", "error", "never" +- `warning` — body contains: "should", "consider", "recommend", "prefer", "suggest", + "missing", "lacks" +- `info` — body contains: "nit", "optional", "minor", "style", "cosmetic", "could" + +Include `critical` and `warning` only. Skip `info` findings. + +**Dimension extraction** — comments posted by `review-research-pr` have format +`[severity] dimension: message`. Extract the dimension label using: + +```python +import re +DIMENSION_PATTERN = re.compile(r'^\[(?:critical|warning|info)\]\s+(\S+):\s+') +``` + +Apply `DIMENSION_PATTERN` to each comment body to extract the dimension label. + +**Dimension group mapping:** + +| Comment dimension | Group key | +|-------------------------------|-----------------| +| statistical-rigor, data-integrity | statistical | +| methodology | methodology | +| reproducibility, isolation | reproducibility | +| report-quality | reporting | +| slop | hygiene | +| (unparseable / no match) | unknown | + +Save `dimension_groups_{pr}.json` with findings keyed by group. + +### Step 3.5: Intent Validation (Parallel Sub-Agents — BEFORE any code changes) + +Before applying any fix, validate every critical and warning finding against the actual +codebase and git history. This analysis phase runs entirely before code changes are made. + +**Dimension grouping:** Group findings by their extracted dimension group key +(`statistical`, `methodology`, `reproducibility`, `reporting`, `hygiene`, `unknown`). +This is dimension-based grouping, NOT file-path grouping. + +Launch one parallel subagent (Task tool, `model: "sonnet"`) per non-empty dimension +group. Each subagent receives: +- Its list of findings (path, line, body, diff_hunk, dimension) +- Instructions to read the actual code at each flagged line (±30 lines context) +- Instructions to run `git log --follow -p --max-count=5 -- {path}` for git history +- Instructions to classify each as `ACCEPT`, `REJECT`, or `DISCUSS` with: + - `verdict` — the classification + - `evidence` — specific references (line numbers, function names, design rationale) + - `category` (REJECT only): one of `methodology_misunderstanding`, + `false_positive_intentional`, `inconclusive_not_deficiency`, `out_of_scope`, + `stale_comment` + - `fix_strategy` (ACCEPT only): one of `report_edit` (research/*.md edits), + `script_fix` (scripts/*.py), `config_fix` (config YAML/seed/env spec), + `rerun_required` (requires experiment re-run), `design_flaw` (fundamental redesign) + - `escalate`: `true` if `fix_strategy` is `rerun_required` or `design_flaw` + - `dimension` — the extracted dimension label + - `commit_sha_hint` — from `git log` + +**REJECT category guidance:** +- `methodology_misunderstanding` — reviewer misread the experimental design +- `false_positive_intentional` — flagged pattern is intentional research design +- `inconclusive_not_deficiency` — reviewer treated inconclusive results as a deficiency; + inconclusive results are valid research outcomes and must never be rejected as deficiencies +- `out_of_scope` — comment addresses something outside this PR's scope +- `stale_comment` — comment refers to code that no longer exists + +**fix_strategy guidance (ACCEPT only):** +- `config_fix` — fix is in config YAML, seed values, or environment spec +- `script_fix` — fix is in scripts/*.py or other experiment code +- `report_edit` — fix is in research/*.md report documents +- `rerun_required` — fix requires re-running the experiment; cannot be applied in-place +- `design_flaw` — fundamental design issue that cannot be fixed without redesign + +**Protocol deviation rule (`rerun_required`):** +When the experiment plan specifies a replication count, sample size, or other +methodological parameter, and the actual execution deviated from that specification +in a way that materially undermines the evidence supporting the report's claims, +classify as `rerun_required` — not `report_edit`. Adding a caveat about inadequate +replication does not constitute remediation when the deviation invalidates the +statistical basis for the claims (e.g., running R=1 instead of planned R=3 means +confidence intervals are computed from within-run iterations rather than between-run +replicates — a different unit of analysis entirely). + +Exception — justified deviations: If the research report provides a substantive +rationale for why the conclusions remain valid despite the methodological difference, +and that rationale withstands scrutiny (not just acknowledging the limitation), then +the classification may remain `report_edit`. Minor deviations that would not +reasonably change the experiment's conclusions (e.g., R=4 instead of R=5 with large +effect size) can also remain `report_edit` with an appropriate caveat. The key test +is: **does this deviation materially undermine the evidence supporting the claims?** + +**Invalid statistics rule (`rerun_required`):** +When a finding identifies confidence intervals, p-values, or significance claims +computed from the wrong unit of analysis (e.g., within-run iterations treated as +independent replicates, or pseudoreplication), and those statistical artifacts are +retained in the report in any form (tables, figures, inline references), classify +as `rerun_required`. Classification as `report_edit` applies only if the invalid +statistical artifacts are **fully removed** from the report and replaced with +appropriately qualified point estimates or narrative descriptions that make no +statistical claims. + +**Fallback:** If a subagent fails, classify all comments in that group as `DISCUSS`. + +Merge results into `classification_map: dict[comment_id, verdict_entry]`. +Save `classification_map_{pr}.json`. + +Write analysis report to `{{AUTOSKILLIT_TEMP}}/resolve-research-review/analysis_{pr}_{ts}.md` +with banner (BEFORE any code changes): +``` +Analysis complete (BEFORE any code changes) +ACCEPT: N | REJECT: N | DISCUSS: N + (report_edit: N, script_fix: N, config_fix: N, rerun_required: N ESCALATED, design_flaw: N ESCALATED) +``` + +Track `accept_count`, `reject_count`, `discuss_count`, and per-strategy counts. + +### Step 4: Apply Fixes + +Initialize before processing: +```python +addressed_thread_ids: list[str] = [] +escalation_records: list = [] +``` + +**Processing order** within ACCEPT findings (critical before warning within each tier): +1. `config_fix` — config YAML, seed, env spec changes +2. `script_fix` — scripts/*.py, experiment code changes +3. `report_edit` — research/*.md document changes + +For each ACCEPT finding, route by `fix_strategy`: + +**`rerun_required` or `design_flaw` → ESCALATE:** +1. Append to `escalation_records` with full finding details +2. Do NOT add to `addressed_thread_ids` +3. Continue processing — escalation does not change the exit code (exit code remains 0) + +**`config_fix` / `script_fix` / `report_edit` → apply edit → commit:** +```bash +git -C "$worktree_path" add {file} +# If pre-commit hooks exist: +pre-commit run --files {file} && git -C "$worktree_path" add {file} +git -C "$worktree_path" commit -m "fix(research-review): {description} [{dimension}]" +``` +Append `thread_node_id` to `addressed_thread_ids` (if not `None`). + +**Classification gate — REJECT/DISCUSS bypass:** +- No code changes; record skip +- Do NOT add to `addressed_thread_ids` + +### Step 5: Run Validation Command (max 3 iterations) + +```python +if validation_command is None: + # Skip validation step entirely — null validation_command means skip + validation_status = "SKIPPED" +else: + # Run with retry logic (max 3 iterations) + for iteration in range(1, 4): + result = run(validation_command, timeout=validation_timeout) + if result.returncode == 0: + validation_status = "PASS" + break + if iteration >= 3: + validation_status = "FAIL" + # Report failure, leave working directory intact, exit non-zero + exit(1) + # Analyze failures, revert/adjust problematic commit, retry +``` + +When `validation_command` is `null`, skip validation — do not run any command. +When configured, enforce max 3 iteration retry loop before exiting non-zero. + +### Step 6: Resolve Addressed Review Threads + +For each `thread_id` in `addressed_thread_ids`: + +```bash +gh api graphql \ + -f query='mutation($threadId:ID!){resolveReviewThread(input:{threadId:$threadId}){thread{isResolved}}}' \ + -f threadId="$thread_id" +``` + +- Success (`isResolved: true`): increment `resolved_count` +- Failure: log warning `"Warning: could not resolve thread {thread_id}: {error}"`, + continue. Do not modify exit code. + +Track `resolved_count` and `resolve_failed_count`. Thread resolution failure must never +cause exit non-zero. + +### Step 6.5: Post Inline Replies + +For every analyzed comment (critical + warning), post one reply using the reply API. + +**Reply templates:** + +``` +ACCEPT (applied): "Addressed in {sha}: {evidence}" +ACCEPT (skipped): "Investigated but could not apply: {reason}" +REJECT: "Investigated — intentional research design. {evidence}" +DISCUSS: "Valid observation — flagged for human judgment. {evidence}" +ESCALATION (rerun): "[ESCALATION] Requires re-running experiment. {message}" +ESCALATION (design): "[ESCALATION] Fundamental design issue. {message}" +``` + +API endpoint: +```bash +gh api repos/{owner}/{repo}/pulls/{pr_number}/comments/{comment_id}/replies \ + --method POST --field body="..." +``` + +Track `reply_posted_count` and `reply_failed_count`. Best-effort — failure to post +any reply must not affect exit code. + +### Step 6.6: Persist Reject Patterns + +Save all REJECT-classified comments to: +`{{AUTOSKILLIT_TEMP}}/resolve-research-review/reject_patterns_{pr}_{ts}.json` + +Schema extends resolve-review's schema with a `dimension` field: +```json +{ + "comment_id": 123, + "path": "research/experiment.md", + "line": 42, + "body": "...", + "evidence": "...", + "category": "inconclusive_not_deficiency", + "dimension": "reporting", + "pr_number": 99, + "feature_branch": "..." +} +``` + +Save escalation records to: +`{{AUTOSKILLIT_TEMP}}/resolve-research-review/escalation_records_{pr}.json` + +### Step 7: Report + +Print structured summary: +``` +resolve-research-review complete +PR: #{pr_number} ({feature_branch} → {base_branch}) +Findings fetched: {total} + - critical: {n}, warning: {n}, info: {n} (skipped) +Intent validation: + - ACCEPT: {n} (report_edit: {n}, script_fix: {n}, config_fix: {n}, + rerun_required: {n} ESCALATED, design_flaw: {n} ESCALATED) + - REJECT: {n} + - DISCUSS: {n} +Fixes applied: {n} +Escalations: {n} +Validation: {SKIPPED | PASS | FAIL} +Threads resolved: {n}/{total} +Inline replies: {reply_posted_count} posted / {reply_failed_count} failed +Status: PASS +``` + +Save full report to `{{AUTOSKILLIT_TEMP}}/resolve-research-review/report_{pr}_{ts}.md`. + +Exit 0. + +## Temp File Layout + +``` +{{AUTOSKILLIT_TEMP}}/resolve-research-review/ +├── inline_comments_{pr}.json +├── reviews_{pr}.json +├── threads_{pr}.json +├── dimension_groups_{pr}.json +├── classification_map_{pr}.json +├── escalation_records_{pr}.json +├── analysis_{pr}_{ts}.md (written BEFORE code changes) +├── reject_patterns_{pr}_{ts}.json +└── report_{pr}_{ts}.md +``` + +## Structured Output + +After completing all thread processing (addressed + escalated), emit structured +output tokens: + +**Verdict decision:** +- If fixes were applied (`Fixes applied: N` where N >= 1): `verdict = real_fix` +- If no fixes were needed (all findings already addressed): `verdict = already_green` + +``` +needs_rerun = {true|false} +verdict = {real_fix|already_green} +fixes_applied = {N} +``` + +- **`needs_rerun = true`**: At least one finding was classified as `rerun_required` in + the escalation records. This includes: (a) fixes that change code affecting measurement + (benchmark code, analysis scripts, normalization logic) requiring result re-validation, + (b) protocol deviations where the experiment execution diverged from the plan in ways + that materially undermine the report's claims, or (c) invalid statistical analyses + (e.g., CIs from the wrong unit of analysis) that remain in the report. +- **`needs_rerun = false`**: No `rerun_required` escalations exist. May still have + `design_flaw` escalations (these are informational and do not require re-running). + +**Determination logic:** After writing `escalation_records_{pr}.json`, check whether any +entry has `"strategy": "rerun_required"`. If yes → `true`. If no entries or all entries +are `design_flaw` → `false`. + +This token is mandatory. The recipe captures it to route between re-validation +(re-run affected benchmarks) and direct push. + +## Output + +Emit the structured output tokens as the very last lines as your final output: + +> **IMPORTANT:** Emit the tokens as **literal plain text with no code fences, no markdown formatting**. The recipe capture system reads raw stdout. + +``` +needs_rerun = {true|false} +verdict = {real_fix|already_green} +fixes_applied = {N} +``` + +Summary: `{{AUTOSKILLIT_TEMP}}/resolve-research-review/report_{pr}_{ts}.md` (relative to the current working directory) diff --git a/src/autoskillit/skills_extended/resolve-review/SKILL.md b/src/autoskillit/skills_extended/resolve-review/SKILL.md index d4f47b8943..daa726864a 100644 --- a/src/autoskillit/skills_extended/resolve-review/SKILL.md +++ b/src/autoskillit/skills_extended/resolve-review/SKILL.md @@ -35,7 +35,7 @@ branch already checked out. ## Critical Constraints **NEVER:** -- Create files outside `.autoskillit/temp/resolve-review/` +- Create files outside `{{AUTOSKILLIT_TEMP}}/resolve-review/` - Merge, push, or call `merge_worktree` - Fix issues beyond the explicit scope of the reviewer's comments - Exceed 3 fix-and-retest iterations @@ -51,6 +51,20 @@ branch already checked out. - Gracefully degrade (exit 0, report skip) if `gh` is unavailable or no PR is found - Report a structured summary: findings fetched, fixes applied, fixes skipped (with reasons) +## Context Limit Behavior + +When context is exhausted mid-execution, edits may be on disk but not committed. +The recipe routes to `on_context_limit` (typically a re-push step), bypassing the +normal commit protocol. + +**Before every test run and before emitting structured output tokens:** +1. Run `git -C {work_dir} status --porcelain` +2. If any files are dirty: `git -C {work_dir} add -A && git -C {work_dir} commit -m "fix: commit pending review changes"` +3. Only then proceed with the test or structured output + +This ensures that even if context exhaustion interrupts the fix loop, all applied +review fixes are committed and the downstream push step receives a clean branch. + ## Workflow Read `test_check.command` from `.autoskillit/config.yaml` (default: `task test-check`). @@ -110,9 +124,9 @@ Collect all `nodes` across pages into a single list. Continue fetching while `pageInfo.hasNextPage` is `true`, passing `pageInfo.endCursor` as `$after`. Save raw responses to: -- `.autoskillit/temp/resolve-review/inline_comments_{pr_number}.json` -- `.autoskillit/temp/resolve-review/reviews_{pr_number}.json` -- `.autoskillit/temp/resolve-review/threads_{pr_number}.json` (first page; subsequent pages merged in memory) +- `{{AUTOSKILLIT_TEMP}}/resolve-review/inline_comments_{pr_number}.json` +- `{{AUTOSKILLIT_TEMP}}/resolve-review/reviews_{pr_number}.json` +- `{{AUTOSKILLIT_TEMP}}/resolve-review/threads_{pr_number}.json` (first page; subsequent pages merged in memory) Build a lookup map from the threads response: - `comment_id_to_thread_id: dict[int, str]` — key: comment `databaseId` (integer), value: thread GraphQL `id` (string node ID) @@ -201,7 +215,7 @@ the error message, domain group name, and affected comment IDs. **Merge results** into a `classification_map: dict[comment_id, verdict_entry]`. -**Write analysis report** to `.autoskillit/temp/resolve-review/analysis_{pr_number}_{ts}.md` before +**Write analysis report** to `{{AUTOSKILLIT_TEMP}}/resolve-review/analysis_{pr_number}_{ts}.md` before any code changes are made. The report must include a summary banner: ``` Analysis complete (BEFORE any code changes) @@ -342,7 +356,7 @@ reject_entries = [ for c in classification_map.values() if c['verdict'] == 'REJECT' ] -pathlib.Path('.autoskillit/temp/resolve-review/reject_patterns_${PR_NUMBER}_${ts}.json').write_text( +pathlib.Path('{{AUTOSKILLIT_TEMP}}/resolve-review/reject_patterns_${PR_NUMBER}_${ts}.json').write_text( json.dumps(reject_entries, indent=2) ) print(f'Saved {len(reject_entries)} reject patterns') @@ -370,20 +384,53 @@ Fixes skipped: {n} Threads resolved: {resolved_count}/{len(addressed_thread_ids)} - {resolve_failed_count} failed (warnings logged above) Inline replies: {reply_posted_count} posted / {reply_failed_count} failed -Reject patterns saved: .autoskillit/temp/resolve-review/reject_patterns_{pr_number}_{ts}.json +Reject patterns saved: {{AUTOSKILLIT_TEMP}}/resolve-review/reject_patterns_{pr_number}_{ts}.json Test iterations: {n} Status: PASS ``` Save full report to: -- Analysis report: `.autoskillit/temp/resolve-review/analysis_{pr_number}_{ts}.md` (written before code changes) -- Final report: `.autoskillit/temp/resolve-review/report_{pr_number}_{ts}.md` +- Analysis report: `{{AUTOSKILLIT_TEMP}}/resolve-review/analysis_{pr_number}_{ts}.md` (written before code changes) +- Final report: `{{AUTOSKILLIT_TEMP}}/resolve-review/report_{pr_number}_{ts}.md` + +Then determine and emit the structured output tokens (required for the +`write_behavior: conditional` contract gate and `on_result:` routing): + +**Verdict Decision:** +- If `{accept_count - skipped_in_fix_phase} >= 1` (fixes were applied): `verdict = real_fix` +- If all ACCEPT findings were skipped (no code changes): `verdict = already_green` + +> **IMPORTANT:** Emit the tokens as **literal plain text with no markdown +> formatting**. Do not wrap in bold or italic. + +``` +verdict = {verdict} +fixes_applied = {accept_count - skipped_in_fix_phase} +``` + +Where: +- `{verdict}` is `real_fix` if fixes were applied, `already_green` otherwise +- `{accept_count - skipped_in_fix_phase}` is the number of ACCEPT findings + where code changes were actually committed + +The Step 1 graceful degradation exit must NOT emit these tokens — no tokens +when skipping due to no PR found. Exit 0. ## Output -No structured output tokens are emitted. The recipe's `resolve_review` step has no -`capture:` block — success/failure drives routing, not captured values. +When a PR is processed, the following structured output tokens are emitted: + +``` +verdict = real_fix|already_green +fixes_applied = {N} +``` + +Where `{N}` is the count of ACCEPT findings where code changes were committed. +`verdict = real_fix` means fixes were applied; `verdict = already_green` means +all review findings were already addressed and no code changes were needed. + +When no PR is found (graceful degradation), no structured tokens are emitted. -Summary written to: `.autoskillit/temp/resolve-review/report_{pr_number}_{ts}.md` (relative to the current working directory) +Summary written to: `{{AUTOSKILLIT_TEMP}}/resolve-review/report_{pr_number}_{ts}.md` (relative to the current working directory) diff --git a/src/autoskillit/skills_extended/retry-worktree/SKILL.md b/src/autoskillit/skills_extended/retry-worktree/SKILL.md index 813854ac5b..f70ffdff9e 100644 --- a/src/autoskillit/skills_extended/retry-worktree/SKILL.md +++ b/src/autoskillit/skills_extended/retry-worktree/SKILL.md @@ -51,6 +51,19 @@ Continue implementing a plan in an **existing** git worktree. This skill is used - Run the project's test suite from the worktree directory - Rebase onto base branch before completion (ready for squash-and-merge) +## Context Limit Behavior + +When context is exhausted mid-execution, implementation changes may be on disk but +not yet committed. The recipe routes to `on_context_limit`, preserving the worktree. + +**Before emitting structured output tokens:** +1. Run `git -C {WORKTREE_PATH} status --porcelain` +2. If any files are dirty: `git -C {WORKTREE_PATH} add -A && git -C {WORKTREE_PATH} commit -m "chore: commit pending changes before context limit"` +3. Only then emit the `worktree_path`, `branch_name`, and `phases_implemented` tokens + +This ensures that all implementation progress is committed and the downstream +merge gate receives a clean worktree when the recipe resumes. + ## Workflow ### Step 0: Receive and Validate Arguments @@ -60,7 +73,7 @@ Parse two positional arguments from the prompt: 2. **Worktree path** — verify the directory exists and is a git worktree. Check that the development environment is set up (e.g. `.venv` exists for Python projects) **Path Detection:** Use path detection to locate both arguments. Scan all -tokens after the skill name for those starting with `/`, `./`, `.autoskillit/temp/`, or +tokens after the skill name for those starting with `/`, `./`, `{{AUTOSKILLIT_TEMP}}/`, or `.autoskillit/`. The first such token is `plan_path`; the second is `worktree_path`. Ignore any non-path tokens that appear before them (e.g., extra descriptive text like "use this plan" or "from worktree"). If fewer than @@ -98,14 +111,14 @@ if [ -z "$BASE_BRANCH" ]; then # Fallback: read explicit file store written by implement-worktree-no-merge MAIN_GIT_DIR=$(git rev-parse --git-common-dir) MAIN_REPO_ROOT=$(dirname "${MAIN_GIT_DIR}") - STORE_FILE="${MAIN_REPO_ROOT}/.autoskillit/temp/worktrees/${CURRENT_BRANCH}/base-branch" + STORE_FILE="${MAIN_REPO_ROOT}/{{AUTOSKILLIT_TEMP}}/worktrees/${CURRENT_BRANCH}/base-branch" BASE_BRANCH=$(cat "${STORE_FILE}" 2>/dev/null) fi if [ -z "$BASE_BRANCH" ]; then echo "ERROR: Cannot determine base branch from git structure." echo "Both the upstream tracking ref and the explicit base-branch file at" - echo ".autoskillit/temp/worktrees/${CURRENT_BRANCH}/base-branch are missing." + echo "{{AUTOSKILLIT_TEMP}}/worktrees/${CURRENT_BRANCH}/base-branch are missing." echo "Ensure the worktree was created by implement-worktree-no-merge," echo "which writes both stores at worktree creation time." exit 1 @@ -146,12 +159,13 @@ Only explore systems related to the **remaining** phases. Do NOT re-explore alre **All commands must run from `{WORKTREE_PATH}`.** Use absolute paths to avoid CWD drift across Bash tool calls. -For each remaining/incomplete phase: -1. Announce phase objective and files to modify -2. Implement changes -3. Run per-phase verification if plan specifies it -4. Commit per phase if possible -5. Report phase completion +Initialize a counter before iterating: `PHASES_IMPLEMENTED=0` + +For each remaining/incomplete phase, begin implementation immediately (no announcement): +1. Implement changes +2. Run per-phase verification if plan specifies it +3. Commit per phase if possible +4. Increment the counter: `PHASES_IMPLEMENTED=$((PHASES_IMPLEMENTED + 1))` Where practical, delegate test updates to subagents to keep main conversation context lean. @@ -193,8 +207,12 @@ Then emit these structured output tokens on their own lines so recipe capture bl ``` worktree_path = ${WORKTREE_PATH} branch_name = ${CURRENT_BRANCH} +phases_implemented = ${PHASES_IMPLEMENTED} ``` +Where `PHASES_IMPLEMENTED` is the count from Step 3. If Step 3 was skipped entirely +(all phases already complete), emit `phases_implemented = 0`. + ### Step 6.5: Reset Code Index to Original Project (REQUIRED) After worktree cleanup, reset the MCP code-index project path back to the original project directory: diff --git a/src/autoskillit/skills_extended/review-approach/SKILL.md b/src/autoskillit/skills_extended/review-approach/SKILL.md index f512229590..f79b62341a 100644 --- a/src/autoskillit/skills_extended/review-approach/SKILL.md +++ b/src/autoskillit/skills_extended/review-approach/SKILL.md @@ -25,7 +25,7 @@ Research modern solutions, approaches, and strategies relevant to the issues or **NEVER:** - Modify any source code files -- Create files outside `.autoskillit/temp/review-approach/` directory +- Create files outside `{{AUTOSKILLIT_TEMP}}/review-approach/` directory **ALWAYS:** - Use subagents with web search for parallel research @@ -36,11 +36,10 @@ Research modern solutions, approaches, and strategies relevant to the issues or - Tie research back to the specific problem context - Include source URLs for all referenced material - After writing the review file, emit the **absolute path** as a structured output - token immediately before `%%ORDER_UP%%`. Resolve the relative `temp/review-approach/...` + token as your final output. Resolve the relative `temp/review-approach/...` save path to absolute by prepending the full CWD: ``` review_path = /absolute/cwd/temp/review-approach/{filename}.md - %%ORDER_UP%% ``` This token is MANDATORY — the pipeline cannot proceed without it. @@ -73,7 +72,7 @@ Drop anything that doesn't meaningfully inform the decision. ### Step 4: Write Review -Save to: `.autoskillit/temp/review-approach/review_approach_{topic}_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +Save to: `{{AUTOSKILLIT_TEMP}}/review-approach/review_approach_{topic}_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) ```markdown # Approach Review: {Topic} diff --git a/src/autoskillit/skills_extended/review-design/SKILL.md b/src/autoskillit/skills_extended/review-design/SKILL.md new file mode 100644 index 0000000000..1c3e1c17e2 --- /dev/null +++ b/src/autoskillit/skills_extended/review-design/SKILL.md @@ -0,0 +1,571 @@ +--- +name: review-design +categories: [research] +description: Validate an experiment plan before execution using triage-first, fail-fast dimensional analysis with an adversarial red-team. Emits verdict (GO/REVISE/STOP), experiment_type, evaluation_dashboard, and revision_guidance. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: review-design] Reviewing experiment design...'" + once: true +--- + +# Review Design Skill + +Validate the quality and feasibility of an experiment plan before compute is spent. +Runs a triage-first, fail-fast multi-level analysis hierarchy with parallel subagents +and an adversarial red-team, then synthesizes a GO/REVISE/STOP verdict. + +## When to Use + +Use when the research recipe's `review_design` ingredient is `true` (the default). The +recipe calls this skill after `plan_experiment` to gate execution on a quality check. +This skill is bounded by `retries: 2` — on exhaustion the recipe proceeds with the +best available plan. + +## Arguments + +`/autoskillit:review-design {experiment_plan_path}` + +- **experiment_plan_path** — Absolute path to the experiment plan file produced by + `/autoskillit:plan-experiment`. Scan tokens after the skill name for the first + path-like token (starts with `/`, `./`, or `.autoskillit/`). + +## Critical Constraints + +**NEVER:** +- Modify the plan file, any source code, or any file outside `{{AUTOSKILLIT_TEMP}}/review-design/` +- Halt the pipeline for a REVISE verdict — emit the verdict and let the recipe route +- Proceed to Level 2, 3, or 4 analysis when any Level 1 finding is classified as + STRUCTURAL (halt at fail-fast gate). ADDRESSABLE L1 criticals continue L2-L4. +- Spawn SILENT (S) dimension subagents — they are not run and not mentioned in output +- Exit non-zero — GO, REVISE, and STOP are all normal outcomes (exit 0 in all cases) +- Include code snippets, shell commands, or specific tool invocations in findings or revision guidance — findings describe gaps and risks, not implementation instructions +- Prescribe HOW to fix an issue — findings must describe WHAT is lacking or at risk; the fix is the plan author's responsibility + +**ALWAYS:** +- Use `model: "sonnet"` when spawning all subagents via the Task tool +- Write output to `{{AUTOSKILLIT_TEMP}}/review-design/` (relative to the current working directory) +- After writing output files, emit the **absolute paths** as structured output tokens + as your final output. Resolve relative save paths to absolute by prepending + the full CWD: + verdict = GO|REVISE|STOP + experiment_type = {type} + evaluation_dashboard = /absolute/cwd/{{AUTOSKILLIT_TEMP}}/review-design/{filename}.md + revision_guidance = /absolute/cwd/{{AUTOSKILLIT_TEMP}}/review-design/{filename}.md (REVISE only) +- `revision_guidance` is written and emitted ONLY when verdict = REVISE +- `evaluation_dashboard` is ALWAYS written and emitted +- Red-team agent always sets `requires_decision: true` on all its findings +- Halt at Level 1 fail-fast gate: if any Level 1 finding is classified as STRUCTURAL, + emit STOP immediately — do NOT proceed to Level 2, 3, or 4. If all L1 criticals are + ADDRESSABLE, tag them as REQUIRED priority fixes and continue L2-L4 analysis. + +## Context Limit Behavior + +When context is exhausted mid-execution, output files may be partially written or +absent. The recipe routes to `on_context_limit`, abandoning the partial review. + +**Before emitting structured output tokens:** +1. If `evaluation_dashboard` was not fully written, emit `verdict = STOP` as a safe fallback +2. Omit `revision_guidance` if not written; the orchestrator handles the context-limit route + +## Workflow + +### Step 0: Read Plan & Setup + +1. Create `{{AUTOSKILLIT_TEMP}}/review-design/` if absent. +2. Extract `experiment_plan_path` from arguments (first path-like token starting with `/`, + `./`, or `.autoskillit/`). + **Error handling:** If no path-like token is found in the arguments, emit + `verdict = STOP` with message "No experiment_plan_path provided" and exit 0 (per + the NEVER exit-non-zero constraint). +3. Read the plan file. + **Error handling:** If the file does not exist or is unreadable at the resolved path, + emit `verdict = STOP` with message "Plan file not found: {path}" and exit 0. +4. **Load the experiment type registry:** + a. Locate bundled types dir: run + `python -c "from autoskillit.core import pkg_root; print(pkg_root() / 'recipes' / 'experiment-types')"` + to get the absolute bundled directory path. + b. Use Glob `*.yaml` in that directory, then Read each file. Parse YAML frontmatter to + extract `name`, `classification_triggers`, `dimension_weights`, `applicable_lenses`, + `red_team_focus`, and `l1_severity` fields from each. + c. Check `.autoskillit/experiment-types/` in the current working directory. If it exists, + read all `*.yaml` files there. A user-defined type with the same `name` as a bundled + type replaces the bundled entry entirely — do not merge fields. + d. The resulting registry is a mapping of type name → spec. The set of valid + `experiment_type` values for this run is the set of keys in the registry. +5. Parse YAML frontmatter using the **backward-compatible two-level fallback**: + - **Level 1 (frontmatter)**: Read YAML frontmatter between `---` delimiters directly + (zero LLM tokens). Return present fields and note which are missing. + Record `source: frontmatter` for each extracted field. + **Error handling:** If the YAML between `---` delimiters is malformed, treat all + fields as missing and fall through to Level 2 for all fields (graceful degradation). + - **Level 2 (LLM extraction)**: For each missing field, launch a targeted LLM + extraction subagent against the corresponding prose section. All extractions are + independent and run in parallel. Record `source: extracted` for each field from + this path. + - Fields: `experiment_type`, `hypothesis_h0/h1`, `estimand`, `metrics`, `baselines`, + `statistical_plan`, `success_criteria` + - Missing-field to prose-target mapping: + + | Missing Field | Prose Target | Extraction Prompt | + |---|---|---| + | experiment_type | Full plan | "Classify using the loaded registry types: {', '.join(registry.keys())}" | + | hypothesis_h0/h1 | ## Hypothesis | "Extract the null/alternative hypothesis" | + | estimand | ## Hypothesis + ## Independent Variables | "Extract: treatment, outcome, population, contrast" | + | metrics | ## Dependent Variables table | "Extract each row as structured object" | + | baselines | ## Independent Variables | "Extract comparators: name, version, tuning" | + | statistical_plan | ## Analysis Plan | "Extract: test, alpha, power, correction, sample size" | + | success_criteria | ## Success Criteria | "Extract three criteria" | + + This two-level approach ensures backward compatibility with plans that lack frontmatter: + the provenance (`source: frontmatter` or `source: extracted`) is tracked for each field + and included in the evaluation dashboard. + +### Step 1: Triage Dispatcher + +Launch one subagent. Receives full plan text plus parsed fields. Returns: +- `experiment_type`: one of the type names in the loaded registry (from Step 0) +- `dimension_weights`: the complete weight matrix for this plan (H/M/L/S per dimension) +- `secondary_modifiers`: list of active modifiers with their effects on weights + +**Schema validation:** After the subagent returns, verify that `experiment_type` is a key +in the loaded registry (from Step 0). If the returned value is not in the registry, default +to `exploratory` and log a warning — do not silently pass an invalid type into the weight +matrix lookup, as this would corrupt all subsequent spawning decisions. + +**Triage classification rules (first-match):** + +Use the `classification_triggers` list from each type in the loaded registry to classify +the experiment. Apply first-match: iterate types in registry insertion order (bundled types +sorted alphabetically, then user-defined types sorted alphabetically). The first type whose +trigger description matches the plan is selected. If no trigger matches, default to +`exploratory`. + +**Secondary modifiers** (additive, increase dimension weights): +- `+causal`: mechanism claim in non-causal type → causal_structure weight +1 tier +- `+high_cost`: resources > 4 GPU-hours → resource_proportionality L→M +- `+deployment`: motivation references production/users → ecological_validity floor = M +- `+multi_metric`: ≥3 DVs → statistical_corrections weight +1 tier + +**Dimension weights:** + +Use the `dimension_weights` dict from the matched type's registry entry (loaded in Step 0). +Each key is a dimension name; each value is one of weight=H (High), weight=M (Medium), weight=L (Low), +or weight=S (SILENT — dimension not spawned, not mentioned in output). Pass the full +`dimension_weights` dict to the triage subagent so it can return the complete weight +matrix for this plan. + +### Subagent Evaluation Scope (applies to ALL dimension subagents) + +**Include this instruction block in every dimension subagent prompt.** + +Every finding must describe WHAT is lacking or at risk in the experimental design. +Never prescribe HOW to fix it — the fix is the plan author's responsibility. + +- GOOD: "The plan does not address how implementation correctness will be verified before measurement" +- BAD: "The plan must contain apply_phase1_changes.sh with inline Python that greps for function ordering" + +- GOOD: "The step-timing instrumentation could introduce inter-iteration contamination if reset ordering is incorrect" +- BAD: "step_timing::reset() uses Ordering::Relaxed — change to Ordering::Release" + +Findings must never include: +- Code snippets or shell commands as required plan content +- Specific tool invocations, package versions, or file paths as mandated fixes +- Implementation-level instructions (these belong in implementation phases, not design review) + +**Design scope boundary:** + +Evaluate the experimental DESIGN: hypotheses, metrics, statistical methodology, +controlled variables, threats to validity, data acquisition strategy, reproducibility specification. + +Do NOT evaluate: +- Correctness of implementation code snippets included as illustrative examples in the plan +- Shell script syntax, path accuracy, or command correctness in plan examples +- Package version pinning, compile-time constants, or infrastructure code correctness + +If a code snippet in the plan reveals a design-level concern (e.g., the metric definition +contradicts the hypothesis), flag the design concern, not the code bug. + +### Step 2: Level 1 Analysis — Fail-Fast (parallel) + +Two subagents run in parallel. Both are always H-weight; severity thresholds are calibrated per experiment_type via the rubric below. + +Each L1 subagent receives as explicit inputs: +- Full plan text +- `experiment_type` (from Step 1 triage output) +- Severity calibration rubric (below) + +**Severity calibration rubric for L1 dimensions:** + +Use the `l1_severity` dict from the matched experiment type's registry entry (loaded in +Step 0). Keys are `estimand_clarity` and `hypothesis_falsifiability`; values are severity +levels (`critical`, `warning`, `info`). Calibration anchors: `causal_inference` → critical; +`benchmark`, `configuration_study`, `robustness_audit` → warning; `exploratory` → info. + +- `estimand_clarity` agent: "Can the claim be written as a formal contrast (A vs B on Y in Z)?" + Reference the exp-lens-estimand-clarity philosophical mode as guidance (do NOT invoke + the skill — reference its lens question only in the subagent prompt). + Use the `l1_severity.estimand_clarity` value from the registry to assign severity. +- `hypothesis_falsifiability` agent: "What result would cause the author to conclude H0?" + Use the `l1_severity.hypothesis_falsifiability` value from the registry to assign severity. + +Each subagent returns findings in the standard JSON structure (see Finding Format below). + +**FAIL-FAST GATE**: After both Level 1 subagents complete, check for critical findings. +If ANY Level 1 subagent returns a finding with `"severity": "critical"`: +- Collect these as `stop_triggers` +- Do not proceed to Level 2, 3, or 4 analysis +- Do not start the red-team agent +- Skip directly to Step 7 (Synthesis) with only L1 findings +- The verdict logic will produce STOP; halt and emit tokens + +**Subagent parse failure:** If a Level 1 subagent returns unparseable output (malformed +JSON, empty response, token-limit truncation), treat it as if it returned one critical +finding with `message: "L1 subagent did not return parseable findings"`. This ensures +parse failures trigger the fail-fast gate rather than silently passing it. + +**ADDRESSABLE vs STRUCTURAL classification**: After collecting critical L1 findings, +classify each one before applying the gate: + +- **ADDRESSABLE**: Concrete methodological flaw with a mechanical fix — the research + question remains answerable after revision (e.g., "decompose composite hypothesis + into independent pairs", "add explicit estimand contrast statement") +- **STRUCTURAL**: The research question is not answerable with this experimental design + regardless of revision (e.g., "no observable outcome exists for this hypothesis", + "estimand requires counterfactual data that cannot be collected") + +**Classification scope limitation**: Initially, only `hypothesis_falsifiability` findings +are eligible for ADDRESSABLE classification — hypothesis restructuring is the dimension +most likely to produce mechanically fixable defects. `estimand_clarity` findings default +to STRUCTURAL (absent estimands typically indicate deeper design flaws). + +**Gate behavior after classification:** +- If ANY critical finding is STRUCTURAL → halt L2-L4 analysis (emit STOP) +- If ALL critical findings are ADDRESSABLE → tag each as `"priority": "REQUIRED"`, + continue L2-L4 analysis. The verdict becomes REVISE (not STOP) with the ADDRESSABLE + findings at the top of the evaluation dashboard. +- If mixed (some ADDRESSABLE, some STRUCTURAL) → halt (STRUCTURAL takes precedence) + +### Step 3: Level 2 + Red-Team (concurrent) + +When the L1 gate passes (no STRUCTURAL critical L1 findings — gate also passes when all L1 criticals are ADDRESSABLE), launch 2–3 Level 2 subagents AND the +red-team agent concurrently — all at the same time without waiting for each other. + +**Level 2 subagents** (parallel, weights from the matrix): +- `baseline_fairness`: "Are all compared systems given symmetric resources and tuning effort?" +- `causal_structure`: weight from matrix (S for benchmark/config_study, H for causal_inference). + Only spawn when weight ≥ L. +- `unit_interference`: "Can treatments spill over between experimental units?" + +**Red-team agent** (concurrent with L2 and L4 — does NOT block L3): + +Receives: full plan text and `experiment_type` (from Step 1 triage output) + +- Five universal challenges (challenge every plan regardless of type): + 1. **Goodhart exploitation** — cheapest way to score well without solving the research question + 2. **Data leakage** — test-set info contaminating training/hyperparameter selection + 3. **Asymmetric tuning** — proposed method tuned against eval while baselines use defaults + 4. **Survivorship bias** — cherry-picking best run from multiple seeds + 5. **Evaluation collision** — same infrastructure in both treatment and measurement +- Type-specific focus: use `red_team_focus.specific` from the matched type's registry + entry (loaded in Step 0). +- ALL red-team findings must set `"requires_decision": true` and `"dimension": "red_team"` + +**Red-team severity calibration rubric:** + +| Dimension | causal_inference | benchmark | configuration_study | robustness_audit | exploratory | +|-----------|-----------------|-----------|---------------------|------------------|-------------| +| red_team | critical | warning | warning | warning | info | + +The red-team agent assigns severity based on the intrinsic quality of each finding. +After the red-team agent returns, **cap each finding's severity** to the maximum +allowed by the experiment type using this rubric — identical to how L1 severity +calibration works. For `causal_inference`: critical red-team findings remain critical +(STOP-eligible). For `benchmark`/`configuration_study`/`robustness_audit`: critical +findings are downgraded to `warning` (REVISE-eligible but never STOP). For +`exploratory`: all red-team findings are capped at `info` (informational only). + +This cap is applied in Step 7 before the verdict logic evaluates `stop_triggers`. + +### Step 4: Level 3 (parallel) + +Run after Level 2 completes. Do not wait for the red-team agent before starting Level 3. + +Each L3 subagent receives: +- Full plan text +- `experiment_type` (from Step 1 triage output) — calibrates expected statistical rigor: + `exploratory` plans do not require pre-registered correction procedures; `causal_inference` + plans demand formal power analysis and correction pre-specification. +- L1 and L2 findings summary as context (findings may inform statistical planning relevance) + +Three subagents run in parallel: +- `error_budget`: "Is power analysis present? Are error rates (Type I / Type II) acknowledged?" +- `statistical_corrections`: "Are multiple comparisons corrections pre-specified for all DVs?" +- `variance_protocol`: "Are seeds fixed? Is run-to-run variance addressed?" + NOTE: absent seeds IS a valid finding for this dimension at H-weight — do not suppress + via foothold validation. + +### Step 5: Level 4 (parallel, gated by triage) + +2–4 subagents. Only spawn subagents for dimensions with weight ≥ L in the matrix. +SILENT (S) dimensions are NOT spawned and NOT mentioned in output. + +Each L4 subagent receives: +- Full plan text +- `experiment_type` (from Step 1 triage output) — calibrates rigor expectations per dimension: + `benchmark` plans have lower ecological validity expectations than `causal_inference` plans + by design; `reproducibility_spec` rigor scales with `causal_inference` > `benchmark` > + `exploratory`. +- `dimension_weights` (from Step 1) — provides context on why this dimension was spawned + (e.g., H-weight dimensions warrant stricter thresholds than L-weight dimensions) + +Level 4 dimensions (spawn when not SILENT): +- `benchmark_representativeness`: "Does this generalize beyond the specific test bed?" +- `ecological_validity`: "Do test conditions match the intended deployment context?" +- `measurement_alignment`: "Do the metrics actually measure what the research question claims?" +- `reproducibility_spec`: "Could an independent party reproduce this experiment?" +- `data_acquisition`: "Does the plan include a complete data acquisition strategy?" +- `agent_implementability`: "Is this plan executable by a code-generating agent without human intervention?" + +#### `data_acquisition` — Data Acquisition Completeness + +Validates that the experiment plan includes a complete data acquisition strategy: + +1. **Hypothesis coverage**: Every hypothesis in `success_criteria` has at least one + `data_manifest` entry specifying its data source. +2. **External source readiness**: Every entry with `source_type: external` has an + explicit acquisition command and a verification criterion. +3. **Gitignored path handling**: Every entry with `source_type: gitignored` has an + acquisition/generation step — gitignored paths are empty in fresh worktrees. +4. **Dependency ordering**: If entry A's `depends_on` references entry B's acquisition, + B must be listed before A (or the dependency chain must be acyclic). +5. **Directive compliance**: If the research task directive specifies particular data, + the `data_manifest` must include acquisition steps for that data. + +**Findings format:** +- STOP if: a hypothesis has no data source at all, or directive-specified data has no acquisition step +- REVISE if: an external source lacks verification criteria, or gitignored path handling is unclear + +#### `agent_implementability` — Agent Execution Feasibility + +Validates that the experiment plan can be implemented by a code-generating agent +without human intervention: + +1. **Step atomicity**: Each implementation step has a single unambiguous action. + Multiple interleaved actions in a single step create ambiguity about ordering + and completion criteria. +2. **File path resolvability**: All referenced files and modules are named with + locatable paths. Vague references like "the utils module" or "the config file" + are insufficient — the agent needs exact paths or unambiguous naming conventions. +3. **Performance feasibility**: Pseudocode and algorithms are viable at the + specified data scale. A nested loop that is O(n^2) at n=50K is a design-level + concern, not an implementation detail. +4. **Verification criteria completeness**: Each implementation phase has a + concrete, runnable acceptance test or verification criterion. Phases without + verification criteria cannot be confirmed complete by an agent. +5. **Dependency ordering**: No step requires an artifact (file, dataset, model + checkpoint) that has not yet been produced by a prior step. Circular or + forward dependencies make deterministic execution impossible. +6. **Absence of human-only actions**: No steps require subjective judgment, + visual inspection, or domain expertise that a code-generating agent cannot + execute deterministically. Examples: "review the output and decide if it looks + reasonable", "manually inspect the plot for anomalies". +7. **Artifact continuity**: No planned artifact from a prior plan version was + silently removed without replacement or explicit justification. Removals + without explanation are data provenance regressions. + +**Findings format:** +- REVISE if: any of checks 1–7 identifies a gap in the plan +- This dimension does not produce STOP-eligible findings (L4 contract) + +Level 3 and Level 4 may run concurrently with the red-team agent (do not block on red-team). + +**Three-layer silencing** (prevents orphan warnings): +1. **Static SILENT** from matrix — dimensions not spawned, not mentioned in output. +2. **Foothold validation** — before spawning M/L dimensions, check plan text has relevant + content. If absent: M→L, L→S. Exception: absent seeds IS a finding for + `variance_protocol` at H-weight. +3. **Finding-count suppression** — L-weight dimensions with zero findings: omit from output + entirely. H/M dimensions with zero findings: emit "No issues identified" (deliberate + clean bill of health). + +### Step 6: Wait for Red-Team + +After Levels 3 and 4 complete, wait for the red-team agent if still running. +All red-team findings are merged into the finding pool with their +`"requires_decision": true` flag preserved. + +### Step 7: Synthesis + +One synthesis pass (no subagent — orchestrator synthesizes directly): + +1. **Merge all findings** from L1, L2, L3, L4, and red-team into a single list. +2. **Deduplicate** by `(dimension, section, message)` — identical findings from parallel + agents are collapsed into one entry. +3. **Consolidate related findings**: If multiple findings address the same underlying + methodological concern (e.g., four separate findings about multiple comparisons + correction from different dimensions), group them as sub-findings under a single + parent finding with the highest severity and priority of the group. The parent + finding's message should describe the shared concern; sub-findings retain their + dimension-specific detail as bullet points beneath the parent. This prevents + the same issue from inflating finding counts and obscuring distinct problems. +4. **Apply red-team severity cap, then verdict logic**: + ```python + # RT_MAX_SEVERITY is built from the registry loaded in Step 0 (dict-of-dicts from YAML parsing): + RT_MAX_SEVERITY = {name: spec["red_team_focus"]["severity_cap"] for name, spec in registry.items()} + SEVERITY_RANK = {"info": 0, "warning": 1, "critical": 2} + rt_cap = RT_MAX_SEVERITY[experiment_type] + + for f in findings: + if f.dimension == "red_team" and SEVERITY_RANK[f.severity] > SEVERITY_RANK[rt_cap]: + f.severity = rt_cap # downgrade before verdict + + # Reclassify after cap + critical_findings = [f for f in findings if f.severity == "critical"] + warning_findings = [f for f in findings if f.severity == "warning"] + + active_dimensions = count_of_spawned_dimensions # tracked from Steps 2-6 + + # Proportional warning threshold: each active dimension gets a budget of 5 + # warnings before the plan is flagged for revision. + WARNING_BUDGET_PER_DIM = 5 + warning_threshold = active_dimensions * WARNING_BUDGET_PER_DIM + + # L1 fail-fast path: only STRUCTURAL defects trigger STOP + l1_criticals = [f for f in critical_findings if f.dimension in {"estimand_clarity", "hypothesis_falsifiability"}] + # Tag ADDRESSABLE L1 criticals as REQUIRED (scope: hypothesis_falsifiability only) + for f in l1_criticals: + if f.fixability == "ADDRESSABLE": + f.priority = "REQUIRED" + # Scope guard: estimand_clarity always STRUCTURAL; None fixability defaults to STRUCTURAL + structural_stop_triggers = [ + f for f in l1_criticals + if f.fixability == "STRUCTURAL" or f.fixability is None or f.dimension == "estimand_clarity" + ] + + # Red-team STOP path: adversarial critical findings after full analysis (L2-L4) + # These fire only when the L1 gate passed AND the severity cap still allows critical. + stop_triggers = structural_stop_triggers + [f for f in critical_findings if f.dimension == "red_team"] + + if stop_triggers: + verdict = "STOP" + elif critical_findings or len(warning_findings) >= warning_threshold: + verdict = "REVISE" + else: + verdict = "GO" + ``` +5. **Write `evaluation_dashboard_{slug}_{YYYY-MM-DD_HHMMSS}.md`** — always written. + Must include: + - Verdict banner and classification summary + - Dimension scorecard table (dimension → weight → findings count → severity summary) + - Adversarial findings section (red-team findings, each marked `requires_decision: true`) + - **Cannot Assess** section with at least 2 items (dimensions where evaluation was + impossible due to absent plan content; minimum 2 entries, e.g., + "Randomization mechanism not described — cannot assess unit interference risk", + "No resource budgets stated — cannot assess resource_proportionality") + - Mechanizable check log — fixed checklist items (always evaluated) plus + ad-hoc additions from subagents: + - **Fixed:** "All implementation phases have runnable verification criteria" + - **Fixed:** "All file paths in the implementation plan resolve to valid locations" + - Ad-hoc entries contributed by dimension subagents during this review cycle + - Machine-readable YAML summary block at end: + ```yaml + # --- review-design machine summary --- + verdict: GO|REVISE|STOP + experiment_type: {type} + critical_count: {n} + warning_count: {n} + blocking_count: {n} + required_count: {n} + advisory_count: {n} + red_team_count: {n} + active_dimensions: {n} + warning_threshold: {n} + ``` + The YAML summary block enables downstream recipe steps to parse verdict and counts + without re-reading prose. +6. **Write `revision_guidance_{slug}_{YYYY-MM-DD_HHMMSS}.md`** — written ONLY when + verdict = REVISE. Must include: + - Required revisions: critical findings with gap and risk descriptions (not implementation instructions) + - Recommended revisions: warning findings with gap and risk descriptions + - Red-team findings with risk descriptions and decision points + Revision guidance describes WHAT needs to change in the experimental design, + never HOW to implement the change. The `revision_guidance` path is passed back + to `plan-experiment` in the recipe loop. + +### Step 8: Emit Output Tokens + +Emit these lines as your final output: + +``` +verdict = GO|REVISE|STOP +experiment_type = {experiment_type} +evaluation_dashboard = /absolute/path/{{AUTOSKILLIT_TEMP}}/review-design/evaluation_dashboard_{slug}_{YYYY-MM-DD_HHMMSS}.md +revision_guidance = /absolute/path/{{AUTOSKILLIT_TEMP}}/review-design/revision_guidance_{slug}_{YYYY-MM-DD_HHMMSS}.md +``` + +`revision_guidance` line is emitted ONLY when verdict = REVISE. When verdict is GO or STOP, +omit the `revision_guidance` line entirely. + +## Finding Format + +All subagents must return findings in this JSON structure: + +```json +{ + "section": "## Hypothesis", + "dimension": "estimand_clarity", + "level": 1, + "severity": "critical | warning | info", + "priority": "BLOCKING | REQUIRED | ADVISORY", + "fixability": "ADDRESSABLE | STRUCTURAL | null", + "message": "{describes what is lacking or at risk — never prescribes how to fix}", + "requires_decision": false +} +``` + +**Fixability classification** (L1 findings only — all other levels use JSON `null`): + +See **ADDRESSABLE vs STRUCTURAL classification** in Step 2 for authoritative definitions +and scope limitations. `null` (JSON null literal, not the string "null") is used for all +non-L1 findings where fixability is not applicable. + +**Priority tiers** (supplementing, not replacing, `severity`): + +- **BLOCKING**: Must be addressed before implementation proceeds. Structural invalidity + that would make results uninterpretable (e.g., "metric |Delta T_B| is mathematically + invalid for Approach B — entire experimental arm produces meaningless data") +- **REQUIRED**: Must be addressed in revision. Methodology gaps that weaken but do not + invalidate results (e.g., "composite hypothesis is unfalsifiable — decompose into + independent pairs") +- **ADVISORY**: Should be addressed but omission will not invalidate results (e.g., + "gitignore coverage for generated artifacts not specified") + +**Priority assignment rules:** +- STRUCTURAL L1 criticals → BLOCKING +- ADDRESSABLE L1 criticals → REQUIRED +- Non-L1 criticals → BLOCKING (default) or REQUIRED (if finding describes a gap + rather than an invalidity) +- Warnings → REQUIRED (default) or ADVISORY (if finding is informational in nature) +- Info → ADVISORY + +Red-team findings: always `"requires_decision": true`, `"dimension": "red_team"`. + +## Output + +``` +{{AUTOSKILLIT_TEMP}}/review-design/ +├── evaluation_dashboard_{slug}_{YYYY-MM-DD_HHMMSS}.md (always written) +└── revision_guidance_{slug}_{YYYY-MM-DD_HHMMSS}.md (REVISE only) +``` + +Emit structured output tokens (absolute paths) as your final output. + +## Related Skills + +- `/autoskillit:plan-experiment` — produces the plan this skill validates +- `/autoskillit:scope` — first step in the research recipe chain +- `/autoskillit:implement-experiment` — consumes this skill's GO output (via recipe routing) +- exp-lens skills — philosophical modes referenced in dimension prompts (not invoked directly) diff --git a/src/autoskillit/skills_extended/review-pr/SKILL.md b/src/autoskillit/skills_extended/review-pr/SKILL.md index 28777a016c..7d141ad07e 100644 --- a/src/autoskillit/skills_extended/review-pr/SKILL.md +++ b/src/autoskillit/skills_extended/review-pr/SKILL.md @@ -34,7 +34,7 @@ by the recipe pipeline after `open_pr_step` opens the PR. ## Critical Constraints **NEVER:** -- Create files outside `.autoskillit/temp/review-pr/` +- Create files outside `{{AUTOSKILLIT_TEMP}}/review-pr/` - Approve a PR that has `changes_requested` findings - Post review comments when `gh` is unavailable — output `verdict=approved` and exit 0 - Review files outside the PR diff — scope all audit to diff content only @@ -105,7 +105,7 @@ gh pr diff {pr_number} gh repo view --json nameWithOwner -q .nameWithOwner ``` -Save the diff to `.autoskillit/temp/review-pr/diff_{pr_number}.txt`. (relative to the current working directory) +Save the diff to `{{AUTOSKILLIT_TEMP}}/review-pr/diff_{pr_number}.txt`. (relative to the current working directory) ### Step 2.7: Deterministic Diff Annotation @@ -435,6 +435,9 @@ Do not proceed to Step 7. Instead, investigate why zero comments were posted. Ch whether the line numbers in your findings match `VALID_LINE_RANGES`. If they do not, attempt to map each finding to the nearest valid hunk line before falling back. +**CRITICAL — No Local File Paths in GitHub Output:** +Never reference local file paths (e.g., `{{AUTOSKILLIT_TEMP}}/...`, `summary_*.md`, absolute paths) in the review body, inline comments, or any content posted to GitHub. The summary file is a local audit artifact only — GitHub readers cannot access local filesystem paths. Reference findings by file path and line number within the repository, not by local temp file locations. + ### Step 7: Submit Summary Review ```bash @@ -450,7 +453,9 @@ gh pr review {pr_number} --comment --body "AutoSkillit review: uncertain trade-o ### Step 8: Write Summary and Emit Verdict -Save findings summary to `.autoskillit/temp/review-pr/summary_{pr_number}_{timestamp}.md`. (relative to the current working directory) +**CRITICAL — Ordering:** Step 8 must execute after Steps 6 and 7. Do not write the summary file before posting inline comments and submitting the review verdict to GitHub. Writing the file first anchors you to treating it as the primary output rather than a local audit artifact. + +Save findings summary to `{{AUTOSKILLIT_TEMP}}/review-pr/summary_{pr_number}_{timestamp}.md`. (relative to the current working directory) Output the verdict as the final line: @@ -472,4 +477,4 @@ Exit 1 only for unrecoverable tool-level errors. - `verdict=changes_requested` — Blocking issues found; recipe routes to `resolve_review` - `verdict=needs_human` — Uncertain trade-offs; human review requested via the authenticated GitHub user mention (derived at runtime) -Summary written to: `.autoskillit/temp/review-pr/summary_{pr_number}_{timestamp}.md` \ No newline at end of file +Summary written to: `{{AUTOSKILLIT_TEMP}}/review-pr/summary_{pr_number}_{timestamp}.md` \ No newline at end of file diff --git a/src/autoskillit/skills_extended/review-research-pr/SKILL.md b/src/autoskillit/skills_extended/review-research-pr/SKILL.md new file mode 100644 index 0000000000..770b5c1f8c --- /dev/null +++ b/src/autoskillit/skills_extended/review-research-pr/SKILL.md @@ -0,0 +1,382 @@ +--- +name: review-research-pr +categories: [research] +description: Automated diff-scoped research PR review using parallel audit subagents aligned to research quality dimensions. Posts inline GitHub review comments and submits a summary verdict. Use after a research PR is opened to gate on review approval. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: review-research-pr] Reviewing research pull request...'" + once: true +--- + +# Review Research PR Skill + +Perform an automated, diff-scoped code review on an open GitHub research PR using parallel +audit subagents tuned to research quality dimensions. Posts inline review comments and submits +a summary verdict. Called by the recipe pipeline after `open_research_pr` opens the PR. + +## Arguments + +`/autoskillit:review-research-pr ` + +- **worktree-path-or-feature-branch** — Either an absolute path to the research worktree + (preferred; skill derives the feature branch from `git rev-parse --abbrev-ref HEAD`) + or the feature branch name directly +- **base-branch** — The base branch the PR targets (e.g., "main") + +## When to Use + +- Called by the recipe orchestrator via `run_skill` after `open_research_pr` +- Can be invoked standalone to review any open research PR + +## Critical Constraints + +**NEVER:** +- Create files outside `{{AUTOSKILLIT_TEMP}}/review-research-pr/` +- Approve a PR that has `changes_requested` findings +- Post review comments when `gh` is unavailable — output `verdict=approved` and exit 0 +- Review files outside the PR diff — scope all audit to diff content only +- Modify any source code +- Flag the absence of a clear experimental conclusion as a deficiency — inconclusive + results are valid outcomes for research PRs (do not flag them) + +**ALWAYS:** +- Find the PR by feature branch at invocation time (not from a pre-captured URL) +- Output `verdict=` on the final line +- Exit 0 in all normal cases; verdict drives recipe routing via on_result, not exit code +- Exit non-zero only for unrecoverable errors (e.g., gh CLI truly unavailable after graceful degradation has already output verdict=approved) +- Tag the authenticated GitHub user (`gh api user -q .login`) in escalation comments (`needs_human` verdict) — omit the mention silently if username derivation fails +- Use `model: "sonnet"` when spawning all subagents via the Task tool +- Deduplicate findings by (file, line) pairs before posting + +## Workflow + +### Step 0: Validate Arguments + +Parse two positional arguments: `worktree_or_branch` and `base_branch`. + +Derive `feature_branch`: + +```bash +if [ -d "$worktree_or_branch" ]; then + feature_branch=$(git -C "$worktree_or_branch" rev-parse --abbrev-ref HEAD 2>/dev/null || echo "") +else + feature_branch="$worktree_or_branch" +fi +``` + +Derive the escalation username for `needs_human` verdicts: + +```bash +escalation_user=$(gh api user -q .login 2>/dev/null || echo "") +``` + +If `escalation_user` is non-empty, set `escalation_user_mention="@${escalation_user}"`. +If empty (gh unavailable or not authenticated), set `escalation_user_mention=""`. + +### Step 0.5 — Code-Index Initialization (required before any code-index tool call) + +Call `set_project_path` with the repo root where this skill was invoked (not a worktree path): + +``` +mcp__code-index__set_project_path(path="{PROJECT_ROOT}") +``` + +Code-index tools require **project-relative paths**. Always use paths like: + + src/mypackage/core/module.py + +NOT absolute paths like: + + /path/to/project/src/mypackage/core/module.py + +Agents launched via `run_skill` inherit no code-index state from the parent session — this +call is mandatory at the start of every headless session that uses code-index tools. + +### Step 1: Find the Open PR + +```bash +gh pr list --head "$feature_branch" --base "$base_branch" \ + --json number,url -q '.[0] | "\(.number) \(.url)"' +``` + +If `gh` is unavailable or not authenticated, or no PR is found: +- Log "No PR found or gh unavailable — skipping review" +- Output `verdict=approved` +- Exit 0 (graceful degradation) + +### Step 2: Get PR Diff and Metadata + +```bash +# Get the PR diff +gh pr diff {pr_number} + +# Get owner/repo +gh repo view --json nameWithOwner -q .nameWithOwner +``` + +Save the diff to `{{AUTOSKILLIT_TEMP}}/review-research-pr/diff_{pr_number}.txt`. (relative to the current working directory) + +### Step 3: Run Parallel Audit Subagents + +Spawn parallel subagents (Task tool, model: sonnet) for each research audit dimension. +Each subagent receives only the PR diff content (not the full codebase) and returns +findings in JSON format: + +```json +[ + { + "file": "path/to/file.py", + "line": 42, + "dimension": "methodology|reproducibility|report-quality|statistical-rigor|isolation|data-integrity|slop|data-scope", + "severity": "critical|warning|info", + "message": "Description of the finding", + "requires_decision": false + } +] +``` + +**Research audit dimensions:** + +1. **methodology** — Experimental design validity: appropriate controls, confounds, hypothesis + alignment, scope creep. + Check for: missing baselines, uncontrolled variables, methodology/hypothesis misalignment. + +2. **reproducibility** — Ability to replicate the experiment independently. + Check for: hardcoded paths, missing environment specs, undocumented random seeds, + missing data provenance, non-deterministic procedures without documentation. + +3. **report-quality** — Clarity, completeness, and honesty of research reporting. + Check for: unexplained findings, missing limitations section, unsupported conclusions. + **Constraint:** Do not flag absence of a clear experimental conclusion — inconclusive + results are a valid outcome and must not be treated as a deficiency. Only flag + reporting issues that obscure or misrepresent findings. + +4. **statistical-rigor** — Correct use of statistical methods and honest interpretation. + Check for: p-hacking indicators, missing confidence intervals, inappropriate aggregations, + cherry-picked metrics, overstated effect sizes. + +5. **isolation** — Experiment environment isolation and interference avoidance. + Check for: shared mutable state across runs, missing teardown, environment contamination, + test interference with production data. + +6. **data-integrity** — Correctness and trustworthiness of data collection and handling. + Check for: off-by-one errors in data slicing, incorrect aggregations, data leakage, + mismatched units, silent NaN/None handling in metrics. + +7. **slop** — AI-generated boilerplate that adds noise without research value. + Check for: commented-out code, TODO without issue refs, over-verbose docstrings, + dead code, backward-compat stubs left by the LLM. + +8. **data-scope** — Data scope coverage and qualification. + Checks whether the experiment's data coverage matches the research task directive: + - **Scope coverage**: Did the experiment use the data types specified in the research + task directive? If the directive said "use MERFISH data" but all benchmarks ran on + synthetic data only, this is a finding. + - **Qualification**: Are domain-specific claims (e.g., "Reduces MERFISH evaluation + wall-clock by X%") qualified with actual data provenance? Claims derived from + synthetic data must state this explicitly. + - **Data Scope Statement**: Does the Executive Summary contain a Data Scope Statement? + If not, this is a finding. + - **Hypothesis gate alignment**: Do GO/NO-GO recommendations reference the correct + pre-specified gate thresholds, or were thresholds silently substituted? + + **Severity guidance:** + - `requires_decision: true` when all benchmarks used synthetic data for a domain-specific project + - Standard finding when Data Scope Statement is missing or incomplete + - Standard finding when claims are unqualified + +Subagent prompt template (all 8 dimensions): + +> You are reviewing a GitHub PR diff for [{dimension}] issues only. +> Scope: examine only the diff content provided. Do not fetch or read files outside the diff. +> Return a JSON array of findings. Each finding must have: +> file, line, severity (critical/warning/info), dimension, message, +> requires_decision (boolean). +> +> Set requires_decision=true ONLY for findings where the correct path forward is +> genuinely ambiguous and cannot be determined without the human's intent or +> preference — for example: design trade-offs, approach choices with valid +> alternatives, unclear intent after a merge conflict, plan/implementation +> divergences where both directions are valid. +> +> Set requires_decision=false for ALL bugs, style issues, or anything with a +> clear fix, regardless of severity. When in doubt, set requires_decision=false. +> +> Each line in the diff is prefixed with `[LNNN]` where NNN is the new-file line number. +> When reporting findings, use the `[LNNN]` number as the `line` value in your finding. +> Do not compute line numbers yourself — use the marker. +> If the finding cannot be anchored to a specific `[LNNN]` marker, use the nearest +> `+` or context line's marker in the same hunk. +> +> If no issues found, return an empty array []. +> Annotated diff content (each line prefixed with [LNNN] markers): +> {annotated_diff_content} + +### Step 4: Aggregate and Deduplicate Findings + +1. Collect all subagent JSON responses +2. Deduplicate by `(file, line)` pairs — keep highest severity for each pair +3. Bucket by actionability: + - `actionable_findings` — requires_decision=false AND severity in ("critical", "warning") + - `decision_findings` — requires_decision=true (any severity) + - `info_findings` — severity == "info" AND requires_decision=false + +### Step 4.5: Echo Primary Obligation + +After aggregating all subagent findings, before proceeding to verdict or posting, you MUST state aloud: + +> "I have N findings. My primary job is to post inline comments on specific code lines for each finding. I must use the GitHub Reviews API to leave comments anchored to the exact lines in the diff." + +This is not optional. Do not proceed to Step 5 without stating this. + +### Step 5: Determine Verdict + +- Any `actionable_findings` present → `verdict = "changes_requested"` (clear fix exists, automated resolver handles it) +- No actionable findings, but `decision_findings` present → `verdict = "needs_human"` (`needs_human` fires only when one or more findings have `requires_decision=true` — meaning the correct path forward requires a human decision that the automated reviewer cannot make) +- No actionable or decision findings → `verdict = "approved"` + +**Verdict logic:** +```python +decision_findings = [f for f in all_findings if f.get("requires_decision")] +actionable_findings = [ + f for f in all_findings + if not f.get("requires_decision") and f["severity"] in ("critical", "warning") +] + +if actionable_findings: + verdict = "changes_requested" +elif decision_findings: + verdict = "needs_human" +else: + verdict = "approved" +``` + +### Step 6: Post Inline Review Comments + +Build review comment bodies for each critical and warning finding. Use the `line` and `side` +fields (modern GitHub Reviews API — not the deprecated `position` field) so that file line +numbers from audit findings map directly without diff-position counting. + +For each finding, `line` is the finding's `line` value (the line number in the new file) and +`side` is always `RIGHT` (referring to the right-hand side of the diff — additions and context +in the updated file). + +Build a proper JSON payload where each comment is a complete object, then post via `--input -`. + +```bash +# Build comments JSON array from findings +COMMENTS_JSON=$(jq -n --argjson findings "$FINDINGS" ' + $findings | map({ + path: .file, + line: .line, + side: "RIGHT", + body: ("[" + .severity + "] " + .dimension + ": " + .message) + }) +') + +# Build and post the full review payload via stdin +jq -n \ + --arg body "AutoSkillit Research PR Review — Verdict: {verdict}" \ + --arg event "{APPROVE|COMMENT|REQUEST_CHANGES}" \ + --argjson comments "$COMMENTS_JSON" \ + '{body: $body, event: $event, comments: $comments}' | \ +gh api /repos/{owner}/{repo}/pulls/{pr_number}/reviews \ + --method POST --input - +``` + +Event mapping: +- `approved` → `APPROVE` +- `needs_human` → `COMMENT` +- `changes_requested` → `REQUEST_CHANGES` + +**Fallback Tier 1 — Individual Comments (if batch POST fails):** + +Attempt to post each finding individually via: + +```bash +COMMIT_ID=$(gh pr view {pr_number} --json headRefOid -q .headRefOid) + +# For each finding: +gh api /repos/{owner}/{repo}/pulls/{pr_number}/comments \ + --method POST \ + --field path="{finding.file}" \ + --field line={finding.line} \ + --field side="RIGHT" \ + --field commit_id="$COMMIT_ID" \ + --field body="[{finding.severity}] {finding.dimension}: {finding.message}" +``` + +Individual POSTs are not atomic — one failure does not block others. +If at least one per-finding comment succeeds, proceed to Step 7. + +**Fallback Tier 2 — DEGRADED: Bullet-List Summary Dump (if all individual posts fail):** + +WARNING: If you reach Tier 2 fallback, the review has FAILED its primary purpose. +Before posting the body dump, you MUST state: + +> "FALLBACK: I was unable to post inline comments. Posting summary as review body instead. This is a DEGRADED review." + +Post ALL findings via: + +```bash +gh pr review {pr_number} --comment --body "{summary_markdown}" +``` + +Format each file's findings as a bullet list: + +``` +## AutoSkillit Research Review Findings + +**Verdict:** {verdict} + +### path/to/file.py +- **L{line}** [{severity}/{dimension}]: {message, truncated to 120 chars} +``` + +### Step 6.5: Post-Completion Confirmation + +After completing Step 6, you MUST state: + +> "I confirm that I posted N inline comments on the following files: [list files]. If I posted 0 inline comments and had findings, this review has FAILED its primary purpose." + +### Step 7: Submit Summary Review + +```bash +# approved +gh pr review {pr_number} --approve --body "AutoSkillit research review passed. No blocking issues found." + +# changes_requested +gh pr review {pr_number} --request-changes --body "AutoSkillit research review found {N} blocking issues. See inline comments." + +# needs_human +gh pr review {pr_number} --comment --body "AutoSkillit research review: uncertain trade-offs detected. {escalation_user_mention} Please review. See inline comments." +``` + +### Step 8: Write Summary and Emit Verdict + +Save findings summary to `{{AUTOSKILLIT_TEMP}}/review-research-pr/summary_{pr_number}_{timestamp}.md`. (relative to the current working directory) + +Output the verdict as the final line: + +> **IMPORTANT:** Emit the structured output tokens as **literal plain text with no +> markdown formatting on the token names**. Do not wrap token names in `**bold**`, +> `*italic*`, or any other markdown. The adjudicator performs a regex match on the +> exact token name — decorators cause match failure. + +``` +verdict = {approved|changes_requested|needs_human} +``` + +Exit 0 in all normal cases (approved, needs_human, changes_requested). +Exit 1 only for unrecoverable tool-level errors. + +## Output + +- `verdict=approved` — No blocking issues; research PR is clear for human review +- `verdict=changes_requested` — Blocking issues found; recipe routes to next step +- `verdict=needs_human` — Uncertain trade-offs; human review requested via the authenticated GitHub user mention (derived at runtime) + +Summary written to: `{{AUTOSKILLIT_TEMP}}/review-research-pr/summary_{pr_number}_{timestamp}.md` diff --git a/src/autoskillit/skills_extended/run-experiment/SKILL.md b/src/autoskillit/skills_extended/run-experiment/SKILL.md new file mode 100644 index 0000000000..0535ee2bc1 --- /dev/null +++ b/src/autoskillit/skills_extended/run-experiment/SKILL.md @@ -0,0 +1,220 @@ +--- +name: run-experiment +categories: [research] +description: Execute a designed experiment in a worktree and collect structured results. Supports --adjust retry mode. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: run-experiment] Running experiment...'" + once: true +--- + +# Run Experiment Skill + +Execute an experiment that has been implemented in a worktree. This skill +runs whatever the experiment requires — scripts, benchmarks, custom tooling, +manual procedures, data collection, or any combination. It collects results +and produces a structured results file. + +The nature of the experiment is entirely determined by the experiment plan. +This skill does NOT prescribe how experiments should be run — it reads the +plan, executes what the plan describes, and reports what happened. + +## When to Use + +- As the execution step of the `research` recipe (phase 2) +- After `/autoskillit:implement-worktree-no-merge` has set up experiment code +- When `--adjust` flag is passed, re-run with modified approach after a failure + +## Arguments + +``` +/autoskillit:run-experiment {worktree_path} [--adjust] +``` + +- `{worktree_path}` — Absolute path to the worktree containing experiment code + (required). Scan tokens for the first path-like token (starts with `/`, `./`, + or `.autoskillit/`). +- `--adjust` — Optional flag indicating this is a retry after a previous failure. + When present, read the previous results/errors from `{{AUTOSKILLIT_TEMP}}/run-experiment/` + and adjust the approach before re-running. + +## Critical Constraints + +**NEVER:** +- Modify files outside the worktree +- Merge the worktree — leave it intact for the orchestrator +- Skip result collection — every run must produce structured output +- Assume what kind of experiment this is — read the plan and follow it +- Commit files under `{{AUTOSKILLIT_TEMP}}/` — this directory is gitignored working space, NOT for version control. Do not use `git add -f` or `git add --force` to bypass the gitignore. + +**ALWAYS:** +- Use `model: "sonnet"` when spawning all subagents via the Task tool +- Write results to `{{AUTOSKILLIT_TEMP}}/run-experiment/` in the worktree (disk only, never committed) +- Report failures with enough detail for the `--adjust` retry to fix them + +## Context Limit Behavior + +When context is exhausted mid-execution, experiment results may be partially written +to `{{AUTOSKILLIT_TEMP}}/run-experiment/`. The recipe routes to `on_context_limit`, +abandoning the partial experiment run. + +**Before emitting structured output tokens:** +1. If results were not fully written, emit `experiment_results = ` (empty) as a fallback +2. The orchestrator's `on_context_limit` route handles the partial state; the + downstream `--adjust` retry can restart the experiment from scratch + +## Workflow + +### Step 1 — Discover Experiment + +Read the experiment plan from `{{AUTOSKILLIT_TEMP}}/experiment-plan.md` in the +worktree (or the project root, checking both locations). This was saved by the +recipe's `save_experiment_plan` step from the approved GitHub issue. + +Also scan the worktree for experiment-related files: +- Scripts, benchmarks, test files, or tools added by `implement-worktree-no-merge` +- Configuration files for the experiment +- Data generators, fixtures, or input files + +Understand what the experiment requires before attempting to run anything. + +### Step 2 — Pre-flight Check + +Before running the experiment: +1. Verify the project builds or that prerequisites are met. +2. Verify experiment artifacts exist (scripts, data, dependencies). +3. If `--adjust` flag is set, read previous results from + `{{AUTOSKILLIT_TEMP}}/run-experiment/` and identify what went wrong. + +Launch subagents (model: "sonnet") if needed to investigate the experiment +setup, resolve dependencies, or research how to use specific tools mentioned +in the plan. + +### Data Manifest Verification (mandatory) + +Before executing any hypothesis: + +1. **Read the Data Manifest** from the experiment plan's YAML frontmatter + (`data_manifest` field). If no frontmatter or no `data_manifest` field exists, + log a warning and proceed with best-effort artifact checks. + +2. **For each `data_manifest` entry**, verify: + - If `location` is specified: the path exists and is non-empty + - If `verification` criteria are specified: evaluate them (e.g., file count, size) + - If `acquisition` command is specified and data is missing: attempt to run + the acquisition command. If it fails, mark the entry as BLOCKED. + +3. **Produce a data readiness table:** + ``` + | Hypothesis | Source Type | Location | Status | + |------------|-------------|----------|--------| + | H1, H2 | synthetic | in-script | READY | + | H5 | external | temp/merfish_100k/ | BLOCKED — directory empty | + ``` + +4. **If any entry the plan said would be acquired is BLOCKED:** + - Do NOT silently degrade to N/A + - Emit the structured output token `blocked_hypotheses` listing all blocked entries + - Set the results file `## Status` to `FAILED` + - Exit with a clear error message: "Pre-flight blocked: planned data for {hypotheses} + is unavailable. Data Manifest declared acquisition via {method} but verification + failed." + +This replaces the current behavior of silently marking missing-data hypotheses as N/A. +When the plan declared acquisition steps for data and those steps did not produce the +data, this is a pipeline failure — not a graceful degradation. + +### Step 3 — Execute Experiment + +Run the experiment as described in the plan. The experiment could be anything: +scripts, benchmarks, data collection, manual measurements, tool invocations, +custom pipelines, or any other procedure. Follow the plan's execution protocol. + +If the plan specifies multiple configurations or comparisons, execute all of +them and collect results for each. + +### Step 4 — Collect Results + +Structure the results as a markdown file: + +```markdown +# Experiment Results: {title} + +## Run Metadata +- Date: {YYYY-MM-DD HH:MM:SS} +- Worktree: {worktree_path} +- Commit: {git rev-parse HEAD} +- Environment: {relevant version info} + +## Configuration +{Parameters used for this run — from the experiment plan} + +## Results + +{Present the data collected. Use tables, code blocks, or whatever format +best represents the measurements. Include raw data when feasible.} + +## Observations +{Notable patterns, anomalies, unexpected behaviors, anything worth noting} + +## Recommendation +{Based on the evidence collected, what does this suggest? This is the +experimenter's interpretation — the generate-report skill will synthesize +the final conclusions.} + +## Status +{One of: CONCLUSIVE_POSITIVE | CONCLUSIVE_NEGATIVE | INCONCLUSIVE | FAILED} +{Brief justification for the status} +``` + +### Step 5 — Save Results + +1. Save results to: + `{{AUTOSKILLIT_TEMP}}/run-experiment/results_{topic}_{YYYY-MM-DD_HHMMSS}.md` + (relative to the current working directory) within the worktree. +2. Also save any raw data files (CSV, JSON, logs) to the same directory. +3. Do NOT `git add` or commit files under `{{AUTOSKILLIT_TEMP}}/`. This directory + is gitignored working space. The files persist on the worktree filesystem + for `generate-report` to read. Final results are published to `research/` by + the `generate-report` skill. + +After saving, emit the structured output token as the very last line of your +text output: + +> **IMPORTANT:** Emit the structured output tokens as **literal plain text with no +> markdown formatting on the token names**. Do not wrap token names in `**bold**`, +> `*italic*`, or any other markdown. The adjudicator performs a regex match on the +> exact token name — decorators cause match failure. + +``` +results_path = {absolute_path_to_results_file} +``` + +**When pre-flight blocks hypotheses due to missing planned data:** + +``` +blocked_hypotheses = H5: MERFISH data missing at temp/merfish_100k/ (acquisition: generate_merfish_subset.py --n 100000) +``` + +This token is emitted ONLY when the pre-flight gate fails due to data declared in the +Data Manifest being unavailable. It is NOT emitted during normal execution. + +When `blocked_hypotheses` is emitted, `results_path` still points to the results file +with `## Status: FAILED`. + +## Adjust Mode (--adjust) + +When `--adjust` is passed, this is a retry after a previous execution failed. + +1. Read previous results from `{{AUTOSKILLIT_TEMP}}/run-experiment/` in the worktree +2. Identify the failure mode +3. Make targeted adjustments to address the specific failure +4. Re-run the experiment with adjustments +5. Document what was changed and why in the results file + +Do NOT redesign the entire experiment — make minimal adjustments to address +the specific failure. If the experiment design itself is fundamentally flawed, +return a FAILED status so the recipe can escalate. diff --git a/src/autoskillit/skills_extended/scope/SKILL.md b/src/autoskillit/skills_extended/scope/SKILL.md new file mode 100644 index 0000000000..92fe895b00 --- /dev/null +++ b/src/autoskillit/skills_extended/scope/SKILL.md @@ -0,0 +1,196 @@ +--- +name: scope +categories: [research] +description: Survey codebase and web sources to build a known/unknown matrix for a research question. Phase 1 of the research recipe. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: scope] Scoping research question...'" + once: true +--- + +# Scope Research Skill + +Explore a technical research question before experiment design. Produces a +structured scope report covering what is known, what is unknown, prior art +in the codebase, and proposed hypotheses. This is the first phase of the +research recipe — it informs experiment design without making any code changes. + +## When to Use + +- As the first step of the `research` recipe (phase 1) +- When you need to understand a technical question before designing experiments +- When scoping what is feasible to investigate in this codebase + +## Arguments + +``` +/autoskillit:scope {research_question} +``` + +`{research_question}` — The technical question or topic to investigate (required). +This may be a free-text description, a GitHub issue reference (#N or URL), or a +combination. + +### GitHub Issue Detection + +If `{research_question}` contains a GitHub issue reference (full URL, `owner/repo#N`, +or bare `#N`), fetch the issue body via `fetch_github_issue` with `include_comments: true` +before analysis. Use the issue body as the primary research question; any surrounding +text is supplementary context. + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Create files outside `{{AUTOSKILLIT_TEMP}}/scope/` directory +- Propose solutions or write implementation code +- Skip the prior art survey — always check what already exists in the codebase + +**ALWAYS:** +- Use `model: "sonnet"` when spawning all subagents via the Task tool +- Write output to `{{AUTOSKILLIT_TEMP}}/scope/` directory +- Clearly separate facts (what the code does) from hypotheses (what might be true) +- Include a known/unknown matrix in the output + +## Workflow + +### Step 0 — Setup + +1. Parse the research question from arguments. +2. If a GitHub issue reference is detected, fetch it via `fetch_github_issue`. +3. Create the output directory: `mkdir -p {{AUTOSKILLIT_TEMP}}/scope/` + +### Step 1 — Parallel Exploration + +Launch subagents via the Task tool (model: "sonnet") to explore in parallel. +You **must launch at least 5 subagents**. Select from the suggested menu below, +define entirely custom subagents, or use any combination. The menu is a guide, +not a mandate — you are free to skip entries that are not relevant and substitute +your own tasks for any or all of them. + +**Suggested subagent menu:** + +**[PRIOR ART — Codebase or Literature]** +> For software questions: search the codebase for existing implementations, tests, +> benchmarks, or documentation related to the research question. For domain-specific +> questions (biology, chemistry, social science, etc.): survey published literature, +> established protocols, and known methods. Report what already exists and what gaps +> remain. + +**[EXTERNAL RESEARCH — Web Search]** +> Search the web for relevant tools, methods, papers, documentation, and prior work +> related to the research question. Look for established methodologies, known solutions, +> documentation for relevant tools, and community discussion of the topic. Report +> findings with source links. + +**[DOMAIN CONTEXT — Architecture or Domain Knowledge]** +> For software questions: understand the architecture surrounding the research area, +> key modules, data structures, algorithms, and their relationships; document current +> behavior and known limitations. For non-software questions: understand the domain- +> specific structures, relationships, mechanisms, and processes that are central to +> the research question. + +**[EVALUATION FRAMEWORK — Metrics or Assessment]** +> Search for whatever evaluation framework the project or domain uses. For software +> projects look for files named `metrics.*`, `benchmark.*`, `evaluation.*`, or any +> assessment/scoring module. For non-software domains, look for standard scales, +> assays, indices, or rubrics that the domain uses to measure outcomes. If no +> dedicated evaluation infrastructure exists, flag it explicitly in the output (do +> not silently emit an empty section). Report what measurement mechanisms exist and +> what gaps remain. + +**[COMPUTATIONAL COMPLEXITY — Algorithm Analysis]** +> Relevant when the research question involves an algorithm, model, or computational +> approach. Identify the most expensive computation involved. For each expensive +> operation found, note its time and space complexity class (O(n²), O(n log n), etc.) +> and any known pitfalls from library documentation or prior art (implicit matrix +> materializations, hidden copies, self-inclusion bugs, baseline/reference computation +> costs). Report findings as: dominant operation, scaling behavior, known bottlenecks, +> and gotchas. + +**[DATA AVAILABILITY — Datasets or Inputs]** +> Survey what data already exists that is relevant to the research question. Can it be +> generated synthetically? Are there existing datasets, fixtures, repositories, or +> domain-standard corpora? Report what is available and what gaps would need to be +> filled to run a meaningful experiment. + +**You may also define entirely custom subagents** for aspects of the research question +that require unique investigation not covered by the menu above. Always consider +launching at least one subagent beyond the obvious selections to explore angles you +might have missed. + +### Step 2 — Synthesize Findings + +Consolidate subagent findings into a structured scope report. The report +must contain these sections: + +```markdown +# Scope Report: {research_question_summary} + +## Research Question +{The precise question being investigated, refined from the raw input} + +## Known / Unknown Matrix + +| Category | Known | Unknown | +|----------|-------|---------| +| Current state | {what is known about how the subject behaves today} | {what we don't know about it} | +| Performance | {existing metrics/benchmarks} | {unmeasured aspects} | +| Edge cases | {known edge cases} | {suspected but unverified} | +| Prior work | {existing implementations} | {gaps in coverage} | + +## Prior Art +{What already exists — implementations, experiments, literature, tests, benchmarks, +documentation, or prior attempts relevant to this research question} + +## External Research +{Relevant findings from web searches — tools, methods, papers, documentation} + +## Domain Context +{For software questions: architecture, key modules, data flow, algorithms involved. +For non-software questions: domain-specific structures, mechanisms, organisms, pathways, +models, or processes that are central to the research question.} + +## Computational Complexity +- **Dominant operation:** {the single most expensive computation the experiment will perform — include the specific library call or algorithm, not just a description} +- **Scaling behavior:** {how cost grows with input size — O(n²), O(n·m), O(n log n), etc. — state both time and space complexity} +- **Known bottlenecks:** {specific library calls, data structures, or algorithms with high memory/time cost — include baseline and reference computations, not just the focal algorithm. If the experiment compares a new method against an exact/standard baseline, the baseline's computational cost must be listed here.} +- **Gotchas:** {known pitfalls from prior art or library documentation — self-inclusion bugs, implicit matrix materializations, hidden copies, dtype-dependent memory multipliers} + +## Hypotheses +{Proposed explanations or predictions to test, stated as falsifiable claims} + +## Proposed Investigation Directions +{2-3 possible experiment approaches, with trade-offs} + +## Success Criteria +{What would constitute a conclusive answer to the research question} + +## Metric Context *(include only when an evaluation framework was found)* +{If the [EVALUATION FRAMEWORK] subagent found a metrics or assessment infrastructure: +list which evaluation dimensions apply to this research question, what the current +threshold values or scoring standards are, and where they are defined. If no evaluation +framework was found, omit this section entirely — do not emit an empty section.} +``` + +### Step 3 — Write Output + +Save the scope report to: +`{{AUTOSKILLIT_TEMP}}/scope/scope_{topic}_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +Where `{topic}` is a snake_case summary of the research question (max 40 chars). + +After saving, emit the structured output token as the very last line of your +text output: + +> **IMPORTANT:** Emit the structured output tokens as **literal plain text with no +> markdown formatting on the token names**. Do not wrap token names in `**bold**`, +> `*italic*`, or any other markdown. The adjudicator performs a regex match on the +> exact token name — decorators cause match failure. + +``` +scope_report = {absolute_path_to_scope_report} +``` diff --git a/src/autoskillit/skills_extended/setup-project/SKILL.md b/src/autoskillit/skills_extended/setup-project/SKILL.md index 2d33814b96..54e9056a6f 100644 --- a/src/autoskillit/skills_extended/setup-project/SKILL.md +++ b/src/autoskillit/skills_extended/setup-project/SKILL.md @@ -1,5 +1,6 @@ --- name: setup-project +activate_deps: [write-recipe] description: Explore a target project and generate tailored recipes and config through an interactive workflow. Use when user wants to onboard a new project to AutoSkillit, says "setup project", or wants a starting point config. hooks: PreToolUse: @@ -33,7 +34,7 @@ Explore a target project and generate tailored recipes and AutoSkillit config th **NEVER:** - Modify any files in the target project without user confirmation at the summary gate - Run commands that change the target project -- Create files outside `.autoskillit/temp/setup-project/` directory (until the summary gate) +- Create files outside `{{AUTOSKILLIT_TEMP}}/setup-project/` directory (until the summary gate) - Assume test framework — detect it from evidence - Use Makefile or `make` in generated examples — use Taskfile/`task` if a task runner is needed - Suggest `reset_guard_marker` config — that's a workspace concern, not project setup @@ -137,12 +138,12 @@ Consolidate subagent findings into a structured profile: - Current git branch (for `base_branch` default) - Discovered workflow patterns from conversation history (if opted in) — recurring tool sequences and skill chains, ranked by frequency, with candidate recipe drafts -### Step 3: Write Analysis to .autoskillit/temp/ (relative to the current working directory) +### Step 3: Write Analysis to {{AUTOSKILLIT_TEMP}}/ (relative to the current working directory) Before presenting anything interactively, write the full analysis (project profile, workflow patterns, candidate workflows, shell command patterns) to: ``` -.autoskillit/temp/setup-project/analysis_{project_name}_{YYYY-MM-DD_HHMMSS}.md +{{AUTOSKILLIT_TEMP}}/setup-project/analysis_{project_name}_{YYYY-MM-DD_HHMMSS}.md ``` Tell the user: "Full analysis saved to {path} for your review." @@ -151,15 +152,9 @@ Tell the user: "Full analysis saved to {path} for your review." Interactive flow. For each candidate workflow discovered: -**CRITICAL:** Do NOT output any prose status text between workflow iterations. -After completing one workflow's presentation and user response, immediately -begin presenting the next workflow. - 1. **Always offer the standard implementation pipeline first** (plan → dry-walkthrough → implement → test → merge), even if not discovered in history. This is the core AutoSkillit workflow. 2. For each candidate workflow (including the standard one): - Do NOT output any prose status text between workflows — immediately begin the - next workflow's presentation after the user responds. - Present the workflow chain and explain what it automates - Ask the user: "Would you like me to generate a recipe for this workflow?" - Before generating, resolve skill references in the workflow: @@ -173,6 +168,7 @@ begin presenting the next workflow. List each conflicting skill name on its own line in the prompt. - Record the user's preferences and pass them as context to write-recipe - If yes: LOAD `/autoskillit:write-recipe` using the Skill tool to generate the script. The agent already has full context from the exploration phases (workflow name, detected variables like project_dir/work_dir/base_branch, tool call sequence, routing logic) — no explicit parameter passing is needed. write-recipe uses that context directly to produce a clean script. + - If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, proceed without recipe generation and prompt the user to create the recipe manually. - Explain what a recipe is (discovered via `list_recipes` MCP tool, loaded via `load_recipe`, the agent interprets the YAML and executes the steps), show the generated script content - Track the user's approval — do NOT write to disk yet - Move to the next candidate workflow @@ -253,7 +249,7 @@ Do NOT include: ## Output Artifacts created: -- `.autoskillit/temp/setup-project/analysis_{project_name}_{YYYY-MM-DD_HHMMSS}.md` — full analysis (always) +- `{{AUTOSKILLIT_TEMP}}/setup-project/analysis_{project_name}_{YYYY-MM-DD_HHMMSS}.md` — full analysis (always) - `.autoskillit/recipes/{name}.yaml` — approved recipes - `.autoskillit/config.yaml` — updated config (if changes approved) diff --git a/src/autoskillit/skills_extended/sprint-planner/SKILL.md b/src/autoskillit/skills_extended/sprint-planner/SKILL.md index 3f84da3aad..744e84e70b 100644 --- a/src/autoskillit/skills_extended/sprint-planner/SKILL.md +++ b/src/autoskillit/skills_extended/sprint-planner/SKILL.md @@ -25,7 +25,7 @@ an existing triage manifest. **NEVER:** - Implement any issues — this skill is planning only -- Create files outside `.autoskillit/temp/sprint-planner/` directory +- Create files outside `{{AUTOSKILLIT_TEMP}}/sprint-planner/` directory - Use native Claude Code tools (Read, Grep, Edit, Write, Bash) to modify the repo - Exceed the requested `sprint_size` when selecting issues diff --git a/src/autoskillit/skills_extended/stage-data/SKILL.md b/src/autoskillit/skills_extended/stage-data/SKILL.md new file mode 100644 index 0000000000..4549cb89bb --- /dev/null +++ b/src/autoskillit/skills_extended/stage-data/SKILL.md @@ -0,0 +1,178 @@ +--- +name: stage-data +categories: [research] +description: > + Pre-flight resource gate for the research recipe. Reads the experiment plan's + data_manifest, checks disk space and network connectivity for external/gitignored + entries, creates data directory structure, and emits a PASS/WARN/FAIL feasibility verdict. +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: stage-data] Checking resource feasibility...'" + once: true +--- + +# Stage Data Skill + +Pre-flight resource gate for the research recipe. Reads the experiment plan's +`data_manifest` frontmatter section, checks available disk space and network +connectivity for `external` and `gitignored` data source entries, creates the +required data directory structure in the worktree, and emits a PASS/WARN/FAIL +feasibility verdict. PASS and WARN proceed to implementation; FAIL escalates +immediately with a detailed resource feasibility report rather than wasting +compute on doomed downloads. + +## When to Use + +- Invoked by the research recipe's `stage_data` step between `create_worktree` + and `decompose_phases` +- Whenever a pre-flight resource check is needed before data-intensive implementation + +## Arguments + +``` +/autoskillit:stage-data +``` + +- `experiment_plan_path` — Absolute path to the experiment plan (positional). + Default: `$AUTOSKILLIT_TEMP/experiment-plan.md` in the current working directory. + +## Critical Constraints + +**NEVER:** +- Modify the experiment plan +- Modify any source files +- Write files outside `{{AUTOSKILLIT_TEMP}}/stage-data/` +- Emit a WARN or FAIL verdict without a specific, actionable explanation + +**ALWAYS:** +- Read the `data_manifest` frontmatter section of the experiment plan +- Check ONLY `external` and `gitignored` source_type entries (`synthetic` and + `fixture` entries require no disk space or network access) +- Create data directories for every entry whose `location` field is non-null, + using `mkdir -p` +- Write the resource feasibility report before emitting the verdict token +- Use `model: "sonnet"` for all subagents + +## Workflow + +### Step 1 — Parse the Experiment Plan + +Read the experiment plan at the provided path (or default path). Parse the +`data_manifest` YAML frontmatter section. Identify all entries where +`source_type` is `"external"` or `"gitignored"`. + +### Step 2 — Short-Circuit for Synthetic/Fixture-Only Plans + +If no `external` or `gitignored` entries exist, skip disk and network checks. +Create any data directories for entries with non-null `location`. Emit +`verdict = PASS` and exit. + +### Step 3 — Launch Parallel Resource Probe Subagents + +Launch parallel subagents — one per `external`/`gitignored` entry — each +performing: + +**a. DISK SPACE AGENT:** Run `df -k .` to get available bytes in the worktree. +Estimate storage need from the entry's `description` field using LLM reasoning +(e.g., "10-50GB h5ad files" → project 50GB worst case). Compute headroom: + +If `available_bytes == 0` (filesystem completely full), emit **FAIL** immediately — +do not proceed to the formula below. + +``` +headroom_pct = (available_bytes - projected_bytes) / available_bytes * 100 +``` + +Disk space verdict thresholds: +- **FAIL**: `projected_bytes > available_bytes` (negative headroom) +- **WARN**: `0 < headroom_pct < 20` (less than 20% remaining) +- **PASS**: `headroom_pct >= 20` + +**b. NETWORK PROBE AGENT:** Infer the API base URL from the `acquisition` +field. Known endpoints to probe: +- GEO / NCBI: `https://eutils.ncbi.nlm.nih.gov/entrez/eutils/einfo.fcgi` +- ENCODE: `https://www.encodeproject.org/` +- UniProt: `https://rest.uniprot.org/uniprotkb/search?query=reviewed:true&size=1` +- For unrecognized sources: attempt a HEAD request to any URL found in + the `acquisition` field. + +Run: `curl -sI --max-time 10 ` and inspect HTTP status: +- **FAIL**: connection refused, timeout, or 5xx response +- **WARN**: 4xx response (auth required but endpoint reachable) +- **PASS**: 2xx or 3xx response + +Network connectivity check: the WARN condition indicates the endpoint is +reachable but authentication may be needed. A network reachability issue +produces FAIL. + +### Step 4 — Create Data Directory Structure + +For every entry whose `location` field is non-null, run: + +```bash +mkdir -p / +``` + +This creates the data dir hierarchy required by the experiment implementation. + +### Step 5 — Synthesize Overall Verdict + +Aggregate results across all entries: +- **FAIL** if ANY entry produced a FAIL result (disk or network) +- **WARN** if any entry produced a WARN result and none produced FAIL +- **PASS** if all entries produced PASS + +### Step 6 — Write Resource Feasibility Report + +Write the resource feasibility report to: + +``` +{{AUTOSKILLIT_TEMP}}/stage-data/resource_feasibility_{YYYY-MM-DD_HHMMSS}.md +``` + +Report structure: + +```markdown +## Resource Feasibility Report +**Date:** {timestamp} +**Verdict:** PASS | WARN | FAIL + +### Disk Space Assessment +| Entry | Source Type | Projected Size | Available | Headroom | Status | +|-------|-------------|----------------|-----------|----------|--------| +... + +### Network Connectivity Assessment +| Entry | Endpoint Probed | HTTP Status | Latency | Status | +|-------|-----------------|-------------|---------|--------| +... + +### Data Directories Created +- {location}: created | skipped (null location) +... + +### Recommended Actions (WARN/FAIL only) +- {specific actionable step to resolve each issue} +``` + +### Step 7 — Emit Structured Output Tokens + +Emit structured output tokens as LITERAL PLAIN TEXT with NO markdown +formatting on the token names. Do not wrap token names in `**bold**`, +`*italic*`, or any other markdown. The adjudicator performs a regex match +on the exact token name — decorators cause match failure. + +``` +verdict = PASS +resource_report = /absolute/path/to/resource_feasibility_{YYYY-MM-DD_HHMMSS}.md +``` + +## Output + +``` +verdict = PASS|WARN|FAIL +resource_report = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/stage-data/resource_feasibility_{YYYY-MM-DD_HHMMSS}.md +``` diff --git a/src/autoskillit/skills_extended/triage-issues/SKILL.md b/src/autoskillit/skills_extended/triage-issues/SKILL.md index 08c014dc19..afec05a475 100644 --- a/src/autoskillit/skills_extended/triage-issues/SKILL.md +++ b/src/autoskillit/skills_extended/triage-issues/SKILL.md @@ -31,12 +31,14 @@ Analyze open GitHub issues, classify each into a recipe route, group them into p - Apply GitHub labels when `--no-label` is passed - Skip human escalation for ambiguous issues - Add useless comments to the codebase — do not use the codebase as a notepad -- Create files outside `.autoskillit/temp/triage-issues/` directory +- Create files outside `{{AUTOSKILLIT_TEMP}}/triage-issues/` directory +- Use `--body` shell substitution (`--body "$(...)`) for `gh issue edit` — always write to + `{{AUTOSKILLIT_TEMP}}/triage-issues/edit_body_{timestamp}.md` and use `--body-file` **ALWAYS:** - Use `model: "sonnet"` when spawning all subagents via the Task tool - Pause for human input on ambiguous classifications -- Write the triage report and manifest to `.autoskillit/temp/triage-issues/` (relative to the current working directory) +- Write the triage report and manifest to `{{AUTOSKILLIT_TEMP}}/triage-issues/` (relative to the current working directory) - Use `gh` CLI for all GitHub operations (not raw API calls) - Include rationale for every recipe classification - Record human decisions in the final report @@ -225,14 +227,19 @@ For each issue in the working set classified as `recipe:implementation`: per issue but skip `gh issue edit`. Record `requirements_generated: true` in manifest. 5. Otherwise, append via: ```bash - gh issue edit {N} --body "$(gh issue view {N} --json body -q .body) + ts=$(date +%Y-%m-%d_%H%M%S) + EDIT_BODY_FILE="{{AUTOSKILLIT_TEMP}}/triage-issues/edit_body_${ts}.md" + REQUIREMENTS_FILE="{{AUTOSKILLIT_TEMP}}/triage-issues/requirements_${ts}.md" + mkdir -p "{{AUTOSKILLIT_TEMP}}/triage-issues" -## Requirements + # Fetch current body to temp file (avoids shell interpolation): + gh issue view {N} --json body -q .body > "${EDIT_BODY_FILE}" -### {Group Name} + # Populate ${REQUIREMENTS_FILE} with the generated requirements content, then: + printf '\n\n## Requirements\n\n' >> "${EDIT_BODY_FILE}" + cat "${REQUIREMENTS_FILE}" >> "${EDIT_BODY_FILE}" -- **REQ-{GRP}-001:** ... -..." + gh issue edit {N} --body-file "${EDIT_BODY_FILE}" ``` 6. If the issue is too vague for clean extraction: skip silently and record `requirements_generated: false` in the manifest for that issue. @@ -271,9 +278,9 @@ Order the batches for sequential execution: ### Step 7: Write Outputs Compute timestamp: `YYYY-MM-DD_HHMMSS`. -Ensure `.autoskillit/temp/triage-issues/` exists. +Ensure `{{AUTOSKILLIT_TEMP}}/triage-issues/` exists. -**7a. Triage report:** `.autoskillit/temp/triage-issues/triage_report_{ts}.md` +**7a. Triage report:** `{{AUTOSKILLIT_TEMP}}/triage-issues/triage_report_{ts}.md` The report contains: - Ordered list of batches with issues, recipe assignments, and rationale @@ -281,7 +288,7 @@ The report contains: - Summary statistics (total issues, batch count, recipe distribution) - Human decisions section (which issues were escalated, what was decided) -**7b. Machine-readable manifest:** `.autoskillit/temp/triage-issues/triage_manifest_{ts}.json` +**7b. Machine-readable manifest:** `{{AUTOSKILLIT_TEMP}}/triage-issues/triage_manifest_{ts}.json` ```json { @@ -334,7 +341,7 @@ gh issue edit {number} --add-label "recipe:{recipe}" ## Output Location ``` -.autoskillit/temp/triage-issues/ +{{AUTOSKILLIT_TEMP}}/triage-issues/ triage_report_{ts}.md # Human-readable triage report triage_manifest_{ts}.json # Machine-readable manifest for downstream pipelines ``` @@ -363,8 +370,8 @@ These emit lines are consumed by `capture:` in orchestrating recipes. The Example emit block: ``` -triage_report = .autoskillit/temp/triage-issues/triage_report_20260310_120000.md -triage_manifest = .autoskillit/temp/triage-issues/triage_manifest_20260310_120000.json +triage_report = {{AUTOSKILLIT_TEMP}}/triage-issues/triage_report_20260310_120000.md +triage_manifest = {{AUTOSKILLIT_TEMP}}/triage-issues/triage_manifest_20260310_120000.json total_issues = 12 batch_count = 3 recipe_distribution = {"implementation": 8, "remediation": 4} diff --git a/src/autoskillit/skills_extended/troubleshoot-experiment/SKILL.md b/src/autoskillit/skills_extended/troubleshoot-experiment/SKILL.md new file mode 100644 index 0000000000..2efccd15bc --- /dev/null +++ b/src/autoskillit/skills_extended/troubleshoot-experiment/SKILL.md @@ -0,0 +1,167 @@ +--- +name: troubleshoot-experiment +categories: [research] +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo '[SKILL: troubleshoot-experiment] Diagnosing experiment failure...'" + once: true +--- + +# troubleshoot-experiment Skill + +Read session logs and process traces for a failed research pipeline step, classify +why it failed, write a structured diagnosis artifact, and emit `is_fixable` signal +for orchestrator routing. + +Called by the `research` recipe on `implement_phase` failure before routing to +`plan_phase` (fixable) or `escalate_stop` (not fixable). + +## Invocation + +``` +/autoskillit:troubleshoot-experiment {worktree_path} {step_name} +``` + +**Positional args:** +- `{worktree_path}` — absolute path to the worktree where execution failed +- `{step_name}` — name of the failed pipeline step (e.g. `implement_phase`) + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Run tests +- Write files outside `{{AUTOSKILLIT_TEMP}}/troubleshoot-experiment/` +- Abort when session data is missing — emit `failure_type=unknown`, `is_fixable=false` and exit cleanly + +**ALWAYS:** +- Initialize code-index before any search +- Write the diagnosis file before emitting output tokens +- Emit the three output tokens (`diagnosis_path`, `failure_type`, `is_fixable`) at the end + +## Workflow + +### Step 1: Initialize Code Index + +``` +mcp__code-index__set_project_path(path="{worktree_path}") +``` + +### Step 2: Locate the Most Recent Failed Session for this Worktree + +Query the global session index: +```bash +jq -r 'select(.success == false)' \ + ~/.local/share/autoskillit/logs/sessions.jsonl \ + | jq -r --arg worktree_path "{worktree_path}" 'select(.cwd // "" | startswith($worktree_path))' \ + | tail -n 1 +``` + +If the `cwd` field is absent from matching records, fall back to the most recent +`success=false` entry regardless of `cwd`. Extract `session_id` from the record. + +If `sessions.jsonl` does not exist or no matching session is found, proceed to +Step 5 with a minimal diagnosis noting the log lookup failure. Never abort. + +### Step 3: Read Session Diagnostics + +From `~/.local/share/autoskillit/logs/sessions/{session_id}/`: + +- `summary.json` — identity fields: `termination_reason`, `write_call_count`, + `exit_code`, `anomaly_count`, `peak_rss_kb`, `elapsed_seconds` +- `anomalies.jsonl` — structured anomaly records (one per line): `kind`, + `severity`, `detail` + +Also read from `{worktree_path}/{{AUTOSKILLIT_TEMP}}/run-experiment/` any +`results_*.md` files (if the failed step was `run_experiment` and produced +partial results). + +If `summary.json` is not found, emit `failure_type=unknown`, `is_fixable=false` +and proceed to Step 5. + +### Step 4: Classify Failure Type + +Apply this decision table in priority order (stop at the first match): + +| Priority | Condition | `failure_type` | `is_fixable` | +|----------|-----------|----------------|--------------| +| 1 | `termination_reason == "context_limit"` | `context_exhaustion` | `true` | +| 2 | `termination_reason == "stale"` | `stale_timeout` | `true` | +| 3 | `exit_code != 0` AND logs contain build/compile error keywords (`SyntaxError`, `ModuleNotFoundError`, `ImportError`, `error: command`) | `build_failure` | `true` | +| 4 | `step_name == "run_experiment"` AND (`blocked_hypotheses` token present in run-experiment results OR results file contains `## Status: FAILED` with data acquisition errors) | `data_missing` | `true` | +| 5 | Logs contain environment/infra keywords (`Permission denied`, `No such file or directory` for system paths, `Connection refused`) | `environment_error` | `false` | +| 6 | `anomaly_count > 0` AND any anomaly `kind` in `["oom_critical", "zombie_persistent"]` | `environment_error` | `false` | +| 7 | All other cases | `unknown` | `false` | + +### Step 5: Write Diagnosis Report + +Create directory `{{AUTOSKILLIT_TEMP}}/troubleshoot-experiment/` if it does not exist. +Write the diagnosis file to: + +`{{AUTOSKILLIT_TEMP}}/troubleshoot-experiment/diagnosis_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) + +```markdown +# Experiment Failure Diagnosis + +## Context +- Step: {step_name} +- Worktree: {worktree_path} +- Session ID: {session_id} +- Diagnosis Time: {timestamp} + +## Failure Classification +- **failure_type:** {type} +- **is_fixable:** {true|false} + +## Evidence +- termination_reason: {value} +- write_call_count: {value} +- exit_code: {value} +- anomaly_count: {value} +- elapsed_seconds: {value} + +## Anomalies Detected +{list anomalies from anomalies.jsonl, or "none"} + +## Recommended Action +{One paragraph describing what likely happened and what the orchestrator should do next: + +- stale_timeout: "The agent was idle while a background task ran. Re-attempt the phase + with a revised plan scope or split long-running operations into separate steps." +- context_exhaustion: "The session hit the context limit mid-implementation. Retry + the phase — the committed artifacts remain intact." +- build_failure: "A code build or import error prevented completion. The next phase + attempt should focus on resolving the identified error." +- data_missing: "Required experiment data was not available. Adjust experiment + parameters or data acquisition strategy." +- environment_error/unknown: "Automated remediation is not feasible. Human review + of the session log is required."} +``` + +### Step 6: Emit Structured Output Tokens + +Emit these tokens on their own lines at the end of the response as literal plain text +with no markdown formatting on the token names. The adjudicator performs a regex match +on the exact token name — decorators cause match failure. + +``` +diagnosis_path = {absolute_path_to_report} +failure_type = {stale_timeout|context_exhaustion|build_failure|data_missing|environment_error|unknown} +is_fixable = {true|false} +``` + +## Graceful Degradation + +If at any point session data is unavailable (missing `sessions.jsonl`, no matching +session, missing `summary.json`): +- Set `failure_type = unknown` +- Set `is_fixable = false` +- Write a minimal diagnosis noting the specific lookup failure +- Emit output tokens and exit cleanly — never abort + +## gh Unavailable Fallback + +This skill does not require `gh`. It reads only local session log files. diff --git a/src/autoskillit/skills_extended/validate-audit/SKILL.md b/src/autoskillit/skills_extended/validate-audit/SKILL.md index 6ea6ff3b51..72ea20a3da 100644 --- a/src/autoskillit/skills_extended/validate-audit/SKILL.md +++ b/src/autoskillit/skills_extended/validate-audit/SKILL.md @@ -31,8 +31,8 @@ signal downstream processing. - `audit_report_path` — absolute path to an audit report produced by `audit-arch`, `audit-tests`, or `audit-cohesion`. If omitted, use the most recent file under - `.autoskillit/temp/audit-arch/`, `.autoskillit/temp/audit-tests/`, or - `.autoskillit/temp/audit-cohesion/` (most recent mtime wins across all three). + `{{AUTOSKILLIT_TEMP}}/audit-arch/`, `{{AUTOSKILLIT_TEMP}}/audit-tests/`, or + `{{AUTOSKILLIT_TEMP}}/audit-cohesion/` (most recent mtime wins across all three). If no files exist under any of these directories, print an error message and exit with a non-zero status. @@ -40,7 +40,7 @@ signal downstream processing. **NEVER:** - Modify any source code files -- Create files outside `.autoskillit/temp/validate-audit/` +- Create files outside `{{AUTOSKILLIT_TEMP}}/validate-audit/` - Issue subagent Task calls sequentially — ALL must be in a single parallel message - Write output files before synthesizing ALL subagent results - Subagents must NOT create their own files — they return findings in response text only @@ -111,7 +111,7 @@ by the top-level package touched (e.g., `pipeline/`, `execution/`, `server/`, `c ### Step 3 — Launch Parallel Subagents (SINGLE MESSAGE) -**Issue ALL Task calls in a single message.** Do not output any prose between tool calls. +**Issue ALL Task calls in a single message.** Spawn the following agents simultaneously using `model: "sonnet"`: @@ -177,10 +177,10 @@ After all agents return: ### Step 5 — Generate Output Files -Ensure `.autoskillit/temp/validate-audit/` exists (`mkdir -p`). +Ensure `{{AUTOSKILLIT_TEMP}}/validate-audit/` exists (`mkdir -p`). **File 1 — Validated report** -Path: `.autoskillit/temp/validate-audit/validated_report_{source}_{YYYY-MM-DD_HHMMSS}.md` +Path: `{{AUTOSKILLIT_TEMP}}/validate-audit/validated_report_{source}_{YYYY-MM-DD_HHMMSS}.md` Structure: @@ -216,7 +216,7 @@ validated: true ``` **File 2 — Contested findings** (write only when `N_contested > 0`) -Path: `.autoskillit/temp/validate-audit/contested_findings_{source}_{YYYY-MM-DD_HHMMSS}.md` +Path: `{{AUTOSKILLIT_TEMP}}/validate-audit/contested_findings_{source}_{YYYY-MM-DD_HHMMSS}.md` Structure: @@ -243,8 +243,8 @@ headless. ``` [validate-audit] Done. Valid: {N_valid} | Exceptions: {N_exception} | Contested: {N_contested} - Report: .autoskillit/temp/validate-audit/validated_report_{source}_{ts}.md - Contested: .autoskillit/temp/validate-audit/contested_findings_{source}_{ts}.md + Report: {{AUTOSKILLIT_TEMP}}/validate-audit/validated_report_{source}_{ts}.md + Contested: {{AUTOSKILLIT_TEMP}}/validate-audit/contested_findings_{source}_{ts}.md ``` (Omit the "Contested:" line if `N_contested == 0`.) @@ -264,7 +264,7 @@ If the user confirms, pass the contested findings file path to `prepare-issue`. ## Output Location ``` -.autoskillit/temp/validate-audit/ +{{AUTOSKILLIT_TEMP}}/validate-audit/ ├── validated_report_{source}_{YYYY-MM-DD_HHMMSS}.md (always written) └── contested_findings_{source}_{YYYY-MM-DD_HHMMSS}.md (when N_contested > 0) ``` diff --git a/src/autoskillit/skills_extended/verify-diag/SKILL.md b/src/autoskillit/skills_extended/verify-diag/SKILL.md index 95f514dad5..211e5b65f9 100644 --- a/src/autoskillit/skills_extended/verify-diag/SKILL.md +++ b/src/autoskillit/skills_extended/verify-diag/SKILL.md @@ -71,6 +71,7 @@ For each ```` ```mermaid ```` block, validate: **6. Class definition syntax:** - `classDef` lines must end with semicolons only if using shorthand - `class A,B,C className;` — verify referenced node IDs exist in the diagram +- Using ONLY classDef styles from the mermaid skill (no invented colors) — flag any non-canonical class names **7. Node ID rules:** - Node IDs must not start with numbers diff --git a/src/autoskillit/skills_extended/vis-lens-always-on/SKILL.md b/src/autoskillit/skills_extended/vis-lens-always-on/SKILL.md new file mode 100644 index 0000000000..d524a5f921 --- /dev/null +++ b/src/autoskillit/skills_extended/vis-lens-always-on/SKILL.md @@ -0,0 +1,270 @@ +--- +name: vis-lens-always-on +categories: [vis-lens] +activate_deps: [mermaid] +description: "Create Always-On visualization triage report running three sequential analysis passes (anti-pattern, accessibility, annotation completeness) and emitting a combined PASS|WARN_N|FAIL_N verdict. Composite lens answering \"What are the blocking visualization issues?\"" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Always-On Lens - Running combined triage passes...'" + once: true +--- + +# Always-On Visualization Triage Lens + +**Philosophical Mode:** Composite +**Primary Question:** "What are the blocking visualization issues?" +**Focus:** Anti-Pattern Detection, Accessibility, Annotation Completeness — combined triage + +## Arguments + +`/autoskillit:vis-lens-always-on [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Fast triage before any figure review or submission — run this first +- Lightweight check when you do not need the full depth of individual lenses +- CI-style gate: FAIL_N blocks, WARN_N is informational, PASS is green +- Quick scan of a figure plan to surface the most important blocking issues +- User invokes `/autoskillit:vis-lens-always-on` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/vis-lens-always-on/` +- Emit PASS if any critical finding exists — any single critical = FAIL_N + +**ALWAYS:** +- Run all three passes in sequence; do not skip any pass +- Tally critical_count and warning_count across all three passes +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/vis-lens-always-on/vis_spec_always_on_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/vis-lens-always-on/vis_spec_always_on_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for all three passes; skip the +CWD exploration for these fields if the context file supplies them. + +### Step 1: Inventory All Figures + +Before running passes, build a complete figure inventory from the experiment plan, context +file, code, and any existing output files. Every figure in this inventory is checked in +all three passes. + +### Step 2: Run THREE Sequential Passes + +#### Pass 1 — Anti-Pattern Scan + +Check all figures against the 16 anti-patterns from `vis-lens-antipattern`: + +| ID | Severity | +|----|----------| +| ap-3d-bar | critical | +| ap-dual-axis | critical | +| ap-rainbow | critical | +| ap-single-seed | critical | +| ap-truncated-bar | critical | +| ap-spider-radar | warning | +| ap-spaghetti | warning | +| ap-bar-no-error | warning | +| ap-smoothed-hidden | warning | +| ap-violin-small-n | warning | +| ap-cherry-baseline | warning | +| ap-overplotting | warning | +| ap-tsne-distance | warning | +| ap-tsne-no-perplexity | warning | +| ap-embedding-single-seed | warning | +| ap-area-encoding | info (counts as 0 in tally) | + +Tally: `pass1_critical_count`, `pass1_warning_count` + +#### Pass 2 — Accessibility Scan + +For each figure, check all four accessibility criteria: + +1. **colorblind_safe** — palette is wong, okabe-ito, viridis, or cividis? (PASS) or jet/rainbow/custom? (FAIL → warning) +2. **font_size_ok** — all axis labels, tick labels, legends ≥ 8pt? Check `fontsize` args in code or figure config. (PASS if ≥ 8pt or undetectable; FAIL → warning) +3. **no_color_only_encoding** — distinction between groups uses shape, pattern, or label in addition to color? Color-only encoding for distinction = FAIL → warning +4. **captions_present** — figure has alt-text, caption, or description in the paper/plan? No caption = FAIL → warning + +Tally: count failures as `pass2_warning_count` (accessibility failures are warnings, not critical) + +#### Pass 3 — Annotation Completeness + +For each figure, check all five annotation criteria: + +1. **all_titles** — every figure has a title or caption title? Missing = warning +2. **axis_labels** — both axes labeled with variable name and units? Missing = warning +3. **legends_ok** — multi-series figures have a legend? Missing = warning +4. **stat_overlay_labeled** — if an uncertainty overlay exists, is it labeled (e.g., "± CI95, n=5")? Unlabeled overlay = warning +5. **data_pointer** — figure has a data source reference or code pointer in caption? Missing = info (not counted in tally) + +Tally: count failures as `pass3_warning_count` + +### Step 3: Compute Combined Verdict + +``` +critical_count = pass1_critical_count +warning_count = pass1_warning_count + pass2_warning_count + pass3_warning_count + +if critical_count > 0: + verdict = f"FAIL_{critical_count}" +elif warning_count > 0: + verdict = f"WARN_{warning_count}" +else: + verdict = "PASS" +``` + +### Step 4: Emit yaml:spec-index Block and Mermaid Diagram + +Emit the `yaml:spec-index` triage index (NOT yaml:figure-spec — this is a triage summary, +not a per-figure spec). Then LOAD `/autoskillit:mermaid` and create the triage diagram. + +--- + +## Output Template + +```markdown +# Always-On Triage Report: {System / Experiment Name} + +**Lens:** Always-On Triage (Composite) +**Question:** What are the blocking visualization issues? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Triage Index + +```yaml +# yaml:spec-index — Always-On triage index +verdict: "FAIL_3" # PASS | WARN_N | FAIL_N +critical_count: 3 +warning_count: 5 +pass_1_antipattern: ["ap-single-seed", "ap-rainbow", "ap-dual-axis"] +pass_2_accessibility: + colorblind_safe: true + font_size_ok: false + no_color_only_encoding: true + captions_present: false +pass_3_annotation: + all_titles: true + axis_labels: false + legends_ok: true + stat_overlay_labeled: false + data_pointer: true +figures_with_critical: ["fig-01-main-results", "fig-03-ablation"] +``` + +## Pass Results + +### Pass 1 — Anti-Pattern Scan + +| Figure | Anti-Patterns Found | Severity | +|--------|---------------------|----------| +| {fig-01} | ap-single-seed, ap-rainbow | critical, critical | +| {fig-03} | ap-dual-axis | critical | +| {fig-02} | ap-bar-no-error | warning | + +### Pass 2 — Accessibility Scan + +| Check | Result | Notes | +|-------|--------|-------| +| colorblind_safe | PASS | wong palette used throughout | +| font_size_ok | FAIL | fig-02 axis labels at 6pt | +| no_color_only_encoding | PASS | shapes used alongside color | +| captions_present | FAIL | fig-01, fig-03 missing captions | + +### Pass 3 — Annotation Completeness + +| Check | Result | Notes | +|-------|--------|-------| +| all_titles | PASS | all figures have titles | +| axis_labels | FAIL | fig-02 y-axis missing units | +| legends_ok | PASS | all multi-series figures have legends | +| stat_overlay_labeled | FAIL | fig-01 error bars unlabeled | +| data_pointer | PASS | all figures reference source | + +## Triage Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000; + + subgraph Pass1 ["PASS 1: ANTI-PATTERN"] + P1["{N} critical
    ━━━━━━━━━━
    {ap-ids found}"] + end + + subgraph Pass2 ["PASS 2: ACCESSIBILITY"] + P2["{N} warnings
    ━━━━━━━━━━
    {failed checks}"] + end + + subgraph Pass3 ["PASS 3: ANNOTATION"] + P3["{N} warnings
    ━━━━━━━━━━
    {failed checks}"] + end + + VERDICT["{FAIL_3 / WARN_5 / PASS}
    ━━━━━━━━━━
    critical={N}, warning={M}"] + + P1 --> VERDICT + P2 --> VERDICT + P3 --> VERDICT + + class P1 detector; + class P2 gap; + class P3 handler; + class VERDICT cli; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Red | Pass 1 Critical | Anti-pattern findings (critical) | +| Amber | Pass 2 Warnings | Accessibility failures | +| Orange | Pass 3 Warnings | Annotation completeness failures | +| Dark Blue | Verdict | Combined PASS/WARN_N/FAIL_N | +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table +- [ ] All three passes completed before computing verdict +- [ ] yaml:spec-index emitted (not yaml:figure-spec) +- [ ] verdict is FAIL_N if critical_count > 0, WARN_N if warning_count > 0, PASS otherwise diff --git a/src/autoskillit/skills_extended/vis-lens-antipattern/SKILL.md b/src/autoskillit/skills_extended/vis-lens-antipattern/SKILL.md new file mode 100644 index 0000000000..7214269129 --- /dev/null +++ b/src/autoskillit/skills_extended/vis-lens-antipattern/SKILL.md @@ -0,0 +1,274 @@ +--- +name: vis-lens-antipattern +categories: [vis-lens] +activate_deps: [mermaid] +description: "Create Anti-Pattern Detection visualization audit showing severity-tiered catalog of visualization anti-patterns present in or planned for the experiment. Diagnostic lens answering \"Which visualization anti-patterns are present?\"" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Anti-Pattern Lens - Scanning for visualization anti-patterns...'" + once: true +--- + +# Anti-Pattern Detection Visualization Lens + +**Philosophical Mode:** Diagnostic +**Primary Question:** "Which visualization anti-patterns are present?" +**Focus:** Severity-Tiered Anti-Pattern Catalog, Evidence-Backed Findings, Remediation Guidance + +## Arguments + +`/autoskillit:vis-lens-antipattern [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Reviewing a figure plan or existing figures for visualization quality issues +- Pre-submission audit of all planned and existing figures +- Checking whether a specific anti-pattern (e.g., single random seed) is present +- Diagnosing why a reviewer rejected or criticized figure choices +- User invokes `/autoskillit:vis-lens-antipattern` + +## Anti-Pattern Catalog + +| ID | Name | Severity | Description | Remediation | +|----|------|----------|-------------|-------------| +| ap-3d-bar | 3D Bar Chart | critical | Occlusion + perspective distortion destroy comparability | Use 2D grouped bar | +| ap-dual-axis | Dual Y-Axis | critical | Two unrelated scales on one chart implies false correlation | Use two separate panels | +| ap-rainbow | Rainbow Colormap | critical | Rainbow has non-monotone luminance; perceptually misleading | Use viridis/cividis/wong | +| ap-single-seed | Single Random Seed | critical | Variance unquantifiable; results may not replicate | Report results across ≥3 seeds | +| ap-truncated-bar | Truncated Bar Y-axis | critical | Non-zero baseline exaggerates differences | Start Y-axis at zero for bars | +| ap-spider-radar | Spider/Radar Chart | warning | Area distorted by axis ordering; angle hard to compare | Use parallel coordinates or bar | +| ap-spaghetti | Spaghetti Line Plot | warning | ≥5 overlapping lines unreadable | Highlight key lines; small multiples | +| ap-bar-no-error | Bar without Error | warning | Mean shown without any uncertainty estimate | Add SE/CI bars or use box/violin | +| ap-smoothed-hidden | Smoothed Line Hiding Raw | warning | Smoothing hides variance structure | Show raw data or rug alongside | +| ap-violin-small-n | Violin with n<10 | warning | KDE shape unreliable at tiny n | Use strip plot or box | +| ap-cherry-baseline | Cherry-picked Baseline | warning | Baseline chosen to maximize apparent improvement | Report against strongest published baseline | +| ap-overplotting | Overplotting | warning | Dense scatter obscures distribution | Use alpha, jitter, hex-bin, or 2D KDE | +| ap-tsne-distance | t-SNE Distance Interpretation | warning | t-SNE distances not meaningful between clusters | Do not interpret inter-cluster distance | +| ap-tsne-no-perplexity | t-SNE Without Perplexity | warning | t-SNE layout varies with perplexity; single plot misleading | Show multiple perplexity values | +| ap-embedding-single-seed | Embedding with Single Random Init | warning | Random init produces different layouts; one layout misleads | Average across runs or show multiple | +| ap-area-encoding | Area Encoding for Data Values | info | Human perception of area is poor (Stevens power ~0.7) | Prefer length or position encoding | + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/vis-lens-antipattern/` +- Skip checking figures that appear only in planning documents — anti-patterns in planned figures must be caught before implementation + +**ALWAYS:** +- Check every identified figure against ALL 16 anti-patterns in the catalog +- Sort findings critical-first, then warning, then info +- Populate the `anti_patterns` field in each yaml:figure-spec with the IDs of matched patterns +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/vis-lens-antipattern/vis_spec_antipattern_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/vis-lens-antipattern/vis_spec_antipattern_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1–4; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Scan for Chart Type and Visualization Clues + +Scan experiment plan, context file, and codebase for evidence of chart type choices: + +**Code Patterns** +- Look for: `plot3D`, `bar3d`, `Axes3D` → ap-3d-bar +- Look for: `twinx`, `twin_y`, `secondary_y` → ap-dual-axis +- Look for: `cmap='jet'`, `cmap='rainbow'`, `cmap='hsv'` → ap-rainbow +- Look for: `seed =`, `np.random.seed`, `torch.manual_seed` (single occurrence) → ap-single-seed +- Look for: `ylim(0.9`, `ylim(0.8`, non-zero bottom on bar axes → ap-truncated-bar +- Look for: `radar`, `spider`, `polar` plot → ap-spider-radar +- Look for: `n_lines >= 5`, many `ax.plot` calls in same axes → ap-spaghetti +- Look for: `ax.bar` without `yerr` or `ax.errorbar` → ap-bar-no-error +- Look for: `smooth`, `rolling`, `savgol_filter`, `gaussian_filter` on line data → ap-smoothed-hidden +- Look for: `violinplot` with n < 10 samples → ap-violin-small-n +- Look for: `TSNE`, `t-SNE`, `tsne` → ap-tsne-distance, ap-tsne-no-perplexity +- Look for: `UMAP`, `umap`, `PCA` single embedding → ap-embedding-single-seed +- Look for: `plt.scatter` with `s=` encoding data values → ap-area-encoding + +**Planning Document Patterns** +- Look for descriptions like "3D bar", "dual axis", "radar chart", "single run" +- Look for baseline selection that seems hand-picked or unpublished + +### Step 2: Check Each Figure Against All Anti-Patterns + +For each figure identified, create a finding record: + +``` +Figure: {figure_id} +Anti-patterns checked: all 16 +Matches found: + - {ap-id}: {evidence excerpt} → {severity} + - {ap-id}: {evidence excerpt} → {severity} +Clean: [{ap-ids not found}] +``` + +### Step 3: Build Severity-Sorted Finding List + +Aggregate all findings and sort: +1. **critical** — must fix before submission +2. **warning** — should fix; reviewer will notice +3. **info** — consider fixing; minor perceptual improvement + +For each critical finding, produce a one-line remediation instruction. + +### Step 4: Emit yaml:figure-spec Blocks and Mermaid Diagram + +For each figure, emit one `yaml:figure-spec` fenced block with `anti_patterns` field populated +with matched ap-* IDs. Then LOAD `/autoskillit:mermaid` and create the severity-bucketed diagram. + +--- + +## Output Template + +```markdown +# Anti-Pattern Detection Spec: {System / Experiment Name} + +**Lens:** Anti-Pattern Detection (Diagnostic) +**Question:** Which visualization anti-patterns are present? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Findings Summary + +| Severity | Count | Anti-Pattern IDs | +|----------|-------|-----------------| +| critical | {N} | {ap-ids} | +| warning | {N} | {ap-ids} | +| info | {N} | {ap-ids} | + +## Detailed Findings + +### CRITICAL: {ap-id} — {Name} + +**Figure:** {figure_id} +**Evidence:** {code or planning doc excerpt} +**Remediation:** {one-line fix} + +--- + +## Figure Specs + +```yaml +# yaml:figure-spec — canonical schema (spec_version: "1.0") +figure_id: "fig-01-main-results" +figure_title: "Main Results" +spec_version: "1.0" +chart_type: "grouped-bar" +chart_type_fallback: "dot-plot" +perceptual_justification: "Position encoding; anti-patterns ap-3d-bar and ap-bar-no-error actively avoided." +data_source: "results/main.csv" +data_mapping: + x: "method" + y: "score" + color: "dataset" + size: "" + facet: "" +layout: + width_inches: 6.5 + height_inches: 4.0 + dpi: 300 +stat_overlay: + type: "error_bar" + measure: "CI95" + n_seeds: 5 +annotations: [] +anti_patterns: ["ap-bar-no-error"] +palette: "wong" +format: "pdf" +target_dpi: 300 +library: "matplotlib" +report_section: "Section 4" +priority: "P0" +placement_tier: "main" +conflicts: [] +metadata: + created_by: "vis-lens-antipattern" + reviewed_by: "" + last_updated: "{YYYY-MM-DD}" +``` + +## Anti-Pattern Severity Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000; + + subgraph Critical ["CRITICAL FINDINGS"] + C1["{ap-id}
    ━━━━━━━━━━
    {figure_id}"] + end + + subgraph Warning ["WARNING FINDINGS"] + W1["{ap-id}
    ━━━━━━━━━━
    {figure_id}"] + end + + subgraph Info ["INFO FINDINGS"] + I1["{ap-id}
    ━━━━━━━━━━
    {figure_id}"] + end + + VERDICT["{Total: N critical, M warning}
    ━━━━━━━━━━
    {overall assessment}"] + + C1 --> VERDICT + W1 --> VERDICT + I1 --> VERDICT + + class C1 detector; + class W1 gap; + class I1 handler; + class VERDICT cli; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Red | Critical | Must fix before submission | +| Amber | Warning | Should fix; reviewer will notice | +| Orange | Info | Consider fixing; minor improvement | +| Dark Blue | Verdict | Aggregate severity assessment | +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table +- [ ] All 16 anti-patterns were checked for each figure +- [ ] Findings are sorted critical-first +- [ ] Each yaml:figure-spec has `anti_patterns` field populated diff --git a/src/autoskillit/skills_extended/vis-lens-caption-annot/SKILL.md b/src/autoskillit/skills_extended/vis-lens-caption-annot/SKILL.md new file mode 100644 index 0000000000..db859919a5 --- /dev/null +++ b/src/autoskillit/skills_extended/vis-lens-caption-annot/SKILL.md @@ -0,0 +1,242 @@ +--- +name: vis-lens-caption-annot +categories: [vis-lens] +activate_deps: [mermaid] +description: "Create Annotative Caption visualization planning spec showing declarative titles, axis labels with units, error definition in legend, baseline references, sample sizes, and venue-specific caption format. Annotative lens answering \"Are figure captions and axis labels fully self-contained?\"" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Caption Annotation Lens - Auditing caption completeness...'" + once: true +--- + +# Annotative Caption Visualization Lens + +**Philosophical Mode:** Annotative +**Primary Question:** "Are figure captions and axis labels fully self-contained?" +**Focus:** Declarative titles (state the result, not "Figure N: Results"), axis labels with + units, error definition in legend (CI95 / std / SEM), baseline references cited in + caption, sample sizes disclosed per condition, venue-specific caption format + +## Arguments + +`/autoskillit:vis-lens-caption-annot [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Auditing figure captions before paper submission +- Checking whether axis labels carry units and direction information +- Verifying error bars are defined in the legend or caption +- Ensuring baseline conditions are referenced explicitly +- Disclosing sample size per plotted condition +- User invokes `/autoskillit:vis-lens-caption-annot` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/vis-lens-caption-annot/` +- Use a non-declarative title like "Results" or "Figure 3: Performance" — titles must state the takeaway (e.g., "Model A outperforms baseline on all benchmarks") +- Omit units from axis labels (e.g., write "Latency (ms)", not "Latency") + +**ALWAYS:** +- Check every figure title for declarative language +- Verify every axis label carries a unit or categorical scale description +- Confirm error bars / shaded regions are defined (CI95, ±1 std, IQR, etc.) in the legend or caption +- Flag any figure that references a baseline without naming it explicitly +- Report sample size per plotted condition (n=X seeds, N=X subjects, etc.) +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool — this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/vis-lens-caption-annot/vis_spec_caption_annot_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/vis-lens-caption-annot/vis_spec_caption_annot_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1–4; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Inventory Figure Titles + +For every figure in the experiment plan or codebase: +- Collect the current title string +- Classify: DECLARATIVE (states a result) vs DESCRIPTIVE (labels the figure) +- FAIL if title is purely descriptive (e.g. "Ablation Results", "Performance Comparison") +- PASS if title states the key finding (e.g. "Removing component X degrades accuracy by 8 pp") + +### Step 2: Axis Label and Unit Audit + +For every axis in every figure: +- Confirm the label is present (no unlabeled axes) +- Confirm units are stated for continuous quantities: time (ms/s), memory (MB/GB), accuracy (%), loss (nats/bits), etc. +- Confirm categorical axes name the grouping variable +- FLAG WARNING for any axis missing a unit on a continuous quantity + +### Step 3: Error and Uncertainty Definition Audit + +For every figure that shows error bars, shaded regions, or confidence intervals: +- Identify the error representation: CI (90/95/99%), ±1 std, ±1 SEM, IQR, min/max +- Verify the definition appears in the legend or caption text +- FLAG FAIL if error bars are shown but not defined + +### Step 4: Baseline and Sample Size Disclosure + +- Identify every "baseline" referenced in a figure or caption +- Verify the baseline name and source are stated (e.g. "GPT-4 (OpenAI, 2023)") +- For each plotted group/condition, verify sample size n is disclosed (seeds, subjects, runs) +- FLAG WARNING for any undisclosed baseline or missing n + +### Step 5: Emit yaml:figure-spec Blocks + +For each figure, emit one `yaml:figure-spec` fenced block with the `annotations` field +describing the caption audit result. Then LOAD `/autoskillit:mermaid` and create a diagram +showing: title audit → axis audit → error definition → baseline/n disclosure → verdict. + +--- + +## Output Template + +```markdown +# Annotative Caption Spec: {System / Experiment Name} + +**Lens:** Annotative Caption (Annotative) +**Question:** Are figure captions and axis labels fully self-contained? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Caption Audit Summary + +| Figure | Declarative Title | Axis Units | Error Defined | Baseline Named | Sample n | Status | +|--------|-------------------|-----------|---------------|----------------|----------|--------| +| fig-01 | FAIL (descriptive) | PASS | PASS | N/A | PASS | FAIL | +| fig-02 | PASS | PASS | PASS | PASS | PASS | OK | + +## Figure Specs + +```yaml +# yaml:figure-spec — canonical schema (spec_version: "1.0") +figure_id: "fig-02-ablation-comparison" +figure_title: "Removing component X degrades accuracy by 8 pp" +spec_version: "1.0" +chart_type: "bar" +chart_type_fallback: "table" +perceptual_justification: "Grouped bar chart shows per-component contribution directly." +data_source: "results/ablation.csv" +data_mapping: + x: "variant" + y: "accuracy_delta_pp" + color: "component" + size: "" + facet: "" +layout: + width_inches: 5.0 + height_inches: 3.5 + dpi: 300 +stat_overlay: + type: "error_bar" + measure: "CI95" + n_seeds: 5 +annotations: ["Declarative title PASS; axis labels with units PASS; CI95 defined in legend PASS; n=5 seeds per condition PASS"] +anti_patterns: [] +palette: "okabe-ito" +format: "pdf" +target_dpi: 300 +library: "matplotlib" +report_section: "Section 5 Ablation" +priority: "P1" +placement_tier: "main" +conflicts: [] +metadata: + created_by: "vis-lens-caption-annot" + reviewed_by: "" + last_updated: "{YYYY-MM-DD}" +``` + +## Caption Annotation Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + + subgraph Titles ["TITLE AUDIT"] + T1["title = {text}
    ━━━━━━━━━━
    declarative: PASS / FAIL"] + end + + subgraph Axes ["AXIS LABEL AUDIT"] + A1["x-axis: {label} ({unit})
    y-axis: {label} ({unit})
    ━━━━━━━━━━
    units present: PASS / FAIL"] + end + + subgraph Errors ["ERROR DEFINITION"] + E1["error type: {CI95/std/SEM}
    ━━━━━━━━━━
    defined in legend: PASS / FAIL"] + end + + subgraph Disclosure ["BASELINE & SAMPLE n"] + D1["baseline: {name}
    n per condition: {N}
    ━━━━━━━━━━
    disclosed: PASS / FAIL"] + end + + subgraph Verdict ["VERDICT"] + V1["{OK / WARNING / FAIL}
    ━━━━━━━━━━
    {reason}"] + end + + T1 --> A1 + A1 --> E1 + E1 --> D1 + D1 --> V1 + + class T1 stateNode; + class A1 handler; + class E1 cli; + class D1 output; + class V1 detector; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Teal | Title | Declarative title audit | +| Orange | Axes | Axis label and unit audit | +| Dark Blue | Error | Error bar definition check | +| Teal | Disclosure | Baseline and sample size disclosure | +| Red | Verdict | OK / WARNING / FAIL assessment | +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table +- [ ] Every figure with a non-declarative title is flagged as FAIL +- [ ] Every axis missing units on a continuous quantity is flagged as WARNING +- [ ] Every figure with undefined error bars is flagged as FAIL diff --git a/src/autoskillit/skills_extended/vis-lens-chart-select/SKILL.md b/src/autoskillit/skills_extended/vis-lens-chart-select/SKILL.md new file mode 100644 index 0000000000..9cd402cc31 --- /dev/null +++ b/src/autoskillit/skills_extended/vis-lens-chart-select/SKILL.md @@ -0,0 +1,313 @@ +--- +name: vis-lens-chart-select +categories: [vis-lens] +activate_deps: [mermaid] +description: "Create Chart Type Selection visualization planning spec showing encoding channel assignments, Cleveland-McGill perceptual hierarchy, and data-type→chart-type matrix. Typological lens answering \"Which chart type is perceptually optimal for this data?\"" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Chart Select Lens - Analyzing chart type fit...'" + once: true +--- + +# Chart Type Selection Visualization Lens + +**Philosophical Mode:** Typological +**Primary Question:** "Which chart type is perceptually optimal for this data?" +**Focus:** Encoding Channel Assignments, Cleveland-McGill Perceptual Hierarchy, Data-Type → Chart-Type Matrix + +## Arguments + +`/autoskillit:vis-lens-chart-select [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Selecting chart types for ML results (accuracy tables, loss curves, ablations) +- Deciding encoding channels (position, length, color, size, angle) for each variable +- Reviewing figure plans before implementation to catch perceptually suboptimal choices +- Building a figure plan from scratch and wanting principled chart-type assignments +- User invokes `/autoskillit:vis-lens-chart-select` + +## yaml:figure-spec Schema + +Canonical schema definition for a single figure planning specification: + +```yaml +# yaml:figure-spec — canonical schema (spec_version: "1.0") +figure_id: str # unique slug, e.g. "fig-01-main-accuracy" +figure_title: str # human-readable title +spec_version: "1.0" # schema version; increment on breaking change +chart_type: str # CONTROLLED VOCAB (see below) — excludes "radar" and "pie" +chart_type_fallback: str # secondary chart if primary unavailable +perceptual_justification: str # Cleveland-McGill rank or encoding channel rationale +data_source: str # variable or file that feeds this figure +data_mapping: + x: str # x-axis variable / encoding + y: str # y-axis variable / encoding + color: str # color encoding (optional) + size: str # size encoding (optional) + facet: str # facet/panel variable (optional) +layout: + width_inches: float + height_inches: float + dpi: int +stat_overlay: + type: str # "error_bar" | "ci_band" | "violin" | "none" + measure: str # "SD" | "SE" | "CI95" | "PI95" + n_seeds: int # number of random seeds used +annotations: list[str] # text annotations to include +anti_patterns: list[str] # anti-pattern IDs being actively avoided (ap-* codes) +palette: str # colorblind-safe palette name, e.g. "wong", "okabe-ito" +format: str # "svg" | "png" | "pdf" +target_dpi: int # 300 for publication, 150 for slides +library: str # "matplotlib" | "seaborn" | "plotly" | "ggplot2" | "vega" +report_section: str # section of the paper/report this figure appears in +priority: str # "P0" | "P1" | "P2" +placement_tier: str # "main" | "appendix" | "supplementary" +conflicts: list[str] # figure_ids this conflicts with (same data, different view) +metadata: + created_by: str + reviewed_by: str + last_updated: str # ISO date +``` + +**Controlled `chart_type` vocabulary** (radar and pie are excluded): + +- bar, grouped-bar, stacked-bar +- line, scatter, scatter-matrix +- box, violin, strip +- heatmap, histogram, kde, ecdf +- forest-plot, dot-plot, bubble +- area, ribbon, step +- parallel-coordinates, table, matrix + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/vis-lens-chart-select/` +- Use `radar` or `pie` chart types — these are perceptually inferior and excluded from the controlled vocabulary + +**ALWAYS:** +- Apply the Cleveland-McGill perceptual hierarchy when ranking chart alternatives: **position > length > angle > area > color saturation > color hue** +- Assign explicit encoding channels (x, y, color, size, facet) for every figure variable +- Document why alternatives were rejected using the perceptual rank +- Use colorblind-safe palettes (wong, okabe-ito, viridis, cividis) +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/vis-lens-chart-select/vis_spec_chart_select_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/vis-lens-chart-select/vis_spec_chart_select_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1–4; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Parallel Exploration + +Spawn parallel exploration tasks to investigate: + +**Existing Figure Inventory** +- Find all existing figures, plots, and visualizations in the project +- Look for: `fig`, `figure`, `plot`, `chart`, `image`, `png`, `svg`, `pdf`, `matplotlib`, `seaborn`, `plotly` + +**Data Types and Variables** +- Find all variables, metrics, and data fields to be visualized +- Look for: `accuracy`, `loss`, `metric`, `score`, `embedding`, `distribution`, `time`, `epoch` + +**Current Chart Choices** +- Find existing chart-type decisions in code, config, or planning docs +- Look for: `bar_plot`, `scatter`, `line_chart`, `heatmap`, `histogram`, `boxplot`, `violinplot` + +**Encoding Channel Usage** +- Find existing axis assignments, color mappings, size mappings +- Look for: `xlabel`, `ylabel`, `hue`, `color`, `size`, `marker`, `alpha`, `facet` + +### Step 2: Build the Data-Type → Chart-Type Matrix + +For each figure slot identified: + +1. Classify the data type of each variable: nominal, ordinal, quantitative-discrete, quantitative-continuous, temporal +2. Classify the relationship to visualize: comparison, distribution, composition, relationship, change-over-time +3. Apply the data-type × relationship matrix to identify candidate chart types +4. Assign encoding channels for all variables: primary (x/y position), secondary (color, size), tertiary (facet, shape) + +| Data Type | Relationship | Recommended Chart Types | +|-----------|-------------|------------------------| +| Nominal × Quantitative | Comparison | bar, dot-plot, forest-plot | +| Quantitative × Quantitative | Relationship | scatter, bubble | +| Quantitative (single) | Distribution | histogram, kde, violin, box, strip, ecdf | +| Nominal × Quantitative (multi) | Comparison + Distribution | violin, box, strip | +| Temporal × Quantitative | Change-over-time | line, area, ribbon | +| Matrix / Grid | Relationship | heatmap, matrix | +| High-dimensional | Relationship | scatter-matrix, parallel-coordinates | + +### Step 3d: Perceptual Rank + +For each figure slot, rank the candidate chart types by Cleveland-McGill position: + +1. **Position (highest accuracy):** bar, scatter, line, dot-plot — use whenever the data allows +2. **Length:** bar (horizontal) — good for labeled categories +3. **Angle:** avoid unless no positional alternative exists +4. **Area:** bubble, scatter (size encoding) — document the Stevens power law limitation (~0.7) +5. **Color saturation:** heatmap — acceptable for matrix data where position is already used +6. **Color hue (lowest accuracy):** nominal encoding only — never encode quantitative data with hue alone + +Document the chosen rank for each figure and explicitly state why alternatives were rejected (e.g., "violin rejected: n < 10 → use strip plot; ecdf preferred over histogram: no bin-width sensitivity"). + +### Step 4: Emit Specs and Diagram + +For each figure, emit one `yaml:figure-spec` fenced block. Then LOAD `/autoskillit:mermaid` +and create the mermaid diagram showing the data-type → chart-type assignment flow. + +--- + +## Output Template + +```markdown +# Chart Type Selection Spec: {System / Experiment Name} + +**Lens:** Chart Type Selection (Typological) +**Question:** Which chart type is perceptually optimal for this data? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Figure Specs + +```yaml +# yaml:figure-spec — canonical schema (spec_version: "1.0") +figure_id: "fig-01-main-accuracy" +figure_title: "Main Results: Accuracy by Method" +spec_version: "1.0" +chart_type: "grouped-bar" +chart_type_fallback: "dot-plot" +perceptual_justification: "Position encoding (Cleveland-McGill rank 1) for nominal × quantitative comparison; grouped-bar preferred over dot-plot for direct label alignment." +data_source: "results/main_results.csv" +data_mapping: + x: "method" + y: "accuracy" + color: "dataset" + size: "" + facet: "" +layout: + width_inches: 6.5 + height_inches: 4.0 + dpi: 300 +stat_overlay: + type: "error_bar" + measure: "CI95" + n_seeds: 5 +annotations: ["Baseline at 0.72", "Best result starred"] +anti_patterns: ["ap-3d-bar", "ap-bar-no-error"] +palette: "wong" +format: "pdf" +target_dpi: 300 +library: "matplotlib" +report_section: "Section 4.1 Main Results" +priority: "P0" +placement_tier: "main" +conflicts: [] +metadata: + created_by: "vis-lens-chart-select" + reviewed_by: "" + last_updated: "{YYYY-MM-DD}" +``` + +## Chart Type Assignment Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff; + classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000; + + subgraph DataTypes ["DATA TYPES"] + DT1["{Variable 1}
    ━━━━━━━━━━
    nominal"] + DT2["{Variable 2}
    ━━━━━━━━━━
    quantitative-continuous"] + end + + subgraph Relationship ["RELATIONSHIP"] + R1["{Comparison}
    ━━━━━━━━━━
    nominal × quantitative"] + end + + subgraph ChartType ["CHART TYPE SELECTED"] + CT1["{grouped-bar}
    ━━━━━━━━━━
    Cleveland-McGill: position rank 1"] + end + + subgraph Encoding ["ENCODING CHANNELS"] + E1["x: {method}
    ━━━━━━━━━━
    position (primary)"] + E2["y: {accuracy}
    ━━━━━━━━━━
    position (primary)"] + E3["color: {dataset}
    ━━━━━━━━━━
    hue (nominal only)"] + end + + DT1 --> R1 + DT2 --> R1 + R1 --> CT1 + CT1 --> E1 + CT1 --> E2 + CT1 --> E3 + + class DT1,DT2 stateNode; + class R1 phase; + class CT1 cli; + class E1,E2 output; + class E3 handler; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Teal | Data Types | Input variable types | +| Purple | Relationship | Visualization relationship class | +| Dark Blue | Chart Type | Selected chart with perceptual justification | +| Teal | Encoding (positional) | x/y encoding channels | +| Orange | Encoding (color/size) | Secondary encoding channels | + +## Perceptual Rank Summary + +| Figure | Chosen Chart | Rank | Alternatives Rejected | Reason | +|--------|-------------|------|-----------------------|--------| +| {fig-01} | grouped-bar | position (1) | dot-plot | bar aligns better with discrete category labels | +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table +- [ ] All chart types are from the controlled vocabulary (no radar, no pie) +- [ ] Each figure spec has `perceptual_justification` filled in diff --git a/src/autoskillit/skills_extended/vis-lens-color-access/SKILL.md b/src/autoskillit/skills_extended/vis-lens-color-access/SKILL.md new file mode 100644 index 0000000000..3e1dabb45b --- /dev/null +++ b/src/autoskillit/skills_extended/vis-lens-color-access/SKILL.md @@ -0,0 +1,235 @@ +--- +name: vis-lens-color-access +categories: [vis-lens] +activate_deps: [mermaid] +description: "Create Chromatic Accessibility visualization planning spec showing colorblind safety (Okabe-Ito, Paul Tol palettes), perceptual uniformity checks (viridis/cividis pass; jet/rainbow fail), non-color redundant encoding (shape + line-style), and text size minimums. Chromatic lens answering \"Is the color encoding accessible and perceptually uniform?\"" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Color Access Lens - Auditing chromatic accessibility...'" + once: true +--- + +# Chromatic Accessibility Visualization Lens + +**Philosophical Mode:** Chromatic +**Primary Question:** "Is the color encoding accessible and perceptually uniform?" +**Focus:** Colorblind Safety (Okabe-Ito, Paul Tol palettes), Perceptual Uniformity + (viridis/cividis pass; jet/rainbow fail), Non-Color Redundant Encoding + (shape + line-style), Text Size Minimums + +## Arguments + +`/autoskillit:vis-lens-color-access [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Auditing figures for colorblind accessibility before submission +- Checking whether colormaps are perceptually uniform for quantitative data +- Verifying that color-distinguished series have redundant non-color encodings +- Reviewing font sizes for accessibility and publication standards +- User invokes `/autoskillit:vis-lens-color-access` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/vis-lens-color-access/` +- Use `jet` or `rainbow` colormaps for any quantitative data — these are perceptually non-uniform and fail colorblind simulation +- Encode quantitative data with hue alone (no luminance gradient) + +**ALWAYS:** +- Use Okabe-Ito (8 colors) or Paul Tol palettes for categorical nominal data +- Use viridis, cividis, or mako for sequential/diverging quantitative data +- Add a redundant non-color encoding (shape marker AND/OR line-style dash pattern) for every color-distinguished series in line and scatter plots +- Caption text and axis labels: minimum 8pt in final figure; 10pt preferred for publication +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool — this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/vis-lens-color-access/vis_spec_color_access_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/vis-lens-color-access/vis_spec_color_access_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1–4; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Inventory Color Usage + +Scan experiment plan, context file, and codebase for: + +**Palette and Colormap Names** +- Find all palette names and colormap strings in plotting code +- Look for: `cmap=`, `palette=`, `color=`, `colors=`, `sns.color_palette`, `plt.cm.` +- Flag FAIL: `jet`, `rainbow`, `hsv`, `Spectral`, `hot`, `cool` +- Pass: `viridis`, `cividis`, `mako`, `okabe-ito`, `wong`, `tol`, `tab10` + +**Hue-Only Encoding** +- Detect cases where quantitative data uses hue without luminance gradient +- Look for: diverging colormaps applied to continuous scales, categorical palettes applied to ordinal data + +**Series Count** +- Count the number of color-distinguished series per figure +- Look for: legend entries, `label=` parameters, series lists + +### Step 2: Redundant Encoding Audit + +For each color-distinguished series in a line or scatter plot: +- Check whether a marker shape (`marker=`) is also assigned +- Check whether a line-style dash (`linestyle=`, `dashes=`) is also assigned +- If neither is present: flag as WARNING — "Series relies on color alone; add marker or linestyle" + +### Step 3: Text Size Audit + +Scan figure creation calls for font size parameters: +- Look for: `fontsize=`, `labelsize=`, `title_fontsize=`, `tick_params(labelsize=...)`, `rcParams` +- Flag any value < 8 as WARNING: "Font size {N}pt is below 8pt minimum" +- Flag any value < 10 as INFO: "Font size {N}pt is below 10pt preferred for publication" + +### Step 4: Emit yaml:figure-spec Blocks + +For each figure, emit one `yaml:figure-spec` fenced block with `palette` field filled. +Then LOAD `/autoskillit:mermaid` and create a diagram showing palette audit → +redundant encoding → text audit → verdict. + +--- + +## Output Template + +```markdown +# Chromatic Accessibility Spec: {System / Experiment Name} + +**Lens:** Chromatic Accessibility (Chromatic) +**Question:** Is the color encoding accessible and perceptually uniform? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Color Audit Summary + +| Figure | Palette | Colorblind Safe | Redundant Encoding | Min Font | Status | +|--------|---------|-----------------|-------------------|----------|--------| +| {fig-01} | jet | FAIL | no | 7pt | FAIL | +| {fig-02} | okabe-ito | PASS | yes (marker+dash) | 10pt | OK | + +## Figure Specs + +```yaml +# yaml:figure-spec — canonical schema (spec_version: "1.0") +figure_id: "fig-02-ablation-comparison" +figure_title: "Ablation: Component Contribution" +spec_version: "1.0" +chart_type: "line" +chart_type_fallback: "grouped-bar" +perceptual_justification: "Okabe-Ito is colorblind-safe; marker shapes provide redundant encoding." +data_source: "results/ablation.csv" +data_mapping: + x: "epoch" + y: "accuracy" + color: "variant" + size: "" + facet: "" +layout: + width_inches: 5.0 + height_inches: 3.5 + dpi: 300 +stat_overlay: + type: "error_bar" + measure: "CI95" + n_seeds: 5 +annotations: ["okabe-ito palette; marker shapes assigned; 10pt axis labels"] +anti_patterns: ["ap-hue-only-encoding"] +palette: "okabe-ito" +format: "pdf" +target_dpi: 300 +library: "matplotlib" +report_section: "Section 5 Ablation" +priority: "P1" +placement_tier: "main" +conflicts: [] +metadata: + created_by: "vis-lens-color-access" + reviewed_by: "" + last_updated: "{YYYY-MM-DD}" +``` + +## Chromatic Accessibility Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + + subgraph Palette ["PALETTE AUDIT"] + P1["palette = {name}
    ━━━━━━━━━━
    colorblind safe: PASS / FAIL"] + end + + subgraph Redundant ["REDUNDANT ENCODING"] + R1["marker: yes/no
    linestyle: yes/no
    ━━━━━━━━━━
    series count = {N}"] + end + + subgraph Text ["TEXT SIZE AUDIT"] + T1["min font = {N}pt
    ━━━━━━━━━━
    OK / WARNING / INFO"] + end + + subgraph Verdict ["VERDICT"] + V1["{OK / WARNING / FAIL}
    ━━━━━━━━━━
    {reason}"] + end + + P1 --> R1 + R1 --> T1 + T1 --> V1 + + class P1 stateNode; + class R1 handler; + class T1 cli; + class V1 detector; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Teal | Palette | Colorblind safety audit result | +| Orange | Redundant Encoding | Marker and linestyle check | +| Dark Blue | Text Size | Font size audit result | +| Red | Verdict | OK / WARNING / FAIL assessment | +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table +- [ ] Every failing colormap (jet, rainbow) is explicitly flagged as FAIL +- [ ] Every color-distinguished series has been checked for redundant encoding +- [ ] Every font size below 8pt has been flagged as WARNING diff --git a/src/autoskillit/skills_extended/vis-lens-domain-norms/SKILL.md b/src/autoskillit/skills_extended/vis-lens-domain-norms/SKILL.md new file mode 100644 index 0000000000..ee19164de0 --- /dev/null +++ b/src/autoskillit/skills_extended/vis-lens-domain-norms/SKILL.md @@ -0,0 +1,279 @@ +--- +name: vis-lens-domain-norms +categories: [vis-lens] +activate_deps: [mermaid] +description: "Create Domain Norms visualization planning spec showing ML sub-area mandatory figures, community conventions, and coverage gaps. Domain-Normative lens answering \"Which domain-specific figures are expected by reviewers?\"" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Domain Norms Lens - Checking ML sub-area figure requirements...'" + once: true +--- + +# Domain Norms Visualization Lens + +**Philosophical Mode:** Domain-Normative +**Primary Question:** "Which domain-specific figures are expected by reviewers?" +**Focus:** ML Sub-Area Mandatory Figures, Community Conventions, Coverage Gap Analysis + +## Arguments + +`/autoskillit:vis-lens-domain-norms [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Preparing a paper submission and checking what figures reviewers will expect +- Auditing a figure plan against community norms for the ML sub-area +- Identifying missing mandatory figures before the camera-ready deadline +- Onboarding to a new ML sub-area and learning its visualization conventions +- User invokes `/autoskillit:vis-lens-domain-norms` + +## ML Sub-Area Mandatory Figures + +| ML Sub-Area | Mandatory Figures | Community Norm Source | +|-------------|-------------------|----------------------| +| Supervised Classification | Confusion matrix, precision-recall curve, ROC-AUC, learning curves | NeurIPS/ICML reviewer norms | +| NLP | Per-task accuracy table, error analysis examples, attention/saliency (if applicable) | ACL anthology norms | +| Computer Vision | Sample predictions grid, failure case gallery, per-class mAP bar | CVPR/ECCV norms | +| Reinforcement Learning | Episode reward curve (mean ± std across seeds), sample efficiency curve | NeurIPS RL track norms | +| Generative Models | Sample grids (unconditional + conditional), FID/IS table, failure modes | NeurIPS/ICLR generative norms | +| Foundation Models | Few-shot performance scaling curve, task contamination analysis, ablation table | LLM paper norms (BIG-bench style) | +| Agentic Systems | Task success rate bar (± CI), step-level trace examples, tool use breakdown | Emerging norm (2023–2025) | +| Time-Series | Forecasting horizon curve, decomposition plots, residual ACF | ICLR/NeurIPS temporal norms | + +## Extensibility + +This lens currently covers 8 ML sub-areas. Future domain-specific variants (e.g., +`vis-lens-domain-norms-cv`, `vis-lens-domain-norms-rl`) may extend this catalog with +venue-specific norms, additional mandatory figure types, or sub-area-specific anti-pattern +overlays. The base lens should remain general enough to bootstrap any sub-area. + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/vis-lens-domain-norms/` +- Declare a figure "present" if it exists only in code but is not yet generated — coverage requires the actual output file or a concrete plan entry + +**ALWAYS:** +- Identify the ML sub-area from the experiment plan or context before checking mandatory figures +- For each mandatory figure type, assign one of three statuses: **present**, **partial**, **absent** +- Sort the gap list absent-first, then partial +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/vis-lens-domain-norms/vis_spec_domain_norms_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/vis-lens-domain-norms/vis_spec_domain_norms_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments and identify ML sub-area + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. + +Identify the ML sub-area by scanning for keywords: +- `classification`, `clf`, `precision`, `recall`, `confusion_matrix` → Supervised Classification +- `NLP`, `language model`, `BLEU`, `ROUGE`, `perplexity`, `token` → NLP +- `image`, `detection`, `segmentation`, `mAP`, `COCO`, `ImageNet` → Computer Vision +- `RL`, `reinforcement`, `reward`, `episode`, `policy`, `agent`, `environment` → Reinforcement Learning +- `GAN`, `VAE`, `diffusion`, `FID`, `IS`, `generation` → Generative Models +- `LLM`, `few-shot`, `zero-shot`, `foundation`, `BIG-bench`, `scaling` → Foundation Models +- `agentic`, `tool use`, `task success`, `step trace`, `function call` → Agentic Systems +- `time series`, `forecasting`, `temporal`, `ACF`, `seasonal`, `trend` → Time-Series + +If multiple sub-areas match, analyze for all matching sub-areas. + +### Step 1: Inventory Existing and Planned Figures + +Scan experiment plan, context file, and codebase for: + +**Existing Figures** +- Find all generated figure files: `*.png`, `*.pdf`, `*.svg` in results/figures directories +- Find figure-generating code: `savefig`, `plt.save`, `fig.write_image` + +**Planned Figures** +- Find figure descriptions in experiment plan, README, or task descriptions +- Look for: `figure`, `plot`, `diagram`, `visualization`, `chart` in planning documents + +**Figure Types Present** +- Match found figures to mandatory types from the sub-area table +- Classify each mandatory type as: present / partial / absent + +### Step 2: Check Coverage for Each Mandatory Figure Type + +For each mandatory figure type in the identified sub-area: + +1. Search for evidence of this figure type in the codebase and plan +2. Assign coverage status: + - **present** — figure exists as generated output or concrete implementation + - **partial** — figure is planned but not generated, or exists but missing key elements + - **absent** — no evidence of this figure type anywhere +3. Record the evidence (file path, code reference, or note of absence) + +### Step 3: Build Gap List + +Collect all absent and partial mandatory figures. Sort: +1. **absent** — highest priority gap; reviewer will flag as missing +2. **partial** — needs completion before submission + +For each gap, assign a recommended figure spec (chart_type, data_source estimate). + +### Step 4: Emit yaml:figure-spec Blocks and Mermaid Coverage Diagram + +For each absent or partial mandatory figure, emit one `yaml:figure-spec` fenced block as a +recommendation. Then LOAD `/autoskillit:mermaid` and create the coverage diagram. + +--- + +## Output Template + +```markdown +# Domain Norms Spec: {System / Experiment Name} + +**Lens:** Domain Norms (Domain-Normative) +**Question:** Which domain-specific figures are expected by reviewers? +**Date:** {YYYY-MM-DD} +**ML Sub-Area:** {detected sub-area} +**Scope:** {What was analyzed} + +## Coverage Summary + +| Mandatory Figure | Status | Evidence | +|-----------------|--------|----------| +| {Confusion matrix} | present | results/figures/confusion_matrix.pdf | +| {PR curve} | partial | code exists; figure not generated | +| {ROC-AUC} | absent | no evidence found | +| {Learning curves} | absent | no evidence found | + +## Gap Analysis + +| Priority | Figure Type | Status | Recommendation | +|----------|-------------|--------|----------------| +| 1 | ROC-AUC | absent | Add roc_curve plot with CI band | +| 2 | Learning curves | absent | Plot train/val loss vs epoch | +| 3 | PR curve | partial | Generate from existing pr_curve.py | + +## Recommended Figure Specs + +```yaml +# yaml:figure-spec — canonical schema (spec_version: "1.0") +figure_id: "fig-missing-roc-auc" +figure_title: "ROC-AUC Curve" +spec_version: "1.0" +chart_type: "line" +chart_type_fallback: "scatter" +perceptual_justification: "Line chart with position encoding for TPR vs FPR; standard domain norm for classification." +data_source: "results/predictions.csv" +data_mapping: + x: "fpr" + y: "tpr" + color: "model" + size: "" + facet: "" +layout: + width_inches: 5.0 + height_inches: 5.0 + dpi: 300 +stat_overlay: + type: "ci_band" + measure: "CI95" + n_seeds: 5 +annotations: ["AUC = {value}", "diagonal baseline shown"] +anti_patterns: [] +palette: "wong" +format: "pdf" +target_dpi: 300 +library: "matplotlib" +report_section: "Section 4 Evaluation" +priority: "P0" +placement_tier: "main" +conflicts: [] +metadata: + created_by: "vis-lens-domain-norms" + reviewed_by: "" + last_updated: "{YYYY-MM-DD}" +``` + +## Domain Norms Coverage Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef newComponent fill:#2e7d32,stroke:#81c784,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000; + + subgraph SubArea ["ML SUB-AREA"] + SA["{Supervised Classification}
    ━━━━━━━━━━
    NeurIPS/ICML norms"] + end + + subgraph Present ["PRESENT"] + P1["{Confusion Matrix}
    ━━━━━━━━━━
    results/figures/cm.pdf"] + end + + subgraph Partial ["PARTIAL"] + W1["{PR Curve}
    ━━━━━━━━━━
    code exists; not generated"] + end + + subgraph Absent ["ABSENT"] + G1["{ROC-AUC}
    ━━━━━━━━━━
    no evidence"] + G2["{Learning Curves}
    ━━━━━━━━━━
    no evidence"] + end + + SA --> P1 + SA --> W1 + SA --> G1 + SA --> G2 + + class SA cli; + class P1 newComponent; + class W1 handler; + class G1,G2 gap; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Blue | Sub-Area | Identified ML domain | +| Green | Present | Mandatory figure covered | +| Orange | Partial | Figure planned but incomplete | +| Amber | Absent | Mandatory figure missing | +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table +- [ ] ML sub-area has been identified from context or experiment plan +- [ ] All mandatory figures for the sub-area have been checked +- [ ] Gap list is sorted absent-first, then partial diff --git a/src/autoskillit/skills_extended/vis-lens-figure-table/SKILL.md b/src/autoskillit/skills_extended/vis-lens-figure-table/SKILL.md new file mode 100644 index 0000000000..9c981b979b --- /dev/null +++ b/src/autoskillit/skills_extended/vis-lens-figure-table/SKILL.md @@ -0,0 +1,230 @@ +--- +name: vis-lens-figure-table +categories: [vis-lens] +activate_deps: [mermaid] +description: "Create Decisional Layout visualization planning spec showing figure-vs-table selection heuristics: tables win for exact values, ≤5 items, leaderboards, and ablation matrices; figures win for trends, distributions, and spatial patterns; borderline cases recommend both. Decisional lens answering \"Should this result be a figure or a table?\"" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Figure-Table Lens - Evaluating figure vs table fit...'" + once: true +--- + +# Decisional Layout Visualization Lens + +**Philosophical Mode:** Decisional +**Primary Question:** "Should this result be a figure or a table?" +**Focus:** Figure vs Table Selection Heuristics — Tables win: exact values, ≤5 items, + leaderboards, ablation matrices; Figures win: trends, distributions, spatial + patterns; Borderline → recommend both + +## Arguments + +`/autoskillit:vis-lens-figure-table [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Planning the presentation format for each result slot in a paper or report +- Deciding whether a leaderboard or ranking should be a table or a bar chart +- Evaluating whether ablation results communicate better as a matrix table or a figure +- Justifying borderline figure/table decisions before creating visualizations +- User invokes `/autoskillit:vis-lens-figure-table` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/vis-lens-figure-table/` +- Force a figure when the reader needs exact numeric values for a leaderboard or lookup +- Force a table when the primary message is a trend, curve, or distributional shape + +**ALWAYS:** +- Apply the decision rule below to every result slot in the experiment plan +- When the verdict is BOTH, recommend the table in the main paper and the figure in the appendix (or vice versa depending on the primary audience) +- Justify borderline decisions with explicit reference to the decision rule criteria +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool — this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/vis-lens-figure-table/vis_spec_figure_table_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/vis-lens-figure-table/vis_spec_figure_table_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1–4; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Inventory Result Slots + +Enumerate every metric, experiment result, or finding that needs to be communicated. +For each result slot, classify it as one of: +- **exact-value query**: reader needs the precise number (leaderboard, lookup table) +- **trend/curve**: the message is a trajectory or change over time/steps +- **distribution**: the message is the shape of a distribution (histogram, violin, KDE) +- **comparison/ranking**: multiple systems compared by a scalar metric +- **spatial/geometric**: data has a spatial or structural layout (heatmap, scatter) +- **ablation matrix**: systematic removal/addition of components in a table grid + +### Step 2: Apply Decision Rule per Slot + +| Signal | Verdict | +|--------|---------| +| Exact values needed OR ≤5 items OR leaderboard OR ablation matrix | TABLE | +| Trend over time/epochs OR distribution shape OR spatial pattern | FIGURE | +| Statistical comparison with CI bands | FIGURE | +| Ranking where exact delta matters AND visual trend also matters | BOTH | + +For every BOTH verdict: +- Recommend the TABLE for the main paper body (exact values for citation) +- Recommend the FIGURE for the appendix (visual intuition for reviewers) +- Document the justification explicitly + +### Step 3: Emit yaml:figure-spec Blocks + +For FIGURE and BOTH verdicts only (TABLE-only results produce no figure-spec). +Then LOAD `/autoskillit:mermaid` and create a decision-tree diagram showing +result-type → verdict flow for all result slots. + +--- + +## Output Template + +```markdown +# Decisional Layout Spec: {System / Experiment Name} + +**Lens:** Decisional Layout (Decisional) +**Question:** Should this result be a figure or a table? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Layout Decision Summary + +| Result Slot | Type | Verdict | Justification | +|-------------|------|---------|---------------| +| {main-results} | exact-value query | TABLE | Leaderboard — readers need precise numbers | +| {loss-curve} | trend/curve | FIGURE | Training trajectory is the message | +| {ablation} | ablation matrix | TABLE | Component grid; exact deltas matter | +| {distribution} | distribution | FIGURE | Shape is the message | +| {ranking-with-ci} | comparison/ranking | BOTH | Exact deltas + visual CI bands | + +## Figure Specs + +```yaml +# yaml:figure-spec — canonical schema (spec_version: "1.0") +figure_id: "fig-loss-curve" +figure_title: "Training Loss Trajectory" +spec_version: "1.0" +chart_type: "line" +chart_type_fallback: "scatter" +perceptual_justification: "Trend over steps is the message; table would obscure the trajectory shape." +data_source: "results/loss_curves.csv" +data_mapping: + x: "global_step" + y: "train_loss" + color: "variant" + size: "" + facet: "" +layout: + width_inches: 6.0 + height_inches: 4.0 + dpi: 300 +stat_overlay: + type: "band" + measure: "CI95" + n_seeds: 5 +annotations: ["FIGURE verdict: trend/curve; TABLE alternative in appendix for exact values"] +anti_patterns: [] +palette: "okabe-ito" +format: "pdf" +target_dpi: 300 +library: "matplotlib" +report_section: "Section 3 Training" +priority: "P1" +placement_tier: "main" +conflicts: [] +metadata: + created_by: "vis-lens-figure-table" + reviewed_by: "" + last_updated: "{YYYY-MM-DD}" +``` + +## Figure vs Table Decision Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + + subgraph ResultType ["RESULT TYPE"] + RT["exact-value / trend / distribution
    comparison / spatial / ablation
    ━━━━━━━━━━
    classified from experiment plan"] + end + + subgraph Rule ["DECISION RULE"] + DR["TABLE: exact / ≤5 / leaderboard / ablation
    FIGURE: trend / distribution / spatial
    BOTH: ranking + visual CI
    ━━━━━━━━━━
    applied per result slot"] + end + + subgraph Verdict ["VERDICT"] + V1["TABLE / FIGURE / BOTH
    ━━━━━━━━━━
    {justification}"] + end + + subgraph Placement ["PLACEMENT"] + PL["BOTH → TABLE: main paper
    BOTH → FIGURE: appendix
    ━━━━━━━━━━
    primary audience considered"] + end + + RT --> DR + DR --> V1 + V1 --> PL + + class RT stateNode; + class DR cli; + class V1 output; + class PL handler; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Teal | Result Type | Classification of the result slot | +| Dark Blue | Decision Rule | Rule application per slot | +| Teal | Verdict | TABLE / FIGURE / BOTH | +| Orange | Placement | Main paper vs appendix recommendation | +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table +- [ ] Every result slot has been classified and assigned a verdict +- [ ] Every BOTH verdict has a documented placement recommendation +- [ ] No `yaml:figure-spec` emitted for TABLE-only result slots diff --git a/src/autoskillit/skills_extended/vis-lens-multi-compare/SKILL.md b/src/autoskillit/skills_extended/vis-lens-multi-compare/SKILL.md new file mode 100644 index 0000000000..4475dbe86f --- /dev/null +++ b/src/autoskillit/skills_extended/vis-lens-multi-compare/SKILL.md @@ -0,0 +1,244 @@ +--- +name: vis-lens-multi-compare +categories: [vis-lens] +activate_deps: [mermaid] +description: "Create Compositional Layout visualization planning spec showing small-multiples vs overlay decisions, faceting strategy (row/col), shared-axis alignment, grouped vs stacked bars, factorial interaction plots, and panel reading order. Compositional lens answering \"Which layout best reveals the comparison structure?\"" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Multi-Compare Lens - Analyzing compositional layout strategy...'" + once: true +--- + +# Compositional Layout Visualization Lens + +**Philosophical Mode:** Compositional +**Primary Question:** "Which layout — small multiples vs overlay — best reveals the comparison?" +**Focus:** Small Multiples vs Overlay, Faceting Strategy (row/col), Shared-Axis Alignment, + Grouped vs Stacked Bars, Factorial Interaction Plots, Panel Reading Order + +## Arguments + +`/autoskillit:vis-lens-multi-compare [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Designing layouts for experiments with multiple conditions, factors, or treatments +- Deciding whether to use small multiples or overlapping traces in a figure +- Planning faceted grids for factorial designs (2+ independent variables × 2+ levels) +- Evaluating whether grouped or stacked bars serve the comparison goal +- User invokes `/autoskillit:vis-lens-multi-compare` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/vis-lens-multi-compare/` +- Use overlapping traces when ≥ 4 conditions are compared — prefer small multiples +- Use stacked bars for comparisons where the baseline shifts — use grouped bars instead + +**ALWAYS:** +- Prefer small multiples over overlays when: num_conditions ≥ 5, OR data series overlap + heavily, OR the comparison requires individual-panel annotation +- Apply consistent shared-axis limits across all panels in a small-multiples layout +- Enforce left-to-right, top-to-bottom panel reading order matching the experimental + factor order (main factor changes columns; secondary factor changes rows) +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool — this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/vis-lens-multi-compare/vis_spec_multi_compare_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/vis-lens-multi-compare/vis_spec_multi_compare_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1–4; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Inventory Conditions and Factors + +Scan experiment plan, context file, and codebase for: + +**Condition and Factor Count** +- Count num_DVs (dependent variables), num_conditions (levels per factor), num_factors (IVs) +- Look for: condition lists, treatment arms, `conditions = [...]`, `groups = [...]`, factor tables + +**Series Overlap** +- Assess whether plotting all conditions on a single axes would create heavy visual overlap +- Look for: overlapping confidence bands, dense line clusters, label collisions + +**Factorial Structure** +- Detect whether the design is factorial (2+ IVs × 2+ levels each) +- Look for: interaction terms, crossed factors, `factorial`, `grid_search` + +### Step 2: Apply Small-Multiples vs Overlay Decision Rule + +For each figure that shows multi-condition data, determine the layout strategy: + +**Overlay (single axes):** +- ≤ 3 conditions, no label collision, primary message is aggregate trend +- Use when: the comparison is a single-axis trend, conditions are well-separated visually + +**Small Multiples (faceted grid):** +- ≥ 4 conditions, OR heavy overlap, OR per-panel annotation needed +- OR factorial (2+ IVs × 2+ levels): always use small multiples +- Assign `row_factor` and `col_factor` explicitly + +**Stacked vs Grouped Bars:** +- Stacked bars: only when part-to-whole is the story AND baselines are shared +- Grouped bars: when individual comparison matters more than the total + +### Step 3: Assign Facet Layout + +For small-multiples layouts: +- Assign `col_factor` to the main independent variable (most levels or primary interest) +- Assign `row_factor` to the secondary independent variable +- Set shared x-axis and y-axis limits across all panels +- Document reading order: left-to-right (col_factor levels), top-to-bottom (row_factor levels) + +### Step 4: Emit yaml:figure-spec Blocks + +For each figure, emit one `yaml:figure-spec` fenced block with `facet` field populated. +Then LOAD `/autoskillit:mermaid` and create a panel-layout schematic diagram (boxes +representing panel grid with row/col labels). + +--- + +## Output Template + +```markdown +# Compositional Layout Spec: {System / Experiment Name} + +**Lens:** Compositional Layout (Compositional) +**Question:** Which layout — small multiples vs overlay — best reveals the comparison? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} +**num_conditions detected:** {N} + +## Layout Decision Summary + +| Figure | num_conditions | num_factors | Strategy | row_factor | col_factor | +|--------|---------------|-------------|----------|------------|------------| +| {fig-01} | 6 | 2 | small-multiples | method | dataset | +| {fig-02} | 3 | 1 | overlay | — | — | + +## Figure Specs + +```yaml +# yaml:figure-spec — canonical schema (spec_version: "1.0") +figure_id: "fig-01-factorial-accuracy" +figure_title: "Accuracy Across Methods × Datasets" +spec_version: "1.0" +chart_type: "line" +chart_type_fallback: "grouped-bar" +perceptual_justification: "Small multiples prevent overlap; shared y-axis enables cross-panel comparison." +data_source: "results/accuracy.csv" +data_mapping: + x: "epoch" + y: "accuracy" + color: "variant" + size: "" + facet: "col=dataset, row=method" +layout: + width_inches: 10.0 + height_inches: 6.0 + dpi: 300 +stat_overlay: + type: "error_bar" + measure: "CI95" + n_seeds: 5 +annotations: ["shared y-axis; panel grid: 3 cols × 2 rows"] +anti_patterns: ["ap-overplotting"] +palette: "okabe-ito" +format: "pdf" +target_dpi: 300 +library: "matplotlib" +report_section: "Section 4 Results" +priority: "P1" +placement_tier: "main" +conflicts: [] +metadata: + created_by: "vis-lens-multi-compare" + reviewed_by: "" + last_updated: "{YYYY-MM-DD}" +``` + +## Compositional Layout Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + + subgraph Conditions ["CONDITION COUNT"] + C1["num_conditions = {N}
    ━━━━━━━━━━
    {factorial: yes/no}"] + end + + subgraph Strategy ["LAYOUT STRATEGY"] + S1["overlay / small-multiples
    ━━━━━━━━━━
    {decision rule applied}"] + end + + subgraph Facet ["FACET ASSIGNMENT"] + F1["col_factor = {X}
    row_factor = {Y}
    ━━━━━━━━━━
    shared axes: yes/no"] + end + + subgraph Verdict ["VERDICT"] + V1["{layout type}
    ━━━━━━━━━━
    {reading order note}"] + end + + C1 --> S1 + S1 --> F1 + F1 --> V1 + + class C1 stateNode; + class S1 cli; + class F1 handler; + class V1 output; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Teal | Condition Count | Number of conditions and factorial structure | +| Dark Blue | Strategy | Overlay vs small-multiples decision | +| Orange | Facet Assignment | Row/col factor and shared-axis configuration | +| Teal | Verdict | Final layout recommendation | +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table +- [ ] Every figure with ≥ 4 conditions has been assigned a small-multiples layout +- [ ] Every `yaml:figure-spec` has the `facet` field filled (or explicitly empty for overlays) diff --git a/src/autoskillit/skills_extended/vis-lens-reproducibility/SKILL.md b/src/autoskillit/skills_extended/vis-lens-reproducibility/SKILL.md new file mode 100644 index 0000000000..c7f4e00916 --- /dev/null +++ b/src/autoskillit/skills_extended/vis-lens-reproducibility/SKILL.md @@ -0,0 +1,258 @@ +--- +name: vis-lens-reproducibility +categories: [vis-lens] +activate_deps: [mermaid] +description: "Create Replicative Reproducibility visualization planning spec showing data availability, preprocessing parameter disclosure (bin widths, smoothing windows), plotting library/version, random seeds, and code reference per figure. Replicative lens answering \"Can the figures be reproduced from the data and code?\"" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Reproducibility Lens - Auditing figure reproducibility...'" + once: true +--- + +# Replicative Reproducibility Visualization Lens + +**Philosophical Mode:** Replicative +**Primary Question:** "Can the figures be reproduced from the data and code?" +**Focus:** Data availability (public / restricted / embargoed), preprocessing parameter + disclosure (bin widths, smoothing windows, normalization), plotting library and + version pinning, random seed documentation, per-figure code reference (script or + notebook cell) + +## Arguments + +`/autoskillit:vis-lens-reproducibility [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Auditing figure reproducibility before public release +- Checking whether preprocessing parameters are fully disclosed +- Verifying that random seeds are documented for stochastic plots +- Linking each figure to the script or notebook cell that generates it +- User invokes `/autoskillit:vis-lens-reproducibility` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/vis-lens-reproducibility/` +- Treat "code available on request" as equivalent to public availability +- Omit random seed documentation for any figure derived from stochastic processes + +**ALWAYS:** +- Check data availability status for every figure (public/restricted/embargoed) +- Document bin widths for histograms, smoothing windows for time-series, normalization parameters for heatmaps +- Pin plotting library name and version (matplotlib 3.8.2, seaborn 0.13.0, etc.) +- Record the random seed(s) used for any stochastic component (sampling, bootstrapping, noise injection) +- Provide a per-figure code reference: script path or notebook cell identifier +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool — this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/vis-lens-reproducibility/vis_spec_reproducibility_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/vis-lens-reproducibility/vis_spec_reproducibility_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1–4; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Data Availability Inventory + +For each figure: +- Identify the data source (file path, dataset name, external URL) +- Classify availability: PUBLIC (DOI / URL), RESTRICTED (license required), EMBARGOED (not yet released) +- FLAG FAIL if data is restricted/embargoed with no access plan stated + +### Step 2: Preprocessing Parameter Audit + +For each figure, identify all preprocessing steps that affect visual output: +- **Histograms**: bin width or bin count; normalization (density vs count vs probability) +- **Time-series / learning curves**: smoothing window type (rolling mean, EMA) and window size +- **Heatmaps**: normalization method (min-max, z-score, none); colormap clipping range +- **Scatter/line with aggregation**: aggregation function (mean, median) and grouping +- FLAG WARNING for any preprocessing parameter not documented + +### Step 3: Library and Version Audit + +Scan the codebase for plotting imports: +- Record: `import matplotlib`, `import seaborn`, `import plotly`, etc. +- Check `pyproject.toml` or `requirements.txt` for pinned versions +- FLAG WARNING if plotting library version is not pinned + +### Step 4: Random Seed Audit + +For each figure involving a stochastic component: +- Identify source of randomness: bootstrapping, subsampling, t-SNE/UMAP, noise injection +- Verify `random_state`, `seed`, `np.random.seed`, or equivalent is documented per figure +- FLAG FAIL if any stochastic figure has no documented seed + +### Step 5: Per-Figure Code Reference + +For each figure: +- Identify the script or notebook cell that generates it +- Record: file path + function or cell ID +- FLAG WARNING if a figure has no traceable code reference + +### Step 6: Emit yaml:figure-spec Blocks + +For each figure, emit one `yaml:figure-spec` fenced block with `data_source` and +`annotations` fields capturing reproducibility metadata. Then LOAD `/autoskillit:mermaid` +and create a diagram showing: data availability → preprocessing → library version → +seed documentation → code reference → verdict. + +--- + +## Output Template + +```markdown +# Replicative Reproducibility Spec: {System / Experiment Name} + +**Lens:** Replicative Reproducibility (Replicative) +**Question:** Can the figures be reproduced from the data and code? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Reproducibility Audit Summary + +| Figure | Data Available | Preprocessing Documented | Library Pinned | Seed Documented | Code Reference | Status | +|--------|---------------|--------------------------|----------------|-----------------|----------------|--------| +| fig-01 | PUBLIC | PASS | PASS | N/A | scripts/plot_main.py | OK | +| fig-02 | RESTRICTED | WARNING | FAIL | PASS | notebooks/ablation.ipynb#cell-7 | FAIL | + +## Figure Specs + +```yaml +# yaml:figure-spec — canonical schema (spec_version: "1.0") +figure_id: "fig-01-main-result" +figure_title: "Model A achieves state-of-the-art on all benchmarks" +spec_version: "1.0" +chart_type: "bar" +chart_type_fallback: "table" +perceptual_justification: "Bars communicate exact values; error bars show CI95 over 5 seeds." +data_source: "results/main.csv (DOI: 10.xxxx/xxxxx)" +data_mapping: + x: "benchmark" + y: "score" + color: "model" + size: "" + facet: "" +layout: + width_inches: 6.0 + height_inches: 4.0 + dpi: 300 +stat_overlay: + type: "error_bar" + measure: "CI95" + n_seeds: 5 +annotations: ["data: public (DOI); preprocessing: none; library: matplotlib==3.8.2; seeds: 0,1,2,3,4; code: scripts/plot_main.py:plot_main_result()"] +anti_patterns: [] +palette: "okabe-ito" +format: "pdf" +target_dpi: 300 +library: "matplotlib==3.8.2" +report_section: "Section 4 Results" +priority: "P0" +placement_tier: "main" +conflicts: [] +metadata: + created_by: "vis-lens-reproducibility" + reviewed_by: "" + last_updated: "{YYYY-MM-DD}" +``` + +## Reproducibility Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef phase fill:#6a1b9a,stroke:#ba68c8,stroke-width:2px,color:#fff; + + subgraph Data ["DATA AVAILABILITY"] + D1["source: {path / DOI}
    ━━━━━━━━━━
    public / restricted / embargoed"] + end + + subgraph Preproc ["PREPROCESSING"] + P1["bin width / window: {N}
    normalization: {method}
    ━━━━━━━━━━
    documented: PASS / FAIL"] + end + + subgraph Library ["LIBRARY VERSION"] + L1["matplotlib=={version}
    ━━━━━━━━━━
    pinned: PASS / WARNING"] + end + + subgraph Seeds ["RANDOM SEEDS"] + S1["seeds: {list}
    ━━━━━━━━━━
    documented: PASS / FAIL / N/A"] + end + + subgraph CodeRef ["CODE REFERENCE"] + C1["script: {path}:{function}
    ━━━━━━━━━━
    traceable: PASS / WARNING"] + end + + subgraph Verdict ["VERDICT"] + V1["{OK / WARNING / FAIL}
    ━━━━━━━━━━
    {reason}"] + end + + D1 --> P1 + P1 --> L1 + L1 --> S1 + S1 --> C1 + C1 --> V1 + + class D1 stateNode; + class P1 handler; + class L1 cli; + class S1 output; + class C1 phase; + class V1 detector; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Teal | Data | Data availability status | +| Orange | Preprocessing | Parameter documentation check | +| Dark Blue | Library | Plotting library version pin | +| Teal | Seeds | Random seed documentation | +| Purple | Code Ref | Per-figure code traceability | +| Red | Verdict | OK / WARNING / FAIL assessment | +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table +- [ ] Every restricted/embargoed dataset is flagged as FAIL or WARNING +- [ ] Every histogram bin width and time-series smoothing window is audited +- [ ] Every stochastic figure has its seeds documented or flagged diff --git a/src/autoskillit/skills_extended/vis-lens-story-arc/SKILL.md b/src/autoskillit/skills_extended/vis-lens-story-arc/SKILL.md new file mode 100644 index 0000000000..15752060f5 --- /dev/null +++ b/src/autoskillit/skills_extended/vis-lens-story-arc/SKILL.md @@ -0,0 +1,226 @@ +--- +name: vis-lens-story-arc +categories: [vis-lens] +activate_deps: [mermaid] +description: "Create Narrative Story Arc visualization planning spec showing visual consistency across the report (same color = same model everywhere), logical figure progression, redundant figure detection, and narrative dependency between figures. Narrative lens answering \"Do the figures tell a coherent story across the report?\"" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Story Arc Lens - Analyzing figure narrative flow...'" + once: true +--- + +# Narrative Story Arc Visualization Lens + +**Philosophical Mode:** Narrative +**Primary Question:** "Do the figures tell a coherent story across the report?" +**Focus:** Visual consistency (same color = same model everywhere), logical figure progression + (each figure builds on the previous), no redundant figures (same data shown twice), + narrative dependency between figures (figure N motivates figure N+1) + +## Arguments + +`/autoskillit:vis-lens-story-arc [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Planning the figure sequence for a paper or technical report +- Checking that the same model/condition uses the same color across all figures +- Identifying redundant figures that show the same data twice +- Verifying that each figure's narrative position is justified +- User invokes `/autoskillit:vis-lens-story-arc` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/vis-lens-story-arc/` +- Assign the same color to two different models, conditions, or categories across figures +- Include a figure that presents the same data and conclusion as another figure already in the plan + +**ALWAYS:** +- Build a global color→entity mapping table across all figures; flag any inconsistency +- Number all figures and write a one-sentence narrative role for each +- Flag any figure whose narrative role duplicates another (same question, same data) +- Verify that figures appear in a logical dependency order (motivation → method → result → implication) +- The primary diagram output is a **figure-sequence flow diagram** (mermaid) showing narrative dependencies +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool — this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/vis-lens-story-arc/vis_spec_story_arc_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/vis-lens-story-arc/vis_spec_story_arc_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1–4; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Enumerate and Number All Figures + +List all planned figures in document order. For each figure record: +- Figure ID (fig-01, fig-02, ...) +- Title / description +- What data/question it addresses +- Which section it appears in (intro, method, results, discussion, appendix) + +### Step 2: Build Global Color Map + +Scan all figure descriptions and plotting code for color/palette assignments: +- Build table: { color_hex_or_name → entity_name } +- Check: is the same entity always the same color across all figures? +- FLAG INCONSISTENCY if entity A is blue in fig-02 but orange in fig-05 + +### Step 3: Detect Redundant Figures + +For each pair of figures, check: +- Do they display the same underlying data (same x/y variables, same conditions)? +- Do they answer the same question? +- If YES → flag as REDUNDANT; recommend merging or removing one + +### Step 4: Map Narrative Dependencies + +For each figure, identify: +- Which figure(s) it logically depends on (must be read first) +- Which figure(s) it motivates (enables interpretation of) +- Whether its narrative position (section) matches its dependency order + +### Step 5: Emit yaml:figure-spec Blocks and Sequence Diagram + +For each figure, emit one `yaml:figure-spec` fenced block. Then LOAD `/autoskillit:mermaid` +and create a **figure-sequence flow diagram** showing narrative dependencies between figures. + +--- + +## Output Template + +```markdown +# Narrative Story Arc Spec: {System / Experiment Name} + +**Lens:** Narrative Story Arc (Narrative) +**Question:** Do the figures tell a coherent story across the report? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} + +## Global Color Map + +| Color | Entity | Consistent Across Figures | +|-------|--------|--------------------------| +| #1f77b4 | Model A | PASS | +| #ff7f0e | Baseline | FAIL (blue in fig-03) | + +## Figure Sequence Summary + +| Figure | Section | Narrative Role | Depends On | Redundant? | +|--------|---------|----------------|------------|------------| +| fig-01 | Results | Establish main result | — | No | +| fig-02 | Results | Show ablation | fig-01 | No | + +## Figure Specs + +```yaml +# yaml:figure-spec — canonical schema (spec_version: "1.0") +figure_id: "fig-01-main-result" +figure_title: "Model A achieves state-of-the-art on all benchmarks" +spec_version: "1.0" +chart_type: "bar" +chart_type_fallback: "table" +perceptual_justification: "Grouped bars directly compare models; color consistent with fig-02 through fig-05." +data_source: "results/main.csv" +data_mapping: + x: "benchmark" + y: "score" + color: "model" + size: "" + facet: "" +layout: + width_inches: 6.0 + height_inches: 4.0 + dpi: 300 +stat_overlay: + type: "error_bar" + measure: "CI95" + n_seeds: 5 +annotations: ["Narrative role: introduce main result; motivates fig-02 ablation"] +anti_patterns: [] +palette: "okabe-ito" +format: "pdf" +target_dpi: 300 +library: "matplotlib" +report_section: "Section 4 Results" +priority: "P0" +placement_tier: "main" +conflicts: [] +metadata: + created_by: "vis-lens-story-arc" + reviewed_by: "" + last_updated: "{YYYY-MM-DD}" +``` + +## Figure Sequence Flow Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + + F1["fig-01: Main Result
    ━━━━━━━━━━
    Establish benchmark SOTA"] + F2["fig-02: Ablation
    ━━━━━━━━━━
    Component contribution"] + F3["fig-03: Scaling
    ━━━━━━━━━━
    Performance vs. size"] + F4["fig-04: Error Analysis
    ━━━━━━━━━━
    Failure mode taxonomy"] + + F1 --> F2 + F1 --> F3 + F2 --> F4 + + class F1 stateNode; + class F2,F3 handler; + class F4 output; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Teal | Anchor | Primary result figure | +| Orange | Derived | Figures that build on anchor | +| Dark Teal (output) | Terminal | Figures that conclude a narrative thread | +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table +- [ ] Global color map table is complete before creating the diagram +- [ ] Every color inconsistency has been flagged +- [ ] Every redundant figure pair has been identified diff --git a/src/autoskillit/skills_extended/vis-lens-temporal/SKILL.md b/src/autoskillit/skills_extended/vis-lens-temporal/SKILL.md new file mode 100644 index 0000000000..e4cbe1db23 --- /dev/null +++ b/src/autoskillit/skills_extended/vis-lens-temporal/SKILL.md @@ -0,0 +1,252 @@ +--- +name: vis-lens-temporal +categories: [vis-lens] +activate_deps: [mermaid] +description: "Create Temporal Dynamics visualization planning spec showing axis scaling (linear vs log), smoothing disclosure, epoch/step alignment, run aggregation (mean + variance bands), early-stopping markers, and wall-clock vs step-count x-axis. Temporal lens answering \"Are training dynamics shown clearly and honestly?\"" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Temporal Lens - Analyzing training curve representation...'" + once: true +--- + +# Temporal Dynamics Visualization Lens + +**Philosophical Mode:** Temporal +**Primary Question:** "Are training dynamics shown clearly and honestly?" +**Focus:** Axis Scaling (linear vs log), Smoothing Disclosure, Epoch/Step Alignment, + Run Aggregation (mean + variance bands), Early-Stopping Markers, + Wall-Clock vs Step-Count X-Axis + +## Arguments + +`/autoskillit:vis-lens-temporal [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Reviewing training curves, learning curves, or any metric-vs-step/epoch plots +- Checking whether x-axis units are consistent across compared runs +- Evaluating whether smoothing is disclosed and appropriate +- Planning multi-run aggregation with variance bands +- User invokes `/autoskillit:vis-lens-temporal` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/vis-lens-temporal/` +- Omit the CRITICAL flag when n_seeds == 1 for training curves — single-seed variance is unquantifiable +- Apply smoothing without disclosing the smoothing window or method +- Mix epoch-count and step-count x-axes on the same multi-run comparison without alignment + +**ALWAYS:** +- CRITICAL: if `n_seeds == 1` for any training curve, flag as **CRITICAL** — single-seed training curves cannot demonstrate stability or convergence robustness +- Disclose smoothing: state the EMA α or window size in the figure caption or axis label +- When comparing runs with different batch sizes or learning rate schedules, align on + wall-clock time OR total gradient steps (not raw epochs), and document the choice +- Use log-scale y-axis when loss spans more than one order of magnitude +- Mark early-stopping epoch/step as a vertical dashed line with label +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool — this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/vis-lens-temporal/vis_spec_temporal_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/vis-lens-temporal/vis_spec_temporal_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1–4; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Inventory Training Curves + +Scan experiment plan, context file, and codebase for: + +**Learning and Loss Curves** +- Find all learning curves, loss curves, metric-vs-step plots +- Look for: `train_loss`, `val_loss`, `reward`, `accuracy_vs_epoch`, `loss_curve`, `plt.plot` + +**Seed Count** +- Find n_seeds for each training run +- Look for: `n_seeds`, `num_seeds`, `seeds`, `SEEDS`, `random_state`, `runs` + +**Smoothing Calls** +- Detect whether smoothing is applied and whether it is disclosed +- Look for: `smooth`, `ema`, `rolling_mean`, `gaussian_filter`, `savgol_filter`, EMA α parameters + +**X-Axis Type** +- Determine whether x-axis is epoch-count, step-count, or wall-clock time +- Look for: `epochs`, `steps`, `global_step`, `time_elapsed`, x-axis labels + +**Early Stopping** +- Detect early-stopping usage and whether it is marked on the plot +- Look for: `early_stopping`, `patience`, `best_epoch`, `EarlyStopping` + +### Step 2: Determine Axis Scaling + +For each loss or metric curve, check the range: +- If loss spans more than one order of magnitude (max/min > 10): recommend log-scale y-axis +- If loss is bounded (e.g., accuracy 0–1): linear scale is acceptable +- Document the recommendation with the detected range + +### Step 3: Alignment Check + +For all multi-run comparisons: +- Verify that all compared runs use the same x-axis unit (epoch vs step vs time) +- Flag mismatches as WARNING: "Runs use mixed x-axis units — align on gradient steps or wall-clock time" +- Check batch size and learning rate schedule consistency across compared runs + +### Step 4: Emit yaml:figure-spec Blocks + +For each figure, emit one `yaml:figure-spec` fenced block with the `stat_overlay` +variance band filled in. Then LOAD `/autoskillit:mermaid` and create a temporal flow +diagram showing x-axis unit → scaling choice → smoothing annotation → variance band → verdict. + +--- + +## Output Template + +```markdown +# Temporal Dynamics Spec: {System / Experiment Name} + +**Lens:** Temporal Dynamics (Temporal) +**Question:** Are training dynamics shown clearly and honestly? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} +**n_seeds detected:** {N} + +## Temporal Audit Summary + +| Figure | n_seeds | x_axis | y_scale | smoothing | early_stop_marked | Status | +|--------|---------|--------|---------|-----------|-------------------|--------| +| {fig-01} | 1 | epoch | linear | none | no | CRITICAL | +| {fig-02} | 5 | step | log | EMA α=0.9 | yes | OK | + +## Figure Specs + +```yaml +# yaml:figure-spec — canonical schema (spec_version: "1.0") +figure_id: "fig-02-loss-curve" +figure_title: "Training Loss vs Gradient Steps" +spec_version: "1.0" +chart_type: "line" +chart_type_fallback: "scatter" +perceptual_justification: "Log-scale y-axis spans 2 orders of magnitude; variance band shows run stability." +data_source: "results/loss_curves.csv" +data_mapping: + x: "global_step" + y: "train_loss" + color: "run_id" + size: "" + facet: "" +layout: + width_inches: 6.0 + height_inches: 4.0 + dpi: 300 +stat_overlay: + type: "band" + measure: "CI95" + n_seeds: 5 +annotations: ["log-scale y; EMA α=0.9 disclosed; early-stop at step 4200"] +anti_patterns: ["ap-missing-variance-band"] +palette: "okabe-ito" +format: "pdf" +target_dpi: 300 +library: "matplotlib" +report_section: "Section 3 Training" +priority: "P1" +placement_tier: "main" +conflicts: [] +metadata: + created_by: "vis-lens-temporal" + reviewed_by: "" + last_updated: "{YYYY-MM-DD}" +``` + +## Temporal Dynamics Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + + subgraph XAxis ["X-AXIS UNIT"] + X1["epoch / step / wall-clock
    ━━━━━━━━━━
    {alignment status}"] + end + + subgraph Scale ["Y-AXIS SCALING"] + Y1["linear / log
    ━━━━━━━━━━
    {loss range: {min}–{max}}"] + end + + subgraph Smooth ["SMOOTHING"] + S1["none / EMA / rolling
    ━━━━━━━━━━
    {α or window disclosed: yes/no}"] + end + + subgraph Variance ["VARIANCE BAND"] + V1["CI95 / SD band
    ━━━━━━━━━━
    n_seeds = {N}"] + end + + subgraph Verdict ["VERDICT"] + VD1["{OK / WARNING / CRITICAL}
    ━━━━━━━━━━
    {reason}"] + end + + X1 --> Y1 + Y1 --> S1 + S1 --> V1 + V1 --> VD1 + + class X1 stateNode; + class Y1 cli; + class S1 handler; + class V1 output; + class VD1 detector; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Teal | X-Axis | Unit choice and alignment status | +| Dark Blue | Y-Axis | Scaling decision based on loss range | +| Orange | Smoothing | Disclosure status | +| Teal | Variance | Band type and seed count | +| Red | Verdict | OK / WARNING / CRITICAL assessment | +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table +- [ ] Every CRITICAL (n_seeds == 1) training curve is flagged +- [ ] Every smoothing call has its parameters disclosed in the figure spec +- [ ] Early-stopping markers are noted for all curves with early stopping diff --git a/src/autoskillit/skills_extended/vis-lens-uncertainty/SKILL.md b/src/autoskillit/skills_extended/vis-lens-uncertainty/SKILL.md new file mode 100644 index 0000000000..2471936c91 --- /dev/null +++ b/src/autoskillit/skills_extended/vis-lens-uncertainty/SKILL.md @@ -0,0 +1,263 @@ +--- +name: vis-lens-uncertainty +categories: [vis-lens] +activate_deps: [mermaid] +description: "Create Uncertainty Representation visualization planning spec showing error bar definitions, distribution-aware alternatives, and multi-seed variance protocols. Statistical lens answering \"How is uncertainty honestly represented?\"" +hooks: + PreToolUse: + - matcher: "*" + hooks: + - type: command + command: "echo 'Uncertainty Lens - Analyzing uncertainty representation...'" + once: true +--- + +# Uncertainty Representation Visualization Lens + +**Philosophical Mode:** Statistical +**Primary Question:** "How is uncertainty honestly represented?" +**Focus:** Error Bar Definitions, Distribution-Aware Alternatives, Multi-Seed Variance Protocols + +## Arguments + +`/autoskillit:vis-lens-uncertainty [context_path] [experiment_plan_path]` + +- **context_path** (optional positional arg 1) — Absolute path to a lens context file + containing IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. + If provided, read this file before beginning analysis to obtain structured context. + If omitted, discover context by exploring the CWD. +- **experiment_plan_path** (optional positional arg 2) — Absolute path to the full + experiment plan. If provided, read for complete experimental methodology and design. + If omitted, locate the experiment plan by exploring the CWD. + +## When to Use + +- Reviewing figures that show means, scores, or aggregate metrics without uncertainty +- Checking whether error bars are correctly defined (SD vs SE vs CI is not interchangeable) +- Evaluating whether n_seeds is sufficient to quantify variance +- Planning uncertainty overlays for distribution-heavy results (RL reward curves, ablations) +- User invokes `/autoskillit:vis-lens-uncertainty` + +## Critical Constraints + +**NEVER:** +- Modify any source code files +- Do not litter the codebase with useless comments, TODO markers, or explanatory annotations — the skill output and diagram speak for themselves +- Create files outside `{{AUTOSKILLIT_TEMP}}/vis-lens-uncertainty/` +- Conflate SD, SE, CI95, and PI95 — they have fundamentally different interpretations +- Omit the CRITICAL flag when n_seeds == 1; single-seed variance is unquantifiable + +**ALWAYS:** +- CRITICAL: if `n_seeds == 1`, flag the figure as **CRITICAL** — single-seed variance is unquantifiable and must be reported +- If `n_seeds >= 10`, prefer violin/box/strip over error bars to show the full distribution shape +- Label every uncertainty overlay with its exact measure (SD, SE, CI95, PI95) and n in the figure caption +- BEFORE creating any diagram, LOAD the `/autoskillit:mermaid` skill using the Skill tool - this is MANDATORY +- If the Skill tool cannot be used (disable-model-invocation) or refuses this invocation, do NOT proceed with diagram creation. Abort this step and omit the diagram from output. +- Write output to `{{AUTOSKILLIT_TEMP}}/vis-lens-uncertainty/vis_spec_uncertainty_{YYYY-MM-DD_HHMMSS}.md` (relative to the current working directory) +- After writing the file, emit the structured output token as **literal plain text** with no + markdown formatting on the token name (the adjudicator performs a regex match): + + ``` + diagram_path = /absolute/path/to/{{AUTOSKILLIT_TEMP}}/vis-lens-uncertainty/vis_spec_uncertainty_{...}.md + ``` + +--- + +## Analysis Workflow + +### Step 0: Parse optional arguments + +If positional arg 1 (context_path) is provided and the file exists, read it to obtain +IV/DV tables, H0/H1 hypotheses, controlled variables, and success criteria. If positional +arg 2 (experiment_plan_path) is provided and exists, read the experiment plan for full +methodology. Use this structured context as the foundation for Steps 1–4; skip the CWD +exploration for these fields if the context file supplies them. + +### Step 1: Inventory Figures and Seeds + +Scan experiment plan, context file, and codebase for: + +**Figures with Error-Bearing Quantities** +- Find all figures that aggregate over multiple runs, seeds, or samples +- Look for: `mean`, `average`, `std`, `stderr`, `ci`, `error_bar`, `errorbar`, `fill_between` + +**Seed Count** +- Find the number of random seeds or independent runs used +- Look for: `n_seeds`, `num_seeds`, `seeds`, `SEEDS`, `random_state`, `seed_list`, `runs` + +**Existing Uncertainty Representation** +- Find whether any uncertainty overlay exists at all +- Look for: `plt.fill_between`, `ax.errorbar`, `capsize`, `yerr`, `xerr`, `ci=`, `sd=`, `ci_band` + +**Claims About Variance** +- Find claims that assert robustness, stability, or statistical significance +- Look for: `significant`, `robust`, `stable`, `p-value`, `consistent`, `reproducible` + +### Step 2: Determine Correct Uncertainty Measure Per Figure + +For each figure that shows an aggregated quantity, determine the correct measure: + +**SD — Standard Deviation** +- Definition: spread of the data distribution (population variability), not inference error +- When to use: when the claim is about spread of the distribution, not precision of the mean +- Formula: `σ = sqrt(1/(n-1) × Σ(xᵢ - x̄)²)` + +**SE — Standard Error of the Mean** +- Definition: SD / √n — sampling error of the estimated mean +- When to use: when the claim is about how precisely the mean is estimated +- Formula: `SE = SD / √n` + +**CI 95% — Confidence Interval** +- Definition: mean ± t(0.975, n−1) × SE — inferential, sample-size dependent +- When to use: when making statistical inference claims; shrinks with larger n +- Formula: `CI = mean ± t(0.975, n−1) × (SD / √n)` + +**PI 95% — Prediction Interval** +- Definition: interval for a future single observation (wider than CI) +- When to use: when the claim is about where a new individual result will fall +- Formula: `PI = mean ± t(0.975, n−1) × SD × sqrt(1 + 1/n)` + +**Distribution-Aware Selection:** +- n_seeds == 1 → **CRITICAL**: variance cannot be quantified; flag this immediately +- n_seeds 2–4 → CI95 or SE; warn that the interval is unreliable at low n +- n_seeds 5–9 → error_bar with CI95 is acceptable; consider box plot +- n_seeds ≥ 10 → prefer violin/box/strip over error bars to show full distribution shape + +### Step 3: Flag Critical Cases + +For every figure where `n_seeds == 1`: +- Mark with severity: **CRITICAL** +- Reason: single-seed variance is unquantifiable; the result may not replicate +- Remediation: report results across ≥ 3 seeds minimum (5+ recommended) + +For figures where the wrong measure is used (e.g., SD labeled as CI, or CI claimed without stating n): +- Mark with severity: **WARNING** +- Document the specific mislabeling and the correct interpretation + +### Step 4: Emit yaml:figure-spec Blocks + +For each figure, emit one `yaml:figure-spec` fenced block (schema defined in vis-lens-chart-select) +with `stat_overlay` filled in. Then LOAD `/autoskillit:mermaid` and create the mermaid diagram. + +--- + +## Output Template + +```markdown +# Uncertainty Representation Spec: {System / Experiment Name} + +**Lens:** Uncertainty Representation (Statistical) +**Question:** How is uncertainty honestly represented? +**Date:** {YYYY-MM-DD} +**Scope:** {What was analyzed} +**n_seeds detected:** {N} + +## Uncertainty Measure Summary + +| Figure | n_seeds | Recommended Measure | Current Measure | Status | +|--------|---------|---------------------|-----------------|--------| +| {fig-01} | 1 | N/A — CRITICAL | none | CRITICAL | +| {fig-02} | 5 | CI95 | SE | WARNING — mislabeled | +| {fig-03} | 10 | violin | error_bar | WARNING — prefer distribution plot | +| {fig-04} | 5 | CI95 | CI95 | OK | + +## Figure Specs + +```yaml +# yaml:figure-spec — canonical schema (spec_version: "1.0") +figure_id: "fig-02-ablation-accuracy" +figure_title: "Ablation Study: Component Contribution" +spec_version: "1.0" +chart_type: "grouped-bar" +chart_type_fallback: "dot-plot" +perceptual_justification: "Position encoding for nominal × quantitative comparison." +data_source: "results/ablation.csv" +data_mapping: + x: "variant" + y: "accuracy" + color: "component" + size: "" + facet: "" +layout: + width_inches: 5.0 + height_inches: 3.5 + dpi: 300 +stat_overlay: + type: "error_bar" + measure: "CI95" + n_seeds: 5 +annotations: ["n=5 seeds; CI95 shown"] +anti_patterns: ["ap-bar-no-error"] +palette: "okabe-ito" +format: "pdf" +target_dpi: 300 +library: "matplotlib" +report_section: "Section 5 Ablation" +priority: "P1" +placement_tier: "main" +conflicts: [] +metadata: + created_by: "vis-lens-uncertainty" + reviewed_by: "" + last_updated: "{YYYY-MM-DD}" +``` + +## Uncertainty Representation Diagram + +```mermaid +%%{init: {'flowchart': {'nodeSpacing': 50, 'rankSpacing': 60, 'curve': 'basis'}}}%% +flowchart TB + %% CLASS DEFINITIONS %% + classDef cli fill:#1a237e,stroke:#7986cb,stroke-width:2px,color:#fff; + classDef stateNode fill:#004d40,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef handler fill:#e65100,stroke:#ffb74d,stroke-width:2px,color:#fff; + classDef output fill:#00695c,stroke:#4db6ac,stroke-width:2px,color:#fff; + classDef detector fill:#b71c1c,stroke:#ef5350,stroke-width:2px,color:#fff; + classDef gap fill:#ff6f00,stroke:#ffa726,stroke-width:2px,color:#000; + + subgraph Seeds ["SEED COUNT"] + N1["n_seeds = {N}
    ━━━━━━━━━━
    {adequacy assessment}"] + end + + subgraph Measure ["UNCERTAINTY MEASURE"] + M1["SD / SE / CI95 / PI95
    ━━━━━━━━━━
    {chosen measure + formula}"] + end + + subgraph Overlay ["OVERLAY TYPE"] + O1["{error_bar / violin / box}
    ━━━━━━━━━━
    {distribution-aware choice}"] + end + + subgraph Verdict ["VERDICT"] + V1["{OK / WARNING / CRITICAL}
    ━━━━━━━━━━
    {reason}"] + end + + N1 --> M1 + M1 --> O1 + O1 --> V1 + + class N1 stateNode; + class M1 cli; + class O1 output; + class V1 detector; +``` + +**Color Legend:** +| Color | Category | Description | +|-------|----------|-------------| +| Dark Teal | Seed Count | Number of independent runs | +| Dark Blue | Measure | Chosen uncertainty measure | +| Teal | Overlay | Distribution-aware display type | +| Red | Verdict | OK / WARNING / CRITICAL assessment | +``` + +--- + +## Pre-Diagram Checklist + +Before creating the diagram, verify: + +- [ ] LOADED `/autoskillit:mermaid` skill using the Skill tool +- [ ] Using ONLY classDef styles from the mermaid skill (no invented colors) +- [ ] Diagram will include a color legend table +- [ ] Every CRITICAL (n_seeds == 1) figure is flagged +- [ ] Every stat_overlay has both `measure` and `n_seeds` filled in diff --git a/src/autoskillit/skills_extended/write-recipe/SKILL.md b/src/autoskillit/skills_extended/write-recipe/SKILL.md index b0d8632a61..dd60b9ac9e 100644 --- a/src/autoskillit/skills_extended/write-recipe/SKILL.md +++ b/src/autoskillit/skills_extended/write-recipe/SKILL.md @@ -17,7 +17,7 @@ Format a workflow into a YAML recipe following the workflow schema. ## When to Use - **Standalone**: User wants to create a new recipe from scratch -- **Loaded by another skill**: Another skill (e.g., setup-project) loads this via the Skill tool to format a workflow it has already discovered +- **Loaded by another skill**: Another skill (e.g., setup-project) loads this via the Skill tool to format a workflow it has already discovered. ## Arguments (standalone mode) @@ -223,12 +223,23 @@ These skills ship with the autoskillit plugin and are invoked as `/autoskillit:< analyze-prs, arch-lens-c4-container, arch-lens-concurrency, arch-lens-data-lineage, arch-lens-deployment, arch-lens-development, arch-lens-error-resilience, arch-lens-module-dependency, arch-lens-operational, arch-lens-process-flow, arch-lens-repository-access, arch-lens-scenarios, arch-lens-security, arch-lens-state-lifecycle, -audit-arch, audit-bugs, audit-cohesion, audit-defense-standards, audit-friction, audit-impl, audit-tests, -close-kitchen, collapse-issues, design-guards, diagnose-ci, dry-walkthrough, elaborate-phase, -enrich-issues, implement-worktree, implement-worktree-no-merge, investigate, issue-splitter, make-arch-diag, -make-groups, make-plan, make-req, merge-pr, mermaid, migrate-recipes, open-integration-pr, open-kitchen, open-pr, pipeline-summary, -prepare-issue, process-issues, rectify, report-bug, resolve-failures, resolve-merge-conflicts, resolve-review, -retry-worktree, review-approach, review-pr, setup-project, smoke-task, sprint-planner, triage-issues, validate-audit, verify-diag, write-recipe +audit-arch, audit-bugs, audit-claims, audit-cohesion, audit-defense-standards, audit-friction, audit-impl, audit-tests, +bundle-local-report, close-kitchen, collapse-issues, compose-pr, compose-research-pr, design-guards, diagnose-ci, dry-walkthrough, elaborate-phase, +enrich-issues, exp-lens-benchmark-representativeness, exp-lens-causal-assumptions, exp-lens-comparator-construction, +exp-lens-error-budget, exp-lens-estimand-clarity, exp-lens-exploratory-confirmatory, exp-lens-fair-comparison, +exp-lens-governance-risk, exp-lens-iterative-learning, exp-lens-measurement-validity, exp-lens-pipeline-integrity, +exp-lens-randomization-blocking, exp-lens-reproducibility-artifacts, exp-lens-sensitivity-robustness, +exp-lens-severity-testing, exp-lens-unit-interference, exp-lens-validity-threats, exp-lens-variance-stability, +implement-experiment, implement-worktree, implement-worktree-no-merge, investigate, issue-splitter, make-arch-diag, +make-experiment-diag, make-groups, make-plan, make-req, merge-pr, mermaid, migrate-recipes, open-integration-pr, +open-kitchen, pipeline-summary, plan-experiment, plan-visualization, prepare-issue, prepare-pr, prepare-research-pr, process-issues, rectify, report-bug, +resolve-claims-review, resolve-design-review, resolve-failures, resolve-merge-conflicts, resolve-research-review, resolve-review, retry-worktree, review-approach, review-design, review-pr, review-research-pr, run-experiment, +scope, setup-project, smoke-task, sprint-planner, stage-data, triage-issues, troubleshoot-experiment, +validate-audit, verify-diag, +vis-lens-always-on, vis-lens-antipattern, vis-lens-caption-annot, vis-lens-chart-select, +vis-lens-color-access, vis-lens-domain-norms, vis-lens-figure-table, vis-lens-multi-compare, +vis-lens-reproducibility, vis-lens-story-arc, vis-lens-temporal, vis-lens-uncertainty, +generate-report, write-recipe ## Skill Reference Disambiguation diff --git a/src/autoskillit/smoke_utils.py b/src/autoskillit/smoke_utils.py index 4287b2f1b2..17123ecc5b 100644 --- a/src/autoskillit/smoke_utils.py +++ b/src/autoskillit/smoke_utils.py @@ -25,15 +25,6 @@ def check_bug_report_non_empty(workspace: str) -> dict[str, str]: return {"non_empty": "false"} -def check_cleanup_mode(defer_cleanup: str) -> dict[str, str]: - """Route helper: return deferred='true' when defer_cleanup is truthy, else 'false'. - - Used by check_defer_cleanup and check_defer_on_failure recipe steps to choose - between immediate per-pipeline cleanup and deferred batch cleanup. - """ - return {"deferred": "true" if defer_cleanup.lower() == "true" else "false"} - - def compute_domain_partitions( integration_branch: str, base_branch: str, cwd: str, output_dir: str ) -> dict[str, str]: @@ -54,6 +45,7 @@ def compute_domain_partitions( text=True, check=True, cwd=cwd, + timeout=60, ) files = [f for f in result.stdout.strip().split("\n") if f] partitions = partition_files_by_domain(files) @@ -80,6 +72,7 @@ def annotate_pr_diff(pr_number: str, cwd: str, output_dir: str) -> dict[str, str text=True, check=True, cwd=cwd, + timeout=60, ) diff = result.stdout out = Path(output_dir) @@ -112,6 +105,7 @@ def fetch_merge_queue_data(base_branch: str, cwd: str, output_dir: str) -> dict[ text=True, check=True, cwd=cwd, + timeout=60, ) info = json.loads(repo_info.stdout) owner = info["owner"]["login"] @@ -128,6 +122,7 @@ def fetch_merge_queue_data(base_branch: str, cwd: str, output_dir: str) -> dict[ capture_output=True, text=True, cwd=cwd, + timeout=60, ) if graphql_result.returncode != 0: entries: list = [] diff --git a/src/autoskillit/workspace/__init__.py b/src/autoskillit/workspace/__init__.py index ec10762836..8589bee3cb 100644 --- a/src/autoskillit/workspace/__init__.py +++ b/src/autoskillit/workspace/__init__.py @@ -4,6 +4,7 @@ All sub-modules depend only on autoskillit.core.*. """ +from autoskillit.core import SkillResolver from autoskillit.workspace.cleanup import ( CleanupResult, DefaultWorkspaceManager, @@ -36,7 +37,7 @@ resolve_ephemeral_root, ) from autoskillit.workspace.skills import ( - SkillResolver, + DefaultSkillResolver, bundled_skills_dir, bundled_skills_extended_dir, detect_project_local_overrides, @@ -64,6 +65,7 @@ "remove_git_worktree", "remove_worktree_sidecar", "RUNS_DIR", + "DefaultSkillResolver", "SkillResolver", "SkillsDirectoryProvider", "bundled_skills_dir", diff --git a/src/autoskillit/workspace/clone.py b/src/autoskillit/workspace/clone.py index f92533a30a..7b2bb189cb 100644 --- a/src/autoskillit/workspace/clone.py +++ b/src/autoskillit/workspace/clone.py @@ -18,10 +18,12 @@ import os import shutil import subprocess +from dataclasses import dataclass from datetime import datetime from pathlib import Path +from typing import Literal -from autoskillit.core import GENERATED_FILES, get_logger, is_protected_branch +from autoskillit.core import GENERATED_FILES, CloneResult, get_logger, is_protected_branch logger = get_logger(__name__) @@ -31,6 +33,19 @@ _NETWORK_URL_PREFIXES = ("https://", "http://", "git@", "git://", "ssh://", "file://") +def _is_not_file_url(url: str) -> bool: + """Return True if url is a usable clone source (not a self-referential file:// URL). + + file:// URLs are written by _ensure_origin_isolated to point at the clone directory + itself. Using them as a clone source would clone from the stale local working tree + instead of fetching fresh state from the real remote (the #817 bug). + + Local bare paths (no scheme) and real network URLs (https://, git@, etc.) are both + valid clone sources and are accepted. + """ + return bool(url) and not url.startswith("file://") + + def classify_remote_url(url: str) -> str: """Classify a git remote URL as 'network', 'bare_local', 'nonbare_local', 'none', or 'unknown'. @@ -183,17 +198,138 @@ def _add_or_set_upstream(clone_path: Path, url: str) -> None: ) -def _resolve_clone_source(source: Path, detected_url: str) -> str: - """Select the clone source for the proceed git-clone strategy. +def _ensure_origin_isolated(clone_path: Path, known_url: str) -> None: + """Rewrite origin to a self-referential file:// URL unconditionally. + + Claude Code reads 'origin' to resolve the project root; a file:// URL + cannot match any registered GitHub project, so the clone is treated as + a fresh project rooted at clone_path — not aliased to the source repo. + + This must fire for every successful clone regardless of URL availability. + The conditional guard that previously skipped this for clone_local and + empty-URL cases was the #377 compounding regression. + + After setting origin, calls _add_or_set_upstream with known_url only + if known_url is truthy — the real remote URL is stored in 'upstream' + when available. + """ + file_url = f"file://{clone_path}" + add_origin = subprocess.run( + ["git", "remote", "add", "origin", file_url], + cwd=str(clone_path), + capture_output=True, + ) + if add_origin.returncode != 0: + add_stderr = ( + add_origin.stderr.decode(errors="replace") + if isinstance(add_origin.stderr, bytes) + else add_origin.stderr + ) + if "already exists" not in add_stderr: + raise RuntimeError( + f"git remote add origin failed: {add_stderr.strip()}\nclone_path={clone_path}" + ) + # origin already exists (cloned from remote); rewrite it + set_origin = subprocess.run( + ["git", "remote", "set-url", "origin", file_url], + cwd=str(clone_path), + capture_output=True, + ) + if set_origin.returncode != 0: + set_origin_stderr = ( + set_origin.stderr.decode(errors="replace") + if isinstance(set_origin.stderr, bytes) + else set_origin.stderr + ) + raise RuntimeError( + f"git remote set-url origin failed: {set_origin_stderr.strip()}" + f"\nclone_path={clone_path}" + ) + if known_url: + _add_or_set_upstream(clone_path, known_url) + + +@dataclass(frozen=True) +class CloneSourceResolution: + """Result of probing a source directory for its clone-source remote URL. + + Tries 'upstream' first (real remote when source_dir is a previous autoskillit + clone), then 'origin'. Returns the first non-file:// URL found. + + reason: + "ok" — a usable remote URL was found and returned + "no_origin" — no origin remote is configured in this repo + "timeout" — subprocess.run timed out (30 s) + "error" — subprocess returned non-zero exit code + url: the remote URL (empty string unless reason == "ok") + stderr: subprocess stderr (empty unless reason == "error") + """ + + reason: Literal["ok", "no_origin", "timeout", "error"] + url: str + stderr: str + + +def _probe_single_remote(source: Path, remote_name: str) -> CloneSourceResolution: + """Run ``git remote get-url `` in source and return a typed result. + + Shared by _probe_clone_source_url for each candidate remote name. + """ + _no_remote_markers = ("no such remote",) + try: + result = subprocess.run( + ["git", "remote", "get-url", remote_name], + cwd=str(source), + capture_output=True, + text=True, + timeout=30, + ) + except subprocess.TimeoutExpired: + return CloneSourceResolution(reason="timeout", url="", stderr="") + except OSError as exc: + return CloneSourceResolution(reason="error", url="", stderr=str(exc)) + + if result.returncode != 0: + stderr = result.stderr.strip() + if any(m in stderr.lower() for m in _no_remote_markers): + return CloneSourceResolution(reason="no_origin", url="", stderr=stderr) + return CloneSourceResolution(reason="error", url="", stderr=stderr) - Always uses the remote URL when source has a configured origin. - Falls back to the local filesystem path only when no remote origin - is configured. Never falls back based on branch availability or - network reachability — when a remote URL is known, it is always - used as the clone source. The clone_local strategy bypasses this - function entirely (shutil.copytree, always local). + url = result.stdout.strip() + if not url: + return CloneSourceResolution(reason="no_origin", url="", stderr="") + return CloneSourceResolution(reason="ok", url=url, stderr="") + + +def _probe_clone_source_url(source: Path) -> CloneSourceResolution: + """Probe source for the best remote URL to use as the git clone source. + + Avoids cloning from stale file:// local state: + 1. Try 'upstream' — when source_dir is a previous autoskillit clone, + _ensure_origin_isolated sets upstream to the real remote and + origin to a self-referential file:// URL. Using upstream avoids cloning + from the stale local filesystem (fix for #817). + 2. Try 'origin' — if upstream is absent or is itself a file:// URL, falls + back to origin, which is the real remote in a fresh dev checkout. + 3. If neither yields a non-file:// URL, returns origin's result so callers + get the appropriate error (no_origin / error / local path as-is). + + file:// URLs are explicitly excluded because _ensure_origin_isolated writes + them to point at the clone directory itself — a stale local reference. + Local bare paths (no scheme) and real network URLs are both accepted. """ - return detected_url if detected_url else str(source) + last_result: CloneSourceResolution | None = None + for remote_name in ("upstream", "origin"): + result = _probe_single_remote(source, remote_name) + last_result = result + if result.reason == "ok" and _is_not_file_url(result.url): + return result + + # No non-file:// URL found — return the last probed result (origin) rather + # than re-invoking _probe_single_remote, which would be a redundant subprocess. + if last_result is not None: + return last_result + return _probe_single_remote(source, "origin") def clone_repo( @@ -202,7 +338,7 @@ def clone_repo( branch: str = "", strategy: str = "", remote_url: str = "", -) -> dict[str, str]: +) -> CloneResult: """Clone source_dir into ../autoskillit-runs/-/. Used as a run_python entry point in pipeline recipes. Raises ValueError if @@ -221,9 +357,10 @@ def clone_repo( committed state only) or strategy="clone_local" (copytree — includes working-tree changes). - When using the ``proceed`` strategy, the git clone is always performed from the - remote URL when source_dir has a configured origin. Falls back to the local path - only when no remote origin is configured. If a branch is requested that does not + When using the ``proceed`` strategy, the git clone is performed from the remote + URL. If origin is not configured, the subprocess times out, or the probe returns + a non-zero exit code, RuntimeError is raised — use ``strategy="clone_local"`` + to clone a repo without a remote origin. If a branch is requested that does not exist on the remote, git clone will fail with RuntimeError — use ``strategy="clone_local"`` to clone a local-only branch. The ``clone_local`` strategy always copies directly from the local filesystem path regardless of @@ -233,7 +370,13 @@ def clone_repo( reading its remote URL. See module docstring for the full SOURCE ISOLATION contract. Returns: - On success: {"clone_path": str, "source_dir": str, "remote_url": str} + On success: { + "clone_path": str, + "source_dir": str, + "remote_url": str, + "clone_source_type": "remote" | "local", + "clone_source_reason": str, + } On uncommitted changes (strategy=""): { "uncommitted_changes": "true", "source_dir": str, @@ -289,32 +432,31 @@ def clone_repo( clone_path = runs_parent / f"{run_name}-{timestamp}" runs_parent.mkdir(parents=True, exist_ok=True) - try: - _pre_url_result = subprocess.run( - ["git", "remote", "get-url", "origin"], - cwd=str(source), - capture_output=True, - text=True, - timeout=30, - ) - except subprocess.TimeoutExpired: - _pre_url_result = None - detected_url = ( - _pre_url_result.stdout.strip() - if _pre_url_result is not None and _pre_url_result.returncode == 0 - else "" - ) + resolution = _probe_clone_source_url(source) if strategy == "clone_local": shutil.copytree(str(source), str(clone_path)) logger.info("clone_created_local_copy", clone_path=str(clone_path), source=str(source)) + source_type: Literal["remote", "local"] = "local" + source_reason = "strategy_clone_local" else: - clone_source = _resolve_clone_source(source, detected_url) + if resolution.reason != "ok": + logger.warning( + "clone_origin_probe_failed", + source=str(source), + reason=resolution.reason, + stderr=resolution.stderr, + ) + raise RuntimeError( + f"clone_origin_probe_failed: reason={resolution.reason};" + f" source={source}; stderr={resolution.stderr};" + f' if a local-only clone is intended, pass strategy="clone_local".' + ) cmd = ["git", "clone"] if branch: cmd += ["--branch", branch] - cmd += [clone_source, str(clone_path)] - result = subprocess.run(cmd, capture_output=True, text=True) + cmd += [resolution.url, str(clone_path)] + result = subprocess.run(cmd, capture_output=True, text=True, timeout=300) if result.returncode != 0: raise RuntimeError( "git clone failed:" @@ -322,31 +464,16 @@ def clone_repo( f"\nstdout: {result.stdout.strip()}" ) logger.info("clone_created", clone_path=str(clone_path), source=str(source), branch=branch) + source_type = "remote" + source_reason = "ok" - # Use caller-supplied override if provided; fall back to pre-clone detected URL - effective_url = remote_url if remote_url else detected_url + # Use caller-supplied override if provided; fall back to probed URL + effective_url = remote_url if remote_url else resolution.url - # Isolate the clone: store the real URL in 'upstream', set 'origin' to a local file:// URL - # that is unique to this clone path. Claude Code reads 'origin' to resolve the project root; - # a file:// URL cannot match any registered GitHub project, so the clone is treated as a - # fresh project rooted at clone_path — not aliased to the source repo. - if effective_url: - _add_or_set_upstream(clone_path, effective_url) - set_origin = subprocess.run( - ["git", "remote", "set-url", "origin", f"file://{clone_path}"], - cwd=str(clone_path), - capture_output=True, - ) - if set_origin.returncode != 0: - set_origin_stderr = ( - set_origin.stderr.decode(errors="replace") - if isinstance(set_origin.stderr, bytes) - else set_origin.stderr - ) - raise RuntimeError( - f"git remote set-url origin failed: {set_origin_stderr.strip()}" - f"\nclone_path={clone_path}" - ) + # Unconditionally isolate the clone: set 'origin' to file:// for every + # successful clone regardless of URL availability. This closes the #377 compounding + # regression where the isolation rewrite was skipped when effective_url was empty. + _ensure_origin_isolated(clone_path, effective_url) # Decontaminate: untrack inherited generated files ls_gen = subprocess.run( @@ -391,7 +518,13 @@ def clone_repo( except FileNotFoundError: pass - return {"clone_path": str(clone_path), "source_dir": str(source), "remote_url": effective_url} + return { + "clone_path": str(clone_path), + "source_dir": str(source), + "remote_url": effective_url, + "clone_source_type": source_type, + "clone_source_reason": source_reason, + } def remove_clone(clone_path: str, keep: str = "false") -> dict[str, str]: @@ -520,6 +653,7 @@ def push_to_remote( cwd=clone_path, capture_output=True, text=True, + timeout=120, ) if push_result.returncode != 0: stderr_text = push_result.stderr.strip() @@ -559,7 +693,7 @@ def clone_repo( branch: str = "", strategy: str = "", remote_url: str = "", - ) -> dict[str, str]: + ) -> CloneResult: return clone_repo( source_dir, run_name, branch=branch, strategy=strategy, remote_url=remote_url ) diff --git a/src/autoskillit/workspace/clone_registry.py b/src/autoskillit/workspace/clone_registry.py index c1198d1470..92d0cd2a72 100644 --- a/src/autoskillit/workspace/clone_registry.py +++ b/src/autoskillit/workspace/clone_registry.py @@ -5,7 +5,7 @@ removes only success-status clones. Registry file format: - {"clones": [{"path": "/abs/path/to/clone", "status": "success|error"}]} + {"clones": [{"path": "/abs/path", "status": "success|error", "owner": "kitchen-uuid"}]} """ from __future__ import annotations @@ -14,9 +14,9 @@ import json from collections.abc import Callable from pathlib import Path -from typing import Any, Literal +from typing import IO, Any, Literal -from autoskillit.core import atomic_write, get_logger +from autoskillit.core import atomic_write, get_logger, resolve_temp_dir _log = get_logger(__name__) @@ -24,40 +24,129 @@ _DEFAULT_REGISTRY_NAME = "clone-cleanup-registry.json" -def _resolve_registry_path(registry_path: str) -> Path: +def _resolve_registry_path(registry_path: str, temp_dir: Path | None = None) -> Path: if registry_path: return Path(registry_path) - # Default location mirrors the project temp convention. atomic_write creates - # parent dirs; no need to call ensure_project_temp (which requires project_dir). - return Path.cwd() / ".autoskillit" / "temp" / _DEFAULT_REGISTRY_NAME + base = temp_dir if temp_dir is not None else resolve_temp_dir(Path.cwd(), None) + return base / _DEFAULT_REGISTRY_NAME + + +def _entry_matches_owner(entry: dict[str, str], owner: str | None) -> bool: + if owner is None: + return True + return entry.get("owner") == owner + + +class CloneRegistry: + """Locked context manager for clone-cleanup-registry.json. + + Acquires fcntl.LOCK_EX on __enter__, reads _entries from disk. + Writes _entries back atomically on __exit__ iff any mutation occurred. + Releases the lock unconditionally on __exit__ (even on exception). + + All mutation methods set _dirty = True so __exit__ knows to persist. + """ + + def __init__(self, path: Path) -> None: + self._path = path + self._lock_path = path.with_suffix(".lock") + self._entries: list[dict[str, str]] = [] + self._dirty: bool = False + self._lock_file: IO[str] | None = None + + def __enter__(self) -> CloneRegistry: + self._lock_path.parent.mkdir(parents=True, exist_ok=True) + fh = open(self._lock_path, "w") + try: + fcntl.flock(fh, fcntl.LOCK_EX) + except BaseException: + fh.close() + raise + self._lock_file = fh + if self._path.exists(): + try: + self._entries = json.loads(self._path.read_text()).get("clones", []) + except (json.JSONDecodeError, OSError, AttributeError) as exc: + _log.warning("clone_registry: could not read %s: %s", self._path, exc) + self._entries = [] + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_val: BaseException | None, + exc_tb: object, + ) -> None: + try: + if self._dirty: + atomic_write( + self._path, + json.dumps({"clones": self._entries}, indent=2), + ) + finally: + if self._lock_file is not None: + self._lock_file.close() # releases fcntl advisory lock + + def append(self, path: str, status: str, owner: str) -> None: + self._entries.append({"path": path, "status": status, "owner": owner}) + self._dirty = True + + def candidates(self, owner: str | None) -> tuple[list[str], list[str]]: + """Return (to_delete, to_preserve) paths scoped to owner. + + to_delete: status=success entries matching owner filter. + to_preserve: status=error entries matching owner filter. + Entries belonging to other owners are not reported in either list. + """ + to_delete: list[str] = [] + to_preserve: list[str] = [] + for entry in self._entries: + if owner is not None and entry.get("owner") != owner: + continue + path = entry.get("path") + if path is None: + continue + if entry.get("status") == "success": + to_delete.append(path) + else: + to_preserve.append(path) + return to_delete, to_preserve + + def prune_deleted(self, deleted_paths: set[str]) -> None: + """Remove successfully-deleted entries from the in-memory list. + + Entries not in deleted_paths (failed deletes, other owners) are retained. + Sets _dirty = True so __exit__ persists the pruned list. + """ + before = len(self._entries) + self._entries = [e for e in self._entries if e["path"] not in deleted_paths] + if len(self._entries) < before: + self._dirty = True def register_clone( clone_path: str, status: CloneStatus, + owner: str, registry_path: str = "", + temp_dir: Path | None = None, ) -> dict[str, str]: """Append a clone entry to the registry. Safe for parallel callers — holds an exclusive advisory lock across the entire read-modify-write sequence.""" - path = _resolve_registry_path(registry_path) - lock_path = path.with_suffix(".lock") - lock_path.parent.mkdir(parents=True, exist_ok=True) - with open(lock_path, "w") as lock_file: - fcntl.flock(lock_file, fcntl.LOCK_EX) - existing: list[dict[str, str]] = [] - if path.exists(): - try: - existing = json.loads(path.read_text()).get("clones", []) - except (json.JSONDecodeError, OSError) as exc: - _log.warning("clone_registry: could not read %s: %s", path, exc) - existing.append({"path": clone_path, "status": status}) - atomic_write(path, json.dumps({"clones": existing}, indent=2)) + if owner == "": + raise ValueError("owner is required") + path = _resolve_registry_path(registry_path, temp_dir) + with CloneRegistry(path) as reg: + reg.append(clone_path, status, owner) return {"registered": "true", "registry_path": str(path)} -def read_registry(registry_path: str = "") -> list[dict[str, str]]: +def read_registry( + registry_path: str = "", + temp_dir: Path | None = None, +) -> list[dict[str, str]]: """Return all registry entries, or [] if the file does not exist.""" - path = _resolve_registry_path(registry_path) + path = _resolve_registry_path(registry_path, temp_dir) if not path.exists(): return [] try: @@ -69,34 +158,72 @@ def read_registry(registry_path: str = "") -> list[dict[str, str]]: def cleanup_candidates( registry_path: str = "", + temp_dir: Path | None = None, + owner: str | None = None, ) -> tuple[list[str], list[str]]: """Return (to_delete, to_preserve) path lists from the registry. to_delete — clones with status='success' (safe to remove) to_preserve — clones with status='error' (preserve for investigation) + + When owner is provided, only entries belonging to that owner are considered. + Entries without an 'owner' field (legacy orphans) are only visible when + owner is None (all-owners mode). """ - entries = read_registry(registry_path) - to_delete = [e["path"] for e in entries if e.get("status") == "success" and "path" in e] - to_preserve = [e["path"] for e in entries if e.get("status") == "error" and "path" in e] + entries = read_registry(registry_path, temp_dir) + to_delete = [ + e["path"] + for e in entries + if e.get("status") == "success" and "path" in e and _entry_matches_owner(e, owner) + ] + to_preserve = [ + e["path"] + for e in entries + if e.get("status") == "error" and "path" in e and _entry_matches_owner(e, owner) + ] return to_delete, to_preserve def batch_delete( registry_path: str, remove_fn: Callable[[str, str], dict[str, str]], + temp_dir: Path | None = None, + owner: str | None = None, ) -> dict[str, Any]: - """Read registry and delete success-status clones via remove_fn. + """Read registry and delete success-status clones via remove_fn, then prune registry. + + Three-phase sequence: + 1. Read candidates under lock (short hold — no I/O inside). + 2. Delete outside lock (slow filesystem I/O). + 3. Prune succeeded entries under lock (re-reads fresh, capturing concurrent appends). Calls remove_fn(path, "false") for each success clone. Error clones are preserved. Returns {"deleted": [...], "delete_failures": [...], "preserved": [...]}. + + When owner is provided, only entries belonging to that owner are considered. + Pass owner=None to operate on all entries (escape hatch mode). """ - to_delete, to_preserve = cleanup_candidates(registry_path) + path = _resolve_registry_path(registry_path, temp_dir) + + # Phase 1: read candidates under lock (short hold — no I/O inside) + with CloneRegistry(path) as reg: + to_delete, to_preserve = reg.candidates(owner) + + # Phase 2: delete outside lock (slow filesystem I/O) deleted: list[str] = [] delete_failures: list[dict[str, str]] = [] - for path in to_delete: - result = remove_fn(path, "false") + for clone_path in to_delete: + result = remove_fn(clone_path, "false") if result.get("removed") == "true": - deleted.append(path) + deleted.append(clone_path) else: - delete_failures.append({"path": path, "reason": result.get("reason", "unknown")}) + delete_failures.append({"path": clone_path, "reason": result.get("reason", "unknown")}) + + # Phase 3: prune successfully-deleted entries (re-reads fresh under lock, + # capturing any register_clone writes that arrived during Phase 2) + if deleted: + with CloneRegistry(path) as reg: + reg.prune_deleted(set(deleted)) + _, to_preserve = reg.candidates(owner) + return {"deleted": deleted, "delete_failures": delete_failures, "preserved": to_preserve} diff --git a/src/autoskillit/workspace/session_skills.py b/src/autoskillit/workspace/session_skills.py index 2a0cd8c007..5fd98ef47b 100644 --- a/src/autoskillit/workspace/session_skills.py +++ b/src/autoskillit/workspace/session_skills.py @@ -19,12 +19,17 @@ PACK_REGISTRY, ClaudeDirectoryConventions, PackDef, + SkillResolver, SkillSource, ValidatedAddDir, atomic_write, get_logger, ) -from autoskillit.workspace.skills import SkillInfo, SkillResolver, detect_project_local_overrides +from autoskillit.workspace.skills import ( + DefaultSkillResolver, + SkillInfo, + detect_project_local_overrides, +) if TYPE_CHECKING: from autoskillit.config import AutomationConfig @@ -101,6 +106,45 @@ def _remove_disable_model_invocation(content: str) -> str: return f"---\n{fm_text}\n---\n{body}" +_ORDER_UP_LINE = re.compile(r"^.*%%ORDER_UP%%.*\n?", re.MULTILINE) + + +def _strip_marker_from_body(content: str, marker: str = "%%ORDER_UP%%") -> str: + """Remove completion marker lines from SKILL.md body content.""" + m = _FM_PATTERN.match(content) + if not m: + return _ORDER_UP_LINE.sub("", content) if marker in content else content + fm_text = m.group(1) + body = m.group(2) + if marker not in body: + return content + body = _ORDER_UP_LINE.sub("", body) + return f"---\n{fm_text}\n---\n{body}" + + +_ACTIVATE_DEPS_PATTERN = re.compile(r"^activate_deps:\s*\[([^\]]*)\]", re.MULTILINE) + + +def _parse_activate_deps(content: str) -> list[str]: + """Extract activate_deps list from SKILL.md frontmatter. + + Parses ``activate_deps: [item1, item2]`` from YAML frontmatter. + Each item is either a PACK_REGISTRY key (pack dependency) or a + bare skill name (individual dependency). + """ + m = _FM_PATTERN.match(content) + if not m: + return [] + fm_text = m.group(1) + match = _ACTIVATE_DEPS_PATTERN.search(fm_text) + if not match: + return [] + items = match.group(1).strip() + if not items: + return [] + return [item.strip() for item in items.split(",") if item.strip()] + + def _is_skill_disabled( skill_info: SkillInfo, disabled: list[str], @@ -171,11 +215,63 @@ def _should_inject_skill( return True +def _build_pack_index(provider: SkillsDirectoryProvider) -> dict[str, set[str]]: + """Build a pack-name → set of member skill names index from the provider.""" + index: dict[str, set[str]] = {} + for skill in provider.list_skills(): + for cat in skill.categories: + index.setdefault(cat, set()).add(skill.name) + return index + + +def compute_skill_closure( + skill_name: str, + provider: SkillsDirectoryProvider, +) -> frozenset[str]: + """Return the transitive activate_deps closure for a skill, including the skill itself. + + Returns ``frozenset()`` if ``skill_name`` does not resolve to a real skill. + Pack-name dependencies are expanded to all pack members. Unknown deps are silently dropped. + """ + if provider.resolver.resolve(skill_name) is None: + return frozenset() + pack_index: dict[str, set[str]] | None = None + visited: set[str] = set() + resolved: set[str] = set() + queue: list[str] = [skill_name] + while queue: + name = queue.pop() + if name in visited: + continue + visited.add(name) + info = provider.resolver.resolve(name) + if info is None: + continue + try: + content = info.path.read_text() + except OSError: + continue + resolved.add(name) + for dep in _parse_activate_deps(content): + if dep in PACK_REGISTRY: + if pack_index is None: + pack_index = _build_pack_index(provider) + for member in pack_index.get(dep, ()): + if member not in visited: + queue.append(member) + elif dep not in visited: + queue.append(dep) + return frozenset(resolved) + + class SkillsDirectoryProvider: """Provides bundled skill content with tier-aware frontmatter injection.""" - def __init__(self) -> None: - self._resolver = SkillResolver() + def __init__(self, temp_dir_relpath: str = ".autoskillit/temp") -> None: + if "\n" in temp_dir_relpath or ": " in temp_dir_relpath: + raise ValueError(f"temp_dir_relpath is YAML-unsafe: {temp_dir_relpath!r}") + self._resolver = DefaultSkillResolver() + self._temp_dir_relpath = temp_dir_relpath @property def resolver(self) -> SkillResolver: @@ -191,6 +287,9 @@ def get_skill_content(self, name: str, *, gated: bool = True) -> str: - gated=True → ensure disable-model-invocation: true is present - gated=False → return unmodified content (cook session or Tier 1) + + Substitutes ``{{AUTOSKILLIT_TEMP}}`` with the configured temp dir relpath. + Tier 1 skills (which contain no placeholder) are unaffected. """ skill_info = self._resolver.resolve(name) if skill_info is None: @@ -198,7 +297,7 @@ def get_skill_content(self, name: str, *, gated: bool = True) -> str: content = skill_info.path.read_text() if gated: content = _inject_disable_model_invocation(content) - return content + return content.replace("{{AUTOSKILLIT_TEMP}}", self._temp_dir_relpath) class DefaultSessionSkillManager: @@ -212,6 +311,13 @@ def __init__( self._provider = provider self._root = ephemeral_root + def compute_skill_closure(self, skill_name: str) -> frozenset[str]: + """Return the transitive activate_deps closure for ``skill_name``. + + See :func:`compute_skill_closure` for semantics. + """ + return compute_skill_closure(skill_name, self._provider) + def init_session( self, session_id: str, @@ -220,6 +326,7 @@ def init_session( config: AutomationConfig | None = None, project_dir: Path | None = None, recipe_packs: frozenset[str] | None = None, + allow_only: frozenset[str] | None = None, ) -> ValidatedAddDir: """Create ephemeral skill dir for session_id. @@ -279,6 +386,9 @@ def init_session( skills_base = session_skills_dir / _SKILLS_SUBDIR skills_base.mkdir(parents=True, exist_ok=True) for skill_info in self._provider.list_skills(): + if allow_only is not None and skill_info.name not in allow_only: + _log.debug("init_session_allow_only_skip", skill=skill_info.name) + continue if not _should_inject_skill( skill_info, overrides=overrides, @@ -299,29 +409,68 @@ def init_session( atomic_write(skill_dir / "SKILL.md", content) return ValidatedAddDir(path=str(session_skills_dir)) - def activate_tier2(self, session_id: str, skill_name: str) -> bool: - """Remove disable-model-invocation from the ephemeral copy of skill_name. + def activate_skill_deps(self, session_id: str, skill_name: str) -> bool: + """Remove disable-model-invocation from a skill and its declared dependencies. - Returns True if the file was found and updated, False otherwise. + Reads ``activate_deps`` from the target skill's frontmatter and transitively + activates all dependencies: + - Pack names (keys in PACK_REGISTRY) -> activate all session skills with that category + - Skill names -> activate the specific named skill + + Cycle-safe: tracks already-activated skills to prevent infinite recursion. """ - if ( - not session_id - or "\x00" in session_id - or "/" in session_id - or "\\" in session_id - or session_id in (".", "..") - ): - raise ValueError(f"Invalid session_id: {session_id!r}") - if not skill_name or "/" in skill_name or "\\" in skill_name or skill_name in (".", ".."): - raise ValueError(f"Invalid skill_name: {skill_name!r}") + for value, label in ((session_id, "session_id"), (skill_name, "skill_name")): + if not value or any(c in value for c in ("/", "\\", "\x00")): + raise ValueError(f"Invalid {label}: {value!r}") + if value in (".", ".."): + raise ValueError(f"Invalid {label}: {value!r}") + + activated: set[str] = set() + return self._activate_with_deps(session_id, skill_name, activated) + + def _activate_with_deps( + self, session_id: str, skill_name: str, activated: set[str], *, _is_root: bool = True + ) -> bool: + """Activate a single skill and recursively activate its dependencies.""" + if skill_name in activated: + return False + activated.add(skill_name) + skill_md = self._root / session_id / _SKILLS_SUBDIR / skill_name / "SKILL.md" if not skill_md.exists(): return False + content = skill_md.read_text() - updated = _remove_disable_model_invocation(content) - atomic_write(skill_md, updated) + new_content = _remove_disable_model_invocation(content) + if not _is_root: + new_content = _strip_marker_from_body(new_content) + if new_content != content: + atomic_write(skill_md, new_content) + + deps = _parse_activate_deps(content) + for dep in deps: + if dep in PACK_REGISTRY: + self._activate_pack_deps(session_id, dep, activated) + else: + self._activate_with_deps(session_id, dep, activated, _is_root=False) + return True + def _activate_pack_deps(self, session_id: str, pack_name: str, activated: set[str]) -> None: + """Activate all session skills whose category matches *pack_name*.""" + skills_base = self._root / session_id / _SKILLS_SUBDIR + if not skills_base.is_dir(): + return + for skill_dir in sorted(skills_base.iterdir()): + if not skill_dir.is_dir(): + continue + name = skill_dir.name + if name in activated: + continue + info = self._provider.resolver.resolve(name) + if info and pack_name in info.categories: + self._activate_with_deps(session_id, name, activated, _is_root=False) + def cleanup_stale(self, max_age_seconds: int = 259200) -> int: """Remove session dirs not accessed within max_age_seconds. diff --git a/src/autoskillit/workspace/skills.py b/src/autoskillit/workspace/skills.py index 6b0e9bfa76..4edff4112b 100644 --- a/src/autoskillit/workspace/skills.py +++ b/src/autoskillit/workspace/skills.py @@ -89,7 +89,7 @@ def _skill_info_from_frontmatter(name: str, source: SkillSource, skill_path: Pat ) -class SkillResolver: +class DefaultSkillResolver: """List bundled skills from both the skills/ and skills_extended/ directories.""" def __init__(self) -> None: diff --git a/src/autoskillit/workspace/worktree.py b/src/autoskillit/workspace/worktree.py index 31a9849df3..f194a815a1 100644 --- a/src/autoskillit/workspace/worktree.py +++ b/src/autoskillit/workspace/worktree.py @@ -11,10 +11,14 @@ import shutil from pathlib import Path -from autoskillit.core import CleanupResult, SubprocessRunner +from autoskillit.core import CleanupResult, SubprocessRunner, resolve_temp_dir WORKTREES_DIR = "worktrees" -_SIDECAR_ROOT = (".autoskillit", "temp", "worktrees") + + +def _sidecar_root_for(temp_dir: Path) -> Path: + """Return the sidecar root directory for worktrees (``/worktrees``).""" + return temp_dir / WORKTREES_DIR async def list_git_worktrees( @@ -86,16 +90,24 @@ async def remove_git_worktree( return result -def remove_worktree_sidecar(project_root: Path, worktree_name: str) -> CleanupResult: - """Remove the .autoskillit/temp/worktrees// sidecar directory. +def remove_worktree_sidecar( + project_root: Path, + worktree_name: str, + *, + temp_dir: Path | None = None, +) -> CleanupResult: + """Remove the ``/worktrees//`` sidecar directory. This directory is written by implement-worktree and implement-worktree-no-merge - skills to store the base-branch name. It lives inside the project root, not inside + skills to store the base-branch name. It lives inside the project root + (under the configured temp dir, default ``.autoskillit/temp``), not inside the worktree, so git worktree remove does not clean it up. + ``temp_dir`` defaults to the canonical ``/.autoskillit/temp``. Never raises. """ result = CleanupResult() - sidecar = project_root.joinpath(*_SIDECAR_ROOT, worktree_name) + resolved_temp = temp_dir if temp_dir is not None else resolve_temp_dir(project_root, None) + sidecar = _sidecar_root_for(resolved_temp) / worktree_name sidecar_str = str(sidecar) if not sidecar.exists(): result.skipped.append(sidecar_str) diff --git a/tests/CLAUDE.md b/tests/CLAUDE.md index f4861d38ff..395a44bd8f 100644 --- a/tests/CLAUDE.md +++ b/tests/CLAUDE.md @@ -128,6 +128,14 @@ tests/ │ ├── test_core_terminal_table.py │ ├── test_type_constants.py │ └── test_types_structure.py +├── docs/ # Documentation integrity tests +│ ├── __init__.py +│ ├── test_banned_phrases.py # Prohibited phrases not present in documentation +│ ├── test_doc_counts.py # Counts of tools, skills, hooks, recipes (regression guard) +│ ├── test_doc_index.py # Doc file index integrity +│ ├── test_doc_links.py # Internal and external link validity +│ ├── test_filename_naming.py # Documentation filename conventions +│ └── test_glossary_spelling.py # Glossary term spelling consistency ├── execution/ # Subprocess integration + session tests │ ├── __init__.py │ ├── test_anomaly_detection.py diff --git a/tests/_subprocess_ready.py b/tests/_subprocess_ready.py new file mode 100644 index 0000000000..a8654acc43 --- /dev/null +++ b/tests/_subprocess_ready.py @@ -0,0 +1,70 @@ +"""Shared subprocess readiness helper for integration tests. + +This is the ONLY approved mechanism for waiting on MCP subprocess readiness +in tests. Inline ``stderr.readline()`` polls for log tokens are forbidden and +enforced by ``tests/execution/test_readiness_helper_contract.py``. + +Import as:: + + from tests._subprocess_ready import wait_for_subprocess_ready + +Usage:: + + proc = subprocess.Popen(...) + sentinel_path = readiness_sentinel_path(proc.pid) + wait_for_subprocess_ready(proc, sentinel_path, deadline_s=10.0) + # subprocess is now ready — safe to interact with it +""" + +from __future__ import annotations + +import subprocess +import time +from pathlib import Path + + +def wait_for_subprocess_ready( + proc: subprocess.Popen, + sentinel_path: Path, + *, + deadline_s: float = 10.0, + poll_interval_s: float = 0.05, +) -> None: + """Wait until ``sentinel_path`` exists or ``proc`` exits; raise on deadline. + + Polls the filesystem at a fixed interval. Does NOT read proc.stdout/stderr. + + :param proc: The subprocess to monitor. + :param sentinel_path: Path to the sentinel file written by the subprocess + lifespan once it is fully initialized and ready to accept signals. + :param deadline_s: Maximum seconds to wait. Raise ``TimeoutError`` on expiry. + :param poll_interval_s: Polling interval in seconds. + + :raises TimeoutError: If the sentinel does not appear within ``deadline_s``. + :raises RuntimeError: If the process exits before the sentinel appears + (includes captured stderr for diagnostics). + """ + deadline = time.monotonic() + deadline_s + while time.monotonic() < deadline: + if sentinel_path.exists(): + return + exit_code = proc.poll() + if exit_code is not None: + # Process died before writing sentinel — capture stderr for diagnosis + try: + remaining_stderr = ( + proc.stderr.read().decode(errors="replace") if proc.stderr else "" + ) + except Exception as exc: + remaining_stderr = f"" + raise RuntimeError( + f"Subprocess exited with code {exit_code} before readiness sentinel appeared.\n" + f"Sentinel path: {sentinel_path}\n" + f"Stderr: {remaining_stderr!r}" + ) + time.sleep(poll_interval_s) + raise TimeoutError( + f"Subprocess readiness sentinel not seen within {deadline_s}s.\n" + f"Sentinel path: {sentinel_path}\n" + f"Process still running: {proc.poll() is None}" + ) diff --git a/tests/arch/_helpers.py b/tests/arch/_helpers.py index 8303cff4ea..39d250f404 100644 --- a/tests/arch/_helpers.py +++ b/tests/arch/_helpers.py @@ -132,6 +132,28 @@ def visit_Call(self, node: ast.Call) -> None: f"'{var_name}' -- use structlog kwargs instead", ) + # Rule ARCH-008 (visitor): start_linux_tracing must not receive a raw .pid Attribute + # Resolve function name: bare Name or trailing Attribute.attr + called_name: str | None = None + if isinstance(func, ast.Name): + called_name = func.id + elif isinstance(func, ast.Attribute): + called_name = func.attr + if called_name == "start_linux_tracing": + for kw in node.keywords: + if ( + kw.arg == "target" + and isinstance(kw.value, ast.Attribute) + and kw.value.attr == "pid" + ): + self._add( + node, + _RULE["ARCH-008"], + "start_linux_tracing(target=.pid) passes a raw .pid attribute; " + "use resolve_trace_target() or trace_target_from_pid() to get a " + "TraceTarget first (issue #806)", + ) + self.generic_visit(node) def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None: @@ -206,6 +228,54 @@ def _is_mcp_tool_decorator(node: ast.expr) -> bool: return False +def _has_toplevel_except_exception(func_node: ast.AsyncFunctionDef | ast.FunctionDef) -> bool: + """Return True if the function has a top-level try/except Exception. + + A leading gate-check guard (if ... return/raise ...) before the try is permitted, + matching the canonical gated-tool pattern used across the server layer. + """ + body = func_node.body + # Skip docstring + stmts = [ + s for s in body if not isinstance(s, ast.Expr) or not isinstance(s.value, ast.Constant) + ] + if not stmts: + return False + # Skip leading guard `if ... return` statements (gate checks, early validation exits) + idx = 0 + while idx < len(stmts): + s = stmts[idx] + if ( + isinstance(s, ast.If) + and len(s.body) == 1 + and isinstance(s.body[0], (ast.Return, ast.Raise)) + and not s.orelse + ): + idx += 1 + else: + break + if idx >= len(stmts): + return False + first = stmts[idx] + if not isinstance(first, ast.Try): + return False + # Check that at least one handler catches Exception or BaseException + for handler in first.handlers: + if handler.type is None: # bare except: + return True + if isinstance(handler.type, ast.Name) and handler.type.id in ( + "Exception", + "BaseException", + ): + return True + if isinstance(handler.type, ast.Attribute) and handler.type.attr in ( + "Exception", + "BaseException", + ): + return True + return False + + def _runtime_import_froms(path: Path) -> list[ast.ImportFrom]: """Return ImportFrom nodes not inside a TYPE_CHECKING guard.""" tree = ast.parse(path.read_text()) diff --git a/tests/arch/_rules.py b/tests/arch/_rules.py index 6a9ee2cc4a..3917b413c5 100644 --- a/tests/arch/_rules.py +++ b/tests/arch/_rules.py @@ -59,17 +59,21 @@ class RuleDescriptor: "_cook.py", "_init_helpers.py", "_onboarding.py", - "_stale_check.py", + "_timed_input.py", + "_update.py", + "_update_checks.py", "app.py", "_doctor.py", "_marketplace.py", "_prompts.py", "_workspace.py", "branch_protection_guard.py", - "pretty_output.py", - "quota_check.py", + "open_kitchen_guard.py", + "pretty_output_hook.py", + "quota_guard.py", + "quota_post_hook.py", "remove_clone_guard.py", - "skill_cmd_check.py", + "skill_cmd_guard.py", "skill_command_guard.py", } ) @@ -79,12 +83,15 @@ class RuleDescriptor: _BROAD_EXCEPT_EXEMPT = frozenset( { "_onboarding.py", - "pretty_output.py", - "quota_check.py", + "open_kitchen_guard.py", + "pretty_output_hook.py", + "quota_guard.py", + "quota_post_hook.py", "remove_clone_guard.py", - "skill_cmd_check.py", + "session_start_hook.py", + "skill_cmd_guard.py", "skill_command_guard.py", - "token_summary_appender.py", + "token_summary_hook.py", } ) @@ -98,7 +105,7 @@ class RuleDescriptor: } ) -# ── RULES tuple — 7 entries ─────────────────────────────────────────────────── +# ── RULES tuple — 8 entries ─────────────────────────────────────────────────── RULES: tuple[RuleDescriptor, ...] = ( RuleDescriptor( @@ -221,6 +228,27 @@ class RuleDescriptor: severity="high", defense_standard="DS-007", ), + RuleDescriptor( + rule_id="ARCH-008", + name="no-raw-pid-to-start-linux-tracing", + lens="process-flow", + description=( + "start_linux_tracing() must receive a TraceTarget, not a raw .pid attribute. " + "Call resolve_trace_target() (or trace_target_from_pid()) first." + ), + rationale=( + "anyio.open_process() returns the PID of any PTY wrapper (script(1)), not the " + "workload binary. Passing proc.pid directly to start_linux_tracing causes the " + "tracer to observe the wrapper (~2 MB RSS, 1 thread) instead of claude, producing " + "silently wrong telemetry in proc_trace.jsonl, sessions.jsonl, and GitHub issue " + "bodies. TraceTarget encapsulates provenance (comm, starttime_ticks) and can only " + "be produced by a resolver that walks descendants to the workload. This rule " + "prevents the bug class from returning via copy-paste. (Issue #806)" + ), + exemptions=frozenset(), + severity="error", + defense_standard="DS-008", + ), ) _RULE: dict[str, RuleDescriptor] = {r.rule_id: r for r in RULES} diff --git a/tests/arch/test_ast_rules.py b/tests/arch/test_ast_rules.py index a75cff943c..1a93b8220c 100644 --- a/tests/arch/test_ast_rules.py +++ b/tests/arch/test_ast_rules.py @@ -414,6 +414,7 @@ def test_no_raw_claude_list_construction() -> None: ("_llm_triage.py", "_triage_batch"), ("commands.py", "build_interactive_cmd"), ("commands.py", "build_headless_cmd"), + ("commands.py", "build_headless_resume_cmd"), ("_init_helpers.py", "_is_plugin_installed"), ("_doctor.py", "_check_mcp_server_registered"), } @@ -571,3 +572,199 @@ def test_get_logger_no_bind() -> None: ) return pytest.fail("get_logger() function not found in core/logging.py") + + +# ── Kill-path structural guards (1f) ───────────────────────────────────────── + + +def test_no_direct_async_kill_process_tree_outside_executor() -> None: + """No src file may call async_kill_process_tree or kill_process_tree + outside the designated kill helper functions. + + Allowed call sites: + - src/autoskillit/execution/_process_kill.py (defines the helpers) + - execute_termination_action in src/autoskillit/execution/process.py + - BaseException handler in run_managed_async in process.py (cleanup path) + - run_managed_sync in process.py (sync cleanup path) + """ + allowed_files = { + SRC_ROOT / "execution" / "_process_kill.py", + SRC_ROOT / "execution" / "process.py", + } + violations: list[str] = [] + + for py_file in sorted(SRC_ROOT.rglob("*.py")): + if py_file in allowed_files: + continue + try: + tree = ast.parse(py_file.read_text()) + except SyntaxError: + continue + for node in ast.walk(tree): + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Name) + and node.func.id in {"async_kill_process_tree", "kill_process_tree"} + ): + violations.append( + f" {py_file.relative_to(SRC_ROOT.parent.parent)}:{node.lineno}: " + f"direct call to {node.func.id}() outside allowed files" + ) + elif ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr in {"async_kill_process_tree", "kill_process_tree"} + ): + violations.append( + f" {py_file.relative_to(SRC_ROOT.parent.parent)}:{node.lineno}: " + f"direct call to .{node.func.attr}() outside allowed files" + ) + + assert not violations, ( + "Direct async_kill_process_tree/kill_process_tree calls found outside allowed files.\n" + "All kill calls must go through execute_termination_action in process.py:\n" + + "\n".join(violations) + ) + + +def test_no_direct_termination_dispatch_ifelse_in_run_managed() -> None: + """run_managed_async must not contain an if/elif chain that inspects + TerminationReason.* or signals.process_exited directly. + + The dispatch must be delegated to decide_termination_action. + """ + process_py = SRC_ROOT / "execution" / "process.py" + tree = ast.parse(process_py.read_text()) + + # Find run_managed_async function body + run_managed_node: ast.AsyncFunctionDef | None = None + for node in ast.walk(tree): + if isinstance(node, ast.AsyncFunctionDef) and node.name == "run_managed_async": + run_managed_node = node + break + + assert run_managed_node is not None, "run_managed_async not found in process.py" + + # Walk the function body and detect any If node whose test references + # TerminationReason.* attribute or signals.process_exited + violations: list[str] = [] + for node in ast.walk(run_managed_node): + if not isinstance(node, ast.If): + continue + test = node.test + # Detect: timeout_scope.cancelled_caught (allowed), but TerminationReason.* is banned + # Walk the test expression for TerminationReason attribute access + for subnode in ast.walk(test): + if ( + isinstance(subnode, ast.Attribute) + and isinstance(subnode.value, ast.Name) + and subnode.value.id == "TerminationReason" + ): + violations.append( + f"process.py:{getattr(node, 'lineno', '?')}: " + f"run_managed_async uses if/elif on TerminationReason.{subnode.attr} " + "— dispatch must go through decide_termination_action" + ) + # Detect: signals.process_exited in if test + if ( + isinstance(subnode, ast.Attribute) + and isinstance(subnode.value, ast.Name) + and subnode.value.id == "signals" + and subnode.attr == "process_exited" + ): + violations.append( + f"process.py:{getattr(node, 'lineno', '?')}: " + "run_managed_async branches on signals.process_exited directly " + "— dispatch must go through decide_termination_action" + ) + + assert not violations, ( + "run_managed_async must not inspect TerminationReason or signals.process_exited directly." + "\nUse decide_termination_action to make the kill decision:\n" + "\n".join(violations) + ) + + +# --------------------------------------------------------------------------- +# ARCH-008: no-raw-pid-to-start-linux-tracing — Test 1.9 calibration tests +# --------------------------------------------------------------------------- + + +def test_arch008_detects_raw_pid_attribute_passed_as_target(tmp_path: Path) -> None: + """ARCH-008 calibration: start_linux_tracing(target=proc.pid) is a violation. + + The .pid attribute on an anyio/subprocess Process object is the wrapper PID when + PTY mode is active. Passing it directly to start_linux_tracing caused issue #806. + """ + f = tmp_path / "bad.py" + f.write_text( + "from autoskillit.execution.linux_tracing import start_linux_tracing\n" + "start_linux_tracing(target=proc.pid, config=cfg, tg=tg)\n" + ) + violations = _scan(f) + arch008 = [v for v in violations if v.rule_id == "ARCH-008"] + assert arch008, ( + "ARCH-008 must fire when start_linux_tracing is called with target=.pid. " + f"All violations found: {violations}" + ) + assert "pid" in arch008[0].message.lower() or "raw" in arch008[0].message.lower(), ( + f"ARCH-008 violation message must mention the raw pid issue. Got: {arch008[0].message!r}" + ) + + +def test_arch008_accepts_resolve_trace_target_result(tmp_path: Path) -> None: + """ARCH-008 calibration: start_linux_tracing(target=resolve_trace_target(...)) is allowed. + + Calling resolve_trace_target() returns a TraceTarget (not a raw int), so it + satisfies the type contract. + """ + f = tmp_path / "good.py" + f.write_text( + "from autoskillit.execution.linux_tracing import (\n" + " start_linux_tracing, resolve_trace_target)\n" + "target = resolve_trace_target(\n" + " root_pid=proc.pid, expected_basename='claude')\n" + "start_linux_tracing(target=target, config=cfg, tg=tg)\n" + ) + violations = _scan(f) + arch008 = [v for v in violations if v.rule_id == "ARCH-008"] + assert not arch008, ( + f"ARCH-008 must NOT fire when target is a Name (variable), not an Attribute. " + f"Violations found: {arch008}" + ) + + +def test_arch008_accepts_trace_target_from_pid_result(tmp_path: Path) -> None: + """ARCH-008 calibration: start_linux_tracing(target=trace_target_from_pid(...)) is allowed.""" + f = tmp_path / "good_direct.py" + f.write_text( + "from autoskillit.execution.linux_tracing import (\n" + " start_linux_tracing, trace_target_from_pid)\n" + "target = trace_target_from_pid(proc.pid)\n" + "start_linux_tracing(target=target, config=cfg, tg=tg)\n" + ) + violations = _scan(f) + arch008 = [v for v in violations if v.rule_id == "ARCH-008"] + assert not arch008, ( + f"ARCH-008 must NOT fire when target is a Name variable, not an Attribute. " + f"Violations found: {arch008}" + ) + + +def test_no_raw_pid_attr_to_start_linux_tracing() -> None: + """ARCH-008 (Test 1.9): no production file passes .pid as target to start_linux_tracing. + + Enforces the PTY wrapper tracer PID immunity contract from issue #806: + any call site that tries to pass proc.pid (or any .pid Attribute) directly + to start_linux_tracing is caught in CI before it ships. + """ + violations = [] + for src_file in _SOURCE_FILES: + file_violations = _scan(src_file) + arch008 = [v for v in file_violations if v.rule_id == "ARCH-008"] + violations.extend(arch008) + + assert not violations, ( + "ARCH-008: start_linux_tracing called with a raw .pid attribute as target. " + "Use resolve_trace_target() (PTY mode) or trace_target_from_pid() (direct mode) " + "to get a TraceTarget first (issue #806):\n" + "\n".join(f" {v}" for v in violations) + ) diff --git a/tests/arch/test_cli_decomposition.py b/tests/arch/test_cli_decomposition.py index e17b66fc65..c65bfa735e 100644 --- a/tests/arch/test_cli_decomposition.py +++ b/tests/arch/test_cli_decomposition.py @@ -81,9 +81,9 @@ def test_skill_command_guard_no_silent_broad_except(): # CD4 def test_quota_check_no_silent_broad_except(): - """CC-2: quota_check.py must not have bare 'except Exception: sys.exit(0)'. + """CC-2: quota_guard.py must not have bare 'except Exception: sys.exit(0)'. Each except must be narrowed to specific errors or log before approving.""" - src = (SRC_ROOT / "hooks" / "quota_check.py").read_text() + src = (SRC_ROOT / "hooks" / "quota_guard.py").read_text() tree = ast.parse(src) violations = [] for node in ast.walk(tree): @@ -91,5 +91,5 @@ def test_quota_check_no_silent_broad_except(): if _is_bare_except_exception(node) and _body_is_only_sys_exit(node): violations.append(node.lineno) assert not violations, ( - f"quota_check.py has silent broad except at lines {violations} -- CC-2 fix required" + f"quota_guard.py has silent broad except at lines {violations} -- CC-2 fix required" ) diff --git a/tests/arch/test_doctor_readonly.py b/tests/arch/test_doctor_readonly.py new file mode 100644 index 0000000000..5000117b82 --- /dev/null +++ b/tests/arch/test_doctor_readonly.py @@ -0,0 +1,62 @@ +"""AST guard: run_doctor() must not perform filesystem mutations (REQ-DOCTOR-READONLY). + +Doctor is a diagnostic command — it reads and reports but must never modify +the filesystem. Any destructive call (shutil.rmtree, os.remove, _clear_plugin_cache, …) +in run_doctor() or its direct callees within _doctor.py is a structural violation. +""" + +from __future__ import annotations + +import ast +from pathlib import Path + +SRC = Path(__file__).resolve().parents[2] / "src" / "autoskillit" + +FORBIDDEN_WRITE_CALLS = frozenset( + { + "shutil.rmtree", + "os.remove", + "os.unlink", + "Path.unlink", + "Path.rmdir", + "_clear_plugin_cache", + } +) + + +def _get_call_name(node: ast.Call) -> str: + """Extract dotted call name from an ast.Call node.""" + if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name): + return f"{node.func.value.id}.{node.func.attr}" + if isinstance(node.func, ast.Name): + return node.func.id + return "" + + +def _find_function(tree: ast.Module, name: str) -> ast.FunctionDef | None: + """Find a top-level FunctionDef by name.""" + for node in ast.walk(tree): + if isinstance(node, ast.FunctionDef) and node.name == name: + return node + return None + + +def test_doctor_performs_no_writes() -> None: + """REQ-DOCTOR-READONLY: run_doctor() must not perform filesystem mutations.""" + source = (SRC / "cli" / "_doctor.py").read_text() + tree = ast.parse(source) + + func = _find_function(tree, "run_doctor") + assert func is not None, "run_doctor() not found in _doctor.py" + + violations: list[str] = [] + for node in ast.walk(func): + if isinstance(node, ast.Call): + call_name = _get_call_name(node) + if call_name in FORBIDDEN_WRITE_CALLS: + violations.append(f"{call_name} at line {node.lineno}") + + assert not violations, ( + "run_doctor() must be read-only — found forbidden write call(s):\n" + + "\n".join(f" {v}" for v in violations) + ) diff --git a/tests/arch/test_file_size_budgets.py b/tests/arch/test_file_size_budgets.py new file mode 100644 index 0000000000..f035c8bd60 --- /dev/null +++ b/tests/arch/test_file_size_budgets.py @@ -0,0 +1,32 @@ +"""Per-file source size budgets (REQ-FILE-001). + +Enforces line-count budgets for source modules where the audit identified an +oversized file and a planned split. Each entry below is the post-split +ceiling, not the natural starting size. +""" + +from __future__ import annotations + +from pathlib import Path + + +def test_pretty_output_below_budget() -> None: + """REQ-FILE-001: hooks/pretty_output_hook.py must stay under 350 lines after + the §4 split (audit finding 8.3). Each split formatter module must stay + under its own budget.""" + src = Path(__file__).resolve().parents[2] / "src" / "autoskillit" / "hooks" + budgets = { + "pretty_output_hook.py": 350, + "_fmt_primitives.py": 200, + "_fmt_execution.py": 300, + "_fmt_status.py": 250, + "_fmt_recipe.py": 300, + } + too_big: list[str] = [] + for name, limit in budgets.items(): + f = src / name + assert f.exists(), f"Required module missing: {name}" + n = sum(1 for _ in f.read_text().splitlines()) + if n > limit: + too_big.append(f"{name}: {n} > {limit}") + assert not too_big, "\n".join(too_big) diff --git a/tests/arch/test_import_linter_contracts.py b/tests/arch/test_import_linter_contracts.py new file mode 100644 index 0000000000..cd6dc4089d --- /dev/null +++ b/tests/arch/test_import_linter_contracts.py @@ -0,0 +1,38 @@ +"""Tests verifying import-linter contract documentation. + +REQ-ARCH-007: IL-003 must document the pipeline → config exception inline. +""" + +from __future__ import annotations + +from pathlib import Path + + +def test_il003_pipeline_config_exception_documented() -> None: + """REQ-ARCH-007: IL-003 must contain an inline `# EXCEPTION` comment + explaining why `autoskillit.config` is omitted from its forbidden_modules + list (pipeline.context holds AutomationConfig as the DI wiring point). + Validates that the exception is captured in source rather than tribal.""" + pyproject_path = Path(__file__).resolve().parents[2] / "pyproject.toml" + raw = pyproject_path.read_text() + lines = raw.splitlines() + in_block = False + block_lines: list[str] = [] + for line in lines: + if 'name = "L1 pipeline does not import L2 or L3"' in line: + in_block = True + if in_block: + block_lines.append(line) + if line.strip().startswith("[[") and len(block_lines) > 1: + block_lines.pop() + break + block = "\n".join(block_lines) + assert "# EXCEPTION" in block or "# Exception" in block, ( + "IL-003 must inline-document the pipeline → config exception. " + "Add a `# EXCEPTION: pipeline.context owns AutomationConfig` " + "comment above forbidden_modules in the IL-003 contract." + ) + fm_section = block.split("forbidden_modules", 1)[1].split("]", 1)[0] + assert '"autoskillit.config"' not in fm_section, ( + "IL-003 forbidden_modules must continue to omit autoskillit.config." + ) diff --git a/tests/arch/test_import_paths.py b/tests/arch/test_import_paths.py index 68830e6123..e5c5cab67a 100644 --- a/tests/arch/test_import_paths.py +++ b/tests/arch/test_import_paths.py @@ -239,16 +239,16 @@ def test_req_imp_006_prompts_no_gate_state_import() -> None: def test_req_imp_007_pretty_output_no_private_recipe_api_import() -> None: - """hooks/pretty_output.py TYPE_CHECKING must not use recipe._api. + """hooks/pretty_output_hook.py TYPE_CHECKING must not use recipe._api. ListRecipesResult and LoadRecipeResult are re-exported via autoskillit.recipe.__all__. Importing from the private recipe._api sub-module bypasses the canonical surface (P14-1). """ - path = SRC / "hooks" / "pretty_output.py" + path = SRC / "hooks" / "pretty_output_hook.py" for mod, in_tc in _parse_imports(path): if in_tc and mod == "autoskillit.recipe._api": pytest.fail( - "hooks/pretty_output.py TYPE_CHECKING must use " + "hooks/pretty_output_hook.py TYPE_CHECKING must use " "'from autoskillit.recipe import ...' " "instead of 'from autoskillit.recipe._api import ...' (P14-1). " "Both ListRecipesResult and LoadRecipeResult are in recipe.__all__." @@ -289,3 +289,52 @@ def test_req_imp_009_session_skills_no_config_settings_import() -> None: "instead of 'from autoskillit.config.settings import AutomationConfig' " "(P14-4). AutomationConfig is available via autoskillit.config.__all__." ) + + +# --------------------------------------------------------------------------- +# REQ-IMP-007: server/ and cli/ files must not import cross-package sub-modules +# (Finding 13.3) — extends REQ-IMP-001 coverage to L3 layers +# --------------------------------------------------------------------------- + + +def test_req_imp_007_server_cli_no_unauthorized_cross_submodule_imports() -> None: + """REQ-IMP-007: every file in server/ and cli/ must obey the same + cross-package submodule rule that REQ-IMP-001 enforces for the L0–L2 + layers, with a small explicit allowlist: + + server/_factory.py — Composition Root, may import any layer + server/git.py — REQ-IMP-005 exemption + server/tools_kitchen.py — REQ-IMP-006 ban (covered separately) + cli/app.py — REQ-IMP-004 exemption (Typer composition) + cli/_cook.py — allowlisted composition boundary + cli/_workspace.py — allowlisted composition boundary + + Every other file in server/ and cli/ must import only: + autoskillit.core, autoskillit.config, autoskillit.pipeline, + autoskillit.{own_pkg}, and gateway-level (`autoskillit.X`, not + `autoskillit.X.Y`) imports of other packages. + """ + allowlist = { + Path("server/_factory.py"), + Path("server/git.py"), + Path("server/tools_kitchen.py"), + Path("cli/app.py"), + Path("cli/_cook.py"), + Path("cli/_workspace.py"), + } + forbidden_pkgs = {"execution", "workspace", "recipe", "migration"} + violations: list[str] = [] + for pkg in ("server", "cli"): + for f in (SRC / pkg).rglob("*.py"): + rel = f.relative_to(SRC) + if rel in allowlist or "__pycache__" in rel.parts: + continue + for mod, in_tc in _parse_imports(f): + if in_tc: + continue + if mod.startswith("autoskillit.") and mod.count(".") >= 2: + parts = mod.split(".") + other_pkg = parts[1] + if other_pkg in forbidden_pkgs and other_pkg != pkg: + violations.append(f"{rel} → {mod}") + assert not violations, "REQ-IMP-007 violations:\n" + "\n".join(violations) diff --git a/tests/arch/test_layer_enforcement.py b/tests/arch/test_layer_enforcement.py index 0cf3351a5d..7159f372cc 100644 --- a/tests/arch/test_layer_enforcement.py +++ b/tests/arch/test_layer_enforcement.py @@ -816,27 +816,41 @@ def test_native_tool_guard_absent_from_hook_registry(): def test_hook_config_filename_and_dir_match_quota_check(): - """quota_check.py must agree with tools_kitchen on the hook config path constants. + """Hook config path constants must agree across all readers and the server writer. - The server (tools_kitchen.py) writes the config; the hook (quota_check.py) reads it. - They must agree on both the filename and the directory components, or the quota hook - will silently fail to read its configuration. + The server (tools_kitchen.py) writes the config; all hooks read it. + Two reader contracts must hold: + - _fmt_primitives._HOOK_CONFIG_PATH_COMPONENTS == server.helpers._hook_config_path + - _hook_settings.py constants == server.helpers constants """ import importlib + from pathlib import Path + from autoskillit.hooks._fmt_primitives import _HOOK_CONFIG_PATH_COMPONENTS from autoskillit.server.helpers import ( _HOOK_CONFIG_FILENAME, _HOOK_DIR_COMPONENTS, + _hook_config_path, + ) + + root = Path("/tmp/project-root") + expected = root.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS) + actual = _hook_config_path(root) + + assert actual == expected, ( + f"server.helpers._hook_config_path({root!r})={actual!r} " + f"does not match path derived from " + f"_fmt_primitives._HOOK_CONFIG_PATH_COMPONENTS={expected!r}" ) - quota_mod = importlib.import_module("autoskillit.hooks.quota_check") + settings_mod = importlib.import_module("autoskillit.hooks._hook_settings") - assert quota_mod.HOOK_CONFIG_FILENAME == _HOOK_CONFIG_FILENAME, ( - f"quota_check.HOOK_CONFIG_FILENAME={quota_mod.HOOK_CONFIG_FILENAME!r} " + assert settings_mod.HOOK_CONFIG_FILENAME == _HOOK_CONFIG_FILENAME, ( + f"_hook_settings.HOOK_CONFIG_FILENAME={settings_mod.HOOK_CONFIG_FILENAME!r} " f"does not match tools_kitchen._HOOK_CONFIG_FILENAME={_HOOK_CONFIG_FILENAME!r}" ) - assert quota_mod.HOOK_DIR_COMPONENTS == _HOOK_DIR_COMPONENTS, ( - f"quota_check.HOOK_DIR_COMPONENTS={quota_mod.HOOK_DIR_COMPONENTS!r} " + assert settings_mod.HOOK_DIR_COMPONENTS == _HOOK_DIR_COMPONENTS, ( + f"_hook_settings.HOOK_DIR_COMPONENTS={settings_mod.HOOK_DIR_COMPONENTS!r} " f"does not match tools_kitchen._HOOK_DIR_COMPONENTS={_HOOK_DIR_COMPONENTS!r}" ) @@ -844,26 +858,63 @@ def test_hook_config_filename_and_dir_match_quota_check(): # ── Tool metadata single source of truth ────────────────────────────────────── -def test_tool_categories_covers_all_tools() -> None: - """Every tool in GATED_TOOLS | HEADLESS_TOOLS | FREE_RANGE_TOOLS appears - in exactly one TOOL_CATEGORIES group, and no extra names exist.""" - from autoskillit.core import ( - FREE_RANGE_TOOLS, - GATED_TOOLS, - HEADLESS_TOOLS, - TOOL_CATEGORIES, - ) +def test_display_categories_sync() -> None: + """Both _DISPLAY_CATEGORIES copies cover all registered tools exactly.""" + from autoskillit.cli._cook import _DISPLAY_CATEGORIES as cook_cats + from autoskillit.core import FREE_RANGE_TOOLS, GATED_TOOLS, HEADLESS_TOOLS + from autoskillit.server.tools_kitchen import _DISPLAY_CATEGORIES as kitchen_cats all_registered = GATED_TOOLS | HEADLESS_TOOLS | FREE_RANGE_TOOLS - categorized: set[str] = set() - for _name, tools in TOOL_CATEGORIES: - for t in tools: - assert t not in categorized, f"Duplicate in TOOL_CATEGORIES: {t}" - categorized.add(t) - assert categorized == all_registered, ( - f"Missing from TOOL_CATEGORIES: {all_registered - categorized}\n" - f"Extra in TOOL_CATEGORIES: {categorized - all_registered}" - ) + + for label, cats in (("kitchen", kitchen_cats), ("cook", cook_cats)): + flat: list[str] = [] + for _name, tools in cats: + flat.extend(tools) + as_set = set(flat) + assert len(flat) == len(as_set), f"Duplicates in {label} _DISPLAY_CATEGORIES" + assert as_set == all_registered, ( + f"{label} _DISPLAY_CATEGORIES mismatch:\n" + f" Missing: {all_registered - as_set}\n" + f" Extra: {as_set - all_registered}" + ) + + kitchen_flat = {t for _, tools in kitchen_cats for t in tools} + cook_flat = {t for _, tools in cook_cats for t in tools} + assert kitchen_flat == cook_flat, "kitchen and cook _DISPLAY_CATEGORIES differ" + + +def test_tool_categories_not_in_core() -> None: + """TOOL_CATEGORIES must not be exported from the L0 core layer.""" + import autoskillit.core + import autoskillit.core._type_constants + + assert "TOOL_CATEGORIES" not in dir(autoskillit.core) + assert "TOOL_CATEGORIES" not in dir(autoskillit.core._type_constants) + assert "TOOL_CATEGORIES" not in autoskillit.core.__all__ + assert "TOOL_CATEGORIES" not in autoskillit.core._type_constants.__all__ + + +def test_ci_tools_not_in_github_category() -> None: + """CI tools must be in 'CI & Automation', not in 'GitHub'.""" + from autoskillit.cli._cook import _DISPLAY_CATEGORIES as cook_cats + from autoskillit.server.tools_kitchen import _DISPLAY_CATEGORIES as kitchen_cats + + ci_tools = {"wait_for_ci", "wait_for_merge_queue", "toggle_auto_merge", "get_ci_status"} + + for label, cats in (("kitchen", kitchen_cats), ("cook", cook_cats)): + github_tools: set[str] = set() + ci_cat_tools: set[str] = set() + for name, tools in cats: + if name == "GitHub": + github_tools = set(tools) + elif name == "CI & Automation": + ci_cat_tools = set(tools) + assert not (ci_tools & github_tools), ( + f"{label}: CI tools found in GitHub category: {ci_tools & github_tools}" + ) + assert ci_tools <= ci_cat_tools, ( + f"{label}: CI tools missing from CI & Automation: {ci_tools - ci_cat_tools}" + ) def test_tool_subset_tags_match_decorators() -> None: @@ -937,3 +988,70 @@ def test_server_docstring_counts_accurate() -> None: "server/__init__.py docstring count claims do not match frozenset sizes:\n" + "\n".join(f" {m}" for m in mismatches) ) + + +# --------------------------------------------------------------------------- +# REQ-P12-002: Default* classes may only be instantiated in the Composition Root +# (Finding 13.1) — AST gate with explicit allowlist +# --------------------------------------------------------------------------- + + +def test_default_classes_only_instantiated_inside_factory_or_allowlist() -> None: + """REQ-P12-002: Default* classes must be instantiated only in + server/_factory.py (the Composition Root). Five allowlisted exception + sites are recognized — they must remain in-place; introducing a sixth + requires either routing through make_context() or an explicit allowlist + update via this test.""" + import ast + + allowlist: dict[Path, set[str]] = { + Path("server/_factory.py"): {"*"}, # Composition Root + Path("cli/_workspace.py"): {"DefaultSubprocessRunner"}, # CLI worktree listing + Path("cli/_cook.py"): {"DefaultSessionSkillManager"}, # interactive cook + Path("cli/app.py"): {"DefaultSkillResolver"}, # skill listing command + Path("execution/recording.py"): {"DefaultSubprocessRunner"}, # lazy fallback + Path("pipeline/context.py"): { # __post_init__ + + "DefaultBackgroundSupervisor", # field default_factory + "DefaultMcpResponseLog", + }, + Path("recipe/_api.py"): {"DefaultSkillResolver"}, # deferred default factory fallback + Path("recipe/contracts.py"): {"DefaultSkillResolver"}, # deferred default factory fallback + Path("recipe/rules_skill_content.py"): { + "DefaultSkillResolver" + }, # deferred default factory fallback + Path("recipe/rules_skills.py"): { + "DefaultSkillResolver" + }, # deferred default factory fallback + Path("workspace/session_skills.py"): { + "DefaultSkillResolver" + }, # ephemeral session resolver fallback + } + + violations: list[str] = [] + for f in SRC_ROOT.rglob("*.py"): + rel = f.relative_to(SRC_ROOT) + if "__pycache__" in rel.parts: + continue + if rel in allowlist and "*" in allowlist[rel]: + continue + tree = ast.parse(f.read_text(), filename=str(f)) + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + func = node.func + name = ( + func.id + if isinstance(func, ast.Name) + else func.attr + if isinstance(func, ast.Attribute) + else None + ) + if not (name and name.startswith("Default") and len(name) > 7 and name[7].isupper()): + continue + permitted = allowlist.get(rel, set()) + if name not in permitted: + violations.append(f"{rel}:{node.lineno} {name}()") + assert not violations, ( + "Default* classes may only be constructed in server/_factory.py " + "or in the allowlisted CLI/recording/context fallback sites:\n" + "\n".join(violations) + ) diff --git a/tests/arch/test_never_raises_contracts.py b/tests/arch/test_never_raises_contracts.py index aeca85aa0f..8770940af9 100644 --- a/tests/arch/test_never_raises_contracts.py +++ b/tests/arch/test_never_raises_contracts.py @@ -15,6 +15,8 @@ import re from pathlib import Path +from tests.arch._helpers import SRC_ROOT, _has_toplevel_except_exception, _is_mcp_tool_decorator + _NEVER_RAISES_RE = re.compile(r"never raises", re.IGNORECASE) @@ -22,33 +24,61 @@ def _repo_root() -> Path: return Path(__file__).parent.parent.parent -def _has_toplevel_except_exception(func_node: ast.AsyncFunctionDef | ast.FunctionDef) -> bool: - """Return True if the function body's first substantive statement is a try/except Exception.""" - body = func_node.body - # Skip docstring - stmts = [ - s for s in body if not isinstance(s, ast.Expr) or not isinstance(s.value, ast.Constant) - ] - if not stmts: - return False - first = stmts[0] - if not isinstance(first, ast.Try): - return False - # Check that at least one handler catches Exception or BaseException - for handler in first.handlers: - if handler.type is None: # bare except: - return True - if isinstance(handler.type, ast.Name) and handler.type.id in ( - "Exception", - "BaseException", - ): - return True - if isinstance(handler.type, ast.Attribute) and handler.type.attr in ( - "Exception", - "BaseException", - ): - return True - return False +def test_all_mcp_tool_handlers_have_except_exception() -> None: + """Every @mcp.tool() decorated function in server/ must have a + top-level try/except Exception block. + + This is stronger than test_never_raises_contracts (which is opt-in via + docstring). This rule is mandatory for all tool handlers — exceptions + that escape to @track_response_size produce generic envelopes that + lack domain-specific fields callers need for routing. + """ + server_dir = SRC_ROOT / "server" + violations: list[str] = [] + + for path in sorted(server_dir.rglob("*.py")): + tree = ast.parse(path.read_text(), filename=str(path)) + for node in ast.walk(tree): + if not isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)): + continue + if not any(_is_mcp_tool_decorator(d) for d in node.decorator_list): + continue + if not _has_toplevel_except_exception(node): + rel = path.relative_to(SRC_ROOT.parent.parent) + violations.append(f"{rel}:{node.lineno} — {node.name}()") + + assert not violations, ( + "@mcp.tool() handlers must have a top-level try/except Exception " + "to return domain-specific structured errors instead of relying on " + "the @track_response_size safety net.\n" + "Violations:\n" + "\n".join(f" {v}" for v in violations) + ) + + +def test_all_mcp_tool_handlers_claim_never_raises() -> None: + """Every @mcp.tool() handler should declare 'Never raises' in its docstring. + + This activates test_never_raises_contracts enforcement as a second layer. + """ + server_dir = SRC_ROOT / "server" + missing: list[str] = [] + + for path in sorted(server_dir.rglob("*.py")): + tree = ast.parse(path.read_text(), filename=str(path)) + for node in ast.walk(tree): + if not isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)): + continue + if not any(_is_mcp_tool_decorator(d) for d in node.decorator_list): + continue + docstring = ast.get_docstring(node) or "" + if "never raises" not in docstring.lower(): + rel = path.relative_to(SRC_ROOT.parent.parent) + missing.append(f"{rel}:{node.lineno} — {node.name}()") + + assert not missing, ( + "@mcp.tool() handlers should claim 'Never raises' in their docstring.\n" + "Missing:\n" + "\n".join(f" {v}" for v in missing) + ) def test_never_raises_contracts_are_structurally_enforced() -> None: diff --git a/tests/arch/test_protocol_names.py b/tests/arch/test_protocol_names.py new file mode 100644 index 0000000000..8ae5fe1ffa --- /dev/null +++ b/tests/arch/test_protocol_names.py @@ -0,0 +1,53 @@ +"""T5-T6: Protocol naming and DefaultSkillResolver export smoke tests.""" + +from __future__ import annotations + +# --------------------------------------------------------------------------- +# T5 — Renamed protocols are importable from autoskillit.core +# --------------------------------------------------------------------------- + + +def test_renamed_protocols_importable() -> None: + """New protocol names (AuditLog etc.) must be importable from autoskillit.core.""" + from autoskillit.core import ( # noqa: F401 + AuditLog, + GateState, + McpResponseLog, + SkillResolver, + TimingLog, + TokenLog, + ) + + assert all( + isinstance(p, type) + for p in [AuditLog, TokenLog, TimingLog, McpResponseLog, GateState, SkillResolver] + ) + + +def test_old_protocol_names_not_exported() -> None: + """Old protocol names must NOT be exported from autoskillit.core after rename.""" + import autoskillit.core as core + + for old_name in [ + "AuditStore", + "TokenStore", + "TimingStore", + "McpResponseStore", + "GatePolicy", + "TargetSkillResolver", + ]: + assert not hasattr(core, old_name), f"{old_name} should not be exported after rename" + + +# --------------------------------------------------------------------------- +# T6 — DefaultSkillResolver is exported from autoskillit.workspace +# --------------------------------------------------------------------------- + + +def test_default_skill_resolver_importable() -> None: + """DefaultSkillResolver must be importable from autoskillit.workspace.""" + from autoskillit.workspace import DefaultSkillResolver + + r = DefaultSkillResolver() + assert hasattr(r, "resolve") + assert hasattr(r, "list_all") diff --git a/tests/arch/test_recipe_rule_registration.py b/tests/arch/test_recipe_rule_registration.py new file mode 100644 index 0000000000..37744856ac --- /dev/null +++ b/tests/arch/test_recipe_rule_registration.py @@ -0,0 +1,36 @@ +"""REQ-RECIPE-001: every recipe/rules_*.py file must be imported by recipe/__init__.py. + +Finding 14.1 — gate that prevents orphan rule modules whose @semantic_rule decorators +never register because the module is never imported. +""" + +import ast +from pathlib import Path + + +def test_every_rules_module_imported_by_recipe_init() -> None: + """REQ-RECIPE-001: every recipe/rules_*.py file must be imported by + recipe/__init__.py so its @semantic_rule decorators register at + import time. Catches accidental orphan rule modules.""" + src = Path(__file__).resolve().parents[2] / "src" / "autoskillit" / "recipe" + rules_files = sorted(p.stem for p in src.glob("rules_*.py")) + init_text = (src / "__init__.py").read_text() + init_tree = ast.parse(init_text) + + imported: set[str] = set() + for node in ast.walk(init_tree): + if isinstance(node, ast.ImportFrom): + # `from . import rules_X` → node.module is None, names hold rules_X + for name in node.names: + imported.add(name.name) + if node.module: + imported.add(node.module.split(".")[-1]) + if isinstance(node, ast.Import): + for name in node.names: + imported.add(name.name.split(".")[-1]) + + missing = [r for r in rules_files if r not in imported] + assert not missing, ( + f"recipe/__init__.py must import these rules modules so their " + f"@semantic_rule decorators register: {missing}" + ) diff --git a/tests/arch/test_registry.py b/tests/arch/test_registry.py index a057554891..1119a301f5 100644 --- a/tests/arch/test_registry.py +++ b/tests/arch/test_registry.py @@ -85,7 +85,16 @@ def test_rule_registry_completeness() -> None: # (c) exact set of IDs must match the visitor's rule set # Add a RuleDescriptor for every new visitor rule and update this set. expected_ids = frozenset( - {"ARCH-001", "ARCH-002", "ARCH-003", "ARCH-004", "ARCH-005", "ARCH-006", "ARCH-007"} + { + "ARCH-001", + "ARCH-002", + "ARCH-003", + "ARCH-004", + "ARCH-005", + "ARCH-006", + "ARCH-007", + "ARCH-008", + } ) actual_ids = frozenset(rule_ids) assert actual_ids == expected_ids, ( diff --git a/tests/arch/test_startup_budget.py b/tests/arch/test_startup_budget.py new file mode 100644 index 0000000000..975ff866c6 --- /dev/null +++ b/tests/arch/test_startup_budget.py @@ -0,0 +1,172 @@ +"""Startup budget enforcement (REQ-STARTUP-001). + +The serve() -> mcp.run() critical path must not contain subprocess calls. +Any subprocess on this path risks exceeding Claude Code's ~5s connection +timeout, causing "No such tool available" for all MCP tools. +""" + +from __future__ import annotations + +import ast +from pathlib import Path + +SRC = Path(__file__).resolve().parents[2] / "src" / "autoskillit" + +FORBIDDEN_SUBPROCESS_CALLS = frozenset( + {"subprocess.run", "subprocess.Popen", "subprocess.call", "subprocess.check_output"} +) + + +def _get_call_name(node: ast.Call) -> str: + """Extract dotted call name from an ast.Call node.""" + if isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name): + return f"{node.func.value.id}.{node.func.attr}" + if isinstance(node.func, ast.Name): + return node.func.id + return "" + + +def test_lifespan_calls_deferred_initialize() -> None: + """Lifespan must wire deferred_initialize as a background task.""" + source = (SRC / "server" / "_lifespan.py").read_text() + tree = ast.parse(source) + + lifespan_func = None + for node in ast.walk(tree): + if isinstance(node, ast.AsyncFunctionDef) and node.name == "_autoskillit_lifespan": + lifespan_func = node + break + assert lifespan_func is not None, "_autoskillit_lifespan not found in _lifespan.py" + + # Walk the entire function body for any call to deferred_initialize + found = False + for node in ast.walk(lifespan_func): + if isinstance(node, ast.Call): + name = _get_call_name(node) + if "deferred_initialize" in name: + found = True + break + # Also check for Name nodes (direct call without module prefix) + if isinstance(node.func, ast.Name) and node.func.id == "_run_deferred_init": + found = True + break + assert found, ( + "_autoskillit_lifespan must call deferred_initialize (or _run_deferred_init) " + "as a background task — deferred startup I/O is not wired into the lifespan" + ) + + +def test_no_subprocess_in_make_context() -> None: + """REQ-STARTUP-001: make_context() must not eagerly call subprocess.""" + factory_src = (SRC / "server" / "_factory.py").read_text() + tree = ast.parse(factory_src) + + for node in ast.walk(tree): + if isinstance(node, ast.FunctionDef) and node.name == "make_context": + for call in _iter_eager_calls(node): + call_name = _get_call_name(call) + assert call_name not in FORBIDDEN_SUBPROCESS_CALLS, ( + f"make_context() eagerly calls {call_name} at line {call.lineno} — " + f"this blocks the MCP server startup path" + ) + break + else: + raise AssertionError("make_context() not found in _factory.py") + + +def _iter_eager_calls(func_node: ast.FunctionDef) -> list[ast.Call]: + """Yield Call nodes that are eagerly executed in func_node. + + Skips calls inside nested lambdas, inner functions, and class bodies + because those are deferred — not executed when the enclosing function runs. + """ + eager_calls: list[ast.Call] = [] + + class _EagerCallVisitor(ast.NodeVisitor): + def visit_Lambda(self, node: ast.Lambda) -> None: + pass # skip lambda bodies — deferred execution + + def visit_FunctionDef(self, node: ast.FunctionDef) -> None: + pass # skip inner function bodies — deferred execution + + def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None: + pass # skip async inner functions + + def visit_Call(self, node: ast.Call) -> None: + eager_calls.append(node) + self.generic_visit(node) + + # Visit direct children of each statement in the function body + for stmt in func_node.body: + _EagerCallVisitor().visit(stmt) + + return eager_calls + + +def test_no_calls_between_initialize_and_anyio_run() -> None: + """REQ-STARTUP-001: serve() must not call anything between _initialize() and anyio.run().""" + source = (SRC / "cli" / "app.py").read_text() + tree = ast.parse(source) + + serve_func = None + for node in ast.walk(tree): + if isinstance(node, ast.FunctionDef) and node.name == "serve": + serve_func = node + break + assert serve_func is not None, "serve() not found in app.py" + + # Find the indices of _initialize(...) and anyio.run(...) in the body + init_idx = None + anyio_idx = None + for i, stmt in enumerate(serve_func.body): + if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call): + name = _get_call_name(stmt.value) + if name == "_initialize": + init_idx = i + # anyio.run is wrapped in try/except — look for ast.Try containing anyio.run + if isinstance(stmt, ast.Try): + for try_stmt in stmt.body: + if isinstance(try_stmt, ast.Expr) and isinstance(try_stmt.value, ast.Call): + name = _get_call_name(try_stmt.value) + if name == "anyio.run": + anyio_idx = i + + assert init_idx is not None, "_initialize() call not found in serve() body" + assert anyio_idx is not None, "anyio.run() call not found in serve() body" + assert init_idx < anyio_idx, "_initialize() must come before anyio.run()" + + # Check for function calls in statements between _initialize and anyio.run + violations: list[str] = [] + for stmt in serve_func.body[init_idx + 1 : anyio_idx]: + if isinstance(stmt, ast.Expr) and isinstance(stmt.value, ast.Call): + name = _get_call_name(stmt.value) + violations.append(f"{name}() at line {stmt.lineno}") + + assert not violations, ( + "serve() must not call anything between _initialize() and anyio.run() — " + "found:\n" + "\n".join(f" {v}" for v in violations) + ) + + +def test_no_gh_cli_token_in_make_context() -> None: + """REQ-STARTUP-001: make_context() must not call _gh_cli_token() eagerly. + + The _gh_cli_token() function runs subprocess.run with a 5s timeout. + Token resolution must be lazy (deferred to first gated tool call). + Calls inside lambdas/closures are acceptable — they are deferred. + """ + factory_src = (SRC / "server" / "_factory.py").read_text() + tree = ast.parse(factory_src) + + for node in ast.walk(tree): + if isinstance(node, ast.FunctionDef) and node.name == "make_context": + for call in _iter_eager_calls(node): + call_name = _get_call_name(call) + assert call_name != "_gh_cli_token", ( + f"make_context() eagerly calls _gh_cli_token() at line {call.lineno} — " + f"this 5s subprocess blocks the MCP server startup path. " + f"Token resolution must be lazy (wrapped in a lambda or factory)." + ) + break + else: + raise AssertionError("make_context() not found in _factory.py") diff --git a/tests/arch/test_subpackage_isolation.py b/tests/arch/test_subpackage_isolation.py index aef749aaea..f1803ff9fb 100644 --- a/tests/arch/test_subpackage_isolation.py +++ b/tests/arch/test_subpackage_isolation.py @@ -74,7 +74,10 @@ def _get_call_func_name(node: ast.Call) -> str | None: "validator", # recipe/validator.py: defensive exemption for decorator-based rule registry "settings", # config/settings.py: _CONFIG_SCHEMA = _build_config_schema() "headless", # execution/headless.py: _OUTPUT_PATH_TOKENS = _build_path_token_set() - "_stale_check", # cli/_stale_check.py: _DISMISS_WINDOW = timedelta(hours=12) + # _STABLE_DISMISS_WINDOW = timedelta(days=7), _DEV_DISMISS_WINDOW = timedelta(hours=12) + "_update_checks", # cli/_update_checks.py: window constants (see comment above) + "_terminal", # cli/_terminal.py: _BASE_RESET = "".join(...) derived from _RESET_SPEC + "hook_registry", # hook_registry.py: HOOK_REGISTRY_HASH = compute_registry_hash(...) } ) _SINGLETON_SAFE_CALL_NAMES: frozenset[str] = frozenset( @@ -98,6 +101,7 @@ def _get_call_func_name(node: ast.Call) -> str | None: "version", "compile", "object", + "MappingProxyType", # types.MappingProxyType — read-only view, no state } ) @@ -398,7 +402,7 @@ def test_recipe_validator_has_regex_patterns() -> None: ast_module = _get_module_ast("recipe/contracts.py") assigns = _top_level_assign_targets(ast_module) assert "_CONTEXT_REF_RE" in assigns, "recipe/contracts.py must define _CONTEXT_REF_RE" - assert "_INPUT_REF_RE" in assigns, "recipe/contracts.py must define _INPUT_REF_RE" + assert "INPUT_REF_RE" in assigns, "recipe/contracts.py must define INPUT_REF_RE" def test_recipe_validator_no_process_lifecycle_import() -> None: @@ -525,15 +529,19 @@ def test_cli_is_package() -> None: def test_server_file_count_under_limit() -> None: - """server/ must not exceed 17 Python files (REQ-DSGN-002). + """server/ must not exceed 18 Python files (REQ-DSGN-002). Limit updated from 14 to 16 after tools_integrations was split into tools_github, tools_issue_lifecycle, and tools_pr_ops. Limit updated from 16 to 17 after _editable_guard.py was added as the pre-deletion editable install guard for perform_merge(). + Limit updated from 17 to 18 after _lifespan.py was added for + FastMCP server lifespan teardown (#745). + Limit updated from 18 to 19 after _wire_compat.py was added for + Claude Code wire-format sanitization middleware. """ py_files = list((SRC_ROOT / "server").glob("*.py")) - assert len(py_files) <= 17, f"server/ has {len(py_files)} files, max is 17" + assert len(py_files) <= 19, f"server/ has {len(py_files)} files, max is 19" def test_tools_integrations_replaced_by_split_modules() -> None: @@ -642,35 +650,55 @@ def test_no_subpackage_exceeds_10_files() -> None: tools_kitchen, helpers, git, _factory, _state, __init__); each file is a thin routing layer. Exempt at 16 files. recipe/ — REQ-CNST-003-E2: recipe/ hosts one file per semantic-rule domain - (rules_bypass, rules_ci, rules_clone, etc.) for independent testability. + (rules_bypass, rules_ci, rules_clone, rules_packs, etc.) for independent testability. + Adding rules_cmd.py for run_cmd echo-capture alignment validation and + rules_isolation.py for workspace isolation checks brings the count to 30. + rules_blocks.py adds the block-level budget rule family, bringing the count to 32. + rules_reachability.py adds symbolic BFS reachability rules, bringing the count to 33. + rules_fixing.py adds conditional-write-skill ungated-push detection, + bringing the count to 34. execution/ — REQ-CNST-003-E3: execution/ decomposes process lifecycle into focused single-concern modules (_process_io, _process_kill, _process_race, etc.) that cannot be merged without re-introducing the coupling they isolate. + recording.py adds the RecordingSubprocessRunner decorator as a separate module + to keep scenario recording concerns isolated from the core process lifecycle. + _headless_scan.py extracts write-path JSONL scanning from headless.py to keep + that module within its REQ-CNST-010-E2 line budget. + Exempt at 26 files. core/ — REQ-CNST-003-E4: core/ types split into per-concern type modules (_type_enums, _type_protocols, _type_results, _type_subprocess, etc.) to prevent circular imports while keeping L0 types co-located. Also houses _terminal_table.py as the L0 shared terminal rendering primitive so that both cli/ (L3) and pipeline/ (L1) can import it without layer violations. - Exempt at 15 files. + _claude_env.py adds the canonical IDE-scrubbing env builder for all + claude subprocess launches. kitchen_state.py adds the stdlib-only + kitchen-open session marker reader for hook subprocesses. + Exempt at 17 files. cli/ — REQ-CNST-003-E5: cli/ retains _terminal_table.py as a re-export shim for backward-compatible cli/ imports; canonical implementation lives in core/_terminal_table.py. Also contains _terminal.py — the terminal state management context manager (terminal_guard) for interactive subprocess - sessions. _stale_check.py adds the stale-install detection surface. - Exempt at 14 files. + sessions. _install_info.py adds pure install classification + policy. + _update_checks.py adds the unified update check orchestration. + _update.py adds the first-class update subcommand implementation. + Exempt at 17 files. hooks/ — REQ-CNST-003-E6: hooks/ hosts one standalone script per hook event (PreToolUse, PostToolUse, SessionStart). Each script must remain a separate - file so Claude Code can invoke it directly as a subprocess. Adding - session_start_reminder.py for the SessionStart event brings the count to 11. - Exempt at 11 files. + file so Claude Code can invoke it directly as a subprocess. pretty_output_hook.py + additionally owns a set of underscore-prefixed private formatter modules + (_fmt_primitives.py, _fmt_execution.py, _fmt_status.py, _fmt_recipe.py) + that are imported helpers — not standalone hook scripts — split out to + keep pretty_output_hook.py under its line budget. ask_user_question_guard.py + gates AskUserQuestion on kitchen-open state. Exempt at 20 files + (15 hook scripts + 4 private helpers + 1 __init__). """ EXEMPTIONS: dict[str, int] = { - "server": 17, - "recipe": 27, - "execution": 23, - "core": 15, - "cli": 15, - "hooks": 12, + "server": 19, + "recipe": 34, + "execution": 26, + "core": 18, + "cli": 20, + "hooks": 20, } violations: list[str] = [] for sub_dir in sorted(SRC_ROOT.iterdir()): @@ -685,6 +713,25 @@ def test_no_subpackage_exceeds_10_files() -> None: ) +def test_data_directories_are_not_python_packages() -> None: + """REQ-ARCH-005: data-only directories under src/autoskillit/ must not + contain __init__.py — that turns them into phantom Python packages + distinct from the real L2 module of similar name.""" + src = Path(__file__).resolve().parents[2] / "src" / "autoskillit" + data_dirs = {"migrations", "recipes", "skills", "skills_extended"} + offenders: list[str] = [] + for name in data_dirs: + d = src / name + if not d.is_dir(): + continue + init = d / "__init__.py" + if init.exists(): + offenders.append(str(init.relative_to(src))) + assert not offenders, ( + f"Data directories must not be Python packages. Remove __init__.py from: {offenders}" + ) + + # ── REQ-CNST-010: Per-module source size limit ─────────────────────────────── # REQ-CNST-010: No source module in src/autoskillit/ may exceed 1000 lines. # Modules that exceed this limit require a documented exemption with rule ID and @@ -704,6 +751,20 @@ def test_no_subpackage_exceeds_10_files() -> None: "REQ-CNST-010-E1: canonical type registry — wide surface required to prevent " "circular imports; all enums/protocols/constants consolidated here", ), + "headless.py": ( + 1300, + "REQ-CNST-010-E2: headless session orchestration — Channel B drain-race " + "recovery + IDLE_STALL routing + contract nudge resume tier " + "+ DIR_MISSING late-bind recovery arm + RecordingSubprocessRunner " + "step-name auto-derivation gate; splitting would fragment the " + "adjudication pipeline across modules", + ), + "session.py": ( + 1050, + "REQ-CNST-010-E3: session adjudication pipeline — exhaustive match arms " + "for TerminationReason require explicit IDLE_STALL arms in _compute_success, " + "_compute_retry, and _normalize_subtype", + ), } @@ -847,7 +908,7 @@ def test_tool_context_service_fields_use_protocol_types() -> None: context_path = AUTOSKILLIT_ROOT / "pipeline" / "context.py" context_tree = ast.parse(context_path.read_text()) - EXEMPT = {"plugin_dir", "config", "active_recipe_packs"} + EXEMPT = {"plugin_dir", "config", "active_recipe_packs", "temp_dir"} violations: list[str] = [] for node in ast.walk(context_tree): @@ -973,6 +1034,35 @@ def test_default_recipe_repository_in_repository_module() -> None: from autoskillit.recipe.repository import DefaultRecipeRepository # noqa: F401 +def test_recipe_lister_callsites_use_protocol_typing() -> None: + """REQ-ARCH-006: callsites in recipe/ that consume the skill listing + must reference the SkillLister Protocol (parameter type), so the + deferred DefaultSkillResolver() instantiation is a default-factory fallback + rather than the only path. + + contracts.py uses .resolve() and therefore references SkillResolver, + not SkillLister. That is checked separately below. + """ + lister_targets = { + "src/autoskillit/recipe/rules_skills.py", + "src/autoskillit/recipe/_api.py", + } + src_root = Path(__file__).resolve().parents[2] + missing: list[str] = [] + for relpath in lister_targets: + text = (src_root / relpath).read_text() + if "SkillLister" not in text: + missing.append(relpath) + assert not missing, ( + f"These files still consume SkillResolver without SkillLister Protocol typing: {missing}" + ) + # contracts.py uses .resolve() — must reference SkillResolver, not SkillLister + contracts_text = (src_root / "src/autoskillit/recipe/contracts.py").read_text() + assert "SkillResolver" in contracts_text, ( + "contracts.py must reference SkillResolver for the resolver parameter" + ) + + def test_default_recipe_repository_not_in_io() -> None: """P2-F1: DefaultRecipeRepository must be removed from recipe/io.py.""" io_path = SRC_ROOT / "recipe" / "io.py" @@ -1080,6 +1170,8 @@ def test_race_signals_fields_unchanged(self): "channel_b_status", "channel_b_session_id", "stdout_session_id", + "idle_stall", + "process_exited_event", } # REQ-SIG-008 def test_race_signals_still_frozen(self): @@ -1127,29 +1219,69 @@ def test_pipeline_init_no_longer_exports_domain_paths(): assert "partition_files_by_domain" not in m.__all__ -def test_singleton_exemption_comment_matches_module_constant() -> None: - """The _stale_check exemption comment in SINGLETON_ALLOWED_MODULES must - accurately reflect the current _DISMISS_WINDOW constant value.""" +def test_singleton_exemption_comment_matches_both_windows() -> None: + """The _update_checks exemption comment in SINGLETON_ALLOWED_MODULES must + accurately reflect both the _STABLE_DISMISS_WINDOW and _DEV_DISMISS_WINDOW values.""" - from autoskillit.cli._stale_check import _DISMISS_WINDOW + from autoskillit.cli._update_checks import _DEV_DISMISS_WINDOW, _STABLE_DISMISS_WINDOW - # Read this test file itself this_file = Path(__file__) content = this_file.read_text(encoding="utf-8") - # Build the expected Python expression from the live constant - total_seconds = _DISMISS_WINDOW.total_seconds() - if total_seconds % 86400 == 0: - days = int(total_seconds // 86400) - expected_fragment = f"timedelta(days={days})" - elif total_seconds % 3600 == 0: - hours = int(total_seconds // 3600) - expected_fragment = f"timedelta(hours={hours})" - else: - expected_fragment = repr(_DISMISS_WINDOW) - - assert expected_fragment in content, ( + def _fmt_td(td: object) -> str: + import datetime + + if not isinstance(td, datetime.timedelta): + return repr(td) + total_seconds = td.total_seconds() + if total_seconds % 86400 == 0: + return f"timedelta(days={int(total_seconds // 86400)})" + if total_seconds % 3600 == 0: + return f"timedelta(hours={int(total_seconds // 3600)})" + return repr(td) + + stable_fragment = _fmt_td(_STABLE_DISMISS_WINDOW) + dev_fragment = _fmt_td(_DEV_DISMISS_WINDOW) + + assert stable_fragment in content, ( + f"Exemption comment in SINGLETON_ALLOWED_MODULES is stale. " + f"Expected to find '{stable_fragment}' " + f"(current _STABLE_DISMISS_WINDOW={_STABLE_DISMISS_WINDOW!r}). " + "Update the comment on the '_update_checks' entry." + ) + assert dev_fragment in content, ( f"Exemption comment in SINGLETON_ALLOWED_MODULES is stale. " - f"Expected to find '{expected_fragment}' (current _DISMISS_WINDOW={_DISMISS_WINDOW!r}). " - "Update the inline comment on the '_stale_check' entry." + f"Expected to find '{dev_fragment}' " + f"(current _DEV_DISMISS_WINDOW={_DEV_DISMISS_WINDOW!r}). " + "Update the comment on the '_update_checks' entry." + ) + + +def test_update_checks_docstring_describes_both_windows() -> None: + """The _update_checks module docstring and _is_dismissed docstring must + mention both branch-aware window values.""" + import ast + + src_root = Path(__file__).parent.parent.parent / "src" + module_path = src_root / "autoskillit" / "cli" / "_update_checks.py" + tree = ast.parse(module_path.read_text(encoding="utf-8")) + + module_doc = ast.get_docstring(tree) or "" + assert "timedelta(days=7)" in module_doc or "days=7" in module_doc, ( + "_update_checks module docstring must mention the 7-day stable window" ) + assert "timedelta(hours=12)" in module_doc or "hours=12" in module_doc, ( + "_update_checks module docstring must mention the 12-hour dev window" + ) + + # Also verify _is_dismissed has a docstring mentioning both windows + for node in ast.walk(tree): + if isinstance(node, ast.FunctionDef) and node.name == "_is_dismissed": + func_doc = ast.get_docstring(node) or "" + assert "days=7" in func_doc or "7 days" in func_doc, ( + "_is_dismissed docstring must mention the 7-day window" + ) + assert "hours=12" in func_doc or "12 hours" in func_doc, ( + "_is_dismissed docstring must mention the 12-hour window" + ) + break diff --git a/src/autoskillit/migrations/__init__.py b/tests/assets/__init__.py similarity index 100% rename from src/autoskillit/migrations/__init__.py rename to tests/assets/__init__.py diff --git a/tests/assets/test_mermaid_vendored.py b/tests/assets/test_mermaid_vendored.py new file mode 100644 index 0000000000..81180d5fa1 --- /dev/null +++ b/tests/assets/test_mermaid_vendored.py @@ -0,0 +1,36 @@ +"""REQ-R741-A01 / REQ-R741-A04 — Vendored mermaid.min.js presence and size.""" + +from __future__ import annotations + +from pathlib import Path + +_MERMAID_DIR = Path(__file__).resolve().parents[2] / "src" / "autoskillit" / "assets" / "mermaid" + + +def test_mermaid_min_js_exists_and_nontrivial() -> None: + """mermaid.min.js must exist at the vendored path and be > 1 MB.""" + asset = _MERMAID_DIR / "mermaid.min.js" + assert asset.exists(), f"mermaid.min.js not vendored at {asset}; run: task vendor-mermaid" + size = asset.stat().st_size + assert size > 1_000_000, ( + f"mermaid.min.js is suspiciously small ({size} bytes); expected > 1 MB. " + "Botched vendor pass? Re-run: task vendor-mermaid" + ) + + +def test_mermaid_license_file_exists() -> None: + """LICENSE.mermaid must accompany the vendored bundle (MIT attribution).""" + lic = _MERMAID_DIR / "LICENSE.mermaid" + assert lic.exists(), f"LICENSE.mermaid missing from {_MERMAID_DIR}" + assert lic.read_text().strip(), "LICENSE.mermaid is empty" + + +def test_mermaid_version_file_is_v11() -> None: + """VERSION file must exist and declare a mermaid 11.x release.""" + ver = _MERMAID_DIR / "VERSION" + assert ver.exists(), f"VERSION file missing from {_MERMAID_DIR}" + content = ver.read_text().strip() + assert content, "VERSION file is empty" + assert content.startswith("11."), ( + f"Expected mermaid 11.x, got {content!r}. Re-run: task vendor-mermaid" + ) diff --git a/tests/cli/test_cli_hooks.py b/tests/cli/test_cli_hooks.py index a73aff3f57..5e690fdb74 100644 --- a/tests/cli/test_cli_hooks.py +++ b/tests/cli/test_cli_hooks.py @@ -101,7 +101,7 @@ def test_evict_stale_hooks_removes_legacy_formats(tmp_path): { "matcher": "mcp__.*autoskillit.*__run_skill.*", "hooks": [ - {"type": "command", "command": "python3 -m autoskillit.hooks.quota_check"}, + {"type": "command", "command": "python3 -m autoskillit.hooks.quota_guard"}, ], }, { @@ -109,7 +109,7 @@ def test_evict_stale_hooks_removes_legacy_formats(tmp_path): "hooks": [ { "type": "command", - "command": "python3 /old/path/hooks/quota_check.py", + "command": "python3 /old/path/hooks/quota_guard.py", }, ], }, @@ -147,13 +147,13 @@ def test_evict_stale_hooks_removes_legacy_formats(tmp_path): all_commands = [ h["command"] for entry in data["hooks"]["PreToolUse"] for h in entry.get("hooks", []) ] - quota_commands = [c for c in all_commands if "quota_check" in c] + quota_commands = [c for c in all_commands if "quota_guard" in c] assert len(quota_commands) == 1 # T-REG-1 def test_install_production_order_includes_quota_check(tmp_path, monkeypatch): - """install() must register quota_check.py regardless of function call order.""" + """install() must register quota_guard.py regardless of function call order.""" import importlib from autoskillit.cli._marketplace import install @@ -176,8 +176,8 @@ def test_install_production_order_includes_quota_check(tmp_path, monkeypatch): data = json.loads(settings_path.read_text()) pretooluse = data.get("hooks", {}).get("PreToolUse", []) all_commands = [h["command"] for e in pretooluse for h in e.get("hooks", [])] - assert any("quota_check.py" in c for c in all_commands), ( - "quota_check.py missing from settings.json after install() — silent drop bug present" + assert any("quota_guard.py" in c for c in all_commands), ( + "quota_guard.py missing from settings.json after install() — silent drop bug present" ) @@ -207,7 +207,10 @@ def test_settings_json_matches_hook_registry_after_install(tmp_path, monkeypatch data = json.loads(settings_path.read_text()) for hook_def in HOOK_REGISTRY: event_entries = data.get("hooks", {}).get(hook_def.event_type, []) - matching = [e for e in event_entries if e.get("matcher") == hook_def.matcher] + if hook_def.event_type == "SessionStart": + matching = [e for e in event_entries if "matcher" not in e] + else: + matching = [e for e in event_entries if e.get("matcher") == hook_def.matcher] assert len(matching) == 1, ( f"Expected exactly 1 {hook_def.event_type} entry for matcher " f"{hook_def.matcher!r}, got {len(matching)}" @@ -285,3 +288,22 @@ def test_sync_hooks_to_settings_is_idempotent(tmp_path): assert len(posttooluse) == posttooluse_count, ( f"Duplicate entries after evict+sync twice: {len(posttooluse)} PostToolUse entries" ) + + +# T-CROSS-1 +def test_sync_hooks_to_settings_session_start_no_matcher(tmp_path): + """sync_hooks_to_settings() must not emit 'matcher' key for SessionStart entries.""" + from autoskillit.cli._hooks import _evict_stale_autoskillit_hooks, sync_hooks_to_settings + + settings = tmp_path / ".claude" / "settings.json" + settings.parent.mkdir() + settings.write_text('{"hooks": {}}') + _evict_stale_autoskillit_hooks(settings) + sync_hooks_to_settings(settings) + data = json.loads(settings.read_text()) + session_start_entries = data.get("hooks", {}).get("SessionStart", []) + assert session_start_entries, "Expected at least one SessionStart entry" + for entry in session_start_entries: + assert "matcher" not in entry, ( + f"SessionStart entry must not have 'matcher' key, got: {entry}" + ) diff --git a/tests/cli/test_cli_prompts.py b/tests/cli/test_cli_prompts.py index f24afd7dc6..c6d475fe27 100644 --- a/tests/cli/test_cli_prompts.py +++ b/tests/cli/test_cli_prompts.py @@ -209,6 +209,33 @@ def test_show_cook_preview_no_diagram(monkeypatch, tmp_path, capsys): assert "RECIPE" not in captured.out +def test_show_cook_preview_uses_resolved_base_branch_for_smoke_test(monkeypatch, capsys): + """T8: show_cook_preview renders the config-resolved base_branch for smoke-test.""" + import autoskillit.recipe._api as api_mod + from autoskillit.cli._prompts import show_cook_preview + from autoskillit.core import pkg_root + from autoskillit.recipe.io import find_recipe_by_name, load_recipe + + project_dir = pkg_root().parent.parent + monkeypatch.setattr(api_mod, "_LOAD_CACHE", {}) + monkeypatch.setattr( + "autoskillit.config.resolve_ingredient_defaults", + lambda _: {"base_branch": "integration"}, + ) + + recipe_info = find_recipe_by_name("smoke-test", project_dir) + assert recipe_info is not None, "smoke-test recipe must exist in project-local recipes" + recipe = load_recipe(recipe_info.path) + + show_cook_preview("smoke-test", recipe, project_dir, project_dir) + captured = capsys.readouterr() + assert "integration" in captured.out + # base_branch row must NOT show the YAML literal "main" + base_branch_lines = [line for line in captured.out.splitlines() if "base_branch" in line] + assert base_branch_lines, "base_branch must appear in the rendered table" + assert all("main" not in line for line in base_branch_lines) + + def test_orchestrator_prompt_contains_multi_issue_guidance(): """System prompt must document the sequential vs parallel decision for multiple issues.""" from autoskillit.cli._prompts import _build_orchestrator_prompt @@ -367,3 +394,43 @@ def test_open_kitchen_prompt_uses_fully_qualified_tool_name(mcp_prefix: str) -> prompt = _build_open_kitchen_prompt(mcp_prefix=mcp_prefix) assert f"{mcp_prefix}open_kitchen" in prompt + + +def test_orchestrator_prompt_contains_quota_routing(): + """_build_orchestrator_prompt output includes QUOTA DENIAL ROUTING section.""" + from autoskillit.cli._prompts import _build_orchestrator_prompt + + prompt = _build_orchestrator_prompt("test-recipe", mcp_prefix=DIRECT_PREFIX) + assert "QUOTA DENIAL ROUTING" in prompt + + +def test_orchestrator_prompt_instructs_toolsearch_when_deferred(): + """PR #750 added DO-NOT-ask; this test pins the recovery path instead.""" + from autoskillit.cli._mcp_names import DIRECT_PREFIX + from autoskillit.cli._prompts import _build_orchestrator_prompt + + prompt = _build_orchestrator_prompt("my_recipe", mcp_prefix=DIRECT_PREFIX) + assert "ToolSearch" in prompt + assert "deferred" in prompt.lower() + assert "select:" in prompt + assert "open_kitchen" in prompt + + +def test_open_kitchen_prompt_instructs_toolsearch_when_deferred(): + from autoskillit.cli._mcp_names import DIRECT_PREFIX + from autoskillit.cli._prompts import _build_open_kitchen_prompt + + prompt = _build_open_kitchen_prompt(mcp_prefix=DIRECT_PREFIX) + assert "ToolSearch" in prompt + assert "deferred" in prompt.lower() + assert "open_kitchen" in prompt + + +def test_prompt_builder_includes_startup_retry(): + """Prompt must include retry instruction for 'No such tool available'.""" + from autoskillit.cli._mcp_names import DIRECT_PREFIX + from autoskillit.cli._prompts import _build_orchestrator_prompt + + prompt = _build_orchestrator_prompt("test", mcp_prefix=DIRECT_PREFIX) + assert "SERVER-STARTUP RECOVERY" in prompt + assert "No such tool available" in prompt diff --git a/tests/cli/test_cli_serve_logging.py b/tests/cli/test_cli_serve_logging.py index a31d3a9bc3..e77c359d98 100644 --- a/tests/cli/test_cli_serve_logging.py +++ b/tests/cli/test_cli_serve_logging.py @@ -7,8 +7,6 @@ import structlog.testing -import autoskillit.server as server_mod - class TestServeLoggingPhases: """Verify serve() calls configure_logging twice: early init then config-driven.""" @@ -24,7 +22,7 @@ def test_serve_reconfigures_logging_from_config(self, tmp_path, monkeypatch): (config_dir / "config.yaml").write_text("logging:\n level: DEBUG\n") with ( - patch.object(server_mod.mcp, "run"), + patch("anyio.run"), # prevent actual event loop; serve() routes through anyio.run patch("autoskillit.core.configure_logging") as mock_configure, structlog.testing.capture_logs(), ): @@ -51,7 +49,7 @@ def test_serve_no_reconfig_when_defaults(self, tmp_path, monkeypatch): # No config file — defaults only with ( - patch.object(server_mod.mcp, "run"), + patch("anyio.run"), # prevent actual event loop; serve() routes through anyio.run patch("autoskillit.core.configure_logging") as mock_configure, structlog.testing.capture_logs(), ): @@ -67,7 +65,7 @@ def test_verbose_flag_wins_over_config(self, tmp_path, monkeypatch): monkeypatch.chdir(tmp_path) with ( - patch.object(server_mod.mcp, "run"), + patch("anyio.run"), # prevent actual event loop; serve() routes through anyio.run patch("autoskillit.core.configure_logging") as mock_configure, structlog.testing.capture_logs(), ): @@ -88,7 +86,7 @@ def test_json_output_from_config(self, tmp_path, monkeypatch): (config_dir / "config.yaml").write_text("logging:\n json_output: true\n") with ( - patch.object(server_mod.mcp, "run"), + patch("anyio.run"), # prevent actual event loop; serve() routes through anyio.run patch("autoskillit.core.configure_logging") as mock_configure, structlog.testing.capture_logs(), ): diff --git a/tests/cli/test_cook.py b/tests/cli/test_cook.py index 05546b1b07..bddbf16cb7 100644 --- a/tests/cli/test_cook.py +++ b/tests/cli/test_cook.py @@ -102,6 +102,17 @@ def _interactive_stdin(self, monkeypatch: pytest.MonkeyPatch) -> None: """Most order() paths require an interactive TTY — default to True for this class.""" monkeypatch.setattr("sys.stdin.isatty", lambda: True) + @pytest.fixture(autouse=True) + def _stub_is_plugin_installed(self, monkeypatch: pytest.MonkeyPatch) -> None: + """Stub _is_plugin_installed in app.py to False to prevent subprocess.run collision.""" + import importlib + import sys as _sys + + _app_mod = _sys.modules.get("autoskillit.cli.app") or importlib.import_module( + "autoskillit.cli.app" + ) + monkeypatch.setattr(_app_mod, "_is_plugin_installed", lambda: False) + # --- workspace init --- def test_prep_station_init_creates_dir_with_marker( @@ -439,6 +450,70 @@ def test_order_builds_correct_command( assert "capture_output" not in kwargs assert "stdin" not in kwargs + @patch("autoskillit.cli.subprocess.run") + def test_order_suppresses_plugin_dir_when_plugin_installed( + self, + mock_run: MagicMock, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + """order omits --plugin-dir when marketplace plugin is installed.""" + import importlib + import sys as _sys + + monkeypatch.delenv("CLAUDECODE", raising=False) + monkeypatch.chdir(tmp_path) + scripts_dir = tmp_path / ".autoskillit" / "recipes" + scripts_dir.mkdir(parents=True) + (scripts_dir / "my-script.yaml").write_text(_SCRIPT_YAML) + monkeypatch.setattr(shutil, "which", lambda cmd: "/usr/bin/claude") + monkeypatch.setattr("builtins.input", lambda _prompt="": "") + _app_mod = _sys.modules.get("autoskillit.cli.app") or importlib.import_module( + "autoskillit.cli.app" + ) + monkeypatch.setattr(_app_mod, "_is_plugin_installed", lambda: True) + mock_run.return_value = subprocess.CompletedProcess( + args=[], returncode=0, stdout="", stderr="" + ) + + cli.order("test-script") + + mock_run.assert_called_once() + cmd = mock_run.call_args[0][0] + assert ClaudeFlags.PLUGIN_DIR not in cmd + + @patch("autoskillit.cli.subprocess.run") + def test_order_includes_plugin_dir_when_no_plugin_installed( + self, + mock_run: MagicMock, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + ) -> None: + """order includes --plugin-dir when marketplace plugin is not installed.""" + import importlib + import sys as _sys + + monkeypatch.delenv("CLAUDECODE", raising=False) + monkeypatch.chdir(tmp_path) + scripts_dir = tmp_path / ".autoskillit" / "recipes" + scripts_dir.mkdir(parents=True) + (scripts_dir / "my-script.yaml").write_text(_SCRIPT_YAML) + monkeypatch.setattr(shutil, "which", lambda cmd: "/usr/bin/claude") + monkeypatch.setattr("builtins.input", lambda _prompt="": "") + _app_mod = _sys.modules.get("autoskillit.cli.app") or importlib.import_module( + "autoskillit.cli.app" + ) + monkeypatch.setattr(_app_mod, "_is_plugin_installed", lambda: False) + mock_run.return_value = subprocess.CompletedProcess( + args=[], returncode=0, stdout="", stderr="" + ) + + cli.order("test-script") + + mock_run.assert_called_once() + cmd = mock_run.call_args[0][0] + assert ClaudeFlags.PLUGIN_DIR in cmd + @patch("autoskillit.cli.subprocess.run") def test_order_system_prompt_contains_behavioral_instructions( self, @@ -647,13 +722,12 @@ def test_order_named_recipe_only_confirmation_prompt( args=[], returncode=0, stdout="", stderr="" ) - prompts_seen: list[str] = [] - monkeypatch.setattr("builtins.input", lambda prompt="": prompts_seen.append(prompt) or "") + input_calls = [] + monkeypatch.setattr("builtins.input", lambda prompt="": input_calls.append(prompt) or "") cli.order("test-script") - assert len(prompts_seen) == 1, "input() should be called exactly once (confirmation)" - assert "Launch session" in prompts_seen[0] + assert len(input_calls) == 1, "input() should be called exactly once (confirmation)" @patch("autoskillit.cli.subprocess.run") def test_order_command_includes_positional_greeting( @@ -1011,6 +1085,17 @@ def _stub_preview(self, monkeypatch: pytest.MonkeyPatch) -> None: lambda *a, **kw: None, ) + @pytest.fixture(autouse=True) + def _stub_is_plugin_installed(self, monkeypatch: pytest.MonkeyPatch) -> None: + """Stub _is_plugin_installed in app.py to False to prevent subprocess.run collision.""" + import importlib + import sys as _sys + + _app_mod = _sys.modules.get("autoskillit.cli.app") or importlib.import_module( + "autoskillit.cli.app" + ) + monkeypatch.setattr(_app_mod, "_is_plugin_installed", lambda: False) + def _make_config_mock(self, disabled: list[str]) -> MagicMock: mock_cfg = MagicMock() mock_cfg.subsets.disabled = disabled @@ -1189,6 +1274,17 @@ def _stub_preview(self, monkeypatch: pytest.MonkeyPatch) -> None: def _interactive_stdin(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr("sys.stdin.isatty", lambda: True) + @pytest.fixture(autouse=True) + def _stub_is_plugin_installed(self, monkeypatch: pytest.MonkeyPatch) -> None: + """Stub _is_plugin_installed in app.py to False to prevent subprocess.run collision.""" + import importlib + import sys as _sys + + _app_mod = _sys.modules.get("autoskillit.cli.app") or importlib.import_module( + "autoskillit.cli.app" + ) + monkeypatch.setattr(_app_mod, "_is_plugin_installed", lambda: False) + @patch("autoskillit.cli.subprocess.run") def test_order_prompt_uses_direct_prefix_when_no_marketplace_install( self, mock_run: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch diff --git a/tests/cli/test_cook_env_scrub.py b/tests/cli/test_cook_env_scrub.py new file mode 100644 index 0000000000..bc278750b0 --- /dev/null +++ b/tests/cli/test_cook_env_scrub.py @@ -0,0 +1,154 @@ +"""Launch-site env-scrub contract tests for _launch_cook_session and cook(). + +Each test monkeypatches ``CLAUDE_CODE_SSE_PORT`` and ``ENABLE_IDE_INTEGRATION`` +into the parent env, drives the launch site with ``subprocess.run`` patched, +and asserts the captured ``env`` kwarg does not contain the IDE discovery +variables and does contain the auto-connect suppressor. +""" + +from __future__ import annotations + +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest + +from autoskillit.execution import _MAX_MCP_OUTPUT_TOKENS_VALUE + + +def test_launch_cook_session_env_excludes_ide_vars( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.setenv("CLAUDE_CODE_SSE_PORT", "23270") + monkeypatch.setenv("ENABLE_IDE_INTEGRATION", "true") + monkeypatch.setenv("VSCODE_GIT_ASKPASS_MAIN", "/fake/vscode") + monkeypatch.setenv("CLAUDE_CODE_IDE_HOST_OVERRIDE", "host") + + from autoskillit.cli.app import _launch_cook_session + + with ( + patch("shutil.which", return_value="/usr/bin/claude"), + patch( + "autoskillit.cli.app.subprocess.run", + return_value=MagicMock(returncode=0), + ) as mock_run, + patch("autoskillit.cli.app.terminal_guard"), + ): + _launch_cook_session("system prompt", initial_message="hello") + + assert mock_run.call_args is not None + env = mock_run.call_args.kwargs["env"] + assert "CLAUDE_CODE_SSE_PORT" not in env + assert "ENABLE_IDE_INTEGRATION" not in env + assert "VSCODE_GIT_ASKPASS_MAIN" not in env + assert "CLAUDE_CODE_IDE_HOST_OVERRIDE" not in env + assert env["CLAUDE_CODE_AUTO_CONNECT_IDE"] == "0" + + +def test_launch_cook_session_extra_env_still_applied( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.setenv("CLAUDE_CODE_SSE_PORT", "23270") + + from autoskillit.cli.app import _launch_cook_session + + with ( + patch("shutil.which", return_value="/usr/bin/claude"), + patch( + "autoskillit.cli.app.subprocess.run", + return_value=MagicMock(returncode=0), + ) as mock_run, + patch("autoskillit.cli.app.terminal_guard"), + ): + _launch_cook_session( + "system prompt", + extra_env={"AUTOSKILLIT_SUBSETS__DISABLED": "@json []"}, + ) + + env = mock_run.call_args.kwargs["env"] + assert env["AUTOSKILLIT_SUBSETS__DISABLED"] == "@json []" + assert "CLAUDE_CODE_SSE_PORT" not in env + + +def test_launch_cook_session_env_has_max_mcp_output_tokens( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """_launch_cook_session (order path) must produce env with MAX_MCP_OUTPUT_TOKENS.""" + from autoskillit.cli.app import _launch_cook_session + + with ( + patch("shutil.which", return_value="/usr/bin/claude"), + patch( + "autoskillit.cli.app.subprocess.run", + return_value=MagicMock(returncode=0), + ) as mock_run, + patch("autoskillit.cli.app.terminal_guard"), + ): + _launch_cook_session("system prompt", initial_message="hello") + + env = mock_run.call_args.kwargs["env"] + assert env["MAX_MCP_OUTPUT_TOKENS"] == _MAX_MCP_OUTPUT_TOKENS_VALUE + + +def test_cook_command_env_excludes_ide_vars( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.setenv("CLAUDE_CODE_SSE_PORT", "23270") + monkeypatch.setenv("ENABLE_IDE_INTEGRATION", "true") + monkeypatch.chdir(tmp_path) + + fake_skills_dir = tmp_path / "skills" + fake_skills_dir.mkdir() + mock_mgr = MagicMock() + mock_mgr.init_session.return_value = fake_skills_dir + + with ( + patch("shutil.which", return_value="/usr/bin/claude"), + patch("builtins.input", return_value=""), + patch("sys.stdin.isatty", return_value=True), + patch("autoskillit.workspace.DefaultSessionSkillManager", return_value=mock_mgr), + patch( + "autoskillit.cli._cook.subprocess.run", + return_value=MagicMock(returncode=0), + ) as mock_run, + patch("autoskillit.cli._cook.terminal_guard"), + ): + from autoskillit.cli._cook import cook + + cook() + + assert mock_run.call_args is not None + env = mock_run.call_args.kwargs["env"] + assert "CLAUDE_CODE_SSE_PORT" not in env + assert "ENABLE_IDE_INTEGRATION" not in env + assert env["CLAUDE_CODE_AUTO_CONNECT_IDE"] == "0" + + +def test_cook_command_env_has_max_mcp_output_tokens( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """cook() must inject MAX_MCP_OUTPUT_TOKENS=50000 into the subprocess env.""" + monkeypatch.chdir(tmp_path) + + fake_skills_dir = tmp_path / "skills" + fake_skills_dir.mkdir() + mock_mgr = MagicMock() + mock_mgr.init_session.return_value = fake_skills_dir + + with ( + patch("shutil.which", return_value="/usr/bin/claude"), + patch("builtins.input", return_value=""), + patch("sys.stdin.isatty", return_value=True), + patch("autoskillit.workspace.DefaultSessionSkillManager", return_value=mock_mgr), + patch( + "autoskillit.cli._cook.subprocess.run", + return_value=MagicMock(returncode=0), + ) as mock_run, + patch("autoskillit.cli._cook.terminal_guard"), + ): + from autoskillit.cli._cook import cook + + cook() + + env = mock_run.call_args.kwargs["env"] + assert env["MAX_MCP_OUTPUT_TOKENS"] == _MAX_MCP_OUTPUT_TOKENS_VALUE diff --git a/tests/cli/test_cook_ide_isolation.py b/tests/cli/test_cook_ide_isolation.py new file mode 100644 index 0000000000..2c99d37fdf --- /dev/null +++ b/tests/cli/test_cook_ide_isolation.py @@ -0,0 +1,63 @@ +"""End-to-end regression canary: _launch_cook_session under simulated IDE state. + +This test encodes the exact scenario the ide-env-leak investigation reproduced: +VS Code (or any IDE) has ``CLAUDE_CODE_SSE_PORT`` set and an active +``~/.claude/ide/$PORT.lock`` file. When autoskillit launches the cook session, +the child must NOT attach to the IDE channel via either discovery path: + +1. **Env scrub** — ``CLAUDE_CODE_SSE_PORT`` and the expanded IDE denylist are + stripped from the child env. +2. **Auto-connect disable** — ``CLAUDE_CODE_AUTO_CONNECT_IDE=0`` is injected, + which suppresses the ``~/.claude/ide/*.lock`` scan fallback that fires even + when no IDE env vars are set. +""" + +from __future__ import annotations + +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest + + +def test_cook_session_ignores_ide_lock_file( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """Launch cook under simulated IDE state; assert env scrub + auto-connect disable.""" + fake_home = tmp_path / "home" + ide_dir = fake_home / ".claude" / "ide" + ide_dir.mkdir(parents=True) + lock_file = ide_dir / "65535.lock" + lock_file.write_text('{"pid": 1, "transport": "ws"}') + + monkeypatch.setenv("HOME", str(fake_home)) + monkeypatch.setenv("CLAUDE_CODE_SSE_PORT", "65535") + monkeypatch.setenv("ENABLE_IDE_INTEGRATION", "1") + monkeypatch.setenv("VSCODE_GIT_ASKPASS_MAIN", "/fake/vscode") + monkeypatch.setenv("CLAUDE_CODE_IDE_HOST_OVERRIDE", "localhost") + + from autoskillit.cli.app import _launch_cook_session + + with ( + patch("shutil.which", return_value="/usr/bin/claude"), + patch( + "autoskillit.cli.app.subprocess.run", + return_value=MagicMock(returncode=0), + ) as mock_run, + patch("autoskillit.cli.app.terminal_guard"), + ): + _launch_cook_session("system prompt", initial_message="hello") + + # (1) Env scrub + env = mock_run.call_args.kwargs["env"] + assert "CLAUDE_CODE_SSE_PORT" not in env + assert "ENABLE_IDE_INTEGRATION" not in env + assert "VSCODE_GIT_ASKPASS_MAIN" not in env + assert "CLAUDE_CODE_IDE_HOST_OVERRIDE" not in env + + # (2) Auto-connect suppressor + assert env["CLAUDE_CODE_AUTO_CONNECT_IDE"] == "0" + + # Argv must no longer carry a leading ['env', ...] prefix. + cmd = mock_run.call_args.args[0] + assert cmd[0] == "claude" diff --git a/tests/cli/test_doctor.py b/tests/cli/test_doctor.py index b37146e867..e6b0764115 100644 --- a/tests/cli/test_doctor.py +++ b/tests/cli/test_doctor.py @@ -69,7 +69,6 @@ def test_doctor_ignores_healthy_coregistered_servers( { "mcpServers": { "other-server": {"type": "stdio", "command": str(fake_bin)}, - "autoskillit": {"type": "stdio", "command": "autoskillit"}, } } ) @@ -80,15 +79,22 @@ def test_doctor_ignores_healthy_coregistered_servers( (tmp_path / ".autoskillit" / "config.yaml").write_text( "test_check:\n command: ['pytest']\n" ) - from autoskillit.core import _AUTOSKILLIT_GITIGNORE_ENTRIES, _ROOT_GITIGNORE_ENTRIES + from autoskillit.core import _AUTOSKILLIT_GITIGNORE_ENTRIES (tmp_path / ".autoskillit" / ".gitignore").write_text( "\n".join(_AUTOSKILLIT_GITIGNORE_ENTRIES) + "\n" ) - (tmp_path / ".gitignore").write_text("\n".join(_ROOT_GITIGNORE_ENTRIES) + "\n") (tmp_path / ".pre-commit-config.yaml").write_text( "repos:\n - repo: dummy\n hooks:\n - id: gitleaks\n" ) + # Create plugin cache directory for Check 2c + (tmp_path / ".claude" / "plugins" / "cache" / "autoskillit-local" / "autoskillit").mkdir( + parents=True, exist_ok=True + ) + # Create installed_plugins.json for Check 2d + (tmp_path / ".claude" / "plugins" / "installed_plugins.json").write_text( + json.dumps({"version": 2, "plugins": {"autoskillit@autoskillit-local": {}}}) + ) # Register hooks so hook_registration check passes # Use explicit path (tmp_path already monkeypatched as Path.home()) from autoskillit.cli._hooks import ( @@ -202,6 +208,9 @@ def test_doctor_json_output_includes_all_checks( "secret_scanning_hook", "editable_install_source_exists", # ★ new "stale_entry_points", # ★ new + "dual_mcp_registration", # ★ new + "plugin_cache_exists", + "installed_plugins_entry", } assert expected <= check_names @@ -574,10 +583,6 @@ def test_doctor_outdated_message_updated( class TestSyncRemovalCLI: - def test_update_command_does_not_exist(self): - """REQ-APP-002: 'autoskillit update' is not a registered command.""" - assert not hasattr(cli, "update") - def test_doctor_has_no_recipe_sync_check( self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture ): @@ -623,16 +628,70 @@ def test_doctor_fix_parameter_does_not_exist(): assert "fix" not in sig.parameters, "doctor --fix is a silent no-op and must be removed" -def test_doctor_clears_plugin_cache(tmp_path, monkeypatch, capsys): - """Doctor must clear the plugin cache on every run.""" +def test_doctor_does_not_modify_plugin_state(tmp_path, monkeypatch, capsys): + """Doctor must not delete the plugin cache or modify installed_plugins.json.""" monkeypatch.setattr(Path, "home", lambda: tmp_path) monkeypatch.chdir(tmp_path) cache_dir = tmp_path / ".claude" / "plugins" / "cache" / "autoskillit-local" / "autoskillit" cache_dir.mkdir(parents=True) (cache_dir / "0.3.0" / "hooks").mkdir(parents=True) - (cache_dir / "0.3.0" / "hooks" / "pretty_output.py").write_text("# stale") + (cache_dir / "0.3.0" / "hooks" / "pretty_output_hook.py").write_text("# cached") + + plugins_json = tmp_path / ".claude" / "plugins" / "installed_plugins.json" + plugins_json.write_text( + json.dumps( + {"version": 2, "plugins": {"autoskillit@autoskillit-local": {"version": "0.8.25"}}} + ) + ) + cli.doctor() - assert not cache_dir.exists() + + assert cache_dir.exists(), "Doctor must not delete the plugin cache directory" + data = json.loads(plugins_json.read_text()) + assert "autoskillit@autoskillit-local" in data.get("plugins", {}), ( + "Doctor must not remove installed_plugins.json entries" + ) + + +def test_doctor_checks_plugin_cache_exists(tmp_path, monkeypatch, capsys): + """Doctor must report when the plugin cache directory is missing.""" + from autoskillit.cli._install_info import InstallInfo, InstallType + + monkeypatch.setattr(Path, "home", lambda: tmp_path) + monkeypatch.chdir(tmp_path) + # Force non-editable install so the cache check actually runs + monkeypatch.setattr( + "autoskillit.cli._install_info.detect_install", + lambda: InstallInfo( + install_type=InstallType.GIT_VCS, + commit_id=None, + requested_revision=None, + url=None, + editable_source=None, + ), + ) + cli.doctor(output_json=True) + captured = capsys.readouterr() + data = json.loads(captured.out) + checks = [r for r in data["results"] if r["check"] == "plugin_cache_exists"] + assert len(checks) == 1, "Expected a plugin_cache_exists check" + assert checks[0]["severity"] in ("warning", "error") + + +def test_doctor_checks_installed_plugins_entry(tmp_path, monkeypatch, capsys): + """Doctor must report when installed_plugins.json is missing the autoskillit entry.""" + monkeypatch.setattr(Path, "home", lambda: tmp_path) + monkeypatch.chdir(tmp_path) + # Create installed_plugins.json without the autoskillit entry + plugins_dir = tmp_path / ".claude" / "plugins" + plugins_dir.mkdir(parents=True) + (plugins_dir / "installed_plugins.json").write_text("{}") + cli.doctor(output_json=True) + captured = capsys.readouterr() + data = json.loads(captured.out) + checks = [r for r in data["results"] if r["check"] == "installed_plugins_entry"] + assert len(checks) == 1, "Expected an installed_plugins_entry check" + assert checks[0]["severity"] in ("warning", "error") def test_stale_gate_check_absent_from_doctor_output(tmp_path, monkeypatch, capsys): @@ -703,61 +762,17 @@ def test_doctor_warns_on_missing_gitignore_entry( def test_doctor_gitignore_ok_when_all_covered( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - """Doctor must report OK when all .autoskillit/ files are covered.""" - from autoskillit.core.io import _ROOT_GITIGNORE_ENTRIES - - autoskillit_dir = tmp_path / ".autoskillit" - autoskillit_dir.mkdir() - (autoskillit_dir / ".gitignore").write_text( - "temp/\n.secrets.yaml\nsync_manifest.json\n.onboarded\n" - ) - (autoskillit_dir / "temp").mkdir() - (autoskillit_dir / ".secrets.yaml").write_text("github:\n token: ''\n") - (tmp_path / ".gitignore").write_text("\n".join(_ROOT_GITIGNORE_ENTRIES) + "\n") - - monkeypatch.chdir(tmp_path) - from autoskillit.cli._doctor import _check_gitignore_completeness - from autoskillit.core import Severity - - result = _check_gitignore_completeness(tmp_path) - assert result.severity == Severity.OK - + """Doctor must report OK when all .autoskillit/ files are covered. -# RG-DROOT-1 -def test_doctor_warns_when_root_gitignore_missing_secrets_entry( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Doctor must WARN when root .gitignore lacks .autoskillit/.secrets.yaml.""" + Root ``.gitignore`` is no longer mutated by autoskillit (self-gitignoring + temp dir pattern), so the doctor only checks ``.autoskillit/.gitignore``. + """ from autoskillit.core.io import _AUTOSKILLIT_GITIGNORE_ENTRIES - autoskillit_dir = tmp_path / ".autoskillit" - autoskillit_dir.mkdir() - # .autoskillit/.gitignore is complete — only root is missing - (autoskillit_dir / ".gitignore").write_text("\n".join(_AUTOSKILLIT_GITIGNORE_ENTRIES) + "\n") - (autoskillit_dir / ".secrets.yaml").write_text("github:\n token: ''\n") - # No root .gitignore - - monkeypatch.chdir(tmp_path) - from autoskillit.cli._doctor import _check_gitignore_completeness - from autoskillit.core import Severity - - result = _check_gitignore_completeness(tmp_path) - assert result.severity == Severity.WARNING - assert ".autoskillit/.secrets.yaml" in result.message - - -# RG-DROOT-2 -def test_doctor_ok_when_root_gitignore_has_all_entries( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - """Doctor must report OK when both .autoskillit/.gitignore and root .gitignore are complete.""" - from autoskillit.core.io import _AUTOSKILLIT_GITIGNORE_ENTRIES, _ROOT_GITIGNORE_ENTRIES - autoskillit_dir = tmp_path / ".autoskillit" autoskillit_dir.mkdir() (autoskillit_dir / ".gitignore").write_text("\n".join(_AUTOSKILLIT_GITIGNORE_ENTRIES) + "\n") (autoskillit_dir / ".secrets.yaml").write_text("github:\n token: ''\n") - (tmp_path / ".gitignore").write_text("\n".join(_ROOT_GITIGNORE_ENTRIES) + "\n") monkeypatch.chdir(tmp_path) from autoskillit.cli._doctor import _check_gitignore_completeness @@ -1079,7 +1094,7 @@ def test_doctor_hook_health_checks_all_event_types(tmp_path: Path) -> None: from autoskillit.cli._doctor import _check_hook_health from autoskillit.core import Severity - # Write a settings.json that includes token_summary_appender (PostToolUse) + # Write a settings.json that includes token_summary_hook (PostToolUse) # but point it at a non-existent path. settings = { "hooks": { @@ -1089,7 +1104,7 @@ def test_doctor_hook_health_checks_all_event_types(tmp_path: Path) -> None: "hooks": [ { "type": "command", - "command": "python3 /nonexistent/token_summary_appender.py", + "command": "python3 /nonexistent/token_summary_hook.py", } ], } @@ -1103,4 +1118,706 @@ def test_doctor_hook_health_checks_all_event_types(tmp_path: Path) -> None: assert result.severity != Severity.OK, ( "hook_health must report non-OK when a PostToolUse hook script is missing" ) - assert "token_summary_appender" in result.message or "PostToolUse" in result.message + assert "token_summary_hook" in result.message or "PostToolUse" in result.message + + +# T-DRIFT-1: _count_hook_registry_drift() detects orphaned hooks +def test_count_hook_registry_drift_detects_orphaned_hooks(tmp_path: Path) -> None: + """deployed − canonical must be counted and returned. + Orphaned hooks are the fatal failure mode (ENOENT on every tool call). + """ + from autoskillit.cli._doctor import _count_hook_registry_drift + + settings = tmp_path / ".claude" / "settings.json" + settings.parent.mkdir() + ghost_cmd = "python3 /path/to/autoskillit/hooks/status_health_guard.py" + data = { + "hooks": { + "PreToolUse": [ + { + "matcher": "mcp__.*autoskillit.*__run_skill.*", + "hooks": [{"type": "command", "command": ghost_cmd}], + } + ] + } + } + settings.write_text(json.dumps(data)) + result = _count_hook_registry_drift(settings) + assert hasattr(result, "orphaned"), ( + "_count_hook_registry_drift must return a result with 'orphaned' field" + ) + assert result.orphaned >= 1, f"Expected orphaned >= 1 for ghost entry, got {result.orphaned}" + + +# T-DRIFT-2: _check_hook_registry_drift() returns ERROR for orphaned hooks +def test_check_hook_registry_drift_error_on_orphaned_hooks(tmp_path: Path) -> None: + from autoskillit.cli._doctor import _check_hook_registry_drift + from autoskillit.core import Severity + + settings = tmp_path / ".claude" / "settings.json" + settings.parent.mkdir() + ghost_cmd = "python3 /path/to/autoskillit/hooks/status_health_guard.py" + data = { + "hooks": { + "PreToolUse": [ + { + "matcher": "mcp__.*autoskillit.*__run_skill.*", + "hooks": [{"type": "command", "command": ghost_cmd}], + } + ] + } + } + settings.write_text(json.dumps(data)) + result = _check_hook_registry_drift(settings) + assert result.severity == Severity.ERROR, ( + f"Orphaned hooks must produce ERROR severity, got {result.severity}" + ) + assert "status_health_guard.py" in result.message, ( + "Error message must name the orphaned script(s)" + ) + + +# T-DRIFT-3: User hooks must not appear as orphans +def test_count_hook_registry_drift_ignores_user_hooks(tmp_path: Path) -> None: + """Non-autoskillit user hooks in settings.json must not be counted as orphaned. + + Regression: _extract_script_basenames() includes ALL commands without filtering, + making user hooks appear as orphans in the deployed - canonical set diff. + """ + from autoskillit.hook_registry import _count_hook_registry_drift, generate_hooks_json + + # Start with all canonical hooks so missing=0 + canonical_data = generate_hooks_json() + # Add non-autoskillit user hooks alongside canonical ones + user_hooks = [ + {"type": "command", "command": "python3 /home/user/my_guard.py"}, + {"type": "command", "command": 'wsl-notify-send.exe "Done!"'}, + ] + canonical_data["hooks"].setdefault("PreToolUse", []).append( + {"matcher": ".*", "hooks": user_hooks} + ) + settings = tmp_path / ".claude" / "settings.json" + settings.parent.mkdir() + settings.write_text(json.dumps(canonical_data)) + + result = _count_hook_registry_drift(settings) + assert result.orphaned == 0, ( + f"User hooks must not be counted as orphaned, got orphaned={result.orphaned}, " + f"orphaned_cmds={result.orphaned_cmds}" + ) + assert result.missing == 0, ( + f"All canonical hooks are deployed, expected missing=0, got {result.missing}" + ) + + +# T-DRIFT-4: Cross-environment path mismatch must not cause false drift +def test_count_hook_registry_drift_cross_env_path_mismatch(tmp_path: Path) -> None: + """settings.json written by a different install (different pkg_root prefix) + must not show drift when all script basenames match. + + Regression: full-path string comparison treats path-prefix differences + as drift, even though the same scripts are deployed. + """ + from autoskillit.hook_registry import HOOK_REGISTRY, _count_hook_registry_drift + + # Build settings.json with a DIFFERENT path prefix than current pkg_root() + foreign_hooks_dir = ( + "/home/user/.local/share/uv/tools/autoskillit/lib/python3.13" + "/site-packages/autoskillit/hooks" + ) + by_event: dict[str, list[dict]] = {} + for hdef in HOOK_REGISTRY: + hook_commands = [ + {"type": "command", "command": f"python3 {foreign_hooks_dir}/{script}"} + for script in hdef.scripts + ] + entry: dict = {"hooks": hook_commands} + if hdef.event_type != "SessionStart": + entry["matcher"] = hdef.matcher + by_event.setdefault(hdef.event_type, []).append(entry) + data = {"hooks": by_event} + + settings = tmp_path / ".claude" / "settings.json" + settings.parent.mkdir() + settings.write_text(json.dumps(data)) + + result = _count_hook_registry_drift(settings) + assert result.orphaned == 0, ( + f"Path prefix difference must not cause orphaned hooks, got orphaned={result.orphaned}" + ) + assert result.missing == 0, ( + f"Path prefix difference must not cause missing hooks, got missing={result.missing}" + ) + + +# --------------------------------------------------------------------------- +# _check_source_version_drift — doctor check (cache-only, no network) +# --------------------------------------------------------------------------- + + +def test_check_source_version_drift_ok_outside_source_repo( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """GIT_VCS install with empty cache reports OK (no drift observable).""" + from autoskillit.cli._doctor import _check_source_version_drift + from autoskillit.cli._install_info import InstallInfo, InstallType + from autoskillit.core import Severity + + info = InstallInfo( + install_type=InstallType.GIT_VCS, + commit_id="abc1234", + requested_revision="integration", + url=None, + editable_source=None, + ) + monkeypatch.setattr("autoskillit.cli._install_info.detect_install", lambda: info) + # Simulate empty cache and no source repo: resolve returns None + monkeypatch.setattr( + "autoskillit.cli._update_checks.resolve_reference_sha", lambda info, home, **kw: None + ) + + result = _check_source_version_drift(home=tmp_path) + assert result.severity == Severity.OK + + +def test_check_source_version_drift_ok_for_editable_install( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """LOCAL_EDITABLE installs are under active development — drift check is skipped.""" + from autoskillit.cli._doctor import _check_source_version_drift + from autoskillit.cli._install_info import InstallInfo, InstallType + from autoskillit.core import Severity + + info = InstallInfo( + install_type=InstallType.LOCAL_EDITABLE, + commit_id=None, + requested_revision=None, + url="file:///home/user/autoskillit", + editable_source=Path("/home/user/autoskillit"), + ) + monkeypatch.setattr("autoskillit.cli._install_info.detect_install", lambda: info) + + result = _check_source_version_drift(home=tmp_path) + assert result.severity == Severity.OK + assert "editable" in result.message.lower() or "not applicable" in result.message.lower() + + +def test_check_source_version_drift_ok_for_pinned_sha( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """When requested_revision == commit_id, resolve_reference_sha short-circuits → no drift.""" + from autoskillit.cli._doctor import _check_source_version_drift + from autoskillit.cli._install_info import InstallInfo, InstallType + from autoskillit.core import Severity + + sha = "abcdef1234567890abcdef1234567890" + info = InstallInfo( + install_type=InstallType.GIT_VCS, + commit_id=sha, + requested_revision=sha, # pinned SHA = no drift possible + url=None, + editable_source=None, + ) + monkeypatch.setattr("autoskillit.cli._install_info.detect_install", lambda: info) + # When requested_revision == commit_id, resolve_reference_sha returns commit_id + monkeypatch.setattr( + "autoskillit.cli._update_checks.resolve_reference_sha", lambda info, home, **kw: sha + ) + + result = _check_source_version_drift(home=tmp_path) + assert result.severity == Severity.OK + + +def test_check_source_version_drift_ok_when_cache_empty( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """When SHA cannot be resolved (network/cache miss), doctor reports OK.""" + from autoskillit.cli._doctor import _check_source_version_drift + from autoskillit.cli._install_info import InstallInfo, InstallType + from autoskillit.core import Severity + + info = InstallInfo( + install_type=InstallType.GIT_VCS, + commit_id="installed123", + requested_revision="integration", + url=None, + editable_source=None, + ) + monkeypatch.setattr("autoskillit.cli._install_info.detect_install", lambda: info) + monkeypatch.setattr( + "autoskillit.cli._update_checks.resolve_reference_sha", lambda info, home, **kw: None + ) + + result = _check_source_version_drift(home=tmp_path) + assert result.severity == Severity.OK + # Message should note that the reference SHA is unavailable + assert "unavailable" in result.message.lower(), ( + f"Expected 'unavailable' in message when resolve returns None, got: {result.message!r}" + ) + + +def test_check_source_version_drift_warning_on_drift( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """When cache has a different reference SHA than installed, reports WARNING with short SHAs.""" + from autoskillit.cli._doctor import _check_source_version_drift + from autoskillit.cli._install_info import InstallInfo, InstallType + from autoskillit.core import Severity + + installed_sha = "installed123abc" + ref_sha = "reference456def" + + info = InstallInfo( + install_type=InstallType.GIT_VCS, + commit_id=installed_sha, + requested_revision="integration", + url=None, + editable_source=None, + ) + monkeypatch.setattr("autoskillit.cli._install_info.detect_install", lambda: info) + monkeypatch.setattr( + "autoskillit.cli._update_checks.resolve_reference_sha", lambda info, home, **kw: ref_sha + ) + + result = _check_source_version_drift(home=tmp_path) + assert result.severity == Severity.WARNING + assert installed_sha[:8] in result.message + assert ref_sha[:8] in result.message + + +# --------------------------------------------------------------------------- +# Check 14: Quota cache schema version (#711 Part B, Phase 4) +# --------------------------------------------------------------------------- + + +class TestCheckQuotaCacheSchema: + """Tests for _check_quota_cache_schema doctor check.""" + + def test_check_quota_cache_schema_ok_when_current(self, tmp_path): + import json + + from autoskillit.cli._doctor import Severity, _check_quota_cache_schema + from autoskillit.execution import QUOTA_CACHE_SCHEMA_VERSION + + cache = tmp_path / "cache.json" + cache.write_text( + json.dumps( + {"schema_version": QUOTA_CACHE_SCHEMA_VERSION, "fetched_at": "2026-01-01T00:00:00"} + ) + ) + result = _check_quota_cache_schema(cache_path=cache) + assert result.severity == Severity.OK + assert f"v{QUOTA_CACHE_SCHEMA_VERSION}" in result.message + + def test_check_quota_cache_schema_ok_when_missing(self, tmp_path): + from autoskillit.cli._doctor import Severity, _check_quota_cache_schema + + cache = tmp_path / "nonexistent.json" + result = _check_quota_cache_schema(cache_path=cache) + assert result.severity == Severity.OK + assert "No quota cache" in result.message + + def test_check_quota_cache_schema_warning_when_no_schema_version_key(self, tmp_path): + import json + + from autoskillit.cli._doctor import Severity, _check_quota_cache_schema + + cache = tmp_path / "cache.json" + cache.write_text(json.dumps({"fetched_at": "2026-01-01T00:00:00"})) + result = _check_quota_cache_schema(cache_path=cache) + assert result.severity == Severity.WARNING + assert "schema drift" in result.message.lower() + + def test_check_quota_cache_schema_warning_when_older_schema_version(self, tmp_path): + import json + + from autoskillit.cli._doctor import Severity, _check_quota_cache_schema + + cache = tmp_path / "cache.json" + cache.write_text(json.dumps({"schema_version": 1, "fetched_at": "2026-01-01T00:00:00"})) + result = _check_quota_cache_schema(cache_path=cache) + assert result.severity == Severity.WARNING + + def test_check_quota_cache_schema_warning_includes_cache_path_and_observed_value( + self, tmp_path + ): + import json + + from autoskillit.cli._doctor import Severity, _check_quota_cache_schema + + cache = tmp_path / "cache.json" + cache.write_text(json.dumps({"schema_version": 1})) + result = _check_quota_cache_schema(cache_path=cache) + assert result.severity == Severity.WARNING + assert str(cache) in result.message + assert "observed=1" in result.message + + +def test_doctor_reports_drift_in_project_scope( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """_check_hook_registry_drift must report drift found in project scope.""" + import json as _json + + from autoskillit.cli._doctor import _check_hook_registry_drift + from autoskillit.core import Severity + + # Seed a stale pretty_output.py in project scope + project_settings = tmp_path / ".claude" / "settings.json" + project_settings.parent.mkdir(parents=True) + project_settings.write_text( + _json.dumps( + { + "hooks": { + "PostToolUse": [ + { + "matcher": "mcp__.*autoskillit.*", + "hooks": [ + {"type": "command", "command": "python3 /stale/pretty_output.py"} + ], + } + ] + } + } + ) + ) + + result = _check_hook_registry_drift(project_settings, scope_label="project") + assert result.severity == Severity.ERROR + assert "[project]" in result.message + assert "pretty_output.py" in result.message + + +# --------------------------------------------------------------------------- +# REQ-DOCTOR-001 — _check_claude_process_state_breakdown +# --------------------------------------------------------------------------- + + +class TestCheckClaudeProcessStateBreakdown: + """Tests for the claude_process_state doctor check (Check 15).""" + + def _ps_result(self, stdout: str, returncode: int = 0): + return type( + "CompletedProcess", + (), + {"returncode": returncode, "stdout": stdout}, + )() + + def test_ok_when_only_sleeping(self, monkeypatch: pytest.MonkeyPatch) -> None: + """Single sleeping claude process → Severity.OK with state breakdown.""" + import subprocess + + from autoskillit.cli._doctor import Severity, _check_claude_process_state_breakdown + + header = "PID STAT %CPU COMMAND\n" + monkeypatch.setattr( + subprocess, + "run", + lambda *a, **kw: self._ps_result(header + "1234 S 0.5 claude"), + ) + result = _check_claude_process_state_breakdown() + assert result.severity == Severity.OK + assert "S=1" in result.message + + def test_warns_on_d_state(self, monkeypatch: pytest.MonkeyPatch) -> None: + """claude process in D state → Severity.WARNING with pid and pcpu in message.""" + import subprocess + + from autoskillit.cli._doctor import Severity, _check_claude_process_state_breakdown + + header = "PID STAT %CPU COMMAND\n" + monkeypatch.setattr( + subprocess, + "run", + lambda *a, **kw: self._ps_result(header + "1234 D 99.0 claude"), + ) + result = _check_claude_process_state_breakdown() + assert result.severity == Severity.WARNING + assert "D=1" in result.message + assert "99.0" in result.message + + def test_ok_when_no_claude_processes(self, monkeypatch: pytest.MonkeyPatch) -> None: + """Empty ps output (no claude rows) → Severity.OK, 'No claude processes running'.""" + import subprocess + + from autoskillit.cli._doctor import Severity, _check_claude_process_state_breakdown + + header = "PID STAT %CPU COMMAND\n" + monkeypatch.setattr( + subprocess, + "run", + lambda *a, **kw: self._ps_result(header + "5678 S 0.1 python"), + ) + result = _check_claude_process_state_breakdown() + assert result.severity == Severity.OK + assert result.message == "No claude processes running" + + def test_ok_when_ps_missing(self, monkeypatch: pytest.MonkeyPatch) -> None: + """FileNotFoundError from ps → Severity.OK explaining ps unavailability.""" + import subprocess + + from autoskillit.cli._doctor import Severity, _check_claude_process_state_breakdown + + def _raise(*a, **kw): + raise FileNotFoundError("ps") + + monkeypatch.setattr(subprocess, "run", _raise) + result = _check_claude_process_state_breakdown() + assert result.severity == Severity.OK + assert "ps unavailable" in result.message + assert "FileNotFoundError" in result.message + + +class TestDoctorInstallClassification: + """Tests for _check_install_classification doctor check.""" + + @pytest.mark.parametrize( + "revision,expected_fragment", + [ + ("stable", "stable"), + ("integration", "integration"), + ], + ) + def test_doctor_reports_install_classification_git_vcs( + self, monkeypatch: pytest.MonkeyPatch, revision: str, expected_fragment: str + ) -> None: + import json + + from autoskillit.cli._doctor import Severity, _check_install_classification + + fake_direct_url = json.dumps( + { + "url": "https://github.com/TalonT-Org/AutoSkillit.git", + "vcs_info": { + "vcs": "git", + "requested_revision": revision, + "commit_id": "abc123", + }, + } + ) + from unittest.mock import MagicMock + + fake_dist = MagicMock() + fake_dist.read_text.return_value = fake_direct_url + monkeypatch.setattr( + "importlib.metadata.Distribution.from_name", + lambda _name: fake_dist, + ) + result = _check_install_classification() + assert result.severity == Severity.OK + assert expected_fragment in result.message + + def test_doctor_reports_install_classification_unknown( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + from unittest.mock import MagicMock + + from autoskillit.cli._doctor import Severity, _check_install_classification + + fake_dist = MagicMock() + fake_dist.read_text.return_value = None + monkeypatch.setattr( + "importlib.metadata.Distribution.from_name", + lambda _name: fake_dist, + ) + result = _check_install_classification() + assert result.severity == Severity.WARNING + assert "could not be detected" in result.message + + +class TestDoctorUpdateDismissalState: + """Tests for _check_update_dismissal_state doctor check.""" + + def test_doctor_reports_dismissal_state_empty(self, tmp_path: Path) -> None: + from autoskillit.cli._doctor import Severity, _check_update_dismissal_state + + result = _check_update_dismissal_state(home=tmp_path) + assert result.severity == Severity.OK + assert "No active dismissal" in result.message + + def test_doctor_reports_dismissal_state_populated( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + import json + from datetime import UTC, datetime + from unittest.mock import MagicMock + + from autoskillit.cli._doctor import Severity, _check_update_dismissal_state + from autoskillit.cli._update_checks import _write_dismiss_state + + # Seed state + dismissed_at = datetime.now(UTC).isoformat() + _write_dismiss_state( + tmp_path, + { + "update_prompt": { + "dismissed_at": dismissed_at, + "dismissed_version": "0.7.77", + "conditions": ["binary"], + } + }, + ) + + # Patch detect_install to return stable GIT_VCS + fake_direct_url = json.dumps( + { + "url": "https://github.com/TalonT-Org/AutoSkillit.git", + "vcs_info": { + "vcs": "git", + "requested_revision": "stable", + "commit_id": "abc123", + }, + } + ) + fake_dist = MagicMock() + fake_dist.read_text.return_value = fake_direct_url + monkeypatch.setattr( + "importlib.metadata.Distribution.from_name", + lambda _name: fake_dist, + ) + + result = _check_update_dismissal_state(home=tmp_path) + assert result.severity == Severity.OK + assert "dismissed until" in result.message + assert "binary" in result.message + + +class TestDoctorSourceVersionDriftUsesNetwork: + """Test that source_version_drift now uses network=True.""" + + def test_doctor_source_version_drift_uses_network_true( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + """_check_source_version_drift must call resolve_reference_sha with network=True.""" + import json + from unittest.mock import MagicMock + + from autoskillit.cli._doctor import _check_source_version_drift + + fake_direct_url = json.dumps( + { + "url": "https://github.com/TalonT-Org/AutoSkillit.git", + "vcs_info": { + "vcs": "git", + "requested_revision": "stable", + "commit_id": "abc123", + }, + } + ) + fake_dist = MagicMock() + fake_dist.read_text.return_value = fake_direct_url + monkeypatch.setattr( + "importlib.metadata.Distribution.from_name", + lambda _name: fake_dist, + ) + + network_args: list[bool] = [] + monkeypatch.setattr( + "autoskillit.cli._update_checks.resolve_reference_sha", + lambda info, home, **kw: network_args.append(kw.get("network", True)) or None, + ) + + _check_source_version_drift(home=tmp_path) + assert any(n is True for n in network_args), ( + "_check_source_version_drift must call resolve_reference_sha with network=True" + ) + + def test_check_source_version_drift_returns_ok_when_network_unavailable( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + """Network error (resolve_reference_sha returns None) → OK, not hard failure.""" + import json + from unittest.mock import MagicMock + + from autoskillit.cli._doctor import _check_source_version_drift + + fake_direct_url = json.dumps( + { + "url": "https://github.com/TalonT-Org/AutoSkillit.git", + "vcs_info": { + "vcs": "git", + "requested_revision": "stable", + "commit_id": "abc123", + }, + } + ) + fake_dist = MagicMock() + fake_dist.read_text.return_value = fake_direct_url + monkeypatch.setattr( + "importlib.metadata.Distribution.from_name", + lambda _name: fake_dist, + ) + monkeypatch.setattr( + "autoskillit.cli._update_checks.resolve_reference_sha", + lambda info, home, **kw: None, + ) + + from autoskillit.cli._doctor import Severity + + result = _check_source_version_drift(home=tmp_path) + assert result.severity == Severity.OK, ( + f"Expected OK (fail-open) when network unavailable, " + f"got {result.severity}: {result.message}" + ) + assert "unavailable" in result.message.lower() or "network" in result.message.lower() + + +def test_doctor_dual_mcp_registration_warns( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """_check_dual_mcp_registration() warns when both direct and marketplace entries exist.""" + from autoskillit.cli._doctor import _check_dual_mcp_registration + from autoskillit.core import Severity + + claude_json = tmp_path / ".claude.json" + claude_json.write_text(json.dumps({"mcpServers": {"autoskillit": {"type": "stdio"}}})) + plugins_dir = tmp_path / ".claude" / "plugins" + plugins_dir.mkdir(parents=True) + (plugins_dir / "installed_plugins.json").write_text( + json.dumps({"plugins": {"autoskillit@autoskillit-local": {"name": "autoskillit"}}}) + ) + monkeypatch.setattr(Path, "home", lambda: tmp_path) + result = _check_dual_mcp_registration() + assert result.severity == Severity.WARNING + assert "autoskillit install" in result.message + + +def test_doctor_no_dual_when_only_direct(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + """_check_dual_mcp_registration() returns OK when only the direct entry exists.""" + from autoskillit.cli._doctor import _check_dual_mcp_registration + from autoskillit.core import Severity + + claude_json = tmp_path / ".claude.json" + claude_json.write_text(json.dumps({"mcpServers": {"autoskillit": {"type": "stdio"}}})) + monkeypatch.setattr(Path, "home", lambda: tmp_path) + result = _check_dual_mcp_registration() + assert result.severity == Severity.OK + + +def test_check_installed_plugins_entry_real_structure_is_ok(tmp_path: Path) -> None: + """With the real nested format, the check must report OK.""" + from autoskillit.cli._doctor import _check_installed_plugins_entry + from autoskillit.core import Severity + + p = tmp_path / "installed_plugins.json" + p.write_text( + json.dumps( + { + "version": 2, + "plugins": {"autoskillit@autoskillit-local": {"name": "autoskillit"}}, + } + ) + ) + result = _check_installed_plugins_entry(plugins_json_path=p) + assert result.severity == Severity.OK + + +def test_check_installed_plugins_entry_flat_structure_is_warning(tmp_path: Path) -> None: + """A flat structure (wrong format) must not be silently treated as OK.""" + from autoskillit.cli._doctor import _check_installed_plugins_entry + from autoskillit.core import Severity + + p = tmp_path / "installed_plugins.json" + p.write_text(json.dumps({"autoskillit@autoskillit-local": {}})) + result = _check_installed_plugins_entry(plugins_json_path=p) + assert result.severity == Severity.WARNING diff --git a/tests/cli/test_init.py b/tests/cli/test_init.py index f815cb4127..b59b6e4cd8 100644 --- a/tests/cli/test_init.py +++ b/tests/cli/test_init.py @@ -23,14 +23,21 @@ def _pre_commit_with_scanner(self, tmp_path: Path) -> None: # CL1 def test_serve_calls_mcp_run(self) -> None: + # serve() now delegates to anyio.run(serve_with_signal_guard, mcp) + # which calls mcp.run_async() inside the event loop. + anyio_run_calls: list = [] mock_mcp = MagicMock() with patch.object(cli, "serve", wraps=cli.serve): with ( patch("autoskillit.server.mcp", mock_mcp), patch("autoskillit.core.configure_logging"), + patch( + "anyio.run", + side_effect=lambda *a, **kw: anyio_run_calls.append(a), + ), ): cli.serve() - mock_mcp.run.assert_called_once() + assert anyio_run_calls, "serve() did not call anyio.run() to start the MCP server" # CL3 def test_init_creates_config_dir( @@ -308,13 +315,20 @@ def test_ensure_project_temp_creates_temp_dir(self, tmp_path): assert result == tmp_path / ".autoskillit" / "temp" assert result.is_dir() - def test_ensure_project_temp_writes_gitignore(self, tmp_path): + def test_ensure_project_temp_writes_self_gitignore(self, tmp_path): + from autoskillit.core.io import ensure_project_temp + + ensure_project_temp(tmp_path) + temp_gitignore = tmp_path / ".autoskillit" / "temp" / ".gitignore" + assert temp_gitignore.exists() + assert "*" in temp_gitignore.read_text() + + def test_ensure_project_temp_writes_autoskillit_gitignore_with_secrets(self, tmp_path): from autoskillit.core.io import ensure_project_temp ensure_project_temp(tmp_path) gitignore = tmp_path / ".autoskillit" / ".gitignore" content = gitignore.read_text() - assert "temp/" in content assert ".secrets.yaml" in content def test_ensure_project_temp_is_idempotent(self, tmp_path): @@ -327,15 +341,15 @@ def test_ensure_project_temp_is_idempotent(self, tmp_path): def test_ensure_project_temp_backfills_secrets_into_existing_gitignore(self, tmp_path): from autoskillit.core.io import ensure_project_temp - # Simulate a pre-fix .gitignore with only temp/ + # Simulate a pre-fix .gitignore without .secrets.yaml autoskillit_dir = tmp_path / ".autoskillit" autoskillit_dir.mkdir() - (autoskillit_dir / ".gitignore").write_text("temp/\n") + (autoskillit_dir / ".gitignore").write_text(".onboarded\n") ensure_project_temp(tmp_path) content = (autoskillit_dir / ".gitignore").read_text() assert ".secrets.yaml" in content - assert "temp/" in content + assert ".onboarded" in content class TestServeStartupLog: @@ -347,7 +361,6 @@ def test_serve_logs_startup_with_config_path(self, tmp_path, monkeypatch): import structlog.testing import autoskillit.cli as cli_mod - import autoskillit.server as server_mod monkeypatch.chdir(tmp_path) (tmp_path / ".autoskillit").mkdir() @@ -356,7 +369,7 @@ def test_serve_logs_startup_with_config_path(self, tmp_path, monkeypatch): ) with ( - patch.object(server_mod.mcp, "run"), + patch("anyio.run"), # prevent actual event loop patch("autoskillit.core.configure_logging"), structlog.testing.capture_logs() as logs, ): @@ -373,12 +386,11 @@ def test_serve_logs_startup_config_path_none_when_no_config(self, tmp_path, monk import structlog.testing import autoskillit.cli as cli_mod - import autoskillit.server as server_mod monkeypatch.chdir(tmp_path) with ( - patch.object(server_mod.mcp, "run"), + patch("anyio.run"), # prevent actual event loop patch("autoskillit.core.configure_logging"), patch("autoskillit.cli.Path.home", return_value=tmp_path), structlog.testing.capture_logs() as logs, @@ -416,7 +428,13 @@ def test_init_creates_secrets_template(tmp_path: Path, monkeypatch: pytest.Monke def test_init_all_created_files_covered_by_gitignore(tmp_path: Path) -> None: - """Every file in .autoskillit/ after init must be gitignored or in the committed allowlist.""" + """Every file in .autoskillit/ after init must be gitignored or self-gitignoring. + + The temp directory uses the self-gitignoring pattern (pytest #3286 / mypy + PR #8193): it owns its own .gitignore containing ``*``. All other files + created in .autoskillit/ must either appear in .autoskillit/.gitignore or + be in the committed allowlist. + """ from autoskillit.cli._init_helpers import _create_secrets_template from autoskillit.core.io import _COMMITTED_BY_DESIGN, ensure_project_temp @@ -431,6 +449,13 @@ def test_init_all_created_files_covered_by_gitignore(tmp_path: Path) -> None: continue if item.name in _COMMITTED_BY_DESIGN: continue + if item.is_dir() and (item / ".gitignore").exists(): + # Self-gitignoring directory — its own .gitignore covers its contents. + self_ignore = (item / ".gitignore").read_text() + assert "*" in self_ignore, ( + f"{item.name}/ is a directory without a self-gitignore covering '*'" + ) + continue check_name = item.name + "/" if item.is_dir() else item.name assert check_name in gitignore_content, ( f"{item.name} was created in .autoskillit/ but is not in .gitignore " @@ -466,74 +491,20 @@ def test_gitignore_entries_includes_secrets_yaml() -> None: assert ".secrets.yaml" in _AUTOSKILLIT_GITIGNORE_ENTRIES -def test_gitignore_entries_includes_temp() -> None: - """_AUTOSKILLIT_GITIGNORE_ENTRIES must include temp/ — regression guard.""" - from autoskillit.core.io import _AUTOSKILLIT_GITIGNORE_ENTRIES - - assert "temp/" in _AUTOSKILLIT_GITIGNORE_ENTRIES - - -# RG-ROOT-2 -def test_root_gitignore_entries_covers_secrets_yaml() -> None: - """_ROOT_GITIGNORE_ENTRIES must include the root-scope secrets entry — regression guard.""" - from autoskillit.core.io import _ROOT_GITIGNORE_ENTRIES +def test_ensure_project_temp_does_not_mutate_root_gitignore(tmp_path: Path) -> None: + """ensure_project_temp() must NOT write to the project root .gitignore. - assert ".autoskillit/.secrets.yaml" in _ROOT_GITIGNORE_ENTRIES - - -# RG-ROOT-3 -def test_ensure_project_temp_writes_root_gitignore(tmp_path: Path) -> None: - """ensure_project_temp() must write all _ROOT_GITIGNORE_ENTRIES to the root .gitignore. - - This is the structural invariant test. Its failure signals that a new sensitive - root-scope entry was added without updating _ROOT_GITIGNORE_ENTRIES in core/io.py. + Per the self-gitignoring directory pattern (pytest #3286 / mypy PR #8193), + the resolved temp directory owns its own .gitignore. The project's + version-controlled root .gitignore is never mutated by this tool. """ - from autoskillit.core.io import _ROOT_GITIGNORE_ENTRIES, ensure_project_temp + from autoskillit.core.io import ensure_project_temp assert not (tmp_path / ".gitignore").exists(), "precondition: no root .gitignore" - - ensure_project_temp(tmp_path) - - root_gitignore = tmp_path / ".gitignore" - assert root_gitignore.exists(), "ensure_project_temp must create root .gitignore" - content = root_gitignore.read_text() - for entry in _ROOT_GITIGNORE_ENTRIES: - assert entry in content, ( - f"Root .gitignore is missing {entry!r}. " - "Add it to _ROOT_GITIGNORE_ENTRIES in core/io.py." - ) - - -# RG-ROOT-4 -def test_ensure_project_temp_appends_to_existing_root_gitignore(tmp_path: Path) -> None: - """ensure_project_temp() must append to an existing root .gitignore without overwriting.""" - from autoskillit.core.io import _ROOT_GITIGNORE_ENTRIES, ensure_project_temp - - existing_content = "*.pyc\n__pycache__/\n.env\n" - (tmp_path / ".gitignore").write_text(existing_content) - ensure_project_temp(tmp_path) - - content = (tmp_path / ".gitignore").read_text() - assert "*.pyc" in content, "existing root .gitignore content must be preserved" - assert "__pycache__/" in content, "existing root .gitignore content must be preserved" - for entry in _ROOT_GITIGNORE_ENTRIES: - assert entry in content, f"Missing entry {entry!r} after append" - - -# RG-ROOT-5 -def test_ensure_project_temp_root_gitignore_idempotent(tmp_path: Path) -> None: - """Running ensure_project_temp() twice must not duplicate root .gitignore entries.""" - from autoskillit.core.io import _ROOT_GITIGNORE_ENTRIES, ensure_project_temp - - ensure_project_temp(tmp_path) - ensure_project_temp(tmp_path) - - content = (tmp_path / ".gitignore").read_text() - for entry in _ROOT_GITIGNORE_ENTRIES: - assert content.count(entry) == 1, ( - f"Root .gitignore has duplicate entry for {entry!r} after two init calls" - ) + assert not (tmp_path / ".gitignore").exists(), ( + "ensure_project_temp must not create a root .gitignore" + ) # SS-INIT-1 @@ -814,3 +785,89 @@ def test_init_no_force_preserves_onboarded_marker( cli.init(force=False) assert marker.exists() + + +def test_init_from_pkg_root_like_cwd_refuses( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """_register_all() must refuse to run from inside the autoskillit source tree.""" + import autoskillit.core.paths as _paths + from autoskillit.cli._init_helpers import _register_all + + fake_pkg_root = tmp_path / "pkg" + fake_pkg_root.mkdir() + monkeypatch.setattr(_paths, "pkg_root", lambda: fake_pkg_root) + monkeypatch.chdir(fake_pkg_root) + + with pytest.raises(Exception, match="inside the autoskillit source tree"): + _register_all(scope="user", project_dir=fake_pkg_root) + + +# --- evict_direct_mcp_entry unit tests --- + + +def test_evict_direct_mcp_entry_removes_key(tmp_path: Path) -> None: + """evict_direct_mcp_entry() removes the autoskillit key and preserves all other keys.""" + from autoskillit.cli._init_helpers import evict_direct_mcp_entry + + claude_json = tmp_path / ".claude.json" + claude_json.write_text( + json.dumps( + { + "mcpServers": { + "autoskillit": {"type": "stdio", "command": "autoskillit", "args": []} + }, + "other": "preserved", + } + ) + ) + result = evict_direct_mcp_entry(claude_json) + assert result is True + data = json.loads(claude_json.read_text()) + assert "autoskillit" not in data.get("mcpServers", {}) + assert data["other"] == "preserved" + + +def test_evict_direct_mcp_entry_idempotent_when_absent(tmp_path: Path) -> None: + """evict_direct_mcp_entry() returns False and leaves the file unchanged when key is absent.""" + from autoskillit.cli._init_helpers import evict_direct_mcp_entry + + claude_json = tmp_path / ".claude.json" + original = {"mcpServers": {}} + claude_json.write_text(json.dumps(original)) + result = evict_direct_mcp_entry(claude_json) + assert result is False + assert json.loads(claude_json.read_text()) == original + + +def test_evict_direct_mcp_entry_returns_false_when_file_absent(tmp_path: Path) -> None: + """evict_direct_mcp_entry() returns False without raising when the file does not exist.""" + from autoskillit.cli._init_helpers import evict_direct_mcp_entry + + result = evict_direct_mcp_entry(tmp_path / "nonexistent.json") + assert result is False + + +def test_register_all_evicts_direct_entry_when_plugin_installed( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """_register_all() evicts the direct MCP entry when the plugin is already installed.""" + (tmp_path / ".pre-commit-config.yaml").write_text( + "repos:\n - repo: dummy\n hooks:\n - id: gitleaks\n" + ) + claude_json = tmp_path / ".claude.json" + claude_json.write_text( + json.dumps( + { + "mcpServers": { + "autoskillit": {"type": "stdio", "command": "autoskillit", "args": []} + } + } + ) + ) + monkeypatch.chdir(tmp_path) + monkeypatch.setattr(Path, "home", lambda: tmp_path) + monkeypatch.setattr("autoskillit.cli._init_helpers._is_plugin_installed", lambda: True) + cli.init(scope="user", test_command="task test-all") + data = json.loads(claude_json.read_text()) + assert "autoskillit" not in data.get("mcpServers", {}) diff --git a/tests/cli/test_input_tty_contracts.py b/tests/cli/test_input_tty_contracts.py index c679ec4d6b..ff583b7dc8 100644 --- a/tests/cli/test_input_tty_contracts.py +++ b/tests/cli/test_input_tty_contracts.py @@ -1,7 +1,7 @@ """ -Structural enforcement: every input() call in src/autoskillit/cli/ must be -preceded by _require_interactive_stdin(), or the function must be in the -allowlist (_TTY_EXEMPT_FUNCTIONS). +Structural enforcement: every input() call in src/autoskillit/cli/ must go +through timed_prompt() in _timed_input.py, or the function must be in the +allowlist (_RAW_INPUT_EXEMPT_FILES). """ from __future__ import annotations @@ -11,79 +11,82 @@ import pytest -# Functions exempt from the _require_interactive_stdin() contract. -# Two allowlist categories: -# - call-site-guarded: only called from contexts that already guarantee isatty() -# - custom-handled: implement their own non-interactive path (return a result, -# not SystemExit) — cannot use _require_interactive_stdin by design -_TTY_EXEMPT_FUNCTIONS: frozenset[str] = frozenset( +# Files that are *allowed* to contain raw input() calls. +# _timed_input.py is the sole module that wraps input() with timeout/TTY/ANSI. +_RAW_INPUT_EXEMPT_FILES: frozenset[str] = frozenset( { - "_prompt_github_repo", # call-site-guarded: only caller (_register_all) wraps in isatty() - "_check_secret_scanning", # custom-handled: returns _ScanResult(False) non-interactively - "run_onboarding_menu", # custom-handled: catches EOFError on each input() - "run_stale_check", # custom-handled: guards with isatty() check at entry + "_timed_input.py", # the prompt primitive itself } ) -_CLI_DIR = Path(__file__).resolve().parent.parent.parent / "src" / "autoskillit" / "cli" +_SRC_DIR = Path(__file__).resolve().parent.parent.parent / "src" +_CLI_DIR = _SRC_DIR / "autoskillit" / "cli" -def _has_tty_guard_before_input(func_body: list[ast.stmt]) -> bool: - """Return True if the function body contains a _require_interactive_stdin() call. - - The canonical TTY guard is exclusively _require_interactive_stdin(). Inline - isatty() checks are NOT accepted — they are too permissive: a function with - multiple input() calls passes even when only one call site is guarded, and - the enforcement silently breaks when the guard is removed. - """ - for node in ast.walk(ast.Module(body=func_body, type_ignores=[])): - if isinstance(node, ast.Call): - if isinstance(node.func, ast.Name) and node.func.id == "_require_interactive_stdin": - return True - return False +# --------------------------------------------------------------------------- +# Test 1a — no raw input() outside _timed_input.py +# --------------------------------------------------------------------------- -def test_all_input_calls_in_cli_are_tty_guarded() -> None: - """Every function in src/autoskillit/cli/ that calls input() must call - _require_interactive_stdin() in its body, OR be listed in _TTY_EXEMPT_FUNCTIONS. +def test_all_cli_prompts_use_timed_prompt_or_are_exempt() -> None: + """No function in src/autoskillit/cli/ may call input() directly except + those inside files listed in _RAW_INPUT_EXEMPT_FILES. - This prevents silent EOFError crashes in non-interactive environments and makes - the class of bugs in issue #470 structurally impossible to re-introduce. + All user-facing prompts must go through timed_prompt() which composes + TTY guard, ANSI formatting, and timeout into a single call. """ violations: list[str] = [] for py_file in sorted(_CLI_DIR.rglob("*.py")): + if py_file.name in _RAW_INPUT_EXEMPT_FILES: + continue source = py_file.read_text() tree = ast.parse(source, filename=str(py_file)) + rel_path = py_file.relative_to(_SRC_DIR) + + # Check inside function/method bodies for node in ast.walk(tree): if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): continue func_name = node.name - if func_name in _TTY_EXEMPT_FUNCTIONS: - continue - # Check if this function contains any input() call has_input = any( isinstance(n, ast.Call) and isinstance(n.func, ast.Name) and n.func.id == "input" for n in ast.walk(ast.Module(body=node.body, type_ignores=[])) ) - if not has_input: - continue - # Function has input() — verify TTY guard - if not _has_tty_guard_before_input(node.body): - rel_path = py_file.relative_to(Path("src")) + if has_input: violations.append( - f"{rel_path}:{node.lineno}: {func_name}() calls input() " - f"without _require_interactive_stdin()" + f"{rel_path}:{node.lineno}: {func_name}() calls raw input() — " + f"use timed_prompt() from _timed_input.py instead" ) + # Check module-level code (outside any function or class) + for stmt in tree.body: + if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)): + continue + for n in ast.walk(stmt): + if ( + isinstance(n, ast.Call) + and isinstance(n.func, ast.Name) + and n.func.id == "input" + ): + violations.append( + f"{rel_path}:{n.lineno}: calls raw input() — " + f"use timed_prompt() from _timed_input.py instead" + ) + assert not violations, ( - "The following CLI functions call input() without _require_interactive_stdin().\n" - "Add _require_interactive_stdin(context) at the start of each function,\n" - "or add the function to _TTY_EXEMPT_FUNCTIONS with a justification comment:\n\n" + "The following CLI functions call input() directly instead of timed_prompt().\n" + "All user-facing prompts must use timed_prompt() which composes TTY guard,\n" + "ANSI formatting, and select.select timeout into a single call:\n\n" + "\n".join(f" • {v}" for v in violations) ) +# --------------------------------------------------------------------------- +# _require_interactive_stdin behavioural tests (kept for regression coverage) +# --------------------------------------------------------------------------- + + def test_require_interactive_stdin_raises_system_exit_when_not_tty( monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture ) -> None: diff --git a/tests/cli/test_install.py b/tests/cli/test_install.py index bb7d729675..e42a981d2e 100644 --- a/tests/cli/test_install.py +++ b/tests/cli/test_install.py @@ -171,6 +171,40 @@ def test_install_idempotent_marketplace( assert (tmp_path / ".autoskillit" / "marketplace" / "plugins" / "autoskillit").is_symlink() + @patch("autoskillit.cli._marketplace.subprocess.run") + def test_install_evicts_stale_direct_mcp_entry( + self, mock_run: MagicMock, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """install() must remove a stale mcpServers.autoskillit entry left by a prior init.""" + import importlib as _importlib + + _app_mod = _importlib.import_module("autoskillit.cli._marketplace") + + # Seed stale direct entry as left by a prior `autoskillit init` + claude_json = tmp_path / ".claude.json" + claude_json.write_text( + json.dumps( + { + "mcpServers": { + "autoskillit": {"type": "stdio", "command": "autoskillit", "args": []} + } + } + ) + ) + monkeypatch.setattr(Path, "home", lambda: tmp_path) + monkeypatch.setattr(shutil, "which", lambda cmd: "/usr/bin/claude") + monkeypatch.delenv("CLAUDECODE", raising=False) + monkeypatch.setattr(_app_mod, "is_git_worktree", lambda path: False) + mock_run.return_value = subprocess.CompletedProcess( + args=[], returncode=0, stdout="", stderr="" + ) + from autoskillit.cli._marketplace import install + + install(scope="user") + + data = json.loads(claude_json.read_text()) + assert "autoskillit" not in data.get("mcpServers", {}) + class TestMigrateCommand: """Tests for the ``autoskillit migrate`` CLI command.""" @@ -409,23 +443,23 @@ def test_quota_hook_script_exists(self): import autoskillit pkg_dir = Path(autoskillit.__file__).parent - hook_script = pkg_dir / "hooks" / "quota_check.py" + hook_script = pkg_dir / "hooks" / "quota_guard.py" assert hook_script.exists(), f"Expected hook script at {hook_script}" def test_generate_hooks_json_includes_quota_hook(self): - """generate_hooks_json() must include quota_check.py in PreToolUse and pretty_output.py in PostToolUse.""" # noqa: E501 + """generate_hooks_json() must include quota_guard.py in PreToolUse and pretty_output_hook.py in PostToolUse.""" # noqa: E501 from autoskillit.hook_registry import generate_hooks_json data = generate_hooks_json() pretooluse_commands = [ hook["command"] for entry in data["hooks"]["PreToolUse"] for hook in entry["hooks"] ] - assert any(cmd.endswith("quota_check.py") for cmd in pretooluse_commands) + assert any(cmd.endswith("quota_guard.py") for cmd in pretooluse_commands) assert "PostToolUse" in data["hooks"] posttooluse_commands = [ hook["command"] for entry in data["hooks"]["PostToolUse"] for hook in entry["hooks"] ] - assert any(cmd.endswith("pretty_output.py") for cmd in posttooluse_commands) + assert any(cmd.endswith("pretty_output_hook.py") for cmd in posttooluse_commands) def test_install_writes_pretooluse_hooks(self, tmp_path, monkeypatch): """install must register the quota PreToolUse hook in .claude/settings.json.""" @@ -519,3 +553,199 @@ def test_install_remove_clone_guard_hook_idempotent(self, tmp_path, monkeypatch) assert len(remove_clone_entries) == 1, ( f"Expected exactly 1 remove_clone hook entry, got {len(remove_clone_entries)}" ) + + +def test_clear_plugin_cache_removes_nested_entry( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """_clear_plugin_cache must remove the entry from data['plugins'], not top-level data.""" + from autoskillit.cli._marketplace import _clear_plugin_cache + + plugins_dir = tmp_path / ".claude" / "plugins" + plugins_dir.mkdir(parents=True) + installed_json = plugins_dir / "installed_plugins.json" + installed_json.write_text( + json.dumps( + { + "version": 2, + "plugins": {"autoskillit@autoskillit-local": {"name": "autoskillit"}}, + } + ) + ) + monkeypatch.setattr(Path, "home", lambda: tmp_path) + _clear_plugin_cache() + data = json.loads(installed_json.read_text()) + assert "autoskillit@autoskillit-local" not in data.get("plugins", {}) + assert data["version"] == 2 # other keys preserved + + +def test_clear_plugin_cache_noop_when_entry_absent( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """_clear_plugin_cache must not raise when the entry is already absent.""" + from autoskillit.cli._marketplace import _clear_plugin_cache + + plugins_dir = tmp_path / ".claude" / "plugins" + plugins_dir.mkdir(parents=True) + installed_json = plugins_dir / "installed_plugins.json" + installed_json.write_text(json.dumps({"version": 2, "plugins": {}})) + monkeypatch.setattr(Path, "home", lambda: tmp_path) + _clear_plugin_cache() # must not raise + data = json.loads(installed_json.read_text()) + assert data == {"version": 2, "plugins": {}} + + +def test_install_claudecode_guard_returns_false( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """install() must return False when CLAUDECODE guard fires, not None-as-success.""" + import importlib as _importlib + + from autoskillit.cli._marketplace import install as _install + + _app_mod = _importlib.import_module("autoskillit.cli._marketplace") + monkeypatch.setattr(_app_mod, "is_git_worktree", lambda path: False) + monkeypatch.setenv("CLAUDECODE", "1") + monkeypatch.setattr(Path, "home", lambda: tmp_path) + result = _install(scope="user") + assert result is False, f"Expected False, got {result!r}" + + +def test_install_claudecode_guard_does_not_print_next_steps( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """app.install() must not print Next Steps when CLAUDECODE guard fires.""" + + import autoskillit.cli._init_helpers as _init_helpers_mod + import autoskillit.cli._marketplace as _mkt_mod + + next_steps_called: list[dict] = [] + monkeypatch.setattr( + _init_helpers_mod, "_print_next_steps", lambda **kw: next_steps_called.append(kw) + ) + monkeypatch.setattr(_mkt_mod, "install", lambda **kw: False) + monkeypatch.setattr(Path, "home", lambda: tmp_path) + + from autoskillit.cli.app import install as app_install + + app_install(scope="user") + assert not next_steps_called, ( + "_print_next_steps must not be called when install() returns False" + ) + + +def test_install_sweeps_all_scopes_for_orphans( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """install() evicts orphaned autoskillit hooks from non-target scopes.""" + import json as _json + + from autoskillit.cli._hooks import sweep_all_scopes_for_orphans + + home = tmp_path / "home" + project = tmp_path / "project" + home.mkdir() + project.mkdir() + + project_settings = project / ".claude" / "settings.json" + project_settings.parent.mkdir(parents=True) + project_settings.write_text( + _json.dumps( + { + "hooks": { + "PostToolUse": [ + { + "matcher": "mcp__.*autoskillit.*", + "hooks": [ + {"type": "command", "command": "python3 /stale/pretty_output.py"} + ], + } + ] + } + } + ) + ) + + monkeypatch.setattr(Path, "home", lambda: home) + monkeypatch.chdir(project) + + sweep_all_scopes_for_orphans(project) + + data = _json.loads(project_settings.read_text()) + for event_hooks in data.get("hooks", {}).values(): + for entry in event_hooks: + for hook in entry.get("hooks", []): + assert "pretty_output.py" not in hook["command"], ( + "Orphaned hook was not evicted from project scope" + ) + + +def test_install_creates_autoskillit_gitignore( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """After install(), .autoskillit/.gitignore must exist (ensure_project_temp was called).""" + import importlib as _importlib + + from autoskillit.cli._marketplace import install as _install + + _app_mod = _importlib.import_module("autoskillit.cli._marketplace") + monkeypatch.setattr(_app_mod, "is_git_worktree", lambda path: False) + monkeypatch.setattr(Path, "home", lambda: tmp_path) + monkeypatch.setattr(Path, "cwd", lambda: tmp_path) + monkeypatch.delenv("CLAUDECODE", raising=False) + monkeypatch.setattr("shutil.which", lambda _: "/usr/bin/claude") + monkeypatch.setattr( + "subprocess.run", + lambda *a, **kw: type("R", (), {"returncode": 0, "stdout": "", "stderr": ""})(), + ) + monkeypatch.setattr("autoskillit.cli._marketplace.evict_direct_mcp_entry", lambda _: False) + monkeypatch.setattr( + "autoskillit.cli._marketplace.sweep_all_scopes_for_orphans", lambda _: None + ) + monkeypatch.setattr("autoskillit.cli._marketplace.sync_hooks_to_settings", lambda _: None) + monkeypatch.setattr("autoskillit.cli._marketplace.generate_hooks_json", lambda: {}) + monkeypatch.setattr("autoskillit.cli._marketplace.atomic_write", lambda *a, **kw: None) + + (tmp_path / ".autoskillit").mkdir() + _install(scope="user") + + assert (tmp_path / ".autoskillit" / ".gitignore").exists(), ( + ".autoskillit/.gitignore must be created by install(), not just by init()" + ) + + +def test_install_calls_upgrade_when_scripts_dir_exists( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """install() must migrate .autoskillit/scripts/ → .autoskillit/recipes/ if scripts/ exists.""" + import importlib as _importlib + + from autoskillit.cli._marketplace import install as _install + + _app_mod = _importlib.import_module("autoskillit.cli._marketplace") + monkeypatch.setattr(_app_mod, "is_git_worktree", lambda path: False) + monkeypatch.setattr(Path, "home", lambda: tmp_path) + monkeypatch.setattr(Path, "cwd", lambda: tmp_path) + monkeypatch.delenv("CLAUDECODE", raising=False) + monkeypatch.setattr("shutil.which", lambda _: "/usr/bin/claude") + monkeypatch.setattr( + "subprocess.run", + lambda *a, **kw: type("R", (), {"returncode": 0, "stdout": "", "stderr": ""})(), + ) + monkeypatch.setattr("autoskillit.cli._marketplace.evict_direct_mcp_entry", lambda _: False) + monkeypatch.setattr( + "autoskillit.cli._marketplace.sweep_all_scopes_for_orphans", lambda _: None + ) + monkeypatch.setattr("autoskillit.cli._marketplace.sync_hooks_to_settings", lambda _: None) + monkeypatch.setattr("autoskillit.cli._marketplace.generate_hooks_json", lambda: {}) + monkeypatch.setattr("autoskillit.cli._marketplace.atomic_write", lambda *a, **kw: None) + + scripts_dir = tmp_path / ".autoskillit" / "scripts" + scripts_dir.mkdir(parents=True) + + _install(scope="user") + + assert (tmp_path / ".autoskillit" / "recipes").exists(), ( + "install() must migrate scripts/ to recipes/ when scripts/ exists" + ) + assert not scripts_dir.exists(), "scripts/ must be renamed away" diff --git a/tests/cli/test_install_info.py b/tests/cli/test_install_info.py new file mode 100644 index 0000000000..0ae8e9b18d --- /dev/null +++ b/tests/cli/test_install_info.py @@ -0,0 +1,346 @@ +"""Tests for cli/_install_info.py — install classification and update policy.""" + +from __future__ import annotations + +import json +from datetime import timedelta +from pathlib import Path +from unittest.mock import MagicMock + +import pytest + +from autoskillit.cli._install_info import ( + _INSTALL_FROM_INTEGRATION, + InstallInfo, + InstallType, + comparison_branch, + detect_install, + dismissal_window, + upgrade_command, +) + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _fake_dist(direct_url_json: str | None) -> MagicMock: + """Return a mock Distribution whose read_text('direct_url.json') returns the given string.""" + dist = MagicMock() + dist.read_text.return_value = direct_url_json + return dist + + +# --------------------------------------------------------------------------- +# detect_install — classification tests +# --------------------------------------------------------------------------- + + +def test_detect_install_git_vcs_stable(monkeypatch: pytest.MonkeyPatch) -> None: + payload = json.dumps( + { + "url": "https://github.com/TalonT-Org/AutoSkillit.git", + "vcs_info": { + "vcs": "git", + "requested_revision": "stable", + "commit_id": "abc123def456", + }, + } + ) + monkeypatch.setattr( + "importlib.metadata.Distribution.from_name", + lambda _name: _fake_dist(payload), + ) + info = detect_install() + assert info.install_type == InstallType.GIT_VCS + assert info.commit_id == "abc123def456" + assert info.requested_revision == "stable" + assert info.editable_source is None + + +def test_detect_install_git_vcs_integration(monkeypatch: pytest.MonkeyPatch) -> None: + payload = json.dumps( + { + "url": "https://github.com/TalonT-Org/AutoSkillit.git", + "vcs_info": { + "vcs": "git", + "requested_revision": "integration", + "commit_id": "deadbeef0000", + }, + } + ) + monkeypatch.setattr( + "importlib.metadata.Distribution.from_name", + lambda _name: _fake_dist(payload), + ) + info = detect_install() + assert info.install_type == InstallType.GIT_VCS + assert info.requested_revision == "integration" + assert info.commit_id == "deadbeef0000" + + +def test_detect_install_git_vcs_release_tag(monkeypatch: pytest.MonkeyPatch) -> None: + payload = json.dumps( + { + "url": "https://github.com/TalonT-Org/AutoSkillit.git", + "vcs_info": { + "vcs": "git", + "requested_revision": "v0.7.75", + "commit_id": "cafebabe1234", + }, + } + ) + monkeypatch.setattr( + "importlib.metadata.Distribution.from_name", + lambda _name: _fake_dist(payload), + ) + info = detect_install() + assert info.install_type == InstallType.GIT_VCS + assert info.requested_revision == "v0.7.75" + assert info.commit_id == "cafebabe1234" + + +def test_detect_install_local_editable(monkeypatch: pytest.MonkeyPatch) -> None: + payload = json.dumps( + { + "url": "file:///tmp/repo", + "dir_info": {"editable": True}, + } + ) + monkeypatch.setattr( + "importlib.metadata.Distribution.from_name", + lambda _name: _fake_dist(payload), + ) + info = detect_install() + assert info.install_type == InstallType.LOCAL_EDITABLE + assert info.editable_source == Path("/tmp/repo") + assert info.requested_revision is None + assert info.commit_id is None + + +def test_detect_install_local_path(monkeypatch: pytest.MonkeyPatch) -> None: + payload = json.dumps( + { + "url": "file:///home/user/autoskillit", + "dir_info": {}, + } + ) + monkeypatch.setattr( + "importlib.metadata.Distribution.from_name", + lambda _name: _fake_dist(payload), + ) + info = detect_install() + assert info.install_type == InstallType.LOCAL_PATH + + +def test_detect_install_unknown_no_direct_url(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + "importlib.metadata.Distribution.from_name", + lambda _name: _fake_dist(None), + ) + info = detect_install() + assert info.install_type == InstallType.UNKNOWN + + +def test_detect_install_unknown_malformed_json(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + "importlib.metadata.Distribution.from_name", + lambda _name: _fake_dist("{{not-json}}"), + ) + info = detect_install() + assert info.install_type == InstallType.UNKNOWN + + +# --------------------------------------------------------------------------- +# comparison_branch — policy tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "requested_revision,expected", + [ + ("stable", "releases/latest"), + ("main", "releases/latest"), + ("v0.7.75", "releases/latest"), + (None, "releases/latest"), # UNKNOWN has no revision + ], +) +def test_comparison_branch_stable_variants(requested_revision: str | None, expected: str) -> None: + info = InstallInfo( + install_type=InstallType.GIT_VCS, + commit_id="abc123", + requested_revision=requested_revision, + url=None, + editable_source=None, + ) + assert comparison_branch(info) == expected + + +def test_comparison_branch_unknown_type() -> None: + info = InstallInfo( + install_type=InstallType.UNKNOWN, + commit_id=None, + requested_revision=None, + url=None, + editable_source=None, + ) + assert comparison_branch(info) == "releases/latest" + + +def test_comparison_branch_integration() -> None: + info = InstallInfo( + install_type=InstallType.GIT_VCS, + commit_id="abc123", + requested_revision="integration", + url=None, + editable_source=None, + ) + assert comparison_branch(info) == "integration" + + +@pytest.mark.parametrize( + "install_type", + [InstallType.LOCAL_EDITABLE, InstallType.LOCAL_PATH], +) +def test_comparison_branch_local_types_returns_none(install_type: InstallType) -> None: + info = InstallInfo( + install_type=install_type, + commit_id=None, + requested_revision=None, + url=None, + editable_source=Path("/tmp/repo") if install_type == InstallType.LOCAL_EDITABLE else None, + ) + assert comparison_branch(info) is None + + +# --------------------------------------------------------------------------- +# dismissal_window — policy tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "requested_revision,install_type", + [ + ("stable", InstallType.GIT_VCS), + ("main", InstallType.GIT_VCS), + ("v0.7.75", InstallType.GIT_VCS), + (None, InstallType.UNKNOWN), + ], +) +def test_dismissal_window_seven_days( + requested_revision: str | None, install_type: InstallType +) -> None: + info = InstallInfo( + install_type=install_type, + commit_id=None, + requested_revision=requested_revision, + url=None, + editable_source=None, + ) + assert dismissal_window(info) == timedelta(days=7) + + +@pytest.mark.parametrize( + "requested_revision,install_type,editable_source", + [ + ("integration", InstallType.GIT_VCS, None), + (None, InstallType.LOCAL_EDITABLE, Path("/tmp/repo")), + ], +) +def test_dismissal_window_twelve_hours( + requested_revision: str | None, + install_type: InstallType, + editable_source: Path | None, +) -> None: + info = InstallInfo( + install_type=install_type, + commit_id=None, + requested_revision=requested_revision, + url=None, + editable_source=editable_source, + ) + assert dismissal_window(info) == timedelta(hours=12) + + +# --------------------------------------------------------------------------- +# upgrade_command — policy tests +# --------------------------------------------------------------------------- + + +def test_upgrade_command_stable() -> None: + info = InstallInfo( + install_type=InstallType.GIT_VCS, + commit_id="abc123", + requested_revision="stable", + url=None, + editable_source=None, + ) + assert upgrade_command(info) == ["uv", "tool", "upgrade", "autoskillit"] + + +def test_upgrade_command_main() -> None: + info = InstallInfo( + install_type=InstallType.GIT_VCS, + commit_id="abc123", + requested_revision="main", + url=None, + editable_source=None, + ) + assert upgrade_command(info) == ["uv", "tool", "upgrade", "autoskillit"] + + +def test_upgrade_command_release_tag() -> None: + info = InstallInfo( + install_type=InstallType.GIT_VCS, + commit_id="abc123", + requested_revision="v0.7.75", + url=None, + editable_source=None, + ) + assert upgrade_command(info) == ["uv", "tool", "upgrade", "autoskillit"] + + +def test_upgrade_command_integration() -> None: + info = InstallInfo( + install_type=InstallType.GIT_VCS, + commit_id="abc123", + requested_revision="integration", + url=None, + editable_source=None, + ) + assert upgrade_command(info) == [ + "uv", + "tool", + "install", + "--force", + _INSTALL_FROM_INTEGRATION, + ] + + +def test_upgrade_command_local_editable() -> None: + editable_source = Path("/home/user/autoskillit") + info = InstallInfo( + install_type=InstallType.LOCAL_EDITABLE, + commit_id=None, + requested_revision=None, + url="file:///home/user/autoskillit", + editable_source=editable_source, + ) + assert upgrade_command(info) == ["uv", "pip", "install", "-e", str(editable_source)] + + +@pytest.mark.parametrize( + "install_type", + [InstallType.UNKNOWN, InstallType.LOCAL_PATH], +) +def test_upgrade_command_unknown_and_local_path_returns_none( + install_type: InstallType, +) -> None: + info = InstallInfo( + install_type=install_type, + commit_id=None, + requested_revision=None, + url=None, + editable_source=None, + ) + assert upgrade_command(info) is None diff --git a/tests/cli/test_installed_plugins_file.py b/tests/cli/test_installed_plugins_file.py new file mode 100644 index 0000000000..f7278ef838 --- /dev/null +++ b/tests/cli/test_installed_plugins_file.py @@ -0,0 +1,81 @@ +"""Unit tests for the InstalledPluginsFile repository.""" + +from __future__ import annotations + +import json +from pathlib import Path + +from autoskillit.cli._installed_plugins import InstalledPluginsFile + +REAL_STRUCTURE = { + "version": 2, + "plugins": {"autoskillit@autoskillit-local": {"name": "autoskillit", "version": "0.8.30"}}, +} + + +def _write(path: Path, data: dict) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data)) + + +def test_contains_finds_entry_in_nested_plugins(tmp_path: Path) -> None: + p = tmp_path / "installed_plugins.json" + _write(p, REAL_STRUCTURE) + assert InstalledPluginsFile(p).contains("autoskillit@autoskillit-local") is True + + +def test_contains_does_not_false_positive_on_flat_structure(tmp_path: Path) -> None: + """A flat dict should NOT be treated as containing the plugin.""" + p = tmp_path / "installed_plugins.json" + _write(p, {"autoskillit@autoskillit-local": {}}) # flat — wrong format + # With the real nested structure absent, contains() must return False + assert InstalledPluginsFile(p).contains("autoskillit@autoskillit-local") is False + + +def test_contains_returns_false_when_missing(tmp_path: Path) -> None: + p = tmp_path / "installed_plugins.json" + _write(p, {"version": 2, "plugins": {}}) + assert InstalledPluginsFile(p).contains("autoskillit@autoskillit-local") is False + + +def test_contains_returns_false_when_file_absent(tmp_path: Path) -> None: + p = tmp_path / "no_file.json" + assert InstalledPluginsFile(p).contains("autoskillit@autoskillit-local") is False + + +def test_remove_deletes_nested_entry(tmp_path: Path) -> None: + p = tmp_path / "installed_plugins.json" + _write(p, REAL_STRUCTURE) + InstalledPluginsFile(p).remove("autoskillit@autoskillit-local") + data = json.loads(p.read_text()) + assert "autoskillit@autoskillit-local" not in data.get("plugins", {}) + + +def test_remove_preserves_other_keys(tmp_path: Path) -> None: + p = tmp_path / "installed_plugins.json" + payload = { + "version": 2, + "plugins": { + "autoskillit@autoskillit-local": {}, + "other@other-local": {"name": "other"}, + }, + } + _write(p, payload) + InstalledPluginsFile(p).remove("autoskillit@autoskillit-local") + data = json.loads(p.read_text()) + assert data["version"] == 2 + assert "other@other-local" in data["plugins"] + + +def test_remove_is_noop_when_key_absent(tmp_path: Path) -> None: + p = tmp_path / "installed_plugins.json" + _write(p, {"version": 2, "plugins": {}}) + InstalledPluginsFile(p).remove("autoskillit@autoskillit-local") # should not raise + data = json.loads(p.read_text()) + assert data == {"version": 2, "plugins": {}} + + +def test_remove_is_noop_when_file_absent(tmp_path: Path) -> None: + p = tmp_path / "no_file.json" + InstalledPluginsFile(p).remove("autoskillit@autoskillit-local") # should not raise + assert not p.exists() diff --git a/tests/cli/test_onboarding.py b/tests/cli/test_onboarding.py index 72828f759e..d49bc607a0 100644 --- a/tests/cli/test_onboarding.py +++ b/tests/cli/test_onboarding.py @@ -93,6 +93,7 @@ def test_run_onboarding_menu_decline_returns_none_and_marks( """User inputs 'n' to the initial prompt. Returns None and marker is created.""" _make_initialized_project(tmp_path) inputs = iter(["n"]) + monkeypatch.setattr("sys.stdin.isatty", lambda: True) monkeypatch.setattr("builtins.input", lambda _prompt="": next(inputs)) result = run_onboarding_menu(tmp_path, color=False) assert result is None @@ -106,6 +107,7 @@ def test_run_onboarding_menu_skip_e_returns_none_and_marks( """User inputs 'y', then 'E'. Returns None and marker is created.""" _make_initialized_project(tmp_path) inputs = iter(["y", "E"]) + monkeypatch.setattr("sys.stdin.isatty", lambda: True) monkeypatch.setattr("builtins.input", lambda _prompt="": next(inputs)) monkeypatch.setattr("autoskillit.cli._onboarding.gather_intel", lambda _p: OnboardingIntel()) result = run_onboarding_menu(tmp_path, color=False) @@ -120,6 +122,7 @@ def test_run_onboarding_menu_option_a_returns_setup_project( """User inputs 'y', then 'A'. Returns /autoskillit:setup-project. Marker NOT created yet.""" _make_initialized_project(tmp_path) inputs = iter(["y", "A"]) + monkeypatch.setattr("sys.stdin.isatty", lambda: True) monkeypatch.setattr("builtins.input", lambda _prompt="": next(inputs)) monkeypatch.setattr("autoskillit.cli._onboarding.gather_intel", lambda _p: OnboardingIntel()) result = run_onboarding_menu(tmp_path, color=False) @@ -135,6 +138,7 @@ def test_run_onboarding_menu_option_b_with_url_returns_prepare_issue( """User inputs 'y', then 'B', then a URL. Returns string with /autoskillit:prepare-issue.""" _make_initialized_project(tmp_path) inputs = iter(["y", "B", "https://github.com/org/repo/issues/42"]) + monkeypatch.setattr("sys.stdin.isatty", lambda: True) monkeypatch.setattr("builtins.input", lambda _prompt="": next(inputs)) monkeypatch.setattr("autoskillit.cli._onboarding.gather_intel", lambda _p: OnboardingIntel()) result = run_onboarding_menu(tmp_path, color=False) @@ -149,6 +153,7 @@ def test_run_onboarding_menu_option_d_returns_write_recipe( """User inputs 'y', then 'D'. Returns string with /autoskillit:write-recipe.""" _make_initialized_project(tmp_path) inputs = iter(["y", "D"]) + monkeypatch.setattr("sys.stdin.isatty", lambda: True) monkeypatch.setattr("builtins.input", lambda _prompt="": next(inputs)) monkeypatch.setattr("autoskillit.cli._onboarding.gather_intel", lambda _p: OnboardingIntel()) result = run_onboarding_menu(tmp_path, color=False) @@ -163,6 +168,7 @@ def test_run_onboarding_menu_option_c_returns_setup_project_prompt( """User inputs 'y', then 'C'. Returns string starting with /autoskillit:setup-project.""" _make_initialized_project(tmp_path) inputs = iter(["y", "C"]) + monkeypatch.setattr("sys.stdin.isatty", lambda: True) monkeypatch.setattr("builtins.input", lambda _prompt="": next(inputs)) monkeypatch.setattr("autoskillit.cli._onboarding.gather_intel", lambda _p: OnboardingIntel()) result = run_onboarding_menu(tmp_path, color=False) diff --git a/tests/cli/test_orchestrator_prompt_contract.py b/tests/cli/test_orchestrator_prompt_contract.py new file mode 100644 index 0000000000..69055a6e20 --- /dev/null +++ b/tests/cli/test_orchestrator_prompt_contract.py @@ -0,0 +1,103 @@ +"""Tests for orchestrator prompt contract: failure predicates and dispatch consistency.""" + +from __future__ import annotations + +import re + + +def _get_prompt() -> str: + """Return the orchestrator prompt for a demo recipe.""" + from autoskillit.cli._prompts import _build_orchestrator_prompt + + return _build_orchestrator_prompt("demo", "mcp__autoskillit__") + + +class TestOpenKitchenFailurePredicate: + """Guards for the FAILURE PREDICATE — open_kitchen block in the orchestrator prompt.""" + + def test_prompt_contains_open_kitchen_failure_predicate(self): + prompt = _get_prompt() + assert "FAILURE PREDICATE — open_kitchen" in prompt + + def test_prompt_open_kitchen_predicate_mentions_success_false_substring(self): + prompt = _get_prompt() + # Find the open_kitchen predicate section + idx = prompt.index("FAILURE PREDICATE — open_kitchen") + section = prompt[idx : idx + 500] + assert '"success": false' in section + + def test_prompt_open_kitchen_predicate_mentions_user_visible_message(self): + prompt = _get_prompt() + idx = prompt.index("FAILURE PREDICATE — open_kitchen") + section = prompt[idx : idx + 500] + assert "user_visible_message" in section + + def test_prompt_open_kitchen_predicate_forbids_askuserquestion(self): + prompt = _get_prompt() + idx = prompt.index("FAILURE PREDICATE — open_kitchen") + section = prompt[idx : idx + 500] + assert "DO NOT call AskUserQuestion" in section + + def test_open_kitchen_predicate_uses_substring_not_json_field_dispatch(self): + """Negative: the predicate block must NOT use JSON-field dispatch phrasing.""" + prompt = _get_prompt() + idx = prompt.index("FAILURE PREDICATE — open_kitchen") + section = prompt[idx : idx + 500] + assert "json.loads" not in section.lower() + assert "parsed[" not in section + + +class TestStep0ToolPredicateCoverage: + """Every tool referenced in STEP 0 must have a failure predicate or shared rule.""" + + def test_every_step0_tool_has_failure_predicate_or_shared_rule(self): + """Parse STEP 0 section, extract tool names, assert each has a predicate.""" + prompt = _get_prompt() + + # Extract tool names from STEP 0 (tools appear as {mcp_prefix} or explicit names) + step0_match = re.search( + r"FIRST ACTION.*?(?=ROUTING RULES|FAILURE PREDICATES|During pipeline)", + prompt, + re.DOTALL, + ) + assert step0_match is not None, "STEP 0 / FIRST ACTION section not found" + step0_text = step0_match.group() + + # Find tool names: mcp__autoskillit__() + tool_names = set(re.findall(r"mcp__autoskillit__(\w+)\(", step0_text)) + assert len(tool_names) > 0, "No tool names found in STEP 0" + + # Each tool must appear in a FAILURE PREDICATE section + for tool in tool_names: + assert f"FAILURE PREDICATE — {tool}" in prompt or f"- {tool}:" in prompt, ( + f"Tool '{tool}' in STEP 0 has no failure predicate or shared rule" + ) + + +class TestFirstActionAskUserQuestionProhibition: + """FIRST ACTION section must explicitly prohibit AskUserQuestion before open_kitchen.""" + + def test_first_action_prohibits_ask_user_question_before_open_kitchen(self): + """The FIRST ACTION section must contain an explicit prohibition on + AskUserQuestion before open_kitchen.""" + prompt = _get_prompt() + first_action_start = prompt.index("FIRST ACTION") + # Find the end of the FIRST ACTION section (next major section) + first_action_end = prompt.index("During pipeline execution", first_action_start) + first_action_section = prompt[first_action_start:first_action_end] + assert "DO NOT call AskUserQuestion" in first_action_section + + +class TestFirstActionTimingResilience: + """FIRST ACTION must acknowledge MCP initialization timing.""" + + def test_first_action_is_timing_resilient(self): + """FIRST ACTION must not unconditionally command 'MUST be first' + without acknowledging MCP initialization timing.""" + prompt = _get_prompt() + first_action_start = prompt.index("FIRST ACTION") + first_action_end = prompt.index("During pipeline execution", first_action_start) + first_action_section = prompt[first_action_start:first_action_end] + assert ( + "retry" in first_action_section.lower() or "available" in first_action_section.lower() + ), "FIRST ACTION must acknowledge MCP init timing with retry/availability guidance" diff --git a/tests/cli/test_serve_sigterm.py b/tests/cli/test_serve_sigterm.py new file mode 100644 index 0000000000..d7395e5a56 --- /dev/null +++ b/tests/cli/test_serve_sigterm.py @@ -0,0 +1,50 @@ +"""Test that serve() uses event-loop-routed signal handling. Regression guard for issue #745. + +The original serve() installed a raw signal.signal(SIGTERM) handler that raised +KeyboardInterrupt, which escaped anyio's C-level event-loop runner before +finally: blocks could fire. The new implementation delegates to anyio.run() +with a _serve_with_signal_guard closure that uses anyio.open_signal_receiver. + +Structural enforcement (no raw signal.signal SIGTERM) is covered by the AST guard +in tests/server/test_no_raw_signal_handler.py. This test covers unit behavior: +serve() must call anyio.run() and pass it an async coroutine function. +""" + +from __future__ import annotations + +import inspect +from unittest.mock import MagicMock + + +def test_serve_uses_anyio_run_not_mcp_run(monkeypatch, tmp_path): + """serve() routes through anyio.run(), not mcp.run() directly.""" + anyio_calls: list = [] + + monkeypatch.chdir(tmp_path) + + mock_cfg = MagicMock() + mock_cfg.logging.level = "INFO" + mock_cfg.logging.json_output = None + mock_cfg.safety.protected_branches = [] + + monkeypatch.setattr("autoskillit.config.load_config", lambda _: mock_cfg) + monkeypatch.setattr("autoskillit.core.configure_logging", lambda **kw: None) + monkeypatch.setattr("autoskillit.server.make_context", lambda *a, **kw: MagicMock()) + monkeypatch.setattr("autoskillit.server._initialize", lambda ctx: None) + + def capture_anyio_run(coro_fn, *args, **kwargs): + anyio_calls.append(coro_fn) + # Do not actually run it — just record the call + + monkeypatch.setattr("anyio.run", capture_anyio_run) + + from autoskillit.cli.app import serve + + serve() + + assert anyio_calls, "serve() did not call anyio.run()" + guard_fn = anyio_calls[0] + # _serve_with_signal_guard is a local async closure — must be a coroutine function + assert inspect.iscoroutinefunction(guard_fn), ( + f"Expected serve() to pass an async coroutine function to anyio.run(), got {guard_fn!r}" + ) diff --git a/tests/cli/test_stale_check.py b/tests/cli/test_stale_check.py deleted file mode 100644 index 2773e0a70c..0000000000 --- a/tests/cli/test_stale_check.py +++ /dev/null @@ -1,545 +0,0 @@ -"""Tests for cli/_stale_check.py — stale-install detection.""" - -from __future__ import annotations - -import io -import subprocess -import sys -from datetime import UTC, datetime, timedelta -from pathlib import Path -from unittest.mock import MagicMock - -import pytest - - -# SC-1: dev mode via ~/.autoskillit/dev marker -def test_is_dev_mode_home_marker(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(Path, "home", lambda: tmp_path) - (tmp_path / ".autoskillit").mkdir() - (tmp_path / ".autoskillit" / "dev").touch() - from autoskillit.cli._stale_check import is_dev_mode - - assert is_dev_mode(home=tmp_path) is True - - -# SC-2: dev mode via project-level .autoskillit/dev marker -def test_is_dev_mode_project_marker(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.chdir(tmp_path) - (tmp_path / ".autoskillit").mkdir() - (tmp_path / ".autoskillit" / "dev").touch() - monkeypatch.setattr(Path, "home", lambda: tmp_path / "home_no_marker") - from autoskillit.cli._stale_check import is_dev_mode - - assert is_dev_mode(home=tmp_path / "home_no_marker") is True - - -# SC-3: dev mode via git main checkout (.git dir, not file) -def test_is_dev_mode_git_checkout(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - (tmp_path / ".git").mkdir() # .git dir = main checkout - import autoskillit.cli._stale_check as _sc - - monkeypatch.setattr(_sc, "pkg_root", lambda: tmp_path / "src" / "autoskillit") - assert _sc.is_dev_mode(home=tmp_path / "home_no_marker") is True - - -# SC-4: no dev markers → False -def test_is_dev_mode_no_markers(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.chdir(tmp_path) - monkeypatch.setattr(Path, "home", lambda: tmp_path) - import autoskillit.cli._stale_check as _sc - - monkeypatch.setattr(_sc, "pkg_root", lambda: tmp_path) # no .git dir, no .autoskillit/dev - assert _sc.is_dev_mode(home=tmp_path) is False - - -# SC-5: read_dismiss_state — missing file → {} -def test_read_dismiss_state_empty(tmp_path: Path) -> None: - from autoskillit.cli._stale_check import _read_dismiss_state - - assert _read_dismiss_state(tmp_path) == {} - - -# SC-6: read_dismiss_state — malformed JSON → {} -def test_read_dismiss_state_malformed(tmp_path: Path) -> None: - state_file = tmp_path / ".autoskillit" / "update_check.json" - state_file.parent.mkdir() - state_file.write_text("not json!") - from autoskillit.cli._stale_check import _read_dismiss_state - - assert _read_dismiss_state(tmp_path) == {} - - -# SC-7: write_dismiss_state round-trips correctly -def test_write_dismiss_state_roundtrip(tmp_path: Path) -> None: - from autoskillit.cli._stale_check import _read_dismiss_state, _write_dismiss_state - - state: dict[str, object] = { - "binary": {"dismissed_at": "2026-03-26T00:00:00+00:00", "dismissed_version": "1.2.3"}, - } - _write_dismiss_state(tmp_path, state) - result = _read_dismiss_state(tmp_path) - assert result == state - - -# SC-8: dismissed within window → is_dismissed returns True -def test_is_dismissed_within_window(tmp_path: Path) -> None: - from autoskillit.cli._stale_check import _DISMISS_WINDOW, _is_dismissed - - recently = datetime.now(UTC) - (_DISMISS_WINDOW - timedelta(hours=1)) - state: dict[str, object] = { - "binary": {"dismissed_at": recently.isoformat(), "dismissed_version": "1.2.3"}, - } - assert _is_dismissed(state, "binary", "1.2.3") is True - - -# SC-9: dismissed beyond window → expired, returns False -def test_is_dismissed_expired(tmp_path: Path) -> None: - from autoskillit.cli._stale_check import _DISMISS_WINDOW, _is_dismissed - - long_ago = datetime.now(UTC) - (_DISMISS_WINDOW + timedelta(hours=1)) - state: dict[str, object] = { - "binary": {"dismissed_at": long_ago.isoformat(), "dismissed_version": "1.2.3"}, - } - assert _is_dismissed(state, "binary", "1.2.3") is False - - -# SC-10: version beyond dismissed_version resets dismissal even within window -def test_is_dismissed_newer_version_resets(tmp_path: Path) -> None: - from autoskillit.cli._stale_check import _is_dismissed - - recently = datetime.now(UTC) - timedelta(days=1) - state: dict[str, object] = { - "binary": {"dismissed_at": recently.isoformat(), "dismissed_version": "1.2.3"}, - } - # latest is 1.3.0, beyond dismissed 1.2.3 → not dismissed - assert _is_dismissed(state, "binary", "1.3.0") is False - - -# SC-11: run_stale_check is no-op when CLAUDECODE=1 -def test_run_stale_check_skips_claudecode(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setenv("CLAUDECODE", "1") - calls: list[str] = [] - import autoskillit.cli._stale_check as _sc - - monkeypatch.setattr(_sc, "_fetch_latest_version", lambda *a: calls.append("fetch") or None) - _sc.run_stale_check() - assert "fetch" not in calls - - -# SC-12: run_stale_check is no-op when stdin is not a tty -def test_run_stale_check_skips_non_tty(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.delenv("CLAUDECODE", raising=False) - monkeypatch.setattr(sys, "stdin", io.StringIO("")) - calls: list[str] = [] - import autoskillit.cli._stale_check as _sc - - monkeypatch.setattr(_sc, "_fetch_latest_version", lambda *a: calls.append("fetch") or None) - _sc.run_stale_check() - assert "fetch" not in calls - - -# SC-13: run_stale_check writes dismiss state when user says no to binary update -def test_run_stale_check_writes_dismiss_on_no( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.delenv("CLAUDECODE", raising=False) - fake_stdin = io.StringIO("n\n") - fake_stdout = io.StringIO() - import autoskillit - import autoskillit.cli._stale_check as _sc - - # Patch at module boundary — swap fakes in, never mutate real stdin/stdout - monkeypatch.setattr(_sc.sys, "stdin", fake_stdin) - monkeypatch.setattr(_sc.sys, "stdout", fake_stdout) - monkeypatch.setattr(fake_stdin, "isatty", lambda: True) - monkeypatch.setattr(fake_stdout, "isatty", lambda: True) - monkeypatch.setattr(Path, "home", lambda: tmp_path) - monkeypatch.setattr(autoskillit, "__version__", "0.5.0") - monkeypatch.setattr(_sc, "_fetch_latest_version", lambda dev_mode: "0.9.0") - monkeypatch.setattr(_sc, "is_dev_mode", lambda home=None: False) - import autoskillit.cli._doctor as _doctor - - monkeypatch.setattr(_doctor, "_count_hook_registry_drift", lambda p: 0) - from autoskillit.cli._stale_check import _read_dismiss_state - - _sc.run_stale_check(home=tmp_path) - state = _read_dismiss_state(tmp_path) - binary_entry = state.get("binary") - assert isinstance(binary_entry, dict) - assert binary_entry.get("dismissed_version") == "0.9.0" - - -# SC-14: binary update Y-path — subprocess calls receive AUTOSKILLIT_SKIP_STALE_CHECK env -def test_run_stale_check_binary_update_y_path_injects_guard_env( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.delenv("CLAUDECODE", raising=False) - monkeypatch.delenv("AUTOSKILLIT_SKIP_STALE_CHECK", raising=False) - fake_stdin = io.StringIO("y\n") - fake_stdout = io.StringIO() - import autoskillit - import autoskillit.cli._stale_check as _sc - - monkeypatch.setattr(_sc.sys, "stdin", fake_stdin) - monkeypatch.setattr(_sc.sys, "stdout", fake_stdout) - monkeypatch.setattr(fake_stdin, "isatty", lambda: True) - monkeypatch.setattr(fake_stdout, "isatty", lambda: True) - monkeypatch.setattr(Path, "home", lambda: tmp_path) - monkeypatch.setattr(autoskillit, "__version__", "0.1.0") - monkeypatch.setattr(_sc, "_fetch_latest_version", lambda dev_mode: "9.9.9") - monkeypatch.setattr(_sc, "is_dev_mode", lambda home=None: False) - import autoskillit.cli._doctor as _doctor - - monkeypatch.setattr(_doctor, "_count_hook_registry_drift", lambda p: 0) - - mock_run = MagicMock(return_value=subprocess.CompletedProcess([], 0)) - monkeypatch.setattr(_sc.subprocess, "run", mock_run) - monkeypatch.setattr(_sc, "_is_dismissed", lambda *a, **kw: False) - - _sc.run_stale_check(home=tmp_path) - - assert mock_run.call_count == 2 - assert mock_run.call_args_list[0][0][0] == ["uv", "tool", "upgrade", "autoskillit"] - assert mock_run.call_args_list[1][0][0] == ["autoskillit", "install"] - assert "AUTOSKILLIT_SKIP_STALE_CHECK" in mock_run.call_args_list[0].kwargs["env"] - assert "AUTOSKILLIT_SKIP_STALE_CHECK" in mock_run.call_args_list[1].kwargs["env"] - assert mock_run.call_args_list[0].kwargs["env"]["AUTOSKILLIT_SKIP_STALE_CHECK"] == "1" - assert mock_run.call_args_list[1].kwargs["env"]["AUTOSKILLIT_SKIP_STALE_CHECK"] == "1" - - -# SC-15: hook drift Y-path — subprocess call receives AUTOSKILLIT_SKIP_STALE_CHECK env -def test_run_stale_check_hook_drift_y_path_injects_guard_env( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - monkeypatch.delenv("CLAUDECODE", raising=False) - monkeypatch.delenv("AUTOSKILLIT_SKIP_STALE_CHECK", raising=False) - fake_stdin = io.StringIO("y\n") - fake_stdout = io.StringIO() - import autoskillit.cli._stale_check as _sc - - monkeypatch.setattr(_sc.sys, "stdin", fake_stdin) - monkeypatch.setattr(_sc.sys, "stdout", fake_stdout) - monkeypatch.setattr(fake_stdin, "isatty", lambda: True) - monkeypatch.setattr(fake_stdout, "isatty", lambda: True) - monkeypatch.setattr(Path, "home", lambda: tmp_path) - monkeypatch.setattr(_sc, "_fetch_latest_version", lambda dev_mode: None) - import autoskillit.cli._doctor as _doctor - - monkeypatch.setattr(_doctor, "_count_hook_registry_drift", lambda p: 3) - monkeypatch.setattr(_sc, "_is_dismissed", lambda *a, **kw: False) - - mock_run = MagicMock(return_value=subprocess.CompletedProcess([], 0)) - monkeypatch.setattr(_sc.subprocess, "run", mock_run) - - _sc.run_stale_check(home=tmp_path) - - assert mock_run.call_count == 1 - assert mock_run.call_args_list[0][0][0] == ["autoskillit", "install"] - assert "AUTOSKILLIT_SKIP_STALE_CHECK" in mock_run.call_args_list[0].kwargs["env"] - assert mock_run.call_args_list[0].kwargs["env"]["AUTOSKILLIT_SKIP_STALE_CHECK"] == "1" - - -# SC-16: re-entry guard — run_stale_check returns immediately when env var set -def test_run_stale_check_returns_immediately_when_skip_env_set( - monkeypatch: pytest.MonkeyPatch, -) -> None: - import autoskillit.cli._stale_check as _sc - - monkeypatch.setenv("AUTOSKILLIT_SKIP_STALE_CHECK", "1") - monkeypatch.setattr(_sc.sys, "stdin", MagicMock(isatty=lambda: True)) - monkeypatch.setattr(_sc.sys, "stdout", MagicMock(isatty=lambda: True)) - calls: list[str] = [] - - monkeypatch.setattr(_sc, "_fetch_latest_version", lambda *a: calls.append("fetch") or None) - mock_run = MagicMock() - monkeypatch.setattr(_sc.subprocess, "run", mock_run) - - _sc.run_stale_check() - - assert "fetch" not in calls - mock_run.assert_not_called() - - -# SC-17: dev-mode Y-path calls uv tool install --force, not uv tool upgrade -def test_run_stale_check_dev_mode_y_path_command( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - """Dev-mode Y-path must call uv tool install --force, not uv tool upgrade.""" - import autoskillit.cli._stale_check as _sc - from autoskillit.cli._stale_check import _INSTALL_FROM_INTEGRATION - - calls: list[tuple[list[str], dict[str, object]]] = [] - monkeypatch.setattr(_sc, "is_dev_mode", lambda home=None: True) - monkeypatch.setattr(_sc, "_fetch_latest_version", lambda dev_mode: "99.0.0") - monkeypatch.setattr(_sc, "_read_dismiss_state", lambda home: {}) - monkeypatch.setattr(_sc, "_write_dismiss_state", lambda home, state: None) - # Force non-editable path so this test continues to assert uv tool install --force - monkeypatch.setattr(_sc, "_detect_install_type", lambda: ("tool", None)) - - def fake_run(cmd: list[str], **kwargs: object) -> object: - calls.append((cmd, kwargs)) - return type("R", (), {"returncode": 0})() - - monkeypatch.setattr(_sc.subprocess, "run", fake_run) - monkeypatch.setattr(_sc.sys.stdin, "isatty", lambda: True) - monkeypatch.setattr(_sc.sys.stdout, "isatty", lambda: True) - monkeypatch.delenv("CLAUDECODE", raising=False) - monkeypatch.delenv("AUTOSKILLIT_SKIP_STALE_CHECK", raising=False) - - import autoskillit as _pkg - - monkeypatch.setattr(_pkg, "__version__", "0.6.7") - monkeypatch.setattr("builtins.input", lambda _: "y") - - _sc.run_stale_check(home=tmp_path) - - uv_calls = [(c, kw) for c, kw in calls if c[0] == "uv"] - assert len(uv_calls) == 1 - assert uv_calls[0][0] == ["uv", "tool", "install", "--force", _INSTALL_FROM_INTEGRATION], ( - f"Expected dev-mode install command, got: {uv_calls[0][0]}" - ) - assert uv_calls[0][1].get("env", {}).get("AUTOSKILLIT_SKIP_STALE_CHECK") == "1", ( # type: ignore[union-attr] - "Dev-mode uv call must carry AUTOSKILLIT_SKIP_STALE_CHECK=1 in env" - ) - autoskillit_calls = [c for c, kw in calls if c[0] == "autoskillit"] - assert autoskillit_calls == [["autoskillit", "install"]] - - -# SC-18: hooks N-path writes state["hooks"], not state["binary"] -def test_run_stale_check_hooks_n_path_writes_dismiss( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - """Answering N to the hook-drift prompt writes state['hooks'], not state['binary'].""" - import autoskillit.cli._stale_check as _sc - - monkeypatch.setattr(_sc, "is_dev_mode", lambda home=None: False) - monkeypatch.setattr(_sc, "_fetch_latest_version", lambda dev_mode: "0.6.7") # no binary prompt - monkeypatch.setattr(_sc.sys.stdin, "isatty", lambda: True) - monkeypatch.setattr(_sc.sys.stdout, "isatty", lambda: True) - monkeypatch.delenv("CLAUDECODE", raising=False) - monkeypatch.delenv("AUTOSKILLIT_SKIP_STALE_CHECK", raising=False) - - import autoskillit as _pkg - - monkeypatch.setattr(_pkg, "__version__", "0.6.7") - - written: dict[str, object] = {} - monkeypatch.setattr(_sc, "_write_dismiss_state", lambda home, state: written.update(state)) - monkeypatch.setattr( - "autoskillit.cli._doctor._count_hook_registry_drift", - lambda settings_path: 2, - ) - monkeypatch.setattr("builtins.input", lambda _: "n") - - _sc.run_stale_check(home=tmp_path) - - assert "hooks" in written, "hooks dismiss state not written on N answer" - assert "dismissed_at" in written["hooks"] # type: ignore[index] - assert "dismissed_version" in written["hooks"] # type: ignore[index] - assert "binary" not in written, ( - "binary dismiss should not be written when no binary update needed" - ) - - -# SC-19: Y-path + silent failure (version unchanged) writes binary_snoozed, not binary -def test_run_stale_check_y_path_silent_failure_writes_snooze( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - """ - After Y-path subprocesses complete, if importlib.metadata.version() reports - the same version as before the update, a snooze record (not a dismiss record) - must be written. - """ - import importlib.metadata - - import autoskillit.cli._stale_check as _sc - - monkeypatch.setattr(_sc, "is_dev_mode", lambda home=None: False) - monkeypatch.setattr(_sc, "_fetch_latest_version", lambda dev_mode: "99.0.0") - monkeypatch.setattr(_sc, "_read_dismiss_state", lambda home: {}) - monkeypatch.setattr(_sc.sys.stdin, "isatty", lambda: True) - monkeypatch.setattr(_sc.sys.stdout, "isatty", lambda: True) - monkeypatch.delenv("CLAUDECODE", raising=False) - monkeypatch.delenv("AUTOSKILLIT_SKIP_STALE_CHECK", raising=False) - - import autoskillit as _pkg - - monkeypatch.setattr(_pkg, "__version__", "0.6.7") - # Simulate failed update: importlib.metadata still reports old version - monkeypatch.setattr(importlib.metadata, "version", lambda name: "0.6.7") - - def fake_run(cmd: list[str], **kwargs: object) -> object: - return type("R", (), {"returncode": 0})() - - monkeypatch.setattr(_sc.subprocess, "run", fake_run) - - written: dict[str, object] = {} - monkeypatch.setattr(_sc, "_write_dismiss_state", lambda home, state: written.update(state)) - monkeypatch.setattr("builtins.input", lambda _: "y") - - _sc.run_stale_check(home=tmp_path) - - assert "binary_snoozed" in written, ( - "Expected binary_snoozed state after silent update failure, " - f"but written state was: {list(written.keys())}" - ) - assert "binary" not in written, ( - "Dismissed state must NOT be written after a failed Y-path update" - ) - assert "snoozed_at" in written["binary_snoozed"] # type: ignore[index] - assert "attempted_version" in written["binary_snoozed"] # type: ignore[index] - assert written["binary_snoozed"]["attempted_version"] == "99.0.0" # type: ignore[index] - - -# SC-20a: _is_snoozed() returns False when snooze window has elapsed -def test_is_snoozed_expired(monkeypatch: pytest.MonkeyPatch) -> None: - """_is_snoozed() returns False when the snooze window has elapsed.""" - from autoskillit.cli._stale_check import _SNOOZE_WINDOW, _is_snoozed - - long_ago = datetime.now(UTC) - (_SNOOZE_WINDOW + timedelta(hours=1)) - state: dict[str, object] = { - "binary_snoozed": {"snoozed_at": long_ago.isoformat(), "attempted_version": "1.0.0"} - } - assert _is_snoozed(state, "binary") is False - - -# SC-20b: _is_snoozed() returns True when within the snooze window -def test_is_snoozed_within_window(monkeypatch: pytest.MonkeyPatch) -> None: - """_is_snoozed() returns True when within the snooze window.""" - from autoskillit.cli._stale_check import _SNOOZE_WINDOW, _is_snoozed - - recently = datetime.now(UTC) - (_SNOOZE_WINDOW - timedelta(minutes=10)) - state: dict[str, object] = { - "binary_snoozed": {"snoozed_at": recently.isoformat(), "attempted_version": "1.0.0"} - } - assert _is_snoozed(state, "binary") is True - - -# SC-21: Y-path success (version advanced) writes no state -def test_run_stale_check_y_path_success_no_state_written( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - """When Y-path update advances the version, no state is written to update_check.json.""" - import importlib.metadata - - import autoskillit.cli._stale_check as _sc - - monkeypatch.setattr(_sc, "is_dev_mode", lambda home=None: False) - monkeypatch.setattr(_sc, "_fetch_latest_version", lambda dev_mode: "99.0.0") - monkeypatch.setattr(_sc, "_read_dismiss_state", lambda home: {}) - monkeypatch.setattr(_sc.sys.stdin, "isatty", lambda: True) - monkeypatch.setattr(_sc.sys.stdout, "isatty", lambda: True) - monkeypatch.delenv("CLAUDECODE", raising=False) - monkeypatch.delenv("AUTOSKILLIT_SKIP_STALE_CHECK", raising=False) - - import autoskillit as _pkg - - monkeypatch.setattr(_pkg, "__version__", "0.6.7") - # Simulate successful update: version advanced - monkeypatch.setattr(importlib.metadata, "version", lambda name: "99.0.0") - - def fake_run(cmd: list[str], **kwargs: object) -> object: - return type("R", (), {"returncode": 0})() - - monkeypatch.setattr(_sc.subprocess, "run", fake_run) - - write_called: list[object] = [] - monkeypatch.setattr( - _sc, "_write_dismiss_state", lambda home, state: write_called.append(state) - ) - monkeypatch.setattr("builtins.input", lambda _: "y") - - _sc.run_stale_check(home=tmp_path) - - assert write_called == [], "No state should be written after a successful Y-path update" - - -# SC-22: _read_dismiss_state() returns {} for non-dict JSON root -def test_read_dismiss_state_non_dict_json_returns_empty(tmp_path: Path) -> None: - """_read_dismiss_state returns {} when update_check.json contains non-dict JSON.""" - from autoskillit.cli._stale_check import _read_dismiss_state - - state_dir = tmp_path / ".autoskillit" - state_dir.mkdir() - (state_dir / "update_check.json").write_text("[1, 2, 3]", encoding="utf-8") - - result = _read_dismiss_state(tmp_path) - assert result == {}, f"Expected empty dict for non-dict JSON root, got: {result}" - - -# SC-B-2: is_dev_mode() returns False when pkg_root() is inside a git worktree -def test_is_dev_mode_git_file_worktree(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: - """is_dev_mode() returns False when pkg_root() is inside a git worktree - (i.e., .git is a file, not a directory).""" - import autoskillit.cli._stale_check as _sc - - repo_root = tmp_path / "repo" - repo_root.mkdir() - worktree_dir = repo_root / "src" / "autoskillit" - worktree_dir.mkdir(parents=True) - # .git as a file = worktree indicator - (repo_root / ".git").write_text("gitdir: /some/real/repo/.git/worktrees/foo") - - monkeypatch.setattr(_sc, "pkg_root", lambda: worktree_dir) - - result = _sc.is_dev_mode(home=tmp_path) - assert result is False, ( - "is_dev_mode() must return False when pkg_root() is inside a git worktree (.git is a file)" - ) - - -# SC-B-3: dev-mode Y-path dispatches editable install command when direct_url.json reports editable -def test_run_stale_check_dev_mode_editable_install_y_path( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path -) -> None: - """Dev-mode Y-path with editable install must dispatch 'uv pip install -e ' - instead of 'uv tool install --force'.""" - import importlib.metadata - - import autoskillit.cli._stale_check as _sc - - monkeypatch.setattr(_sc, "is_dev_mode", lambda home=None: True) - monkeypatch.setattr(_sc, "_fetch_latest_version", lambda dev_mode: "99.0.0") - monkeypatch.setattr(_sc, "_read_dismiss_state", lambda home: {}) - monkeypatch.setattr(_sc.sys.stdin, "isatty", lambda: True) - monkeypatch.setattr(_sc.sys.stdout, "isatty", lambda: True) - monkeypatch.delenv("CLAUDECODE", raising=False) - monkeypatch.delenv("AUTOSKILLIT_SKIP_STALE_CHECK", raising=False) - - import autoskillit as _pkg - - monkeypatch.setattr(_pkg, "__version__", "0.6.7") - - # Simulate editable install: direct_url.json reports editable=True - fake_dist = MagicMock() - fake_dist.read_text.return_value = ( - '{"url": "file:///home/user/autoskillit", "dir_info": {"editable": true}}' - ) - monkeypatch.setattr( - importlib.metadata.Distribution, - "from_name", - staticmethod(lambda name: fake_dist), - ) - # Simulate successful update - monkeypatch.setattr(importlib.metadata, "version", lambda name: "99.0.0") - - calls: list[list[str]] = [] - - def fake_run(cmd: list[str], **kwargs: object) -> object: - calls.append(cmd) - return type("R", (), {"returncode": 0})() - - monkeypatch.setattr(_sc.subprocess, "run", fake_run) - monkeypatch.setattr("builtins.input", lambda _: "y") - - _sc.run_stale_check(home=tmp_path) - - uv_calls = [c for c in calls if c[0] == "uv"] - assert len(uv_calls) == 1 - assert uv_calls[0][:3] == ["uv", "pip", "install"], ( - f"Editable install should use 'uv pip install -e', got: {uv_calls[0]}" - ) - assert "-e" in uv_calls[0] - assert "/home/user/autoskillit" in uv_calls[0] - # Must NOT use uv tool install --force for editable installs - assert not any("tool" in str(c) and "install" in str(c) for c in uv_calls) diff --git a/tests/cli/test_startup_budget.py b/tests/cli/test_startup_budget.py new file mode 100644 index 0000000000..e06cc0b1ef --- /dev/null +++ b/tests/cli/test_startup_budget.py @@ -0,0 +1,50 @@ +"""Integration test: serve() must call anyio.run() within the startup timing budget. + +REQ-STARTUP-001: The pre-transport startup work (serve() entry to anyio.run() call) +must complete within 2 seconds, leaving 3s of margin before Claude Code's ~5s +connection timeout. +""" + +from __future__ import annotations + +import time +from unittest.mock import patch + +import structlog.testing + +from autoskillit.server import _state + + +def test_serve_calls_mcp_run_within_budget(monkeypatch, tmp_path): + """serve() pre-anyio.run() synchronous work must complete within 2 seconds.""" + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("GITHUB_TOKEN", raising=False) + + # Ensure _state._ctx is restored after the test (xdist safety) + original_ctx = _state._ctx + monkeypatch.setattr(_state, "_ctx", None) + + run_called_at: list[float] = [] + + def timed_anyio_run(*_a, **_kw): + run_called_at.append(time.monotonic()) + # Do not actually start the event loop — just record the call site + + with ( + patch("anyio.run", side_effect=timed_anyio_run), + structlog.testing.capture_logs(), + ): + import autoskillit.cli as cli_mod + + start = time.monotonic() + cli_mod.serve() + + # Restore global state + monkeypatch.setattr(_state, "_ctx", original_ctx) + + assert run_called_at, "anyio.run() was never called" + elapsed = run_called_at[0] - start + assert elapsed < 2.0, ( + f"serve() took {elapsed:.2f}s before anyio.run() — exceeds 2s budget. " + f"Claude Code timeout is ~5s; budget is 2s to leave margin." + ) diff --git a/tests/cli/test_subprocess_env_contracts.py b/tests/cli/test_subprocess_env_contracts.py index 5ce48dfdb9..259b8bf1d3 100644 --- a/tests/cli/test_subprocess_env_contracts.py +++ b/tests/cli/test_subprocess_env_contracts.py @@ -11,6 +11,13 @@ same source file, confirming the env dict is built from the guard (the variable pattern ``_skip_env = {**os.environ, "AUTOSKILLIT_SKIP_STALE_CHECK": "1"}`` satisfies this without requiring the literal to appear inside the call expression). + +Also contains ``test_no_raw_claude_env``: the sibling rule for claude-launching +subprocess calls. Every claude-launching site must route its env through +:func:`autoskillit.core.build_claude_env` (via ``spec.env`` from a +``Claude*Cmd`` dataclass, or via a direct builder call). The rule bans +``env={**os.environ, ...}``, ``env=os.environ``, ``env=None``, missing ``env=``, +and ``env=`` at every claude-launching site. """ from __future__ import annotations @@ -21,8 +28,17 @@ import pytest CLI_ROOT = Path(__file__).parents[2] / "src" / "autoskillit" / "cli" +SRC_ROOT = Path(__file__).parents[2] / "src" / "autoskillit" REQUIRED_GUARD = "AUTOSKILLIT_SKIP_STALE_CHECK" +_CLAUDE_BUILDER_NAMES = frozenset( + { + "build_interactive_cmd", + "build_headless_cmd", + "build_full_headless_cmd", + } +) + def _collect_autoskillit_subprocess_calls(source: str) -> list[tuple[int, str, bool]]: """Return (lineno, source_fragment, has_env_kwarg) for every @@ -86,19 +102,20 @@ def test_autoskillit_subprocess_calls_inject_skip_stale_check_guard() -> None: ) -def test_stale_check_all_subprocess_calls_have_env_kwarg() -> None: - """Every subprocess.run call in cli/_stale_check.py must carry env=. +DRIFT_GUARD = "AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK" + + +def test_update_checks_all_subprocess_calls_have_env_kwarg() -> None: + """Every subprocess.run call in cli/_update_checks.py must carry env=. - This is a stronger contract than the autoskillit-prefix scanner in this file, - which only checks ['autoskillit', ...] prefix calls. The stale check also - invokes ['uv', ...] commands and those must also carry env=_skip_env to - prevent environment pollution into child processes. + The unified update check invokes ['uv', ...] and ['autoskillit', ...] + commands and must pass _skip_env to prevent re-entering the check. """ - stale_check = CLI_ROOT / "_stale_check.py" - if not stale_check.exists(): + update_checks = CLI_ROOT / "_update_checks.py" + if not update_checks.exists(): pytest.skip("Source tree unavailable") - content = stale_check.read_text(encoding="utf-8") + content = update_checks.read_text(encoding="utf-8") tree = ast.parse(content) violations: list[str] = [] @@ -118,9 +135,393 @@ def test_stale_check_all_subprocess_calls_have_env_kwarg() -> None: violations.append(f"Line {node.lineno}: subprocess.{func.attr}() missing env= kwarg") assert not violations, ( - "All subprocess calls in _stale_check.py must carry env=_skip_env.\n" + "All subprocess calls in _update_checks.py must carry env=_skip_env.\n" + "\n".join(violations) ) - # File-level: must also define AUTOSKILLIT_SKIP_STALE_CHECK + # File-level: must define both guard env vars assert REQUIRED_GUARD in content + assert DRIFT_GUARD in content + + +def test_all_call_sites_set_autoskillit_skip_source_drift_check() -> None: + """Every CLI file that defines AUTOSKILLIT_SKIP_STALE_CHECK must also define + AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK — both guards travel together. + + Rationale: a subprocess launched by the update-check path could re-enter the + drift gate unless both skip vars are set. This test enforces co-location. + """ + if not CLI_ROOT.is_dir(): + pytest.skip("Source tree unavailable") + + violations: list[str] = [] + for py_file in sorted(CLI_ROOT.rglob("*.py")): + content = py_file.read_text(encoding="utf-8") + non_comment = "\n".join( + line for line in content.splitlines() if not line.lstrip().startswith("#") + ) + if REQUIRED_GUARD not in non_comment: + continue + if DRIFT_GUARD not in non_comment: + rel = py_file.relative_to(CLI_ROOT.parents[2]) + violations.append(f"{rel}: defines '{REQUIRED_GUARD}' but not '{DRIFT_GUARD}'") + + assert not violations, ( + f"Found {len(violations)} file(s) with {REQUIRED_GUARD!r} but missing " + f"{DRIFT_GUARD!r}:\n\n" + "\n".join(violations) + ) + + +def test_update_command_all_subprocess_calls_have_env_kwarg() -> None: + """Every subprocess.run call in cli/_update.py must carry env=.""" + update_cmd = CLI_ROOT / "_update.py" + if not update_cmd.exists(): + pytest.skip("Source tree unavailable") + + content = update_cmd.read_text(encoding="utf-8") + tree = ast.parse(content) + + violations: list[str] = [] + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + func = node.func + if not ( + isinstance(func, ast.Attribute) + and func.attr in ("run", "Popen") + and isinstance(func.value, ast.Name) + and func.value.id == "subprocess" + ): + continue + has_env = any(kw.arg == "env" for kw in node.keywords) + if not has_env: + violations.append(f"Line {node.lineno}: subprocess.{func.attr}() missing env= kwarg") + + assert not violations, ( + "All subprocess calls in _update.py must carry env=_skip_env.\n" + "\n".join(violations) + ) + + assert REQUIRED_GUARD in content + assert DRIFT_GUARD in content + + +# ───────────────────────────────────────────────────────────────────────────── +# Sibling rule: _run_subprocess(env=...) calls in server/ must start from +# os.environ — enforced via per-function AST walk with single-assignment +# tracking. +# ───────────────────────────────────────────────────────────────────────────── + +SERVER_ROOT = Path(__file__).parents[2] / "src" / "autoskillit" / "server" + + +def _dict_has_os_environ_unpack(dict_node: ast.Dict) -> bool: + """True if the dict literal contains **os.environ.""" + for key, val in zip(dict_node.keys, dict_node.values): + if key is None and isinstance(val, ast.Attribute): + if isinstance(val.value, ast.Name) and val.value.id == "os" and val.attr == "environ": + return True + return False + + +def _check_env_value( + env_val: ast.expr, + bindings: dict[str, ast.expr], + lineno: int, + path: Path, +) -> str | None: + """Return a violation string if env_val is unsafe, None if safe. + + Safe patterns: + - env=None literal + - env= containing **os.environ + - env= (builder function) + - env= bound to a safe value (resolved one level via bindings) + - env= unresolvable (parameter/outer scope — trusted) + """ + if isinstance(env_val, ast.Constant) and env_val.value is None: + return None + if isinstance(env_val, ast.Dict): + if _dict_has_os_environ_unpack(env_val): + return None + rel = path.relative_to(SERVER_ROOT.parents[2]) + return f"{rel}:{lineno}: _run_subprocess(env=) without **os.environ" + if isinstance(env_val, ast.Call): + return None + if isinstance(env_val, ast.Name): + bound = bindings.get(env_val.id) + if bound is None: + return None + return _check_env_value(bound, {}, lineno, path) + return None + + +def _find_run_subprocess_env_violations(source: str, path: Path) -> list[str]: + """Find _run_subprocess() calls with unsafe env= kwargs, per-function.""" + tree = ast.parse(source) + violations: list[str] = [] + for func_node in ast.walk(tree): + if not isinstance(func_node, (ast.FunctionDef, ast.AsyncFunctionDef)): + continue + bindings: dict[str, ast.expr] = {} + for stmt in ast.walk(func_node): + if isinstance(stmt, ast.Assign) and len(stmt.targets) == 1: + target = stmt.targets[0] + if isinstance(target, ast.Name): + bindings[target.id] = stmt.value + elif isinstance(stmt, ast.AnnAssign) and stmt.value is not None: + if isinstance(stmt.target, ast.Name): + bindings[stmt.target.id] = stmt.value + for node in ast.walk(func_node): + if not isinstance(node, ast.Call): + continue + func = node.func + if not (isinstance(func, ast.Name) and func.id == "_run_subprocess"): + continue + env_kw = None + for kw in node.keywords: + if kw.arg == "env": + env_kw = kw.value + break + if env_kw is None: + continue + violation = _check_env_value(env_kw, bindings, node.lineno, path) + if violation: + violations.append(violation) + return violations + + +def test_run_subprocess_callers_use_safe_env_pattern() -> None: + """Every _run_subprocess(env=...) call in server/ must start from os.environ.""" + if not SERVER_ROOT.is_dir(): + pytest.skip("Source tree unavailable") + violations: list[str] = [] + for py_file in sorted(SERVER_ROOT.rglob("*.py")): + source = py_file.read_text(encoding="utf-8") + if "_run_subprocess" not in source: + continue + violations.extend(_find_run_subprocess_env_violations(source, py_file)) + assert not violations, ( + "Found _run_subprocess() calls with unsafe env= patterns:\n" + + "\n".join(f" {v}" for v in violations) + ) + + +# ───────────────────────────────────────────────────────────────────────────── +# Sibling rule: claude-launching subprocess calls must route env through +# build_claude_env() — enforced via intra-function AST walk. +# ───────────────────────────────────────────────────────────────────────────── + + +def _call_func_name(func: ast.AST) -> str: + """Return the simple/qualified name of a Call's .func expression (best-effort).""" + if isinstance(func, ast.Name): + return func.id + if isinstance(func, ast.Attribute): + return func.attr + return "" + + +def _is_claude_builder_call(node: ast.AST) -> bool: + """True if *node* is a call to any claude command builder.""" + if not isinstance(node, ast.Call): + return False + return _call_func_name(node.func) in _CLAUDE_BUILDER_NAMES + + +def _is_literal_claude_list(node: ast.AST) -> bool: + """True if *node* is a literal list whose first element is the string 'claude'.""" + if not isinstance(node, ast.List) or not node.elts: + return False + first = node.elts[0] + return isinstance(first, ast.Constant) and first.value == "claude" + + +class _ClaudeLaunchWalker: + """Per-function walker: tracks single-assignment symbol table for a FunctionDef. + + Detects claude-launching call patterns on the first positional or ``cmd=`` + kwarg and verifies the ``env=`` kwarg shape is one of: + + - ``Attribute(value=Name, attr="env")`` where Name was assigned from a + ``build_interactive_cmd``/``build_headless_cmd``/``build_full_headless_cmd`` + call earlier in the same function body (spec.env pattern). + - ``Call(func=Name("build_claude_env") | Attribute(..., "build_claude_env"))`` + (direct builder escape hatch). + """ + + def __init__(self, func_node: ast.AST, path: Path) -> None: + self.func_node = func_node + self.path = path + # Name -> most recent assigned value (single-assignment tracker). + self._bindings: dict[str, ast.expr] = {} + self.violations: list[str] = [] + + def walk(self) -> None: + for stmt in ast.walk(self.func_node): + # Track simple assignments first so calls later in the body can resolve. + if isinstance(stmt, ast.Assign) and len(stmt.targets) == 1: + target = stmt.targets[0] + if isinstance(target, ast.Name): + self._bindings[target.id] = stmt.value + elif isinstance(stmt, ast.AnnAssign) and stmt.value is not None: + if isinstance(stmt.target, ast.Name): + self._bindings[stmt.target.id] = stmt.value + elif isinstance(stmt, ast.Call): + self._check_call(stmt) + + def _resolve_name(self, node: ast.AST) -> ast.expr | None: + """Follow a Name through one level of assignment; return the bound value or None.""" + if isinstance(node, ast.Name) and node.id in self._bindings: + return self._bindings[node.id] + return None + + def _cmd_is_claude_launching(self, cmd_arg: ast.AST) -> bool: + """True if *cmd_arg* refers to a claude-launching argv (via spec or literal).""" + # Direct literal: ["claude", ...] + if _is_literal_claude_list(cmd_arg): + return True + + # spec.cmd attribute access where spec was assigned from a builder. + if isinstance(cmd_arg, ast.Attribute) and cmd_arg.attr == "cmd": + bound = self._resolve_name(cmd_arg.value) + if bound is not None and _is_claude_builder_call(bound): + return True + + # Name: resolve one level. + if isinstance(cmd_arg, ast.Name): + bound = self._resolve_name(cmd_arg) + if bound is None: + return False + # cmd = ["claude", ...] + if _is_literal_claude_list(bound): + return True + # cmd = spec.cmd (+ [...]) or cmd = spec.cmd + if isinstance(bound, ast.Attribute) and bound.attr == "cmd": + return self._cmd_is_claude_launching(bound) + if isinstance(bound, ast.BinOp) and isinstance(bound.op, ast.Add): + return self._cmd_is_claude_launching(bound.left) or self._cmd_is_claude_launching( + bound.right + ) + # cmd = spec_result_of_builder → treat attribute .cmd the same way + if _is_claude_builder_call(bound): + return True + + # cmd = spec.cmd + [...] passed inline as BinOp. + if isinstance(cmd_arg, ast.BinOp) and isinstance(cmd_arg.op, ast.Add): + return self._cmd_is_claude_launching(cmd_arg.left) or self._cmd_is_claude_launching( + cmd_arg.right + ) + + return False + + @staticmethod + def _cmd_arg_of(call: ast.Call) -> ast.AST | None: + """Return the claude argv argument: first positional, or cmd= kwarg.""" + if call.args: + return call.args[0] + for kw in call.keywords: + if kw.arg == "cmd": + return kw.value + return None + + @staticmethod + def _env_kwarg(call: ast.Call) -> ast.expr | None: + for kw in call.keywords: + if kw.arg == "env": + return kw.value + return None + + def _env_shape_ok(self, env_val: ast.expr | None) -> tuple[bool, str]: + if env_val is None: + return False, "missing env= kwarg" + if isinstance(env_val, ast.Constant) and env_val.value is None: + return False, "env=None is not allowed" + if isinstance(env_val, ast.Dict): + # env={**os.environ, ...} or env={"K": "V"} — both are banned. + return False, "env= is not allowed" + if isinstance(env_val, ast.Attribute): + # env=os.environ + if ( + isinstance(env_val.value, ast.Name) + and env_val.value.id == "os" + and env_val.attr == "environ" + ): + return False, "env=os.environ is not allowed" + # env=spec.env / env=foo.env + if env_val.attr == "env": + return True, "" + if isinstance(env_val, ast.Call): + fn = _call_func_name(env_val.func) + if fn == "build_claude_env": + return True, "" + if isinstance(env_val, ast.Name): + # Resolve one level of local binding to catch aliased os.environ. + bound = self._resolve_name(env_val) + if bound is not None: + return self._env_shape_ok(bound) + # Unresolvable name (parameter / outer scope): rely on the function + # owning it to pass a scrubbed env. + return True, "" + return False, f"env= has unrecognised shape: {ast.dump(env_val)[:60]}" + + def _check_call(self, call: ast.Call) -> None: + cmd_arg = self._cmd_arg_of(call) + if cmd_arg is None: + return + if not self._cmd_is_claude_launching(cmd_arg): + return + env_val = self._env_kwarg(call) + ok, reason = self._env_shape_ok(env_val) + if not ok: + rel = self.path.relative_to(SRC_ROOT.parents[1]) + self.violations.append( + f"{rel}:{call.lineno}: claude-launching call at " + f"{_call_func_name(call.func) or ''}(...) — {reason}" + ) + + +# Allowlist: administrative ``claude plugin ...`` subprocess calls that are +# plugin marketplace / registration operations, NOT skill sessions. They do +# not present a tool surface to the model, so IDE-channel attach is not a +# concern. Each entry is (filename, enclosing_function_name). +# +# Adding a new entry requires a comment justifying why the call cannot use +# build_claude_env — matching the convention in +# ``tests/arch/test_ast_rules.py::test_no_raw_claude_list_construction``. +_CLAUDE_ENV_RULE_ALLOWED: frozenset[tuple[str, str]] = frozenset( + { + # doctor check: `claude plugin list` — read-only registration probe. + ("_doctor.py", "_check_mcp_server_registered"), + # onboarding probe: `claude plugin list` — read-only install check. + ("_init_helpers.py", "_is_plugin_installed"), + # marketplace registration + install: `claude plugin marketplace add` / + # `claude plugin install`. Administrative ops invoked once during setup. + ("_marketplace.py", "install"), + } +) + + +def test_no_raw_claude_env() -> None: + """Every claude-launching subprocess call must route env through build_claude_env().""" + if not SRC_ROOT.is_dir(): + pytest.skip("Source tree unavailable") + + violations: list[str] = [] + for py_file in sorted(SRC_ROOT.rglob("*.py")): + try: + tree = ast.parse(py_file.read_text(encoding="utf-8")) + except SyntaxError: + continue + for node in ast.walk(tree): + if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + continue + if (py_file.name, node.name) in _CLAUDE_ENV_RULE_ALLOWED: + continue + walker = _ClaudeLaunchWalker(node, py_file) + walker.walk() + violations.extend(walker.violations) + + assert not violations, ( + "Found claude-launching subprocess calls that bypass build_claude_env():\n" + + "\n".join(f" {v}" for v in violations) + ) diff --git a/tests/cli/test_terminal.py b/tests/cli/test_terminal.py index ff50c310cc..fb3dc8dc12 100644 --- a/tests/cli/test_terminal.py +++ b/tests/cli/test_terminal.py @@ -6,11 +6,14 @@ from __future__ import annotations +import os import termios from unittest.mock import patch import pytest +from autoskillit.cli._terminal import _RESET_SPEC + class TestTerminalGuardTTYRestore: """terminal_guard() saves and restores termios attrs in all exit paths.""" @@ -80,8 +83,9 @@ def test_restores_on_system_exit(self): mock_termios.tcsetattr.assert_called_once_with(0, termios.TCSAFLUSH, fake_attrs) - def test_emits_vt100_reset_sequences_on_normal_exit(self): - """Escape sequences are written to stdout after normal subprocess exit.""" + @pytest.mark.parametrize("entry", _RESET_SPEC, ids=lambda e: e.name) + def test_emits_all_spec_sequences_on_normal_exit(self, entry): + """Every sequence in _RESET_SPEC is emitted by terminal_guard() on normal exit.""" from autoskillit.cli._terminal import terminal_guard with ( @@ -96,12 +100,13 @@ def test_emits_vt100_reset_sequences_on_normal_exit(self): pass written = "".join(c.args[0] for c in mock_stdout.write.call_args_list if c.args) - assert "\033[?1049l" in written, "Must exit alternate screen buffer" - assert "\033[?1l" in written, "Must reset application cursor keys" - assert "\033>" in written, "Must reset application keypad mode" + assert entry.sequence in written, ( + f"Must emit {entry.name} ({entry.sequence!r}) — layer: {entry.layer.value}" + ) - def test_emits_vt100_reset_sequences_on_exception(self): - """Escape sequences are written even when subprocess raises.""" + @pytest.mark.parametrize("entry", _RESET_SPEC, ids=lambda e: e.name) + def test_emits_all_spec_sequences_on_exception(self, entry): + """Every sequence in _RESET_SPEC is emitted by terminal_guard() on exception.""" from autoskillit.cli._terminal import terminal_guard with ( @@ -117,8 +122,9 @@ def test_emits_vt100_reset_sequences_on_exception(self): raise KeyboardInterrupt written = "".join(c.args[0] for c in mock_stdout.write.call_args_list if c.args) - assert "\033[?1049l" in written, "Must exit alternate screen buffer" - assert "\033[?1l" in written + assert entry.sequence in written, ( + f"Must emit {entry.name} ({entry.sequence!r}) — layer: {entry.layer.value}" + ) def test_noop_in_non_tty_environment(self): """When stdin is not a TTY, tcgetattr and tcsetattr are never called.""" @@ -250,6 +256,162 @@ def test_noop_does_not_emit_escape_sequences(self): mock_stdout.write.assert_not_called() + def test_kitty_sequences_emitted_on_supported_terminal(self): + """Kitty KBP sequences are emitted when TERM_PROGRAM indicates support.""" + from autoskillit.cli._terminal import terminal_guard + + with ( + patch("autoskillit.cli._terminal.sys.stdin") as mock_stdin, + patch("autoskillit.cli._terminal.termios"), + patch("autoskillit.cli._terminal.sys.stdout") as mock_stdout, + patch.dict("os.environ", {"TERM_PROGRAM": "kitty"}, clear=False), + ): + mock_stdin.isatty.return_value = True + mock_stdin.fileno.return_value = 0 + + with terminal_guard(): + pass + + written = "".join(c.args[0] for c in mock_stdout.write.call_args_list if c.args) + assert "\033[=0u" in written, "Must hard-disable Kitty keyboard protocol" + assert "\033[<99u" in written, "Must drain Kitty keyboard protocol push stack" + + def test_kitty_sequences_not_emitted_on_unsupported_terminal(self): + """Kitty KBP sequences must NOT be emitted on unsupported terminals. + + JediTerm (JetBrains IDEs) echoes literal garbage from \\033[<99u. + """ + from autoskillit.cli._terminal import terminal_guard + + env = os.environ.copy() + env.pop("TERM_PROGRAM", None) + env.pop("KITTY_WINDOW_ID", None) + + with ( + patch("autoskillit.cli._terminal.sys.stdin") as mock_stdin, + patch("autoskillit.cli._terminal.termios"), + patch("autoskillit.cli._terminal.sys.stdout") as mock_stdout, + patch.dict("os.environ", env, clear=True), + ): + mock_stdin.isatty.return_value = True + mock_stdin.fileno.return_value = 0 + + with terminal_guard(): + pass + + written = "".join(c.args[0] for c in mock_stdout.write.call_args_list if c.args) + assert "\033[=0u" not in written, ( + "Kitty hard-disable must not be emitted on unsupported terminals" + ) + assert "\033[<99u" not in written, ( + "Kitty stack drain must not be emitted on unsupported terminals" + ) + # Base sequences must still be present + assert "\033[?2004l" in written, "Base reset must still be emitted" + assert "\033[!p" in written, "DECSTR must still be emitted" + + def test_kitty_sequences_emitted_via_kitty_window_id(self): + """KITTY_WINDOW_ID triggers Kitty KBP sequences regardless of TERM_PROGRAM.""" + from autoskillit.cli._terminal import terminal_guard + + with ( + patch("autoskillit.cli._terminal.sys.stdin") as mock_stdin, + patch("autoskillit.cli._terminal.termios"), + patch("autoskillit.cli._terminal.sys.stdout") as mock_stdout, + patch.dict("os.environ", {"KITTY_WINDOW_ID": "1"}, clear=False), + ): + mock_stdin.isatty.return_value = True + mock_stdin.fileno.return_value = 0 + + with terminal_guard(): + pass + + written = "".join(c.args[0] for c in mock_stdout.write.call_args_list if c.args) + assert "\033[=0u" in written, "Must hard-disable Kitty keyboard protocol" + + def test_kitty_protocol_sequences_emitted_after_decstr(self): + """Kitty KBP sequences must follow DECSTR to avoid being reset.""" + from autoskillit.cli._terminal import terminal_guard + + with ( + patch("autoskillit.cli._terminal.sys.stdin") as mock_stdin, + patch("autoskillit.cli._terminal.termios"), + patch("autoskillit.cli._terminal.sys.stdout") as mock_stdout, + patch.dict("os.environ", {"TERM_PROGRAM": "kitty"}, clear=False), + ): + mock_stdin.isatty.return_value = True + mock_stdin.fileno.return_value = 0 + + with terminal_guard(): + pass + + written = "".join(c.args[0] for c in mock_stdout.write.call_args_list if c.args) + decstr_pos = written.index("\033[!p") + kitty_hard_pos = written.index("\033[=0u") + kitty_drain_pos = written.index("\033[<99u") + assert decstr_pos < kitty_hard_pos, "Kitty hard-disable must follow DECSTR" + assert decstr_pos < kitty_drain_pos, "Kitty stack drain must follow DECSTR" + + +class TestResetSpecificationCompleteness: + """Bidirectional completeness tests for the terminal reset specification. + + Follows the GATED_TOOLS pattern: a structured specification is tested + via set operations to detect missing, extra, or duplicate entries. + """ + + def test_reset_spec_covers_all_layers(self): + """Every ResetLayer enum member must have >= 1 entry in _RESET_SPEC.""" + from autoskillit.cli._terminal import _RESET_SPEC, ResetLayer + + covered_layers = {entry.layer for entry in _RESET_SPEC} + missing = set(ResetLayer) - covered_layers + assert not missing, ( + f"ResetLayer members {missing} have no entry in _RESET_SPEC. " + "Every layer must have at least one reset sequence." + ) + + def test_base_reset_matches_spec_bidirectional(self): + """_BASE_RESET must contain exactly the sequences in _RESET_SPEC.""" + import re + + from autoskillit.cli._terminal import _BASE_RESET, _RESET_SPEC + + spec_sequences = {entry.sequence for entry in _RESET_SPEC} + for seq in spec_sequences: + assert seq in _BASE_RESET, f"Spec sequence {seq!r} missing from _BASE_RESET" + + # Reverse: parse _BASE_RESET and verify every sequence is in the spec. + found = set(re.findall(r"\033(?:[\[\(!][^a-zA-Z]*[a-zA-Z]|[>-~])", _BASE_RESET)) + unregistered = found - spec_sequences + assert not unregistered, ( + f"Sequences in _BASE_RESET not registered in _RESET_SPEC: {unregistered}" + ) + + def test_content_layer_sequences_are_last(self): + """CONTENT layer sequences must follow all other layers in _BASE_RESET.""" + from autoskillit.cli._terminal import _BASE_RESET, _RESET_SPEC, ResetLayer + + content_seqs = [e.sequence for e in _RESET_SPEC if e.layer == ResetLayer.CONTENT] + other_seqs = [e.sequence for e in _RESET_SPEC if e.layer != ResetLayer.CONTENT] + + for content_seq in content_seqs: + content_pos = _BASE_RESET.index(content_seq) + for other_seq in other_seqs: + other_pos = _BASE_RESET.index(other_seq) + assert other_pos < content_pos, ( + f"CONTENT sequence {content_seq!r} must follow " + f"non-CONTENT sequence {other_seq!r}" + ) + + def test_reset_spec_has_no_duplicate_sequences(self): + """Each escape sequence must appear exactly once in _RESET_SPEC.""" + from autoskillit.cli._terminal import _RESET_SPEC + + sequences = [e.sequence for e in _RESET_SPEC] + duplicates = [s for s in sequences if sequences.count(s) > 1] + assert not duplicates, f"Duplicate sequences in _RESET_SPEC: {set(duplicates)}" + class TestCookTerminalGuard: """cook() and _launch_cook_session() apply terminal_guard correctly.""" @@ -276,6 +438,7 @@ def test_cook_restores_terminal_on_keyboard_interrupt(self, monkeypatch, tmp_pat lambda *a, **kw: (_ for _ in ()).throw(KeyboardInterrupt()), ) monkeypatch.setattr("shutil.which", lambda cmd: "/usr/bin/claude") + monkeypatch.setattr("autoskillit.cli._init_helpers._is_plugin_installed", lambda: False) # is_first_run is imported inside cook() body — patch the source module monkeypatch.setattr("autoskillit.cli._onboarding.is_first_run", lambda _: False) # cook() calls input() for launch confirmation before subprocess.run @@ -321,6 +484,7 @@ def test_launch_cook_session_restores_terminal_on_keyboard_interrupt(self, monke lambda *a, **kw: (_ for _ in ()).throw(KeyboardInterrupt()), ) monkeypatch.setattr("shutil.which", lambda cmd: "/usr/bin/claude") + monkeypatch.setattr(app_mod, "_is_plugin_installed", lambda: False) with pytest.raises(KeyboardInterrupt): app_mod._launch_cook_session("system prompt") diff --git a/tests/cli/test_update_checks.py b/tests/cli/test_update_checks.py new file mode 100644 index 0000000000..3d80dfa170 --- /dev/null +++ b/tests/cli/test_update_checks.py @@ -0,0 +1,1577 @@ +"""Tests for cli/_update_checks.py — unified update check orchestration. + +Absorbs and extends the behavioral coverage from the deleted +test_stale_check.py and test_source_drift.py files. +""" + +from __future__ import annotations + +import io +import json +import sys +from datetime import UTC, datetime, timedelta +from pathlib import Path +from typing import Any +from unittest.mock import MagicMock, patch + +import pytest + +from autoskillit.cli._install_info import InstallInfo, InstallType +from autoskillit.cli._update_checks import ( + _fetch_with_cache, + _is_dismissed, + _read_dismiss_state, + _write_dismiss_state, + run_update_checks, +) + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _make_stable_info(commit_id: str = "abc123", revision: str = "stable") -> InstallInfo: + return InstallInfo( + install_type=InstallType.GIT_VCS, + commit_id=commit_id, + requested_revision=revision, + url="https://github.com/TalonT-Org/AutoSkillit.git", + editable_source=None, + ) + + +def _make_integration_info(commit_id: str = "def456") -> InstallInfo: + return InstallInfo( + install_type=InstallType.GIT_VCS, + commit_id=commit_id, + requested_revision="integration", + url="https://github.com/TalonT-Org/AutoSkillit.git", + editable_source=None, + ) + + +def _make_mock_client( + status_code: int = 200, + json_body: dict[str, Any] | None = None, + etag: str | None = None, + raise_exc: Exception | None = None, +) -> MagicMock: + """Build a MagicMock httpx.Client context manager for fetch cache tests.""" + response = MagicMock() + response.status_code = status_code + response.json.return_value = json_body or {} + response.headers = {"ETag": etag} if etag else {} + + client_instance = MagicMock() + if raise_exc is not None: + client_instance.get.side_effect = raise_exc + else: + client_instance.get.return_value = response + + ctx_manager = MagicMock() + ctx_manager.__enter__.return_value = client_instance + ctx_manager.__exit__.return_value = False + return ctx_manager + + +# --------------------------------------------------------------------------- +# UC-1 Guards +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "env_var,value", + [ + ("CLAUDECODE", "1"), + ("CI", "1"), + ("AUTOSKILLIT_SKIP_STALE_CHECK", "1"), + ("AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK", "1"), + ], +) +def test_run_update_checks_skips_on_guard_env_var( + monkeypatch: pytest.MonkeyPatch, + env_var: str, + value: str, + tmp_path: Path, +) -> None: + monkeypatch.setenv(env_var, value) + # Ensure no other guard vars are set + for other in [ + "CLAUDECODE", + "CI", + "AUTOSKILLIT_SKIP_STALE_CHECK", + "AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK", + ]: + if other != env_var: + monkeypatch.delenv(other, raising=False) + fetched: list[str] = [] + monkeypatch.setattr( + "autoskillit.cli._update_checks._fetch_with_cache", + lambda url, **kw: fetched.append(url) or None, + ) + prompted: list[str] = [] + monkeypatch.setattr("builtins.input", lambda _: prompted.append("called") or "n") + run_update_checks(home=tmp_path) + assert not fetched, "No network fetch should occur under guard env" + assert not prompted, "No input() call under guard env" + + +def test_run_update_checks_skips_non_tty_stdin( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.delenv("CLAUDECODE", raising=False) + monkeypatch.delenv("CI", raising=False) + monkeypatch.delenv("AUTOSKILLIT_SKIP_STALE_CHECK", raising=False) + monkeypatch.delenv("AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK", raising=False) + fake_stdin = io.StringIO() + fake_stdout = io.StringIO() + monkeypatch.setattr(sys, "stdin", fake_stdin) + monkeypatch.setattr(sys, "stdout", fake_stdout) + fetched: list[str] = [] + monkeypatch.setattr( + "autoskillit.cli._update_checks._fetch_with_cache", + lambda url, **kw: fetched.append(url) or None, + ) + run_update_checks(home=tmp_path) + assert not fetched + + +def test_run_update_checks_skips_non_tty_stdout( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.delenv("CLAUDECODE", raising=False) + monkeypatch.delenv("CI", raising=False) + monkeypatch.delenv("AUTOSKILLIT_SKIP_STALE_CHECK", raising=False) + monkeypatch.delenv("AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK", raising=False) + + fake_stdin = MagicMock() + fake_stdin.isatty.return_value = True + fake_stdout = io.StringIO() + monkeypatch.setattr(sys, "stdin", fake_stdin) + monkeypatch.setattr(sys, "stdout", fake_stdout) + fetched: list[str] = [] + monkeypatch.setattr( + "autoskillit.cli._update_checks._fetch_with_cache", + lambda url, **kw: fetched.append(url) or None, + ) + run_update_checks(home=tmp_path) + assert not fetched + + +@pytest.mark.parametrize( + "install_type", + [InstallType.LOCAL_EDITABLE, InstallType.LOCAL_PATH, InstallType.UNKNOWN], +) +def test_run_update_checks_skips_local_and_unknown_install_types( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, install_type: InstallType +) -> None: + monkeypatch.delenv("CLAUDECODE", raising=False) + monkeypatch.delenv("CI", raising=False) + monkeypatch.delenv("AUTOSKILLIT_SKIP_STALE_CHECK", raising=False) + monkeypatch.delenv("AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK", raising=False) + monkeypatch.delenv("AUTOSKILLIT_FORCE_UPDATE_CHECK", raising=False) + + fake_stdin = MagicMock() + fake_stdin.isatty.return_value = True + fake_stdout = MagicMock() + fake_stdout.isatty.return_value = True + monkeypatch.setattr(sys, "stdin", fake_stdin) + monkeypatch.setattr(sys, "stdout", fake_stdout) + + info = InstallInfo( + install_type=install_type, + commit_id=None, + requested_revision=None, + url=None, + editable_source=Path(tmp_path) if install_type == InstallType.LOCAL_EDITABLE else None, + ) + monkeypatch.setattr("autoskillit.cli._update_checks.detect_install", lambda: info) + fetched: list[str] = [] + monkeypatch.setattr( + "autoskillit.cli._update_checks._fetch_with_cache", + lambda url, **kw: fetched.append(url) or None, + ) + prompted: list[str] = [] + monkeypatch.setattr("builtins.input", lambda _: prompted.append("called") or "n") + run_update_checks(home=tmp_path) + assert not fetched + assert not prompted + + +# --------------------------------------------------------------------------- +# UC-2 Signal gathering +# --------------------------------------------------------------------------- + + +def test_binary_signal_fires_when_newer_version_available( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update_checks import _binary_signal + + info = _make_stable_info() + monkeypatch.setattr( + "autoskillit.cli._update_checks._fetch_latest_version", + lambda target, home: "0.9.0", + ) + sig = _binary_signal(info, tmp_path, "0.7.77") + assert sig is not None + assert sig.kind == "binary" + assert "0.9.0" in sig.message + assert "0.7.77" in sig.message + + +def test_binary_signal_silent_when_same_version( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update_checks import _binary_signal + + info = _make_stable_info() + monkeypatch.setattr( + "autoskillit.cli._update_checks._fetch_latest_version", + lambda target, home: "0.7.77", + ) + assert _binary_signal(info, tmp_path, "0.7.77") is None + + +def test_binary_signal_silent_when_fetch_returns_none( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update_checks import _binary_signal + + info = _make_stable_info() + monkeypatch.setattr( + "autoskillit.cli._update_checks._fetch_latest_version", + lambda target, home: None, + ) + assert _binary_signal(info, tmp_path, "0.7.77") is None + + +def test_binary_signal_uses_releases_url_for_stable( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update_checks import _binary_signal + + info = _make_stable_info() + targets: list[str] = [] + monkeypatch.setattr( + "autoskillit.cli._update_checks._fetch_latest_version", + lambda target, home: targets.append(target) or "0.9.0", + ) + _binary_signal(info, tmp_path, "0.7.77") + assert targets == ["releases/latest"] + + +def test_binary_signal_uses_integration_url_for_integration( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update_checks import _binary_signal + + info = _make_integration_info() + targets: list[str] = [] + monkeypatch.setattr( + "autoskillit.cli._update_checks._fetch_latest_version", + lambda target, home: targets.append(target) or "0.9.0", + ) + _binary_signal(info, tmp_path, "0.7.77") + assert targets == ["integration"] + + +def test_hooks_signal_fires_on_missing_hooks( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update_checks import _hooks_signal + from autoskillit.hook_registry import HookDriftResult + + monkeypatch.setattr( + "autoskillit.cli._update_checks._count_hook_registry_drift", + lambda path: HookDriftResult(missing=3, orphaned=0), + ) + sig = _hooks_signal(tmp_path / "settings.json") + assert sig is not None + assert sig.kind == "hooks" + assert "3" in sig.message + + +def test_hooks_signal_fires_on_orphaned_hooks( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update_checks import _hooks_signal + from autoskillit.hook_registry import HookDriftResult + + monkeypatch.setattr( + "autoskillit.cli._update_checks._count_hook_registry_drift", + lambda path: HookDriftResult(missing=0, orphaned=2), + ) + sig = _hooks_signal(tmp_path / "settings.json") + assert sig is not None + assert sig.kind == "hooks" + assert "2" in sig.message + + +def test_hooks_signal_silent_when_no_drift( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update_checks import _hooks_signal + from autoskillit.hook_registry import HookDriftResult + + monkeypatch.setattr( + "autoskillit.cli._update_checks._count_hook_registry_drift", + lambda path: HookDriftResult(missing=0, orphaned=0), + ) + assert _hooks_signal(tmp_path / "settings.json") is None + + +def test_source_drift_signal_fires_when_commit_lags_ref( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update_checks import _source_drift_signal + + info = _make_stable_info(commit_id="aaaaaa") + monkeypatch.setattr( + "autoskillit.cli._update_checks.resolve_reference_sha", + lambda info, home, **kw: "bbbbbb", + ) + sig = _source_drift_signal(info, tmp_path) + assert sig is not None + assert sig.kind == "source_drift" + # "source drift" must NOT appear in user-visible text (per plan verification item 11) + assert "source drift" not in sig.message.lower() + + +def test_source_drift_signal_silent_when_sha_matches( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update_checks import _source_drift_signal + + info = _make_stable_info(commit_id="aaaaaa") + monkeypatch.setattr( + "autoskillit.cli._update_checks.resolve_reference_sha", + lambda info, home, **kw: "aaaaaa", + ) + assert _source_drift_signal(info, tmp_path) is None + + +def test_source_drift_signal_silent_when_ref_sha_none( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update_checks import _source_drift_signal + + info = _make_stable_info(commit_id="aaaaaa") + monkeypatch.setattr( + "autoskillit.cli._update_checks.resolve_reference_sha", + lambda info, home, **kw: None, + ) + assert _source_drift_signal(info, tmp_path) is None + + +def test_dual_mcp_signal_fires_when_both_registered( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from autoskillit.cli._update_checks import _dual_mcp_signal + + monkeypatch.setattr( + "autoskillit.cli._update_checks._is_dual_mcp_registered", + lambda home: True, + ) + sig = _dual_mcp_signal(tmp_path) + assert sig is not None + assert sig.kind == "dual_mcp" + assert "autoskillit install" in sig.message + + +def test_dual_mcp_signal_silent_when_only_one_registered( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from autoskillit.cli._update_checks import _dual_mcp_signal + + monkeypatch.setattr( + "autoskillit.cli._update_checks._is_dual_mcp_registered", + lambda home: False, + ) + sig = _dual_mcp_signal(tmp_path) + assert sig is None + + +def test_dual_mcp_signal_silent_on_corrupted_files( + tmp_path: Path, +) -> None: + # _check_dual_mcp_files is fail-open: corrupted JSON → False → no signal + from autoskillit.cli._update_checks import _dual_mcp_signal + + claude_json = tmp_path / ".claude.json" + claude_json.write_text("{invalid json") + sig = _dual_mcp_signal(tmp_path) + assert sig is None + + +# --------------------------------------------------------------------------- +# find_source_repo behavioral tests +# --------------------------------------------------------------------------- + + +def test_find_source_repo_env_var_override_valid( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """AUTOSKILLIT_SOURCE_REPO env var pointing to a valid repo root is returned.""" + from autoskillit.cli._update_checks import find_source_repo + + src_dir = tmp_path / "src" / "autoskillit" + src_dir.mkdir(parents=True) + monkeypatch.setenv("AUTOSKILLIT_SOURCE_REPO", str(tmp_path)) + result = find_source_repo() + assert result == tmp_path + + +def test_find_source_repo_env_var_override_invalid_falls_through( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """AUTOSKILLIT_SOURCE_REPO pointing to a path without src/autoskillit/ is ignored.""" + from autoskillit.cli._update_checks import find_source_repo + + monkeypatch.setenv("AUTOSKILLIT_SOURCE_REPO", str(tmp_path / "nonexistent")) + monkeypatch.setattr("autoskillit.cli._update_checks.Path.cwd", lambda: tmp_path) + result = find_source_repo() + assert result is None + + +def test_find_source_repo_cwd_walk_finds_pyproject( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """CWD walk finds the project root when pyproject.toml has name=autoskillit.""" + from autoskillit.cli._update_checks import find_source_repo + + project_root = tmp_path / "project" + src_dir = project_root / "src" / "autoskillit" + src_dir.mkdir(parents=True) + pyproject = project_root / "pyproject.toml" + pyproject.write_text('[project]\nname = "autoskillit"\n', encoding="utf-8") + + nested_cwd = project_root / "src" / "autoskillit" / "cli" + nested_cwd.mkdir(parents=True) + monkeypatch.delenv("AUTOSKILLIT_SOURCE_REPO", raising=False) + monkeypatch.setattr("autoskillit.cli._update_checks.Path.cwd", lambda: nested_cwd) + result = find_source_repo() + assert result == project_root + + +def test_find_source_repo_cwd_walk_no_match_returns_none( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """CWD walk returns None when no autoskillit project is found.""" + from autoskillit.cli._update_checks import find_source_repo + + monkeypatch.delenv("AUTOSKILLIT_SOURCE_REPO", raising=False) + monkeypatch.setattr("autoskillit.cli._update_checks.Path.cwd", lambda: tmp_path) + result = find_source_repo() + assert result is None + + +# --------------------------------------------------------------------------- +# UC-3 Prompt consolidation +# --------------------------------------------------------------------------- + + +def _setup_run_checks( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + *, + info: InstallInfo | None = None, + binary_signal: bool = False, + hooks_signal: bool = False, + source_drift_signal: bool = False, + answer: str = "n", + current_version: str = "0.7.77", + state: dict | None = None, +) -> tuple[list[str], list[str]]: + """Set up mocks for run_update_checks and return (printed_lines, input_calls).""" + import select as _select_mod + + from autoskillit.cli._update_checks import Signal + + monkeypatch.delenv("CLAUDECODE", raising=False) + monkeypatch.delenv("CI", raising=False) + monkeypatch.delenv("AUTOSKILLIT_SKIP_STALE_CHECK", raising=False) + monkeypatch.delenv("AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK", raising=False) + monkeypatch.delenv("AUTOSKILLIT_FORCE_UPDATE_CHECK", raising=False) + + fake_stdin = MagicMock() + fake_stdin.isatty.return_value = True + fake_stdout = MagicMock() + fake_stdout.isatty.return_value = True + monkeypatch.setattr(sys, "stdin", fake_stdin) + monkeypatch.setattr(sys, "stdout", fake_stdout) + + # timed_prompt uses select.select to implement timeout; mock it to + # report "stdin is ready" so tests proceed without real file descriptors. + monkeypatch.setattr( + _select_mod, "select", lambda rlist, wlist, xlist, timeout=None: (rlist, [], []) + ) + + _info = info or _make_stable_info() + monkeypatch.setattr("autoskillit.cli._update_checks.detect_install", lambda: _info) + + if state is not None: + (tmp_path / ".autoskillit").mkdir(parents=True, exist_ok=True) + (tmp_path / ".autoskillit" / "update_check.json").write_text( + json.dumps(state), encoding="utf-8" + ) + + import autoskillit as _pkg + + monkeypatch.setattr(_pkg, "__version__", current_version) + + monkeypatch.setattr( + "autoskillit.cli._update_checks._binary_signal", + lambda info, home, current: ( + Signal("binary", "New release: 0.9.0 (you have 0.7.77)") if binary_signal else None + ), + ) + monkeypatch.setattr( + "autoskillit.cli._update_checks._hooks_signal", + lambda settings_path: ( + Signal("hooks", "1 new/changed hook(s) detected") if hooks_signal else None + ), + ) + monkeypatch.setattr( + "autoskillit.cli._update_checks._source_drift_signal", + lambda info, home: ( + Signal("source_drift", "A newer version is available on the stable branch (aaa..bbb)") + if source_drift_signal + else None + ), + ) + monkeypatch.setattr( + "autoskillit.cli._update_checks._claude_settings_path", + lambda scope: tmp_path / "settings.json", + ) + + printed: list[str] = [] + monkeypatch.setattr( + "builtins.print", lambda *args, **kw: printed.append(" ".join(str(a) for a in args)) + ) + + input_calls: list[str] = [] + monkeypatch.setattr("builtins.input", lambda _="": input_calls.append("called") or answer) + + return printed, input_calls + + +def test_no_prompt_when_no_conditions_fire( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + printed, input_calls = _setup_run_checks(monkeypatch, tmp_path) + run_update_checks(home=tmp_path) + assert not input_calls + + +def test_single_prompt_when_only_binary_fires( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + printed, input_calls = _setup_run_checks(monkeypatch, tmp_path, binary_signal=True) + run_update_checks(home=tmp_path) + assert len(input_calls) == 1 + + +def test_single_prompt_when_only_hooks_fires( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + printed, input_calls = _setup_run_checks(monkeypatch, tmp_path, hooks_signal=True) + run_update_checks(home=tmp_path) + assert len(input_calls) == 1 + + +def test_single_prompt_when_only_source_drift_fires( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + printed, input_calls = _setup_run_checks(monkeypatch, tmp_path, source_drift_signal=True) + run_update_checks(home=tmp_path) + assert len(input_calls) == 1 + + +def test_consolidated_prompt_when_binary_plus_hooks_fire( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + printed, input_calls = _setup_run_checks( + monkeypatch, tmp_path, binary_signal=True, hooks_signal=True + ) + run_update_checks(home=tmp_path) + assert len(input_calls) == 1 + combined = " ".join(printed) + # Should contain 2 bullet lines + assert combined.count(" - ") == 2 + + +def test_consolidated_prompt_when_all_three_fire( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + printed, input_calls = _setup_run_checks( + monkeypatch, tmp_path, binary_signal=True, hooks_signal=True, source_drift_signal=True + ) + run_update_checks(home=tmp_path) + assert len(input_calls) == 1 + combined = " ".join(printed) + assert combined.count(" - ") == 3 + + +def test_prompt_never_contains_phrase_source_drift( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + printed, _ = _setup_run_checks(monkeypatch, tmp_path, source_drift_signal=True) + run_update_checks(home=tmp_path) + combined = " ".join(printed) + assert "source drift" not in combined.lower() + + +def test_prompt_uses_friendly_branch_language( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + printed, _ = _setup_run_checks(monkeypatch, tmp_path, source_drift_signal=True) + run_update_checks(home=tmp_path) + combined = " ".join(printed) + assert "newer version is available on the stable branch" in combined + + +# --------------------------------------------------------------------------- +# UC-4 Yes path +# --------------------------------------------------------------------------- + + +def test_yes_runs_upgrade_command_from_install_info_not_hardcoded( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._install_info import upgrade_command + + info = _make_stable_info() + printed, input_calls = _setup_run_checks( + monkeypatch, tmp_path, binary_signal=True, answer="y", info=info + ) + run_calls: list[list[str]] = [] + monkeypatch.setattr( + "autoskillit.cli._update_checks.subprocess.run", + lambda cmd, **kw: run_calls.append(list(cmd)), + ) + monkeypatch.setattr("autoskillit.cli._update_checks.terminal_guard", MagicMock()) + monkeypatch.setattr( + "autoskillit.cli._update_checks._verify_update_result", lambda *a, **kw: True + ) + monkeypatch.setattr( + "autoskillit.cli._update_checks._fetch_latest_version", lambda *a, **kw: "0.9.0" + ) + expected_cmd = upgrade_command(info) + run_update_checks(home=tmp_path) + assert expected_cmd in run_calls, ( + f"Expected upgrade command {expected_cmd!r} from upgrade_command(info); got {run_calls!r}" + ) + + +def test_yes_runs_autoskillit_install_after_upgrade_command( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + printed, input_calls = _setup_run_checks(monkeypatch, tmp_path, binary_signal=True, answer="y") + run_calls: list[list[str]] = [] + + class FakeTG: + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + monkeypatch.setattr("autoskillit.cli._update_checks.terminal_guard", FakeTG) + monkeypatch.setattr( + "autoskillit.cli._update_checks.subprocess.run", + lambda cmd, **kw: run_calls.append(list(cmd)), + ) + monkeypatch.setattr( + "autoskillit.cli._update_checks._verify_update_result", lambda *a, **kw: True + ) + run_update_checks(home=tmp_path) + # ["autoskillit", "install"] must be among the calls + assert any(cmd[:2] == ["autoskillit", "install"] for cmd in run_calls) + + +def test_yes_passes_skip_env_to_subprocess( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + printed, input_calls = _setup_run_checks(monkeypatch, tmp_path, binary_signal=True, answer="y") + env_passed: list[dict] = [] + + class FakeTG: + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + monkeypatch.setattr("autoskillit.cli._update_checks.terminal_guard", FakeTG) + monkeypatch.setattr( + "autoskillit.cli._update_checks.subprocess.run", + lambda cmd, **kw: env_passed.append(kw.get("env", {})), + ) + monkeypatch.setattr( + "autoskillit.cli._update_checks._verify_update_result", lambda *a, **kw: True + ) + run_update_checks(home=tmp_path) + for env in env_passed: + assert env.get("AUTOSKILLIT_SKIP_STALE_CHECK") == "1" + assert env.get("AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK") == "1" + + +def test_yes_single_invocation_exits_without_any_other_prompt( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + printed, input_calls = _setup_run_checks( + monkeypatch, tmp_path, binary_signal=True, hooks_signal=True, answer="y" + ) + + class FakeTG: + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + monkeypatch.setattr("autoskillit.cli._update_checks.terminal_guard", FakeTG) + monkeypatch.setattr("autoskillit.cli._update_checks.subprocess.run", lambda *a, **kw: None) + monkeypatch.setattr( + "autoskillit.cli._update_checks._verify_update_result", lambda *a, **kw: True + ) + run_update_checks(home=tmp_path) + assert len(input_calls) == 1 + + +# --------------------------------------------------------------------------- +# UC-5 No path +# --------------------------------------------------------------------------- + + +def test_no_writes_single_unified_dismissal_entry( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + printed, input_calls = _setup_run_checks(monkeypatch, tmp_path, binary_signal=True, answer="n") + run_update_checks(home=tmp_path) + state = _read_dismiss_state(tmp_path) + assert "update_prompt" in state + # No legacy sub-keys + assert "binary" not in state + assert "hooks" not in state + assert "source_drift" not in state + + +def test_no_records_conditions_list_in_dismissal_entry( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + printed, input_calls = _setup_run_checks( + monkeypatch, tmp_path, binary_signal=True, hooks_signal=True, answer="n" + ) + run_update_checks(home=tmp_path) + state = _read_dismiss_state(tmp_path) + entry = state["update_prompt"] + assert isinstance(entry, dict) + conditions = entry["conditions"] + assert "binary" in conditions + assert "hooks" in conditions + + +def test_no_prints_expiry_date_line_with_correct_date( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + printed, input_calls = _setup_run_checks(monkeypatch, tmp_path, binary_signal=True, answer="n") + run_update_checks(home=tmp_path) + combined = " ".join(printed) + # Should mention "Dismissed until" + assert "Dismissed until" in combined + # And an escape hatch hint + assert "autoskillit update" in combined or "AUTOSKILLIT_SKIP_STALE_CHECK" in combined + + +def test_no_prints_escape_hatch_hint(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + printed, input_calls = _setup_run_checks(monkeypatch, tmp_path, binary_signal=True, answer="n") + run_update_checks(home=tmp_path) + combined = " ".join(printed) + assert "autoskillit update" in combined + assert "AUTOSKILLIT_SKIP_STALE_CHECK=1" in combined + + +# --------------------------------------------------------------------------- +# UC-6 Branch-aware dismissal windows +# --------------------------------------------------------------------------- + + +def _dismissed_state( + ago: timedelta, + version: str = "0.7.77", + conditions: list[str] | None = None, +) -> dict: + return { + "update_prompt": { + "dismissed_at": (datetime.now(UTC) - ago).isoformat(), + "dismissed_version": version, + "conditions": conditions or ["binary"], + } + } + + +def test_stable_install_dismissal_silent_within_six_days( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + state = _dismissed_state(ago=timedelta(days=6)) + printed, input_calls = _setup_run_checks( + monkeypatch, tmp_path, binary_signal=True, state=state + ) + run_update_checks(home=tmp_path) + assert not input_calls + + +def test_stable_install_dismissal_reprompts_after_eight_days( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + state = _dismissed_state(ago=timedelta(days=8)) + printed, input_calls = _setup_run_checks( + monkeypatch, tmp_path, binary_signal=True, state=state + ) + run_update_checks(home=tmp_path) + assert len(input_calls) == 1 + + +def test_integration_install_dismissal_silent_within_eleven_hours( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + state = _dismissed_state(ago=timedelta(hours=11)) + printed, input_calls = _setup_run_checks( + monkeypatch, + tmp_path, + binary_signal=True, + info=_make_integration_info(), + state=state, + ) + run_update_checks(home=tmp_path) + assert not input_calls + + +def test_integration_install_dismissal_reprompts_after_thirteen_hours( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + state = _dismissed_state(ago=timedelta(hours=13)) + printed, input_calls = _setup_run_checks( + monkeypatch, + tmp_path, + binary_signal=True, + info=_make_integration_info(), + state=state, + ) + run_update_checks(home=tmp_path) + assert len(input_calls) == 1 + + +def test_dismissal_window_chosen_from_current_install_not_stored( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """User dismisses on stable (7d window), then migrates to integration (12h window). + 13 hours later the prompt should re-appear under the integration window.""" + state = _dismissed_state(ago=timedelta(hours=13)) + # Info is now integration — 12h window applies + printed, input_calls = _setup_run_checks( + monkeypatch, + tmp_path, + binary_signal=True, + info=_make_integration_info(), + state=state, + ) + run_update_checks(home=tmp_path) + assert len(input_calls) == 1 + + +# --------------------------------------------------------------------------- +# UC-7 Time-windowed source-drift dismissal (no SHA keying) +# --------------------------------------------------------------------------- + + +def test_source_drift_dismissal_survives_new_upstream_commit_within_window( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """Dismissed with ref=B; new check sees ref=C within window → still silent.""" + state = _dismissed_state(ago=timedelta(hours=1), conditions=["source_drift"]) + printed, input_calls = _setup_run_checks( + monkeypatch, tmp_path, source_drift_signal=True, state=state + ) + run_update_checks(home=tmp_path) + assert not input_calls + + +def test_source_drift_dismissal_expires_on_window_boundary( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + state = _dismissed_state(ago=timedelta(days=8), conditions=["source_drift"]) + printed, input_calls = _setup_run_checks( + monkeypatch, tmp_path, source_drift_signal=True, state=state + ) + run_update_checks(home=tmp_path) + assert len(input_calls) == 1 + + +def test_source_drift_dismissal_expires_on_version_delta( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + """Version advanced past dismissed_version → re-prompts regardless of time.""" + state = _dismissed_state(ago=timedelta(hours=1), version="0.7.77", conditions=["source_drift"]) + printed, input_calls = _setup_run_checks( + monkeypatch, tmp_path, source_drift_signal=True, state=state, current_version="0.7.78" + ) + run_update_checks(home=tmp_path) + assert len(input_calls) == 1 + + +# --------------------------------------------------------------------------- +# UC-8 Hook dismissal with version-delta +# --------------------------------------------------------------------------- + + +def test_hook_dismissal_expires_when_version_advances( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + state = _dismissed_state(ago=timedelta(hours=1), version="0.7.77", conditions=["hooks"]) + printed, input_calls = _setup_run_checks( + monkeypatch, tmp_path, hooks_signal=True, state=state, current_version="0.7.78" + ) + run_update_checks(home=tmp_path) + assert len(input_calls) == 1 + + +def test_hook_dismissal_holds_within_window_at_same_version( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + state = _dismissed_state(ago=timedelta(hours=1), version="0.7.77", conditions=["hooks"]) + printed, input_calls = _setup_run_checks( + monkeypatch, tmp_path, hooks_signal=True, state=state, current_version="0.7.77" + ) + run_update_checks(home=tmp_path) + assert not input_calls + + +# --------------------------------------------------------------------------- +# Dismiss state I/O +# --------------------------------------------------------------------------- + + +def test_read_dismiss_state_empty(tmp_path: Path) -> None: + assert _read_dismiss_state(tmp_path) == {} + + +def test_read_dismiss_state_malformed(tmp_path: Path) -> None: + p = tmp_path / ".autoskillit" / "update_check.json" + p.parent.mkdir(parents=True) + p.write_text("not-json", encoding="utf-8") + assert _read_dismiss_state(tmp_path) == {} + + +def test_write_dismiss_state_roundtrip(tmp_path: Path) -> None: + state = {"update_prompt": {"dismissed_at": "2026-01-01T00:00:00+00:00"}} + _write_dismiss_state(tmp_path, state) + assert _read_dismiss_state(tmp_path) == state + + +def test_read_dismiss_state_non_dict_json_returns_empty(tmp_path: Path) -> None: + p = tmp_path / ".autoskillit" / "update_check.json" + p.parent.mkdir(parents=True) + p.write_text("[1, 2, 3]", encoding="utf-8") + assert _read_dismiss_state(tmp_path) == {} + + +# --------------------------------------------------------------------------- +# _is_dismissed +# --------------------------------------------------------------------------- + + +def test_is_dismissed_within_window() -> None: + state = { + "update_prompt": { + "dismissed_at": (datetime.now(UTC) - timedelta(hours=1)).isoformat(), + "dismissed_version": "0.9.0", + "conditions": ["binary"], + } + } + assert _is_dismissed( + state, window=timedelta(hours=12), current_version="0.7.77", condition="binary" + ) + + +def test_is_dismissed_expired() -> None: + state = { + "update_prompt": { + "dismissed_at": (datetime.now(UTC) - timedelta(days=8)).isoformat(), + "dismissed_version": "0.9.0", + "conditions": ["binary"], + } + } + assert not _is_dismissed( + state, window=timedelta(days=7), current_version="0.7.77", condition="binary" + ) + + +def test_is_dismissed_newer_version_resets() -> None: + state = { + "update_prompt": { + "dismissed_at": (datetime.now(UTC) - timedelta(hours=1)).isoformat(), + "dismissed_version": "0.7.77", + "conditions": ["binary"], + } + } + assert not _is_dismissed( + state, window=timedelta(days=7), current_version="0.7.78", condition="binary" + ) + + +def test_is_dismissed_condition_not_in_list() -> None: + state = { + "update_prompt": { + "dismissed_at": (datetime.now(UTC) - timedelta(hours=1)).isoformat(), + "dismissed_version": "0.9.0", + "conditions": ["binary"], + } + } + # hooks was NOT dismissed — should still fire + assert not _is_dismissed( + state, window=timedelta(days=7), current_version="0.7.77", condition="hooks" + ) + + +def test_is_dismissed_empty_state() -> None: + assert not _is_dismissed( + {}, window=timedelta(days=7), current_version="0.7.77", condition="binary" + ) + + +# --------------------------------------------------------------------------- +# UC-9 Fetch-cache regression coverage +# --------------------------------------------------------------------------- + + +def test_fetch_latest_version_uses_cache_within_ttl(tmp_path: Path) -> None: + # Seed a cache entry that is fresh (1 second old, TTL = 30 min) + import time + + from autoskillit.cli._update_checks import _fetch_latest_version + + cache_data = { + "https://api.github.com/repos/TalonT-Org/AutoSkillit/releases/latest": { + "body": {"tag_name": "v0.9.0"}, + "etag": '"test-etag"', + "cached_at": time.time() - 1, + } + } + (tmp_path / ".autoskillit").mkdir(parents=True, exist_ok=True) + (tmp_path / ".autoskillit" / "github_fetch_cache.json").write_text( + json.dumps(cache_data), encoding="utf-8" + ) + call_count = [0] + + class CountingClient: + def __init__(self, **kw): + pass + + def __enter__(self): + call_count[0] += 1 + return self + + def __exit__(self, *a): + return False + + def get(self, url, **kw): + raise AssertionError("Should not hit network when cache is fresh") + + with patch("httpx.Client", CountingClient): + result = _fetch_latest_version("releases/latest", tmp_path) + + assert result == "0.9.0" + assert call_count[0] == 0 + + +def test_fetch_cache_expires_after_ttl(tmp_path: Path) -> None: + import time + + from autoskillit.cli._update_checks import _fetch_latest_version + + cache_data = { + "https://api.github.com/repos/TalonT-Org/AutoSkillit/releases/latest": { + "body": {"tag_name": "v0.8.0"}, + "etag": '"stale-etag"', + "cached_at": time.time() - 3601, # 1 hour + 1 second old + } + } + (tmp_path / ".autoskillit").mkdir(parents=True, exist_ok=True) + (tmp_path / ".autoskillit" / "github_fetch_cache.json").write_text( + json.dumps(cache_data), encoding="utf-8" + ) + + mock_client = _make_mock_client( + status_code=200, + json_body={"tag_name": "v0.9.0"}, + etag='"new-etag"', + ) + with patch("httpx.Client", return_value=mock_client): + result = _fetch_latest_version("releases/latest", tmp_path) + + assert result == "0.9.0" + + +def test_fetch_cache_respects_env_var_ttl(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + import time + + from autoskillit.cli._update_checks import _fetch_latest_version + + # Entry is 61 seconds old — older than the custom 60s TTL + cache_data = { + "https://api.github.com/repos/TalonT-Org/AutoSkillit/releases/latest": { + "body": {"tag_name": "v0.8.0"}, + "etag": '"stale-etag"', + "cached_at": time.time() - 61, + } + } + (tmp_path / ".autoskillit").mkdir(parents=True, exist_ok=True) + (tmp_path / ".autoskillit" / "github_fetch_cache.json").write_text( + json.dumps(cache_data), encoding="utf-8" + ) + monkeypatch.setenv("AUTOSKILLIT_FETCH_CACHE_TTL_SECONDS", "60") + + mock_client = _make_mock_client( + status_code=200, + json_body={"tag_name": "v0.9.0"}, + ) + with patch("httpx.Client", return_value=mock_client): + result = _fetch_latest_version("releases/latest", tmp_path) + + assert result == "0.9.0" + + +def test_fetch_sends_github_token_auth_header( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + + monkeypatch.setenv("GITHUB_TOKEN", "my-secret-token") + (tmp_path / ".autoskillit").mkdir(parents=True, exist_ok=True) + + received_headers: dict = {} + + class CapturingClient: + def __init__(self, **kw): + pass + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def get(self, url, headers=None, **kw): + received_headers.update(headers or {}) + r = MagicMock() + r.status_code = 200 + r.json.return_value = {"tag_name": "v0.9.0"} + r.headers = {} + return r + + with patch("httpx.Client", CapturingClient): + _fetch_with_cache( + "https://api.github.com/repos/TalonT-Org/AutoSkillit/releases/latest", + home=tmp_path, + ) + + assert "Authorization" in received_headers + assert received_headers["Authorization"] == "Bearer my-secret-token" + + +# --------------------------------------------------------------------------- +# timed_prompt primitive tests +# --------------------------------------------------------------------------- + + +def test_timed_prompt_returns_default_on_timeout(monkeypatch: pytest.MonkeyPatch) -> None: + """timed_prompt returns the default value when select.select times out.""" + import select as _select_mod + + from autoskillit.cli._timed_input import timed_prompt + + monkeypatch.setattr("sys.stdin.isatty", lambda: True) + monkeypatch.setattr("sys.stdout.isatty", lambda: True) + monkeypatch.delenv("NO_COLOR", raising=False) + + # select.select returns empty list = timeout + monkeypatch.setattr( + _select_mod, "select", lambda rlist, wlist, xlist, timeout=None: ([], [], []) + ) + + printed: list[str] = [] + monkeypatch.setattr("builtins.print", lambda *args, **kw: printed.append(str(args))) + + result = timed_prompt("Test prompt?", default="n", timeout=30, label="test") + assert result == "n" + assert any("timed out" in p for p in printed) + + +def test_timed_prompt_applies_ansi_formatting(monkeypatch: pytest.MonkeyPatch) -> None: + """timed_prompt output includes ANSI escape sequences when color is supported.""" + import select as _select_mod + + from autoskillit.cli._timed_input import timed_prompt + + monkeypatch.setattr("sys.stdin.isatty", lambda: True) + monkeypatch.setattr("sys.stdout.isatty", lambda: True) + monkeypatch.delenv("NO_COLOR", raising=False) + monkeypatch.delenv("TERM", raising=False) + + monkeypatch.setattr( + _select_mod, "select", lambda rlist, wlist, xlist, timeout=None: (rlist, [], []) + ) + monkeypatch.setattr("builtins.input", lambda _="": "y") + + raw_output: list[str] = [] + monkeypatch.setattr( + "builtins.print", + lambda *args, **kw: raw_output.append(" ".join(str(a) for a in args)), + ) + + timed_prompt("Update now? [Y/n]", default="n", timeout=30, label="test") + combined = " ".join(raw_output) + assert "\x1b[" in combined # ANSI escape present + + +def test_timed_prompt_respects_no_color(monkeypatch: pytest.MonkeyPatch) -> None: + """timed_prompt output has no ANSI sequences when NO_COLOR is set.""" + import select as _select_mod + + from autoskillit.cli._timed_input import timed_prompt + + monkeypatch.setattr("sys.stdin.isatty", lambda: True) + monkeypatch.setattr("sys.stdout.isatty", lambda: True) + monkeypatch.setenv("NO_COLOR", "1") + + monkeypatch.setattr( + _select_mod, "select", lambda rlist, wlist, xlist, timeout=None: (rlist, [], []) + ) + monkeypatch.setattr("builtins.input", lambda _="": "y") + + raw_output: list[str] = [] + monkeypatch.setattr( + "builtins.print", + lambda *args, **kw: raw_output.append(" ".join(str(a) for a in args)), + ) + + timed_prompt("Update now? [Y/n]", default="n", timeout=30, label="test") + combined = " ".join(raw_output) + assert "\x1b[" not in combined # No ANSI escapes + + +# --------------------------------------------------------------------------- +# Pre-flight feedback ordering test +# --------------------------------------------------------------------------- + + +def test_run_update_checks_emits_status_before_network( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + """The first print() call in run_update_checks occurs before any signal + gatherer is invoked (the 'time to first output' structural test).""" + import select as _select_mod + + from autoskillit.cli._update_checks import Signal + + monkeypatch.delenv("CLAUDECODE", raising=False) + monkeypatch.delenv("CI", raising=False) + monkeypatch.delenv("AUTOSKILLIT_SKIP_STALE_CHECK", raising=False) + monkeypatch.delenv("AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK", raising=False) + monkeypatch.delenv("AUTOSKILLIT_FORCE_UPDATE_CHECK", raising=False) + + fake_stdin = MagicMock() + fake_stdin.isatty.return_value = True + fake_stdout = MagicMock() + fake_stdout.isatty.return_value = True + monkeypatch.setattr(sys, "stdin", fake_stdin) + monkeypatch.setattr(sys, "stdout", fake_stdout) + + monkeypatch.setattr( + _select_mod, + "select", + lambda rlist, wlist, xlist, timeout=None: (rlist, [], []), + ) + + info = _make_stable_info() + monkeypatch.setattr("autoskillit.cli._update_checks.detect_install", lambda: info) + monkeypatch.setattr( + "autoskillit.cli._update_checks._claude_settings_path", + lambda scope: tmp_path / "settings.json", + ) + + import autoskillit as _pkg + + monkeypatch.setattr(_pkg, "__version__", "0.7.77") + + # Track call order: print vs signal gatherers + call_log: list[str] = [] + + def tracking_print(*args: Any, **kw: Any) -> None: + call_log.append("print") + + monkeypatch.setattr("builtins.print", tracking_print) + + monkeypatch.setattr( + "autoskillit.cli._update_checks._binary_signal", + lambda info, home, current: ( + call_log.append("binary_signal") + or Signal("binary", "New release: 0.9.0 (you have 0.7.77)") + ), + ) + monkeypatch.setattr( + "autoskillit.cli._update_checks._hooks_signal", + lambda settings_path: call_log.append("hooks_signal"), + ) + monkeypatch.setattr( + "autoskillit.cli._update_checks._source_drift_signal", + lambda info, home: call_log.append("source_drift_signal"), + ) + + monkeypatch.setattr("builtins.input", lambda _="": "n") + + run_update_checks(home=tmp_path) + + # The first print (status_line) must come before any signal gatherer + assert call_log[0] == "print", ( + f"Expected first call to be print() (status_line), got: {call_log}" + ) + signal_calls = [c for c in call_log if c.endswith("_signal")] + assert signal_calls, f"No signal gatherers were called — call_log: {call_log}" + first_signal_idx = call_log.index(signal_calls[0]) + first_print_idx = call_log.index("print") + assert first_print_idx < first_signal_idx, ( + f"print() must occur before signal gatherers. Order: {call_log}" + ) + + +# --------------------------------------------------------------------------- +# AUTOSKILLIT_FORCE_UPDATE_CHECK override +# --------------------------------------------------------------------------- + + +def test_force_update_check_env_overrides_local_editable( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, +) -> None: + """AUTOSKILLIT_FORCE_UPDATE_CHECK=1 bypasses the LOCAL_EDITABLE early return.""" + info = InstallInfo( + install_type=InstallType.LOCAL_EDITABLE, + commit_id=None, + requested_revision=None, + url=None, + editable_source=Path(tmp_path), + ) + printed, input_calls = _setup_run_checks( + monkeypatch, tmp_path, info=info, binary_signal=True, answer="n" + ) + monkeypatch.setenv("AUTOSKILLIT_FORCE_UPDATE_CHECK", "1") + run_update_checks(home=tmp_path) + # The prompt should have been reached (not early-returned) + assert len(input_calls) == 1 + + +def test_fetch_sends_if_none_match_when_cached_etag(tmp_path: Path) -> None: + import time + + cache_data = { + "https://api.github.com/repos/TalonT-Org/AutoSkillit/releases/latest": { + "body": {"tag_name": "v0.8.0"}, + "etag": '"cached-etag"', + "cached_at": time.time() - 3601, # stale, so will hit network + } + } + (tmp_path / ".autoskillit").mkdir(parents=True, exist_ok=True) + (tmp_path / ".autoskillit" / "github_fetch_cache.json").write_text( + json.dumps(cache_data), encoding="utf-8" + ) + + received_headers: dict = {} + + class CapturingClient: + def __init__(self, **kw): + pass + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def get(self, url, headers=None, **kw): + received_headers.update(headers or {}) + r = MagicMock() + r.status_code = 200 + r.json.return_value = {"tag_name": "v0.9.0"} + r.headers = {} + return r + + with patch("httpx.Client", CapturingClient): + _fetch_with_cache( + "https://api.github.com/repos/TalonT-Org/AutoSkillit/releases/latest", + home=tmp_path, + ) + + assert received_headers.get("If-None-Match") == '"cached-etag"' + + +def test_fetch_304_response_returns_cached_payload(tmp_path: Path) -> None: + import time + + url = "https://api.github.com/repos/TalonT-Org/AutoSkillit/releases/latest" + cache_data = { + url: { + "body": {"tag_name": "v0.8.5"}, + "etag": '"my-etag"', + "cached_at": time.time() - 3601, # stale + } + } + (tmp_path / ".autoskillit").mkdir(parents=True, exist_ok=True) + (tmp_path / ".autoskillit" / "github_fetch_cache.json").write_text( + json.dumps(cache_data), encoding="utf-8" + ) + + mock_client = _make_mock_client(status_code=304) + with patch("httpx.Client", return_value=mock_client): + result = _fetch_with_cache(url, home=tmp_path) + + assert result == {"tag_name": "v0.8.5"} + + +def test_fetch_uses_correct_timeout(tmp_path: Path) -> None: + from autoskillit.cli._update_checks import _HTTP_TIMEOUT + + assert _HTTP_TIMEOUT.connect == 2.0 + assert _HTTP_TIMEOUT.read == 1.0 + assert _HTTP_TIMEOUT.write == 5.0 + assert _HTTP_TIMEOUT.pool == 1.0 + + +def test_fetch_sends_modern_github_api_version_header(tmp_path: Path) -> None: + (tmp_path / ".autoskillit").mkdir(parents=True, exist_ok=True) + + received_headers: dict = {} + + class CapturingClient: + def __init__(self, **kw): + pass + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def get(self, url, headers=None, **kw): + received_headers.update(headers or {}) + r = MagicMock() + r.status_code = 200 + r.json.return_value = {"tag_name": "v0.9.0"} + r.headers = {} + return r + + with patch("httpx.Client", CapturingClient): + _fetch_with_cache( + "https://api.github.com/repos/TalonT-Org/AutoSkillit/releases/latest", + home=tmp_path, + ) + + assert received_headers.get("X-GitHub-Api-Version") == "2022-11-28" + assert received_headers.get("Accept") == "application/vnd.github+json" + + +def test_fetch_sends_user_agent_with_package_version(tmp_path: Path) -> None: + (tmp_path / ".autoskillit").mkdir(parents=True, exist_ok=True) + + received_headers: dict = {} + + class CapturingClient: + def __init__(self, **kw): + pass + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def get(self, url, headers=None, **kw): + received_headers.update(headers or {}) + r = MagicMock() + r.status_code = 200 + r.json.return_value = {} + r.headers = {} + return r + + with patch("httpx.Client", CapturingClient): + _fetch_with_cache( + "https://api.github.com/repos/TalonT-Org/AutoSkillit/releases/latest", + home=tmp_path, + ) + + assert received_headers.get("User-Agent", "").startswith("autoskillit/") + + +def test_fetch_scrubs_authorization_header_from_logged_errors( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + import logging + + monkeypatch.setenv("GITHUB_TOKEN", "super-secret-token-xyz") + (tmp_path / ".autoskillit").mkdir(parents=True, exist_ok=True) + + import httpx as _httpx + + class FailingClient: + def __init__(self, **kw): + pass + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def get(self, url, headers=None, **kw): + raise _httpx.ConnectError("Connection refused [super-secret-token-xyz]") + + with caplog.at_level(logging.DEBUG, logger="autoskillit"): + with patch("httpx.Client", FailingClient): + result = _fetch_with_cache( + "https://api.github.com/repos/TalonT-Org/AutoSkillit/releases/latest", + home=tmp_path, + ) + + assert result is None + # The token must not appear in any log record + for record in caplog.records: + assert "super-secret-token-xyz" not in record.getMessage() + + +def test_fetch_fails_fast_offline(tmp_path: Path) -> None: + import httpx as _httpx + + from autoskillit.cli._update_checks import _fetch_latest_version + + (tmp_path / ".autoskillit").mkdir(parents=True, exist_ok=True) + + class OfflineClient: + def __init__(self, **kw): + pass + + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + def get(self, url, **kw): + raise _httpx.ConnectError("Network unreachable") + + with patch("httpx.Client", OfflineClient): + result = _fetch_latest_version("releases/latest", tmp_path) + + assert result is None diff --git a/tests/cli/test_update_command.py b/tests/cli/test_update_command.py new file mode 100644 index 0000000000..8922295608 --- /dev/null +++ b/tests/cli/test_update_command.py @@ -0,0 +1,251 @@ +"""Tests for cli/_update.py — first-class update command.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from autoskillit.cli._install_info import InstallInfo, InstallType + + +def _make_info( + install_type: InstallType, + revision: str | None = None, + editable_source: Path | None = None, +) -> InstallInfo: + return InstallInfo( + install_type=install_type, + commit_id="abc123" if install_type == InstallType.GIT_VCS else None, + requested_revision=revision, + url=None, + editable_source=editable_source, + ) + + +class FakeTG: + def __enter__(self): + return self + + def __exit__(self, *a): + return False + + +def _setup_run_update( + monkeypatch: pytest.MonkeyPatch, + info: InstallInfo, + tmp_path: Path, + current_version: str = "0.7.77", + new_version: str = "0.9.0", +) -> list[list[str]]: + """Patch run_update_command dependencies, return captured subprocess.run call args.""" + monkeypatch.setattr("autoskillit.cli._update.detect_install", lambda: info) + monkeypatch.setattr("autoskillit.cli._update.terminal_guard", FakeTG) + + run_calls: list[list[str]] = [] + monkeypatch.setattr( + "autoskillit.cli._update.subprocess.run", + lambda cmd, **kw: run_calls.append(list(cmd)), + ) + + import autoskillit as _pkg + + monkeypatch.setattr(_pkg, "__version__", current_version) + + import importlib.metadata + + monkeypatch.setattr(importlib.metadata, "version", lambda _name: new_version) + return run_calls + + +def test_update_subcommand_registered_in_help() -> None: + """autoskillit update --help must exit 0.""" + import subprocess as _sp + import sys + + result = _sp.run( + [sys.executable, "-m", "autoskillit", "update", "--help"], + capture_output=True, + text=True, + ) + assert result.returncode == 0, f"update --help failed: {result.stderr}" + + +@pytest.mark.parametrize( + "revision,expected_cmd_prefix", + [ + ("stable", ["uv", "tool", "upgrade", "autoskillit"]), + ("main", ["uv", "tool", "upgrade", "autoskillit"]), + ("v0.7.75", ["uv", "tool", "upgrade", "autoskillit"]), + ("integration", ["uv", "tool", "install", "--force"]), + ], +) +def test_update_runs_upgrade_command_for_git_vcs_install( + monkeypatch: pytest.MonkeyPatch, + tmp_path: Path, + revision: str, + expected_cmd_prefix: list[str], +) -> None: + from autoskillit.cli._update import run_update_command + + info = _make_info(InstallType.GIT_VCS, revision=revision) + run_calls = _setup_run_update(monkeypatch, info, tmp_path) + run_update_command(home=tmp_path) + assert any(cmd[: len(expected_cmd_prefix)] == expected_cmd_prefix for cmd in run_calls), ( + f"Expected cmd prefix {expected_cmd_prefix} in calls {run_calls}" + ) + + +def test_update_runs_upgrade_command_for_local_editable( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update import run_update_command + + editable_source = tmp_path / "repo" + editable_source.mkdir() + info = _make_info(InstallType.LOCAL_EDITABLE, editable_source=editable_source) + run_calls = _setup_run_update(monkeypatch, info, tmp_path) + run_update_command(home=tmp_path) + assert any(cmd[:4] == ["uv", "pip", "install", "-e"] for cmd in run_calls), ( + f"Expected uv pip install -e in calls {run_calls}" + ) + + +def test_update_runs_autoskillit_install_after_upgrade_command( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update import run_update_command + + info = _make_info(InstallType.GIT_VCS, revision="stable") + run_calls = _setup_run_update(monkeypatch, info, tmp_path) + run_update_command(home=tmp_path) + assert any(cmd[:2] == ["autoskillit", "install"] for cmd in run_calls) + + +def test_update_passes_skip_env_to_subprocess( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update import run_update_command + + info = _make_info(InstallType.GIT_VCS, revision="stable") + monkeypatch.setattr("autoskillit.cli._update.detect_install", lambda: info) + monkeypatch.setattr("autoskillit.cli._update.terminal_guard", FakeTG) + + env_passed: list[dict] = [] + monkeypatch.setattr( + "autoskillit.cli._update.subprocess.run", + lambda cmd, **kw: env_passed.append(kw.get("env", {})), + ) + + import autoskillit as _pkg + + monkeypatch.setattr(_pkg, "__version__", "0.7.77") + + import importlib.metadata + + monkeypatch.setattr(importlib.metadata, "version", lambda _name: "0.9.0") + run_update_command(home=tmp_path) + + for env in env_passed: + assert env.get("AUTOSKILLIT_SKIP_STALE_CHECK") == "1" + assert env.get("AUTOSKILLIT_SKIP_SOURCE_DRIFT_CHECK") == "1" + + +def test_update_verifies_version_advance_and_warns_on_failure( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update import run_update_command + from autoskillit.cli._update_checks import _read_dismiss_state + + info = _make_info(InstallType.GIT_VCS, revision="stable") + monkeypatch.setattr("autoskillit.cli._update.detect_install", lambda: info) + monkeypatch.setattr("autoskillit.cli._update.terminal_guard", FakeTG) + monkeypatch.setattr("autoskillit.cli._update.subprocess.run", lambda *a, **kw: None) + monkeypatch.setattr( + "autoskillit.cli._update_checks._fetch_latest_version", lambda *a, **kw: "0.9.0" + ) + + import autoskillit as _pkg + + monkeypatch.setattr(_pkg, "__version__", "0.7.77") + + # version unchanged after upgrade — simulates a silent failure + import importlib.metadata + + monkeypatch.setattr(importlib.metadata, "version", lambda _name: "0.7.77") + + printed: list[str] = [] + monkeypatch.setattr( + "builtins.print", lambda *args, **kw: printed.append(" ".join(str(a) for a in args)) + ) + run_update_command(home=tmp_path) + combined = " ".join(printed) + assert "still" in combined or "unchanged" in combined or "still 0.7.77" in combined + + # Verify binary_snoozed disk state records the correct attempted_version + state = _read_dismiss_state(tmp_path) + assert "binary_snoozed" in state, ( + f"Expected 'binary_snoozed' key in dismiss state after failed update; got {list(state)}" + ) + snooze = state["binary_snoozed"] + assert isinstance(snooze, dict), f"Expected dict for binary_snoozed; got {type(snooze)}" + assert snooze.get("attempted_version") == "0.9.0", ( + f"Expected attempted_version='0.9.0' (from _fetch_latest_version); " + f"got {snooze.get('attempted_version')!r}" + ) + + +def test_update_clears_dismissal_state_on_success( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update import run_update_command + from autoskillit.cli._update_checks import _read_dismiss_state, _write_dismiss_state + + # Seed dismissal state + (tmp_path / ".autoskillit").mkdir(parents=True, exist_ok=True) + _write_dismiss_state( + tmp_path, + { + "update_prompt": { + "dismissed_at": "2026-01-01T00:00:00+00:00", + "dismissed_version": "0.7.77", + "conditions": ["binary"], + } + }, + ) + + info = _make_info(InstallType.GIT_VCS, revision="stable") + monkeypatch.setattr("autoskillit.cli._update.detect_install", lambda: info) + monkeypatch.setattr("autoskillit.cli._update.terminal_guard", FakeTG) + monkeypatch.setattr("autoskillit.cli._update.subprocess.run", lambda *a, **kw: None) + + import autoskillit as _pkg + + monkeypatch.setattr(_pkg, "__version__", "0.7.77") + + import importlib.metadata + + monkeypatch.setattr(importlib.metadata, "version", lambda _name: "0.9.0") + + monkeypatch.setattr("builtins.print", lambda *a, **kw: None) + run_update_command(home=tmp_path) + state = _read_dismiss_state(tmp_path) + assert "update_prompt" not in state + + +def test_update_reports_actionable_error_on_unknown_install_type( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from autoskillit.cli._update import run_update_command + + info = _make_info(InstallType.UNKNOWN) + monkeypatch.setattr("autoskillit.cli._update.detect_install", lambda: info) + printed: list[str] = [] + monkeypatch.setattr( + "builtins.print", lambda *args, **kw: printed.append(" ".join(str(a) for a in args)) + ) + with pytest.raises(SystemExit) as exc_info: + run_update_command(home=tmp_path) + assert exc_info.value.code == 2 + combined = " ".join(printed) + assert "Unknown install type" in combined or "install.sh" in combined diff --git a/tests/config/test_config.py b/tests/config/test_config.py index a90704417b..aa296e0056 100644 --- a/tests/config/test_config.py +++ b/tests/config/test_config.py @@ -305,17 +305,17 @@ def test_run_skill_retry_config_removed(self): class TestRunSkillConfigExitAfterStopDelay: - def test_default_exit_after_stop_delay_is_120000(self): + def test_default_exit_after_stop_delay_is_2000(self): cfg = AutomationConfig() - assert cfg.run_skill.exit_after_stop_delay_ms == 120000 + assert cfg.run_skill.exit_after_stop_delay_ms == 2000 def test_yaml_loads_exit_after_stop_delay(self, tmp_path): (tmp_path / ".autoskillit").mkdir() (tmp_path / ".autoskillit" / "config.yaml").write_text( - "run_skill:\n exit_after_stop_delay_ms: 60000\n" + "run_skill:\n exit_after_stop_delay_ms: 1500\n" ) cfg = load_config(tmp_path) - assert cfg.run_skill.exit_after_stop_delay_ms == 60000 + assert cfg.run_skill.exit_after_stop_delay_ms == 1500 def test_zero_disables_injection(self, tmp_path): (tmp_path / ".autoskillit").mkdir() @@ -329,7 +329,7 @@ def test_partial_run_skill_config_preserves_default(self, tmp_path): (tmp_path / ".autoskillit").mkdir() (tmp_path / ".autoskillit" / "config.yaml").write_text("run_skill:\n timeout: 1800\n") cfg = load_config(tmp_path) - assert cfg.run_skill.exit_after_stop_delay_ms == 120000 + assert cfg.run_skill.exit_after_stop_delay_ms == 2000 def test_run_skill_config_fields_include_exit_delay(self): names = {f.name for f in dc_fields(RunSkillConfig)} @@ -342,7 +342,8 @@ def test_default_enabled(self): config = AutomationConfig() assert config.quota_guard.enabled is True - assert config.quota_guard.threshold == pytest.approx(90.0) + assert config.quota_guard.short_window_threshold == pytest.approx(85.0) + assert config.quota_guard.long_window_threshold == pytest.approx(98.0) assert config.quota_guard.buffer_seconds == 60 assert config.quota_guard.cache_max_age == 300 @@ -352,14 +353,120 @@ def test_load_quota_guard_from_yaml(self, tmp_path): config_dir = tmp_path / ".autoskillit" config_dir.mkdir() (config_dir / "config.yaml").write_text( - yaml.dump({"quota_guard": {"enabled": True, "threshold": 90.0}}) + yaml.dump( + { + "quota_guard": { + "enabled": True, + "short_window_threshold": 85.0, + "long_window_threshold": 98.0, + } + } + ) ) config = load_config(tmp_path) assert config.quota_guard.enabled is True - assert config.quota_guard.threshold == pytest.approx(90.0) + assert config.quota_guard.short_window_threshold == pytest.approx(85.0) + assert config.quota_guard.long_window_threshold == pytest.approx(98.0) # Unspecified fields keep defaults assert config.quota_guard.buffer_seconds == 60 + def test_short_window_threshold_defaults_to_85(self): + from autoskillit.config.settings import QuotaGuardConfig + + assert QuotaGuardConfig().short_window_threshold == 85.0 + + def test_long_window_threshold_defaults_to_98(self): + from autoskillit.config.settings import QuotaGuardConfig + + assert QuotaGuardConfig().long_window_threshold == 98.0 + + def test_long_window_patterns_default(self): + from autoskillit.config.settings import QuotaGuardConfig + + assert QuotaGuardConfig().long_window_patterns == ["weekly", "sonnet", "opus"] + + def test_threshold_field_removed(self): + import dataclasses + + from autoskillit.config.settings import QuotaGuardConfig + + names = {f.name for f in dataclasses.fields(QuotaGuardConfig)} + assert "threshold" not in names + + def test_quota_guard_yaml_round_trip_per_window(self, tmp_path): + import pytest + + config_dir = tmp_path / ".autoskillit" + config_dir.mkdir() + (config_dir / "config.yaml").write_text( + yaml.dump( + { + "quota_guard": { + "short_window_threshold": 85.0, + "long_window_threshold": 98.0, + "long_window_patterns": ["weekly", "sonnet", "opus"], + } + } + ) + ) + config = load_config(tmp_path) + assert config.quota_guard.short_window_threshold == pytest.approx(85.0) + assert config.quota_guard.long_window_threshold == pytest.approx(98.0) + assert config.quota_guard.long_window_patterns == ["weekly", "sonnet", "opus"] + + def test_quota_guard_config_has_cache_refresh_interval(self): + """QG_C3: QuotaGuardConfig has cache_refresh_interval defaulting to 240.""" + from autoskillit.config.settings import QuotaGuardConfig + + config = QuotaGuardConfig() + assert config.cache_refresh_interval == 240 + + def test_defaults_yaml_has_cache_refresh_interval(self): + """QG_C4: defaults.yaml defines quota_guard.cache_refresh_interval < cache_max_age.""" + from autoskillit.core.paths import pkg_root + + defaults = yaml.safe_load((pkg_root() / "config" / "defaults.yaml").read_text()) + assert "cache_refresh_interval" in defaults["quota_guard"] + interval = defaults["quota_guard"]["cache_refresh_interval"] + max_age = defaults["quota_guard"]["cache_max_age"] + assert interval < max_age, ( + f"cache_refresh_interval ({interval}) must be < cache_max_age ({max_age}); " + "otherwise the loop arrives after the cache has already expired" + ) + + def test_quota_guard_per_window_enabled_defaults_true(self): + """Test 14: QuotaGuardConfig() defaults both per-window flags to True.""" + from autoskillit.config.settings import QuotaGuardConfig + + config = QuotaGuardConfig() + assert config.short_window_enabled is True + assert config.long_window_enabled is True + + def test_quota_guard_per_window_enabled_yaml_round_trip(self, tmp_path): + """Test 15: per-window enabled flags survive a YAML round-trip.""" + config_dir = tmp_path / ".autoskillit" + config_dir.mkdir() + (config_dir / "config.yaml").write_text( + yaml.dump({"quota_guard": {"short_window_enabled": False}}) + ) + config = load_config(tmp_path) + assert config.quota_guard.short_window_enabled is False + assert config.quota_guard.long_window_enabled is True + + def test_defaults_yaml_has_per_window_enabled_keys(self): + """Test 16: defaults.yaml has both per-window enabled keys set to True.""" + from autoskillit.core.paths import pkg_root + + defaults = yaml.safe_load((pkg_root() / "config" / "defaults.yaml").read_text()) + assert defaults["quota_guard"]["short_window_enabled"] is True + assert defaults["quota_guard"]["long_window_enabled"] is True + + def test_quota_guard_env_var_override_short_window_enabled(self, monkeypatch, tmp_path): + """Test 17: AUTOSKILLIT_QUOTA_GUARD__SHORT_WINDOW_ENABLED=false is cast to bool False.""" + monkeypatch.setenv("AUTOSKILLIT_QUOTA_GUARD__SHORT_WINDOW_ENABLED", "false") + config = load_config(tmp_path) + assert config.quota_guard.short_window_enabled is False + class TestLoggingConfig: """LoggingConfig dataclass and YAML loading.""" @@ -708,10 +815,13 @@ def test_branching_config_promotion_target_overridable(self) -> None: def test_branching_config_promotion_target_defaults_match_yaml(self, tmp_path) -> None: """Python default for promotion_target matches defaults.yaml.""" from autoskillit.config import load_config - from autoskillit.config.settings import BranchingConfig + from autoskillit.core.io import load_yaml + from autoskillit.core.paths import pkg_root loaded = load_config(tmp_path / "settings.toml") - assert loaded.branching.promotion_target == BranchingConfig().promotion_target + defaults = load_yaml(pkg_root() / "config" / "defaults.yaml") + expected = defaults["branching"]["promotion_target"] + assert loaded.branching.promotion_target == expected def test_branching_config_promotion_target_env_var_override( self, monkeypatch, tmp_path @@ -727,32 +837,13 @@ def test_branching_config_promotion_target_env_var_override( class TestBuildSubsetsConfigCustomTagsValidation: """CC-F2: _build_subsets_config must raise ValueError for non-dict custom_tags.""" - def test_build_subsets_config_raises_for_non_dict_custom_tags(self): + @pytest.mark.parametrize("bad_value", [["list", "not", "dict"], "oops", 42]) + def test_build_subsets_config_raises_for_non_dict_custom_tags(self, bad_value: object) -> None: """Non-dict custom_tags must raise ValueError, not silently coerce to {}.""" - import pytest - from autoskillit.config.settings import _build_subsets_config with pytest.raises(ValueError, match="custom_tags"): - _build_subsets_config({"custom_tags": ["list", "not", "dict"]}) - - def test_build_subsets_config_raises_for_string_custom_tags(self): - """String custom_tags must raise ValueError.""" - import pytest - - from autoskillit.config.settings import _build_subsets_config - - with pytest.raises(ValueError, match="custom_tags"): - _build_subsets_config({"custom_tags": "oops"}) - - def test_build_subsets_config_raises_for_int_custom_tags(self): - """Integer custom_tags must raise ValueError.""" - import pytest - - from autoskillit.config.settings import _build_subsets_config - - with pytest.raises(ValueError, match="custom_tags"): - _build_subsets_config({"custom_tags": 42}) + _build_subsets_config({"custom_tags": bad_value}) def test_build_subsets_config_dict_custom_tags_accepted(self): """Valid dict custom_tags must not raise.""" @@ -813,7 +904,7 @@ def test_load_config_populates_skills_tiers(self, tmp_path) -> None: cfg = load_config(tmp_path / "settings.toml") assert "open-kitchen" in cfg.skills.tier1 assert "make-plan" in cfg.skills.tier2 - assert "open-pr" in cfg.skills.tier3 + assert "compose-pr" in cfg.skills.tier3 def test_skills_config_exported_from_config_package(self) -> None: """SkillsConfig is importable from autoskillit.config and has expected fields.""" @@ -1043,20 +1134,20 @@ def test_write_config_layer_writes_valid_content(self, tmp_path: Path) -> None: class TestWorkspaceConfig: """WorkspaceConfig section is present in AutomationConfig with correct defaults.""" - def test_workspace_config_exists_on_automation_config(self): + def test_workspace_config_exists_on_automation_config(self, tmp_path): from autoskillit.config import load_config - cfg = load_config() + cfg = load_config(tmp_path / "settings.toml") assert hasattr(cfg, "workspace") - def test_workspace_worktree_root_defaults_to_none(self): + def test_workspace_worktree_root_defaults_to_none(self, tmp_path): from autoskillit.config import load_config - cfg = load_config() + cfg = load_config(tmp_path / "settings.toml") assert cfg.workspace.worktree_root is None - def test_workspace_runs_root_defaults_to_none(self): + def test_workspace_runs_root_defaults_to_none(self, tmp_path): from autoskillit.config import load_config - cfg = load_config() + cfg = load_config(tmp_path / "settings.toml") assert cfg.workspace.runs_root is None diff --git a/tests/config/test_defaults.py b/tests/config/test_defaults.py new file mode 100644 index 0000000000..8f02f2814c --- /dev/null +++ b/tests/config/test_defaults.py @@ -0,0 +1,44 @@ +"""Settings coherence guard tests (1g). + +Validates that natural_exit_grace_seconds and exit_after_stop_delay_ms are +configured coherently so the drain window can always absorb the self-exit delay. +""" + +from __future__ import annotations + +import pytest + +from autoskillit.config import AutomationConfig +from autoskillit.config.settings import RunSkillConfig + + +class TestGraceWindowCoherence: + """natural_exit_grace_seconds must cover exit_after_stop_delay_ms + margin.""" + + def test_natural_exit_grace_covers_exit_after_stop_delay(self) -> None: + """Default settings: grace_s * 1000 >= exit_after_stop_delay_ms + 500.""" + cfg = AutomationConfig() + rs = cfg.run_skill + assert rs.natural_exit_grace_seconds * 1000 >= rs.exit_after_stop_delay_ms + 500, ( + f"natural_exit_grace_seconds={rs.natural_exit_grace_seconds} is too small: " + f"{rs.natural_exit_grace_seconds * 1000} ms < " + f"{rs.exit_after_stop_delay_ms + 500} ms (exit_after_stop_delay_ms + 500). " + "Increase natural_exit_grace_seconds in defaults.yaml." + ) + + def test_settings_validator_rejects_incoherent_grace_window(self) -> None: + """RunSkillConfig raises ValueError when grace window is too small.""" + with pytest.raises(ValueError, match="natural_exit_grace_seconds"): + RunSkillConfig( + natural_exit_grace_seconds=1.0, + exit_after_stop_delay_ms=2000, + ) + + def test_settings_validator_accepts_coherent_config(self) -> None: + """RunSkillConfig with sufficient grace window constructs without error.""" + cfg = RunSkillConfig( + natural_exit_grace_seconds=3.0, + exit_after_stop_delay_ms=2000, + ) + # 3.0 * 1000 = 3000 >= 2000 + 500 = 2500 ✓ + assert cfg.natural_exit_grace_seconds == 3.0 diff --git a/tests/config/test_settings_allowed_labels.py b/tests/config/test_settings_allowed_labels.py index 689a430518..9cf28db5e1 100644 --- a/tests/config/test_settings_allowed_labels.py +++ b/tests/config/test_settings_allowed_labels.py @@ -5,11 +5,6 @@ class TestGitHubConfigAllowedLabelsField: - def test_github_config_allowed_labels_default_is_empty(self): - """GitHubConfig has allowed_labels field defaulting to empty list.""" - cfg = GitHubConfig() - assert cfg.allowed_labels == [] - def test_automation_config_allowed_labels_default_is_empty(self): """AutomationConfig().github.allowed_labels defaults to empty list.""" cfg = AutomationConfig() diff --git a/tests/config/test_workspace_temp_dir_config.py b/tests/config/test_workspace_temp_dir_config.py new file mode 100644 index 0000000000..60289c960e --- /dev/null +++ b/tests/config/test_workspace_temp_dir_config.py @@ -0,0 +1,77 @@ +"""Tests for workspace.temp_dir layered config resolution.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from autoskillit.config import WorkspaceConfig, load_config + + +def test_workspace_config_has_temp_dir_field() -> None: + assert WorkspaceConfig().temp_dir is None + + +def test_temp_dir_layered_priority_project_wins( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + user_home = tmp_path / "home" + user_cfg = user_home / ".autoskillit" + user_cfg.mkdir(parents=True) + (user_cfg / "config.yaml").write_text("workspace:\n temp_dir: /user/x\n") + monkeypatch.setattr("pathlib.Path.home", lambda: user_home) + + project_dir = tmp_path / "project" + project_cfg = project_dir / ".autoskillit" + project_cfg.mkdir(parents=True) + (project_cfg / "config.yaml").write_text("workspace:\n temp_dir: /proj/y\n") + + cfg = load_config(project_dir) + assert cfg.workspace.temp_dir == "/proj/y" + + +def test_temp_dir_layered_priority_user_wins_over_default( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + user_home = tmp_path / "home" + user_cfg = user_home / ".autoskillit" + user_cfg.mkdir(parents=True) + (user_cfg / "config.yaml").write_text("workspace:\n temp_dir: /user/x\n") + monkeypatch.setattr("pathlib.Path.home", lambda: user_home) + + project_dir = tmp_path / "project" + project_dir.mkdir() + cfg = load_config(project_dir) + assert cfg.workspace.temp_dir == "/user/x" + + +def test_temp_dir_env_override_wins(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + project_dir = tmp_path / "project" + project_cfg = project_dir / ".autoskillit" + project_cfg.mkdir(parents=True) + (project_cfg / "config.yaml").write_text("workspace:\n temp_dir: /proj/y\n") + + monkeypatch.setenv("AUTOSKILLIT_WORKSPACE__TEMP_DIR", "/env/z") + cfg = load_config(project_dir) + assert cfg.workspace.temp_dir == "/env/z" + + +def test_default_yaml_contains_temp_dir_key() -> None: + import yaml + + from autoskillit.core import pkg_root + + defaults_path = pkg_root() / "config" / "defaults.yaml" + data = yaml.safe_load(defaults_path.read_text()) + assert data["workspace"]["temp_dir"] == ".autoskillit/temp" + + +def test_temp_dir_empty_string_normalized_to_none( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("AUTOSKILLIT_WORKSPACE__TEMP_DIR", "") + project_dir = tmp_path / "project" + project_dir.mkdir() + cfg = load_config(project_dir) + assert cfg.workspace.temp_dir is None diff --git a/tests/conftest.py b/tests/conftest.py index 2edf3e0672..df37dff378 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -255,5 +255,11 @@ def tool_ctx(monkeypatch, tmp_path): ctx = make_context(AutomationConfig(), runner=mock_runner, plugin_dir=str(tmp_path)) ctx.gate = DefaultGateState(enabled=True) ctx.config.linux_tracing.log_dir = str(tmp_path / "session_logs") + ctx.config.linux_tracing.tmpfs_path = str(tmp_path / "shm") + # Anchor temp_dir to tmp_path so server tools that read from ctx.temp_dir + # (e.g. _apply_triage_gate's staleness cache) write under the per-test + # tmp directory rather than the cwd captured at fixture-init time. + ctx.temp_dir = tmp_path / ".autoskillit" / "temp" monkeypatch.setattr(_state, "_ctx", ctx) + monkeypatch.setattr(_state, "_startup_ready", None) return ctx diff --git a/tests/contracts/conftest.py b/tests/contracts/conftest.py new file mode 100644 index 0000000000..a20fc8341c --- /dev/null +++ b/tests/contracts/conftest.py @@ -0,0 +1,18 @@ +"""Shared constants for contract tests — avoids cross-file duplication.""" + +REFUSAL_SIGNALS = [ + "disable-model-invocation", + "cannot be used", + "refused", + "Skill tool returns", + "Skill tool fails", +] + +ACTION_SIGNALS = [ + "do not", + "do NOT", + "discard", + "skip", + "omit", + "proceed without", +] diff --git a/tests/contracts/test_activate_deps_completeness.py b/tests/contracts/test_activate_deps_completeness.py new file mode 100644 index 0000000000..3e42432c9e --- /dev/null +++ b/tests/contracts/test_activate_deps_completeness.py @@ -0,0 +1,89 @@ +"""Contracts: SKILL.md activate_deps must cover invoked Skill tool calls. + +Catches the four known cases (rectify, open-integration-pr, elaborate-phase, +make-arch-diag) and prevents future regressions where a SKILL.md body invokes +``/autoskillit:`` via the Skill tool without declaring the corresponding +``activate_deps`` entry. +""" + +from __future__ import annotations + +import re + +import pytest + +from autoskillit.workspace.session_skills import ( + SkillsDirectoryProvider, + compute_skill_closure, +) +from autoskillit.workspace.skills import bundled_skills_extended_dir + +_INVOCATION_PATTERNS = ( + re.compile( + r"(?i)\bLOAD(?:ED)?\b[^\n]{0,120}/autoskillit:([a-z][\w-]+)[^\n]{0,120}\bSkill tool\b" + ), + re.compile(r"(?i)\bSkill tool\b[^\n]{0,120}/autoskillit:([a-z][\w-]+)"), +) + +_FM_PATTERN = re.compile(r"^---\n(.*?)\n?---\n?(.*)", re.DOTALL) + + +def _strip_frontmatter(content: str) -> str: + m = _FM_PATTERN.match(content) + return m.group(2) if m else content + + +@pytest.fixture(scope="module") +def provider() -> SkillsDirectoryProvider: + return SkillsDirectoryProvider() + + +def test_make_arch_diag_declares_arch_lens_dep(provider: SkillsDirectoryProvider) -> None: + closure = compute_skill_closure("make-arch-diag", provider) + assert "make-arch-diag" in closure # contract: target is always included in its own closure + assert any(name.startswith("arch-lens-") for name in closure), closure + + +def test_elaborate_phase_declares_dry_walkthrough_dep(provider: SkillsDirectoryProvider) -> None: + closure = compute_skill_closure("elaborate-phase", provider) + assert "dry-walkthrough" in closure, closure + + +def test_rectify_declares_arch_lens_dep(provider: SkillsDirectoryProvider) -> None: + closure = compute_skill_closure("rectify", provider) + assert any(name.startswith("arch-lens-") for name in closure), closure + + +def test_open_integration_pr_declares_arch_lens_dep(provider: SkillsDirectoryProvider) -> None: + closure = compute_skill_closure("open-integration-pr", provider) + assert any(name.startswith("arch-lens-") for name in closure), closure + + +def test_all_skills_skill_tool_invocations_match_activate_deps( + provider: SkillsDirectoryProvider, +) -> None: + """Every Skill-tool invocation must resolve to a name in the invoker's closure. + + Captured names that do not resolve to a real skill (template placeholders such + as ``arch-lens-*`` or ``exp-lens-{slug}``) are silently skipped. + """ + extended_dir = bundled_skills_extended_dir() + failures: list[str] = [] + for skill_md in sorted(extended_dir.glob("*/SKILL.md")): + skill_name = skill_md.parent.name + body = _strip_frontmatter(skill_md.read_text()) + invoked: set[str] = set() + for pattern in _INVOCATION_PATTERNS: + for match in pattern.finditer(body): + invoked.add(match.group(1)) + real_invoked = {n for n in invoked if provider.resolver.resolve(n) is not None} + if not real_invoked: + continue + closure = compute_skill_closure(skill_name, provider) + for name in sorted(real_invoked): + if name not in closure: + failures.append( + f"{skill_md.parent.name}/SKILL.md: invokes /autoskillit:{name} " + f"but it is not in compute_skill_closure({skill_name!r})" + ) + assert not failures, "Undeclared Skill-tool invocations:\n" + "\n".join(failures) diff --git a/tests/contracts/test_claude_code_interface_contracts.py b/tests/contracts/test_claude_code_interface_contracts.py index bb72a3dac1..7429470f31 100644 --- a/tests/contracts/test_claude_code_interface_contracts.py +++ b/tests/contracts/test_claude_code_interface_contracts.py @@ -330,7 +330,7 @@ def test_multi_channel_uniqueness_contract(self, tmp_path: Path, cook_session: b SkillsDirectoryProvider, ) from autoskillit.workspace.skills import ( - SkillResolver, + DefaultSkillResolver, detect_project_local_overrides, ) @@ -345,7 +345,7 @@ def test_multi_channel_uniqueness_contract(self, tmp_path: Path, cook_session: b ) # Channel 1: BUNDLED skill names (served by --plugin-dir) - resolver = SkillResolver() + resolver = DefaultSkillResolver() channel_1 = {s.name for s in resolver.list_all() if s.source == SkillSource.BUNDLED} # Channel 2: skills written to ephemeral dir diff --git a/tests/contracts/test_collapse_issues_contracts.py b/tests/contracts/test_collapse_issues_contracts.py index 21faf6fbb2..ef0e8924cc 100644 --- a/tests/contracts/test_collapse_issues_contracts.py +++ b/tests/contracts/test_collapse_issues_contracts.py @@ -155,3 +155,40 @@ def test_collapse_issues_no_angle_bracket_body_placeholder(): "collapse-issues must not use angle-bracket placeholder syntax for " "body-copy instructions — use explicit imperative language instead" ) + + +def test_collapse_issues_gh_issue_create_uses_body_file(): + """collapse-issues gh issue create must use --body-file, not inline --body.""" + text = skill_text() + create_pos = text.find("gh issue create") + assert create_pos != -1, "Sanity: 'gh issue create' not found in collapse-issues" + create_context = text[create_pos : create_pos + 300] + assert "--body-file" in create_context, ( + "collapse-issues 'gh issue create' must use --body-file for the combined body, " + "not inline --body — the combined body is large verbatim multi-issue content" + ) + + +def test_collapse_issues_body_file_uses_autoskillit_temp(): + """collapse-issues must write combined body to AUTOSKILLIT_TEMP/collapse-issues/.""" + text = skill_text() + assert "AUTOSKILLIT_TEMP" in text, ( + "collapse-issues must write combined body to {{AUTOSKILLIT_TEMP}}/collapse-issues/ " + "before calling gh issue create --body-file" + ) + + +def test_collapse_issues_never_inline_body_for_create(): + """collapse-issues CRITICAL CONSTRAINTS must prohibit inline --body for gh issue create.""" + text = skill_text() + never_pos = text.find("**NEVER:**") + assert never_pos != -1, "Sanity: '**NEVER:**' block not found" + always_pos = text.find("**ALWAYS:**", never_pos) + never_block = ( + text[never_pos:always_pos] if always_pos != -1 else text[never_pos : never_pos + 800] + ) + lower = never_block.lower() + assert "--body" in never_block and "inline" in lower, ( + "collapse-issues NEVER block must prohibit inline '--body' " + "for combined-body issue creation" + ) diff --git a/tests/contracts/test_config_field_coverage.py b/tests/contracts/test_config_field_coverage.py new file mode 100644 index 0000000000..87adc93255 --- /dev/null +++ b/tests/contracts/test_config_field_coverage.py @@ -0,0 +1,91 @@ +"""REQ-CONFIG-001: every sub-config dataclass field must be referenced in from_dynaconf. + +Finding 9.1 — gate that prevents silent omissions when new fields are added to any +*Config dataclass in settings.py without a corresponding val(...) line in +AutomationConfig.from_dynaconf (or in a _build_* helper directly called from it). +""" + +import ast +import dataclasses +from pathlib import Path + +import pytest + +import autoskillit.config.settings as settings_mod +from autoskillit.config.settings import AutomationConfig + +_SUBCONFIG_DATACLASSES = [ + cls + for cls in vars(settings_mod).values() + if isinstance(cls, type) and dataclasses.is_dataclass(cls) and cls is not AutomationConfig +] + + +def _collect_referenced_names(tree: ast.Module) -> set[str]: + """Collect all string constants and keyword argument names from from_dynaconf + and any _build_* module-level helper functions it calls directly. + + Rationale: some sub-configs (e.g. SubsetsConfig, PacksConfig) are built by + dedicated _build_* helpers that contain the actual val(...) / .get(...) calls. + These helpers are called directly from from_dynaconf and are part of the same + construction pipeline — their field references are equally authoritative. + """ + # Collect all module-level function definitions by name + top_level_fns: dict[str, ast.FunctionDef] = {} + for node in ast.walk(tree): + if isinstance(node, ast.FunctionDef): + top_level_fns[node.name] = node + + fn: ast.FunctionDef | None = top_level_fns.get("from_dynaconf") + assert fn is not None, "from_dynaconf must exist" + + # Collect _build_* function names called from from_dynaconf + helper_names: set[str] = set() + for node in ast.walk(fn): + if isinstance(node, ast.Call): + func = node.func + name = ( + func.id + if isinstance(func, ast.Name) + else func.attr + if isinstance(func, ast.Attribute) + else None + ) + if name and name.startswith("_build_"): + helper_names.add(name) + + # Walk from_dynaconf + all called _build_* helpers + nodes_to_walk: list[ast.AST] = [fn] + for helper_name in helper_names: + helper_fn = top_level_fns.get(helper_name) + if helper_fn is not None: + nodes_to_walk.append(helper_fn) + + referenced: set[str] = set() + for root in nodes_to_walk: + for node in ast.walk(root): + if isinstance(node, ast.Constant) and isinstance(node.value, str): + referenced.add(node.value) + if isinstance(node, ast.keyword) and node.arg: + referenced.add(node.arg) + return referenced + + +@pytest.mark.parametrize("dc", _SUBCONFIG_DATACLASSES, ids=lambda c: c.__name__) +def test_every_subconfig_field_referenced_in_from_dynaconf(dc: type) -> None: + """REQ-CONFIG-001: every dataclass field declared in any *Config + dataclass in settings.py must appear at least once as a string + constant or kwarg name inside AutomationConfig.from_dynaconf (or in + a _build_* helper function directly called from it). + Catches silent omissions when a new field is added without a + corresponding val(...) line.""" + src = Path(settings_mod.__file__).read_text() + tree = ast.parse(src) + + referenced = _collect_referenced_names(tree) + + missing = [f.name for f in dataclasses.fields(dc) if f.name not in referenced] + assert not missing, ( + f"{dc.__name__} fields missing from from_dynaconf/_build_* helpers: {missing}. " + f"Add an explicit val(...) line for each." + ) diff --git a/tests/contracts/test_enrich_issues_contracts.py b/tests/contracts/test_enrich_issues_contracts.py new file mode 100644 index 0000000000..e3282fa820 --- /dev/null +++ b/tests/contracts/test_enrich_issues_contracts.py @@ -0,0 +1,35 @@ +"""Contract tests for the enrich-issues skill SKILL.md.""" + +from __future__ import annotations + +from pathlib import Path + +SKILL_DIR = Path(__file__).parents[2] / "src/autoskillit/skills_extended/enrich-issues" +SKILL_MD = SKILL_DIR / "SKILL.md" + + +def test_enrich_issues_skill_exists(): + assert SKILL_MD.exists(), f"SKILL.md not found at {SKILL_MD}" + + +def test_enrich_issues_gh_issue_edit_uses_body_file(): + """enrich-issues gh issue edit must use --body-file, not inline --body shell substitution.""" + text = SKILL_MD.read_text() + # Find the Apply or Preview step (Step 5e) where the mutation happens + apply_pos = text.find("5e. Apply or Preview") + assert apply_pos != -1, "Sanity: 'Apply or Preview' section not found in enrich-issues" + apply_section = text[apply_pos : apply_pos + 800] + assert "gh issue edit" in apply_section, "Sanity: 'gh issue edit' not found in Step 5e" + assert "--body-file" in apply_section, ( + "enrich-issues 'gh issue edit' must use --body-file to prevent shell-substitution " + "truncation and LLM body recomposition" + ) + + +def test_enrich_issues_body_file_uses_autoskillit_temp(): + """enrich-issues must write edit body to AUTOSKILLIT_TEMP/enrich-issues/.""" + text = SKILL_MD.read_text() + assert "AUTOSKILLIT_TEMP" in text, ( + "enrich-issues must write issue body to {{AUTOSKILLIT_TEMP}}/enrich-issues/ " + "before calling gh issue edit --body-file" + ) diff --git a/tests/contracts/test_generate_report_contracts.py b/tests/contracts/test_generate_report_contracts.py new file mode 100644 index 0000000000..3bdc779000 --- /dev/null +++ b/tests/contracts/test_generate_report_contracts.py @@ -0,0 +1,159 @@ +"""Contract tests for generate-report SKILL.md — data provenance lifecycle.""" + +from pathlib import Path + +SKILL_PATH = ( + Path(__file__).resolve().parent.parent.parent + / "src" + / "autoskillit" + / "skills_extended" + / "generate-report" + / "SKILL.md" +) + + +def test_data_scope_statement_required() -> None: + text = SKILL_PATH.read_text() + assert "Data Scope Statement" in text or "data scope statement" in text.lower() + + +def test_data_scope_in_executive_summary() -> None: + text = SKILL_PATH.read_text() + assert "Executive Summary" in text + + +def test_metrics_provenance_check() -> None: + text = SKILL_PATH.read_text() + lower = text.lower() + assert "provenance" in lower + + +def test_gate_enforcement_no_substitution() -> None: + text = SKILL_PATH.read_text() + lower = text.lower() + assert "substitut" in lower + + +def test_gate_enforcement_fail_state() -> None: + text = SKILL_PATH.read_text() + lower = text.lower() + assert "fail" in lower and "gate" in lower + + +def test_no_rust_specific_package_manager() -> None: + """Environment section must not reference cargo tree (Rust-specific).""" + text = SKILL_PATH.read_text() + assert "cargo tree" not in text, ( + "generate-report/SKILL.md references 'cargo tree' (Rust-specific). " + "Use language-agnostic package manager examples." + ) + + +def test_domain_adaptive_ordering_guidance() -> None: + """SKILL.md must include guidance on domain-adaptive section ordering.""" + text = SKILL_PATH.read_text() + lower = text.lower() + assert "biology" in lower, ( + "generate-report/SKILL.md has no domain-adaptive ordering guidance. " + "Add notes on biology/non-engineering section ordering conventions." + ) + assert "domain-adaptive" in lower, ( + "generate-report/SKILL.md must mention 'domain-adaptive' section ordering " + "to verify the guidance actually covers non-engineering conventions." + ) + + +def test_data_availability_section_supported() -> None: + """SKILL.md must include an optional Data Availability section in the template.""" + text = SKILL_PATH.read_text() + assert "Data Availability" in text, ( + "generate-report/SKILL.md template is missing an optional 'Data Availability' " + "section. Required by biology and social science journals." + ) + + +def test_recommendations_or_discussion_framing() -> None: + """SKILL.md must allow 'Discussion and Future Directions' as an alternative + to 'Recommendations' for non-engineering domains.""" + text = SKILL_PATH.read_text() + assert "Discussion and Future Directions" in text, ( + "generate-report/SKILL.md does not offer 'Discussion and Future Directions' " + "as an alternative framing for the Recommendations section." + ) + + +def test_generate_report_step25_no_host_venv() -> None: + """Step 2.5 must not create a .plot-venv on the host filesystem.""" + text = SKILL_PATH.read_text() + assert "### Step 2.5" in text, ( + "generate-report/SKILL.md is missing '### Step 2.5' section header" + ) + assert "### Step 3" in text, "generate-report/SKILL.md is missing '### Step 3' section header" + step25_section = text.split("### Step 2.5")[1].split("### Step 3")[0] + assert ".plot-venv" not in step25_section, ( + "generate-report/SKILL.md Step 2.5 must not create a .plot-venv on the host — " + "all package installation must happen inside the Docker container" + ) + + +def test_generate_report_step25_uses_docker_run() -> None: + """Step 2.5 must use docker run to execute visualization scripts.""" + text = SKILL_PATH.read_text() + assert "### Step 2.5" in text, ( + "generate-report/SKILL.md is missing '### Step 2.5' section header" + ) + assert "### Step 3" in text, "generate-report/SKILL.md is missing '### Step 3' section header" + step25_section = text.split("### Step 2.5")[1].split("### Step 3")[0] + assert "docker run" in step25_section.lower(), ( + "generate-report/SKILL.md Step 2.5 must reference 'docker run' for executing " + "visualization scripts inside the experiment container" + ) + + +def test_dockerfile_template_asset_exists() -> None: + """assets/research/Dockerfile.template must exist.""" + asset_path = ( + Path(__file__).resolve().parent.parent.parent + / "src" + / "autoskillit" + / "assets" + / "research" + / "Dockerfile.template" + ) + assert asset_path.exists(), ( + "src/autoskillit/assets/research/Dockerfile.template must exist — " + "this is the canonical Docker template for research worktrees" + ) + + +def test_dockerfile_template_uses_micromamba_base() -> None: + """Dockerfile.template must use mambaorg/micromamba base image.""" + asset_path = ( + Path(__file__).resolve().parent.parent.parent + / "src" + / "autoskillit" + / "assets" + / "research" + / "Dockerfile.template" + ) + content = asset_path.read_text() + assert "mambaorg/micromamba" in content, ( + "assets/research/Dockerfile.template must use mambaorg/micromamba as the base image" + ) + + +def test_dockerfile_template_wires_bash_env() -> None: + """Dockerfile.template must set BASH_ENV to wire micromamba activation into every shell.""" + asset_path = ( + Path(__file__).resolve().parent.parent.parent + / "src" + / "autoskillit" + / "assets" + / "research" + / "Dockerfile.template" + ) + content = asset_path.read_text() + assert "BASH_ENV" in content, ( + "assets/research/Dockerfile.template must set BASH_ENV to wire micromamba " + "activation into every shell context (including non-interactive)" + ) diff --git a/tests/contracts/test_implement_experiment_contracts.py b/tests/contracts/test_implement_experiment_contracts.py new file mode 100644 index 0000000000..5f2fe2b15c --- /dev/null +++ b/tests/contracts/test_implement_experiment_contracts.py @@ -0,0 +1,116 @@ +"""Contract tests for implement-experiment SKILL.md — test infrastructure requirements.""" + +from pathlib import Path + +SKILL_PATH = ( + Path(__file__).resolve().parent.parent.parent + / "src" + / "autoskillit" + / "skills_extended" + / "implement-experiment" + / "SKILL.md" +) + + +def test_implement_experiment_always_includes_test_creation() -> None: + """implement-experiment ALWAYS list must include a directive to write test files.""" + text = SKILL_PATH.read_text() + always_section = text.split("**ALWAYS:**")[1].split("##")[0] if "**ALWAYS:**" in text else text + assert "tests/test_" in always_section, ( + "implement-experiment/SKILL.md ALWAYS list must direct the agent to write " + "tests/test_{name}.py files alongside experiment scripts" + ) + + +def test_implement_experiment_step4_mentions_test_files() -> None: + """implement-experiment Step 4 must mention creating tests/test_ files.""" + text = SKILL_PATH.read_text() + step4_section = ( + text.split("### Step 4")[1].split("### Step 5")[0] + if "### Step 4" in text and "### Step 5" in text + else text + ) + assert "tests/test_" in step4_section, ( + "implement-experiment/SKILL.md Step 4 must reference creating tests/test_{name}.py " + "files alongside each experiment script" + ) + + +def test_implement_experiment_allows_pytest_collect_only() -> None: + """implement-experiment must allow running pytest --collect-only as a verification step.""" + text = SKILL_PATH.read_text() + assert "collect-only" in text or "collect_only" in text, ( + "implement-experiment/SKILL.md must include 'pytest --collect-only' as a " + "test discovery verification step (distinct from running the full test suite)" + ) + + +def test_implement_experiment_step3_references_docker_build() -> None: + """Step 3 must instruct the agent to build a Docker image.""" + text = SKILL_PATH.read_text() + step3_section = ( + text.split("### Step 3")[1].split("### Step 4")[0] + if "### Step 3" in text and "### Step 4" in text + else text + ) + assert "docker build" in step3_section.lower(), ( + "implement-experiment/SKILL.md Step 3 must reference 'docker build' — " + "Docker is the primary isolation mechanism for research execution" + ) + + +def test_implement_experiment_step3_references_dockerfile() -> None: + """Step 3 must instruct the agent to write a Dockerfile.""" + text = SKILL_PATH.read_text() + step3_section = ( + text.split("### Step 3")[1].split("### Step 4")[0] + if "### Step 3" in text and "### Step 4" in text + else text + ) + assert "Dockerfile" in step3_section, ( + "implement-experiment/SKILL.md Step 3 must reference writing a Dockerfile " + "so the container image is built from the experiment's environment.yml" + ) + + +def test_implement_experiment_step3_references_taskfile() -> None: + """Step 3 must instruct the agent to write a Taskfile.yml with build-env task.""" + text = SKILL_PATH.read_text() + step3_section = ( + text.split("### Step 3")[1].split("### Step 4")[0] + if "### Step 3" in text and "### Step 4" in text + else text + ) + assert "Taskfile.yml" in step3_section or "Taskfile" in step3_section, ( + "implement-experiment/SKILL.md Step 3 must reference writing a Taskfile.yml " + "with standardized build-env / run-experiment / test tasks" + ) + + +def test_implement_experiment_step6_conditional_precommit() -> None: + """Step 6 pre-commit check must be conditional on .pre-commit-config.yaml existence.""" + text = SKILL_PATH.read_text() + step6_section = ( + text.split("### Step 6")[1].split("### Step 7")[0] + if "### Step 6" in text and "### Step 7" in text + else text + ) + assert ".pre-commit-config.yaml" in step6_section, ( + "implement-experiment/SKILL.md Step 6 must gate pre-commit on the existence " + "of .pre-commit-config.yaml — research worktrees are not software projects" + ) + + +def test_implement_experiment_subagent_b_not_software_specific() -> None: + """Subagent B must not use software-project-specific language.""" + text = SKILL_PATH.read_text() + # Subagent B section is between "**Subagent B" and "**Additional" + if "**Subagent B" in text and "**Additional" in text: + subagent_b_section = text.split("**Subagent B")[1].split("**Additional")[0] + else: + subagent_b_section = text + # The old text had "build system, test framework, benchmark infrastructure" + assert "build system" not in subagent_b_section, ( + "implement-experiment/SKILL.md Subagent B must not reference 'build system' — " + "this is software-project language inappropriate for research experiments" + ) diff --git a/tests/contracts/test_instruction_surface.py b/tests/contracts/test_instruction_surface.py index 47b09c9077..602f3bf5d6 100644 --- a/tests/contracts/test_instruction_surface.py +++ b/tests/contracts/test_instruction_surface.py @@ -353,6 +353,28 @@ def test_workspace_clone_module_has_source_isolation(self): "autoskillit.workspace.clone module docstring must contain 'SOURCE ISOLATION'" ) + def test_git_mutating_recipes_have_clone_step(self): + """Recipes using MCP git-mutation tools must use clone_repo.""" + from autoskillit.recipe.io import list_recipes, load_recipe + + GIT_MUTATION_TOOLS = {"create_unique_branch", "push_to_remote"} + workflows = list_recipes(Path("/nonexistent")) + bundled = [w for w in workflows.items if w.source.value == "builtin"] + for wf_info in bundled: + wf = load_recipe(wf_info.path) + uses_mutation_tool = any(step.tool in GIT_MUTATION_TOOLS for step in wf.steps.values()) + if not uses_mutation_tool: + continue + has_clone = any( + step.tool == "clone_repo" or (step.python and "clone_repo" in step.python) + for step in wf.steps.values() + ) + assert has_clone, ( + f"{wf_info.name} uses MCP git-mutation tools " + f"({GIT_MUTATION_TOOLS & {s.tool for s in wf.steps.values()}}) " + f"but never calls clone_repo — workspace isolation is missing." + ) + class TestSousChefMergePhaseContract: """sous-chef/SKILL.md must carry a MERGE PHASE mandatory section.""" @@ -411,25 +433,6 @@ def test_sous_chef_routes_conflict_to_on_failure(self): ) -def test_open_pr_skill_does_not_contain_git_push(): - """The open-pr SKILL.md must not contain 'git push -u origin' as a workflow step. - The recipe manages all push operations via push_to_remote. The skill is a pure - PR creation operation.""" - import re - - from autoskillit.core.paths import pkg_root - - skill_path = pkg_root() / "skills_extended" / "open-pr" / "SKILL.md" - content = skill_path.read_text() - # Match lines that start with a step number and contain 'git push -u origin' - push_step_pattern = re.compile(r"^\s*\d+\.\s.*git push\s+-u origin", re.MULTILINE) - matches = push_step_pattern.findall(content) - assert not matches, ( - "open-pr SKILL.md must not contain 'git push -u origin' as a workflow step. " - "The recipe's push_to_remote step manages publishing the branch." - ) - - class TestPathArgSkillsContract: """Path-argument skills must document path-detection parsing in their SKILL.md.""" @@ -473,6 +476,99 @@ def test_resolve_failures_mentions_dirty_tree(self): ) +class TestResolveFailuresCITruthContract: + """resolve-failures SKILL.md must document the CI-truth rule.""" + + def test_resolve_failures_rejects_local_pass_when_ci_failing(self): + skill_md = _project_root() / "src/autoskillit/skills_extended/resolve-failures/SKILL.md" + content = skill_md.read_text().lower() + # Must mention that CI is the source of truth and local pass != resolution + assert "ci is the source of truth" in content, ( + "resolve-failures SKILL.md must state CI is the source of truth" + ) + + def test_resolve_failures_documents_flaky_test_investigation(self): + skill_md = _project_root() / "src/autoskillit/skills_extended/resolve-failures/SKILL.md" + content = skill_md.read_text().lower() + # Must describe what to do when tests pass locally but CI failed + assert "passes locally" in content or "flak" in content, ( + "resolve-failures SKILL.md must document the flaky test / " + "local-pass != resolution case" + ) + + def test_resolve_failures_parses_ci_context_args(self): + skill_md = _project_root() / "src/autoskillit/skills_extended/resolve-failures/SKILL.md" + content = skill_md.read_text() + # Must document parsing of ci_conclusion and diagnosis_path + assert ( + "ci_conclusion" in content or "ci_failed" in content or "diagnosis_path" in content + ), ( + "resolve-failures SKILL.md must document parsing of CI context arguments " + "passed by the resolve_ci recipe step" + ) + + +class TestContextLimitBehaviorContract: + """File-writing skills in pipeline recipes must document Context Limit Behavior.""" + + _SKILLS_ROOT = ( + Path(__file__).resolve().parent.parent.parent / "src" / "autoskillit" / "skills_extended" + ) + + def test_resolve_failures_has_context_limit_section(self): + """resolve-failures SKILL.md must contain '## Context Limit Behavior'.""" + skill_md = self._SKILLS_ROOT / "resolve-failures" / "SKILL.md" + content = skill_md.read_text() + assert "## Context Limit Behavior" in content, ( + "resolve-failures/SKILL.md must contain a '## Context Limit Behavior' section. " + "This skill commits during execution; context exhaustion can leave edits " + "uncommitted on disk. The section must instruct the skill to verify tree " + "cleanliness before emitting structured output." + ) + + def test_pipeline_file_writing_skills_have_context_limit_section(self): + """Every write_behavior=always skill used in a step with on_context_limit must + document Context Limit Behavior in its SKILL.md. + + Checks all bundled recipe steps: if a step has on_context_limit AND invokes a + skill with write_behavior=always, that skill's SKILL.md must contain the section. + """ + from autoskillit.core import SKILL_TOOLS + from autoskillit.recipe.contracts import load_bundled_manifest, resolve_skill_name + from autoskillit.recipe.io import builtin_recipes_dir, load_recipe + + manifest = load_bundled_manifest() + assert manifest is not None, "load_bundled_manifest() returned None" + skills = manifest.get("skills", {}) + + missing: list[str] = [] + for yaml_path in sorted(builtin_recipes_dir().glob("*.yaml")): + recipe = load_recipe(yaml_path) + for _step_name, step in recipe.steps.items(): + if step.tool not in SKILL_TOOLS: + continue + if step.on_context_limit is None: + continue + skill_cmd = step.with_args.get("skill_command", "") + skill = resolve_skill_name(skill_cmd) + if not skill: + continue + skill_data = skills.get(skill, {}) + if skill_data.get("write_behavior") != "always": + continue + skill_md_path = self._SKILLS_ROOT / skill / "SKILL.md" + if not skill_md_path.exists(): + continue + content = skill_md_path.read_text() + if "## Context Limit Behavior" not in content: + missing.append(f"{skill} (used in {yaml_path.name})") + + assert not missing, ( + "These write_behavior=always skills lack a '## Context Limit Behavior' section " + f"in their SKILL.md: {', '.join(sorted(set(missing)))}" + ) + + def test_claude_md_documents_all_source_modules() -> None: """Every .py file in src/autoskillit/ must appear by name in CLAUDE.md. diff --git a/tests/contracts/test_mermaid_palette_contracts.py b/tests/contracts/test_mermaid_palette_contracts.py new file mode 100644 index 0000000000..5fe2e238e2 --- /dev/null +++ b/tests/contracts/test_mermaid_palette_contracts.py @@ -0,0 +1,83 @@ +""" +Contract: any SKILL.md that generates mermaid diagrams must either embed the canonical +9-class palette or explicitly mandate loading the mermaid skill before drawing. +Parametrized over all qualifying skills — self-updating as skills are added. +""" + +import re +from pathlib import Path + +import pytest + +_SKILLS_DIR = Path(__file__).parents[2] / "src/autoskillit/skills_extended" + +# Signals that a skill generates mermaid diagrams +_MERMAID_GENERATOR_PATTERN = re.compile( + r"```mermaid|mermaid block|diagram_path|" + r"mermaid diagram|generate.{0,30}diagram|create.{0,30}diagram", + re.IGNORECASE, +) + +# Canonical class names — at least 7 of 9 must appear +_CANONICAL_CLASSES = frozenset( + { + "cli", + "stateNode", + "handler", + "phase", + "output", + "integration", + "newComponent", + "detector", + "gap", + } +) + +# Alternative: explicit mandate to load mermaid skill before drawing +_MERMAID_LOAD_PATTERN = re.compile( + r"LOAD.{0,50}/autoskillit:mermaid|" + r"load.{0,50}mermaid.{0,30}Skill tool|" + r"Using ONLY classDef styles from the mermaid skill", + re.IGNORECASE, +) + + +def _find_diagram_generating_skills() -> list[tuple[str, Path]]: + results = [] + for skill_dir in sorted(_SKILLS_DIR.iterdir()): + skill_md = skill_dir / "SKILL.md" + if not skill_md.exists(): + continue + text = skill_md.read_text(encoding="utf-8") + if _MERMAID_GENERATOR_PATTERN.search(text): + results.append((skill_dir.name, skill_md)) + return results + + +_DIAGRAM_SKILLS = _find_diagram_generating_skills() + + +@pytest.mark.parametrize( + "skill_name,skill_md", + _DIAGRAM_SKILLS, + ids=[s[0] for s in _DIAGRAM_SKILLS], +) +def test_diagram_generating_skill_has_palette_or_mermaid_load(skill_name: str, skill_md: Path): + """ + Any skill that generates mermaid diagrams must either embed at least 7 of the 9 + canonical class names OR mandate loading the mermaid skill before drawing. + Prevents invented class names and unstyled gray diagrams. + """ + text = skill_md.read_text(encoding="utf-8") + found = { + name for name in _CANONICAL_CLASSES if re.search(rf"classDef\s+{re.escape(name)}\b", text) + } + has_palette = len(found) >= 7 + has_mermaid_load = bool(_MERMAID_LOAD_PATTERN.search(text)) + assert has_palette or has_mermaid_load, ( + f"{skill_name}/SKILL.md generates mermaid diagrams but neither embeds the " + f"canonical palette (found only {sorted(found)} of {len(_CANONICAL_CLASSES)}) " + f"nor mandates loading the mermaid skill before drawing. " + f"Add the 9-classDef block from mermaid/SKILL.md, or add to the checklist: " + f"'Using ONLY classDef styles from the mermaid skill (no invented colors)'." + ) diff --git a/tests/contracts/test_open_pr_contracts.py b/tests/contracts/test_open_pr_contracts.py deleted file mode 100644 index 12805aaef2..0000000000 --- a/tests/contracts/test_open_pr_contracts.py +++ /dev/null @@ -1,96 +0,0 @@ -"""Contract tests for open-pr skill — requirement traceability.""" - -import re -from pathlib import Path - -import pytest - -SKILLS_DIR = Path(__file__).parents[2] / "src/autoskillit/skills_extended" -SKILL = SKILLS_DIR / "open-pr/SKILL.md" - - -@pytest.fixture() -def text(): - return SKILL.read_text() - - -def test_open_pr_skill_file_exists(): - assert SKILL.exists(), "open-pr/SKILL.md must exist" - - -def test_open_pr_fetches_requirements_from_closing_issue(text): - """open-pr must document extracting ## Requirements from the closing_issue.""" - # Must reference fetching the closing issue body to extract requirements - has_fetch = ("closing_issue" in text and "## Requirements" in text) or ( - "gh issue view" in text and "## Requirements" in text - ) - assert has_fetch, "open-pr must document extracting requirements from closing_issue" - - -def test_open_pr_includes_requirements_in_pr_body(text): - """open-pr PR body composition must include the ## Requirements section.""" - # The body composition section must reference requirements - body_idx = text.find("PR body") if "PR body" in text else text.find("pr_body") - assert body_idx != -1, "open-pr must document PR body composition" - body_section = text[body_idx:] - assert "## Requirements" in body_section or "requirements" in body_section.lower() - - -def test_open_pr_requirements_conditional_on_presence(text): - """open-pr must only include requirements section if the issue has one.""" - lower = text.lower() - conditional = ( - "if present" in lower - or "if extracted" in lower - or "if the issue has" in lower - or "when requirements exist" in lower - or "only if" in lower - and "requirements" in lower - ) - assert conditional, ( - "Requirements must be included conditionally — only if the issue has a" - " ## Requirements section" - ) - - -def test_open_pr_requirements_section_placement(text): - """Requirements section must appear before Architecture Impact in PR body.""" - req_pos = text.find("## Requirements") - arch_pos = text.find("## Architecture Impact") - if req_pos == -1 or arch_pos == -1: - pytest.skip("Section placement not yet documented") - assert req_pos < arch_pos, "## Requirements must precede ## Architecture Impact in PR body" - - -def test_open_pr_skill_token_summary_via_hook(text): - """SKILL.md must document that token summary is appended by the PostToolUse hook.""" - assert "token_summary_appender" in text, ( - "SKILL.md must reference token_summary_appender PostToolUse hook" - ) - - -def test_open_pr_skill_removes_token_summary_path_arg(text): - """token_summary_path must no longer be documented as a positional arg.""" - assert "token_summary_path" not in text, ( - "token_summary_path arg must be removed; skill self-retrieves now" - ) - - -def test_part_suffix_stripped_in_bash_block(text): - """Step 2 bash block must strip the '— PART X ONLY' suffix from BASE_TITLE.""" - # Verify the sed strip is chained on the same line as the BASE_TITLE assignment, - # and requires a pipe — guards against sed and PART pattern appearing separately - pattern = r"BASE_TITLE=.*\|.*sed.*PART \[A-Z\] ONLY" - assert re.search(pattern, text), ( - "BASE_TITLE extraction must pipe through sed stripping PART X ONLY suffix" - ) - - -def test_step2_prose_instructs_suffix_stripping(text): - """Step 2 prose must explicitly instruct stripping the PART X ONLY suffix.""" - step2_idx = text.find("### Step 2") - assert step2_idx != -1, "Step 2 must exist" - step2_section = text[step2_idx : step2_idx + 2000] - assert re.search(r"PART.*ONLY", step2_section), ( - "Step 2 prose must mention stripping the PART X ONLY suffix as a complete phrase" - ) diff --git a/tests/contracts/test_package_gateways.py b/tests/contracts/test_package_gateways.py index bdf1b99ba6..a28f27a55b 100644 --- a/tests/contracts/test_package_gateways.py +++ b/tests/contracts/test_package_gateways.py @@ -211,6 +211,7 @@ def test_factory_make_context_returns_toolcontext(monkeypatch): from autoskillit.pipeline.context import ToolContext from autoskillit.server._factory import make_context + monkeypatch.setattr("autoskillit.server._factory._check_plugin_installed", lambda: False) ctx = make_context(AutomationConfig()) assert isinstance(ctx, ToolContext) assert ctx.gate.enabled is False # starts closed diff --git a/tests/contracts/test_plan_experiment_contracts.py b/tests/contracts/test_plan_experiment_contracts.py new file mode 100644 index 0000000000..2293ad27c3 --- /dev/null +++ b/tests/contracts/test_plan_experiment_contracts.py @@ -0,0 +1,78 @@ +"""Contract tests for plan-experiment SKILL.md — data provenance lifecycle.""" + +from pathlib import Path + +SKILL_PATH = ( + Path(__file__).resolve().parent.parent.parent + / "src" + / "autoskillit" + / "skills_extended" + / "plan-experiment" + / "SKILL.md" +) + + +def test_data_manifest_in_frontmatter_schema() -> None: + text = SKILL_PATH.read_text() + assert "data_manifest" in text + + +def test_data_manifest_required_fields() -> None: + text = SKILL_PATH.read_text() + after_manifest = text.lower().split("data_manifest")[1][:2000] + for field in ("source_type", "acquisition", "verification", "hypothesis"): + assert field in after_manifest, f"data_manifest missing field: {field}" + + +def test_directive_data_acquisition_requirement() -> None: + text = SKILL_PATH.read_text() + lower = text.lower() + assert "directive" in lower + assert "acquisition" in lower + + +def test_plan_experiment_includes_tests_directory_in_layout() -> None: + """plan-experiment/SKILL.md Experiment Directory Layout must include a tests/ folder.""" + content = SKILL_PATH.read_text() + # The directory layout template must show a tests/ directory + assert "tests/" in content, ( + "plan-experiment/SKILL.md Experiment Directory Layout must include a tests/ " + "subfolder so the agent knows to plan test infrastructure" + ) + + +def test_plan_experiment_has_test_infrastructure_phase() -> None: + """plan-experiment/SKILL.md Implementation Phases must include a test infrastructure phase.""" + content = SKILL_PATH.read_text() + lower = content.lower() + assert "test infrastructure" in lower, ( + "plan-experiment/SKILL.md must include a 'Test Infrastructure' phase in the " + "Implementation Phases section so agents plan test creation alongside scripts" + ) + + +def test_plan_experiment_environment_mentions_pytest() -> None: + """plan-experiment/SKILL.md must mention pytest in the environment specification.""" + content = SKILL_PATH.read_text() + assert "pytest" in content, ( + "plan-experiment/SKILL.md must reference pytest in the environment section so " + "agents know to include it in environment.yml for test runner availability" + ) + + +def test_plan_experiment_layout_includes_dockerfile() -> None: + """plan-experiment/SKILL.md Experiment Directory Layout must include Dockerfile.""" + content = SKILL_PATH.read_text() + assert "Dockerfile" in content, ( + "plan-experiment/SKILL.md Experiment Directory Layout must include a Dockerfile " + "so the agent plans Docker container build as part of the experiment" + ) + + +def test_plan_experiment_layout_includes_taskfile() -> None: + """plan-experiment/SKILL.md Experiment Directory Layout must include Taskfile.yml.""" + content = SKILL_PATH.read_text() + assert "Taskfile.yml" in content, ( + "plan-experiment/SKILL.md Experiment Directory Layout must include Taskfile.yml " + "with standardized build-env / run-experiment / test tasks" + ) diff --git a/tests/contracts/test_prepare_compose_pr_contracts.py b/tests/contracts/test_prepare_compose_pr_contracts.py new file mode 100644 index 0000000000..ca313c4c82 --- /dev/null +++ b/tests/contracts/test_prepare_compose_pr_contracts.py @@ -0,0 +1,74 @@ +"""Contract tests for prepare-pr and compose-pr skills.""" + +from pathlib import Path + +SKILLS_DIR = Path(__file__).parents[2] / "src/autoskillit/skills_extended" +PREPARE_PR = SKILLS_DIR / "prepare-pr/SKILL.md" +COMPOSE_PR = SKILLS_DIR / "compose-pr/SKILL.md" + + +def test_prepare_pr_skill_exists(): + assert PREPARE_PR.exists() + + +def test_compose_pr_skill_exists(): + assert COMPOSE_PR.exists() + + +def test_prepare_pr_outputs_prep_path(): + text = PREPARE_PR.read_text() + assert "prep_path" in text + + +def test_prepare_pr_outputs_selected_lenses(): + text = PREPARE_PR.read_text() + assert "selected_lenses" in text + + +def test_prepare_pr_outputs_lens_context_paths(): + text = PREPARE_PR.read_text() + assert "lens_context_paths" in text + + +def test_prepare_pr_never_invokes_arch_lens(): + """prepare-pr must explicitly state it does NOT invoke arch-lens skills.""" + text = PREPARE_PR.read_text() + assert "NOT invoke arch-lens" in text or "Does NOT invoke any arch-lens" in text + + +def test_prepare_pr_classifies_new_vs_modified(): + """prepare-pr must classify files as new (★) vs modified (●).""" + text = PREPARE_PR.read_text() + assert "★" in text and "●" in text + + +def test_compose_pr_outputs_pr_url(): + text = COMPOSE_PR.read_text() + assert "pr_url" in text + + +def test_compose_pr_validates_diagrams_with_markers(): + """compose-pr must validate that diagrams contain ★ or ●.""" + text = COMPOSE_PR.read_text() + assert "★" in text and "●" in text + + +def test_compose_pr_degrades_gracefully_without_diagrams(): + """compose-pr must handle empty diagram list gracefully.""" + text = COMPOSE_PR.read_text() + assert ( + "empty" in text.lower() + or "no diagrams" in text.lower() + or "all_diagram_paths is empty" in text + ) + + +def test_compose_pr_never_invokes_sub_skills(): + text = COMPOSE_PR.read_text() + assert "NOT invoke any sub-skills" in text or "Does NOT invoke sub-skills" in text + + +def test_compose_pr_gh_degrades_gracefully(): + text = COMPOSE_PR.read_text() + assert "gh auth status" in text + assert "empty" in text.lower() or "pr_url =" in text diff --git a/tests/contracts/test_prepare_issue_contracts.py b/tests/contracts/test_prepare_issue_contracts.py index 79cc4c9aa0..59d7de3442 100644 --- a/tests/contracts/test_prepare_issue_contracts.py +++ b/tests/contracts/test_prepare_issue_contracts.py @@ -267,3 +267,107 @@ def test_prepare_issue_strips_artifact_paths_from_validated_report_body(): assert "Original report" in body_section, ( "Skill must document removing the 'Original report:' line (artifact path) from the body" ) + + +# --------------------------------------------------------------------------- +# DETERMINISTIC STRIP: New tests for validated-report strip completeness +# --------------------------------------------------------------------------- + + +def test_prepare_issue_does_not_keep_findings_with_exceptions(): + """## Findings with Exceptions must be stripped, not kept.""" + text = SKILL_MD.read_text() + # Confirm the section name is referenced (validates the test is meaningful) + assert "Findings with Exceptions" in text, ( + "Sanity: 'Findings with Exceptions' not found at all in SKILL.md" + ) + # No line in the file may simultaneously contain 'Keep' and 'Findings with Exceptions' + for line in text.splitlines(): + assert not ("Keep" in line and "Findings with Exceptions" in line), ( + f"prepare-issue must NOT Keep '## Findings with Exceptions'. Offending line: {line!r}" + ) + + +def test_prepare_issue_strips_contested_table_rows(): + """prepare-issue must explicitly strip '| CONTESTED |' table rows.""" + text = SKILL_MD.read_text() + validated_pos = text.find("is_validated_report") + assert validated_pos != -1, "Sanity: 'is_validated_report' not found" + body_section = text[validated_pos:] + assert "| CONTESTED |" in body_section, ( + "prepare-issue validated-report section must reference '| CONTESTED |' " + "as a strip target (e.g. grep -v or Remove rule)" + ) + + +def test_prepare_issue_strips_exception_warranted_table_rows(): + """prepare-issue must explicitly strip '| VALID BUT EXCEPTION WARRANTED |' rows.""" + text = SKILL_MD.read_text() + validated_pos = text.find("is_validated_report") + assert validated_pos != -1, "Sanity: 'is_validated_report' not found" + body_section = text[validated_pos:] + assert ( + "VALID BUT EXCEPTION WARRANTED" in body_section or "EXCEPTION WARRANTED" in body_section + ), ( + "prepare-issue validated-report section must reference 'VALID BUT EXCEPTION WARRANTED' " + "as a strip target" + ) + + +def test_prepare_issue_validated_report_uses_body_file(): + """prepare-issue must use --body-file (not inline --body) for validated report creation.""" + text = SKILL_MD.read_text() + validated_pos = text.find("is_validated_report") + assert validated_pos != -1, "Sanity: 'is_validated_report' not found" + body_section = text[validated_pos:] + # --body-file must appear in the validated-report section + assert "--body-file" in body_section, ( + "prepare-issue must use 'gh issue create --body-file' for validated-report input, " + "not inline '--body'" + ) + # The temp file must live under AUTOSKILLIT_TEMP + assert "AUTOSKILLIT_TEMP" in body_section and "issue_body_" in body_section, ( + "prepare-issue must write the issue body to " + "{{AUTOSKILLIT_TEMP}}/prepare-issue/issue_body_*.md before calling gh issue create" + ) + + +def test_prepare_issue_never_constraint_prohibits_inline_body(): + """CRITICAL CONSTRAINTS must explicitly prohibit inline --body for validated-report path.""" + text = SKILL_MD.read_text() + # Find the NEVER block within Critical Constraints + never_pos = text.find("**NEVER:**") + assert never_pos != -1, "Sanity: '**NEVER:**' block not found" + # Find end of NEVER block (next **ALWAYS:** or end of constraints section) + always_pos = text.find("**ALWAYS:**", never_pos) + never_block = ( + text[never_pos:always_pos] if always_pos != -1 else text[never_pos : never_pos + 800] + ) + lower = never_block.lower() + assert "--body" in never_block and "inline" in lower, ( + "prepare-issue NEVER block must prohibit inline '--body' for validated-report " + "issue creation. Add: 'Use --body inline for the path — always use --body-file'" + ) + + +def test_prepare_issue_requirements_append_uses_body_file(): + """prepare-issue Step 7a (requirements append via gh issue edit) must use --body-file.""" + import re + + text = SKILL_MD.read_text() + # Ensure no gh issue edit call uses inline --body with shell substitution ($(...)) + inline_pattern = re.compile(r'gh issue edit[^\n]+--body\s+"\$\(') + matches = inline_pattern.findall(text) + assert not matches, ( + "prepare-issue 'gh issue edit' (requirements append) must use --body-file, " + "not inline --body shell substitution" + ) + + +def test_prepare_issue_no_tmp_paths(): + """prepare-issue must not use /tmp/ paths — all temp files go in {{AUTOSKILLIT_TEMP}}.""" + text = SKILL_MD.read_text() + assert "/tmp/" not in text, ( + "prepare-issue uses /tmp/ path(s). All temp files must live in " + "{{AUTOSKILLIT_TEMP}}/prepare-issue/ per project convention" + ) diff --git a/tests/contracts/test_process_issues_contracts.py b/tests/contracts/test_process_issues_contracts.py index cff3c74ac5..bc2dcda139 100644 --- a/tests/contracts/test_process_issues_contracts.py +++ b/tests/contracts/test_process_issues_contracts.py @@ -64,8 +64,8 @@ def test_process_issues_documents_pr_title_prefix(skill_text: str) -> None: def test_process_issues_writes_to_temp_dir(skill_text: str) -> None: - """process-issues must document output to .autoskillit/temp/process-issues/.""" - assert ".autoskillit/temp/process-issues/" in skill_text + """process-issues must document output to {{AUTOSKILLIT_TEMP}}/process-issues/.""" + assert "{{AUTOSKILLIT_TEMP}}/process-issues/" in skill_text def test_process_issues_supports_merge_batch_flag(skill_text: str) -> None: @@ -80,9 +80,9 @@ def test_process_issues_derives_issue_url(skill_text: str) -> None: assert github_url_ref in skill_text or "default_repo" in skill_text -def test_open_pr_supports_run_name_title_prefix() -> None: - """open-pr must derive [FEATURE]/[FIX] PR title prefix from run_name convention.""" - content = (bundled_skills_extended_dir() / "open-pr" / "SKILL.md").read_text() +def test_prepare_pr_supports_run_name_title_prefix() -> None: + """prepare-pr must derive [FEATURE]/[FIX] PR title prefix from run_name convention.""" + content = (bundled_skills_extended_dir() / "prepare-pr" / "SKILL.md").read_text() assert "[FEATURE]" in content assert "[FIX]" in content # Must document the run_name-based convention diff --git a/tests/contracts/test_protocol_definitions.py b/tests/contracts/test_protocol_definitions.py new file mode 100644 index 0000000000..c60599ed18 --- /dev/null +++ b/tests/contracts/test_protocol_definitions.py @@ -0,0 +1,28 @@ +"""Tests for Protocol definitions in core/_type_protocols.py. + +REQ-PROTO-007: SkillLister Protocol must live in core/_type_protocols.py. +""" + +from __future__ import annotations + +import inspect + + +def test_skill_lister_protocol_defined() -> None: + """REQ-PROTO-007: SkillLister Protocol must live in + core/_type_protocols.py and define a `list_all() -> list[Any]` + method, so L2 recipe code can type-annotate against L0 instead of + binding to the L1 workspace concrete class.""" + from autoskillit.core._type_protocols import SkillLister + + assert hasattr(SkillLister, "list_all") + sig = inspect.signature(SkillLister.list_all) + assert "self" in sig.parameters + + +def test_skill_resolver_satisfies_skill_lister() -> None: + from autoskillit.core._type_protocols import SkillLister + from autoskillit.workspace.skills import DefaultSkillResolver + + instance: SkillLister = DefaultSkillResolver() + assert callable(instance.list_all) diff --git a/tests/contracts/test_protocol_satisfaction.py b/tests/contracts/test_protocol_satisfaction.py index 726014c61c..c8442a1453 100644 --- a/tests/contracts/test_protocol_satisfaction.py +++ b/tests/contracts/test_protocol_satisfaction.py @@ -22,14 +22,14 @@ def test_nine_protocols_importable_from_core(): from autoskillit.core import ( # noqa: F401 - AuditStore, + AuditLog, DatabaseReader, - GatePolicy, + GateState, HeadlessExecutor, MigrationService, RecipeRepository, TestRunner, - TokenStore, + TokenLog, WorkspaceManager, ) @@ -51,35 +51,26 @@ def test_truncate_text_importable_from_core(): assert truncate_text("short", 100) == "short" -# ── Backward compatibility ───────────────────────────────────────────────────── - - -def test_truncate_private_alias_still_available(): - from autoskillit.execution.session import _truncate - - assert _truncate("x" * 20, 10).startswith("...[truncated") - - # ── Runtime-checkable ────────────────────────────────────────────────────────── def test_all_new_protocols_are_runtime_checkable(): from autoskillit.core import ( - AuditStore, + AuditLog, DatabaseReader, - GatePolicy, + GateState, HeadlessExecutor, MigrationService, RecipeRepository, TestRunner, - TokenStore, + TokenLog, WorkspaceManager, ) for proto in [ - GatePolicy, - AuditStore, - TokenStore, + GateState, + AuditLog, + TokenLog, TestRunner, HeadlessExecutor, RecipeRepository, @@ -96,40 +87,40 @@ def test_all_new_protocols_are_runtime_checkable(): def test_defaultgatestate_satisfies_gatepolicy(): - from autoskillit.core import GatePolicy + from autoskillit.core import GateState from autoskillit.pipeline.gate import DefaultGateState - assert isinstance(DefaultGateState(), GatePolicy) + assert isinstance(DefaultGateState(), GateState) def test_defaultauditlog_satisfies_auditstore(): - from autoskillit.core import AuditStore + from autoskillit.core import AuditLog from autoskillit.pipeline.audit import DefaultAuditLog - assert isinstance(DefaultAuditLog(), AuditStore) + assert isinstance(DefaultAuditLog(), AuditLog) def test_defaulttokenlog_satisfies_tokenstore(): - from autoskillit.core import TokenStore + from autoskillit.core import TokenLog from autoskillit.pipeline.tokens import DefaultTokenLog - assert isinstance(DefaultTokenLog(), TokenStore) + assert isinstance(DefaultTokenLog(), TokenLog) def test_default_timing_log_satisfies_timing_store_protocol(): - from autoskillit.core import TimingStore + from autoskillit.core import TimingLog from autoskillit.pipeline.timings import DefaultTimingLog - assert isinstance(DefaultTimingLog(), TimingStore) + assert isinstance(DefaultTimingLog(), TimingLog) def test_default_token_log_satisfies_token_store_with_order_id(): - """F-1: DefaultTokenLog satisfies updated TokenStore Protocol (includes order_id params).""" - from autoskillit.core import TokenStore + """F-1: DefaultTokenLog satisfies updated TokenLog Protocol (includes order_id params).""" + from autoskillit.core import TokenLog from autoskillit.pipeline.tokens import DefaultTokenLog log = DefaultTokenLog() - assert isinstance(log, TokenStore) + assert isinstance(log, TokenLog) # Verify the order_id param is accepted by record/get_report/compute_total log.record( "plan", @@ -147,12 +138,12 @@ def test_default_token_log_satisfies_token_store_with_order_id(): def test_default_timing_log_satisfies_timing_store_with_order_id(): - """F-2: DefaultTimingLog satisfies updated TimingStore Protocol (includes order_id params).""" - from autoskillit.core import TimingStore + """F-2: DefaultTimingLog satisfies updated TimingLog Protocol (includes order_id params).""" + from autoskillit.core import TimingLog from autoskillit.pipeline.timings import DefaultTimingLog log = DefaultTimingLog() - assert isinstance(log, TimingStore) + assert isinstance(log, TimingLog) # Verify the order_id param is accepted by record/get_report/compute_total log.record("plan", 5.0, order_id="test-order") assert log.get_report(order_id="test-order") != [] @@ -257,9 +248,9 @@ def test_all_ten_protocols_in_core_all(): expected_protocols = { "SubprocessRunner", - "GatePolicy", - "AuditStore", - "TokenStore", + "GateState", + "AuditLog", + "TokenLog", "TestRunner", "HeadlessExecutor", "RecipeRepository", @@ -311,7 +302,10 @@ def test_req_api_001_public_params_present(self): "stale_threshold", "session_record_types", "completion_drain_timeout", + "natural_exit_grace_seconds", "linux_tracing_config", + "idle_output_timeout", + "max_suppression_seconds", } assert expected == public_params, ( f"run_managed_async public params changed.\n" @@ -371,6 +365,8 @@ def test_req_api_002_call_params_match_protocol(self): "completion_drain_timeout", "linux_tracing_config", "env", + "idle_output_timeout", + "max_suppression_seconds", } assert expected == actual, ( f"DefaultSubprocessRunner.__call__ params changed.\n" @@ -468,7 +464,7 @@ def test_req_api_004_server_helpers_subprocess_result_under_type_checking(self): # ------------------------------------------------------------------ def test_req_api_005_subprocess_result_field_names(self): - """SubprocessResult must have exactly the 12 canonical fields.""" + """SubprocessResult must have exactly the 14 canonical fields.""" from autoskillit.core.types import SubprocessResult fields = {f.name for f in dataclasses.fields(SubprocessResult)} @@ -485,6 +481,8 @@ def test_req_api_005_subprocess_result_field_names(self): "start_ts", "end_ts", "elapsed_seconds", + "kill_reason", + "tracked_comm", } assert fields == expected, ( f"SubprocessResult fields changed.\n" @@ -511,6 +509,7 @@ def test_req_api_006_termination_reason_members(self): TerminationReason.NATURAL_EXIT, TerminationReason.COMPLETED, TerminationReason.STALE, + TerminationReason.IDLE_STALL, TerminationReason.TIMED_OUT, } @@ -521,16 +520,18 @@ def test_req_api_006_termination_reason_string_values(self): assert TerminationReason.NATURAL_EXIT == "natural_exit" assert TerminationReason.COMPLETED == "completed" assert TerminationReason.STALE == "stale" + assert TerminationReason.IDLE_STALL == "idle_stall" assert TerminationReason.TIMED_OUT == "timed_out" def test_req_api_006_channel_confirmation_members(self): - """ChannelConfirmation must have exactly the 3 canonical values.""" + """ChannelConfirmation must have exactly the 4 canonical values.""" from autoskillit.core.types import ChannelConfirmation assert set(ChannelConfirmation) == { ChannelConfirmation.CHANNEL_A, ChannelConfirmation.CHANNEL_B, ChannelConfirmation.UNMONITORED, + ChannelConfirmation.DIR_MISSING, } def test_req_api_006_channel_confirmation_string_values(self): diff --git a/tests/contracts/test_review_pr_diff_annotation.py b/tests/contracts/test_review_pr_diff_annotation.py index 412df3cd40..d29dd9344d 100644 --- a/tests/contracts/test_review_pr_diff_annotation.py +++ b/tests/contracts/test_review_pr_diff_annotation.py @@ -30,6 +30,32 @@ def test_review_pr_contract_has_hunk_ranges_path() -> None: ) +def test_review_pr_annotated_diff_path_is_recommended() -> None: + """The annotated_diff_path input must be marked recommended in skill_contracts.yaml.""" + from autoskillit.recipe.contracts import get_skill_contract, load_bundled_manifest + + contract = get_skill_contract("review-pr", load_bundled_manifest()) + assert contract is not None + inp = next((i for i in contract.inputs if i.name == "annotated_diff_path"), None) + assert inp is not None, "annotated_diff_path input not found in review-pr contract" + assert inp.recommended is True, ( + "annotated_diff_path must be marked recommended=True in skill_contracts.yaml" + ) + + +def test_review_pr_hunk_ranges_path_is_recommended() -> None: + """The hunk_ranges_path input must be marked recommended in skill_contracts.yaml.""" + from autoskillit.recipe.contracts import get_skill_contract, load_bundled_manifest + + contract = get_skill_contract("review-pr", load_bundled_manifest()) + assert contract is not None + inp = next((i for i in contract.inputs if i.name == "hunk_ranges_path"), None) + assert inp is not None, "hunk_ranges_path input not found in review-pr contract" + assert inp.recommended is True, ( + "hunk_ranges_path must be marked recommended=True in skill_contracts.yaml" + ) + + def test_review_pr_skill_reads_annotated_diff_from_file() -> None: """review-pr SKILL.md must reference annotated_diff_path (no autoskillit import).""" skill_text = _SKILL_MD.read_text() diff --git a/tests/contracts/test_run_experiment_contracts.py b/tests/contracts/test_run_experiment_contracts.py new file mode 100644 index 0000000000..c8f2f94661 --- /dev/null +++ b/tests/contracts/test_run_experiment_contracts.py @@ -0,0 +1,24 @@ +"""Contract tests for run-experiment SKILL.md — data provenance lifecycle.""" + +from pathlib import Path + +SKILL_PATH = ( + Path(__file__).resolve().parent.parent.parent + / "src" + / "autoskillit" + / "skills_extended" + / "run-experiment" + / "SKILL.md" +) + + +def test_blocked_hypotheses_token_documented() -> None: + text = SKILL_PATH.read_text() + assert "blocked_hypotheses" in text + + +def test_data_manifest_preflight_check() -> None: + text = SKILL_PATH.read_text() + lower = text.lower() + assert "data manifest" in lower + assert "pre-flight" in lower or "preflight" in lower diff --git a/tests/contracts/test_scope_contracts.py b/tests/contracts/test_scope_contracts.py new file mode 100644 index 0000000000..5d6332114e --- /dev/null +++ b/tests/contracts/test_scope_contracts.py @@ -0,0 +1,66 @@ +"""Contract tests for the scope skill's SKILL.md template.""" + +from __future__ import annotations + +import re + +import pytest + +from autoskillit.core import pkg_root + + +def _read_scope_skill_md() -> str: + return (pkg_root() / "skills_extended" / "scope" / "SKILL.md").read_text() + + +class TestComputationalComplexitySection: + """Validate the Computational Complexity section in scope SKILL.md.""" + + def test_section_exists(self) -> None: + content = _read_scope_skill_md() + assert "## Computational Complexity" in content + + @pytest.mark.parametrize( + "field", + [ + "Dominant operation", + "Scaling behavior", + "Known bottlenecks", + "Gotchas", + ], + ) + def test_field_present(self, field: str) -> None: + content = _read_scope_skill_md() + cc_idx = content.index("## Computational Complexity") + hyp_idx = content.index("## Hypotheses") + section = content[cc_idx:hyp_idx] + assert field in section, ( + f"Scope SKILL.md missing '{field}' in Computational Complexity section" + ) + + def test_section_between_domain_context_and_hypotheses(self) -> None: + content = _read_scope_skill_md() + dc_idx = content.index("## Domain Context") + cc_idx = content.index("## Computational Complexity") + hyp_idx = content.index("## Hypotheses") + assert dc_idx < cc_idx < hyp_idx, ( + "## Computational Complexity must appear between ## Domain Context and ## Hypotheses" + ) + + def test_baseline_computation_instruction(self) -> None: + content = _read_scope_skill_md() + assert re.search(r"baseline.*computation", content, re.IGNORECASE), ( + "Known bottlenecks field must include instruction about " + "baseline/reference computation costs" + ) + + def test_complexity_subagent_instruction(self) -> None: + content = _read_scope_skill_md() + assert re.search( + r"(?:Subagent|subagent).*?Complexity.*?dominant.*?operation", + content, + re.DOTALL | re.IGNORECASE, + ), ( + "Step 1 subagent must instruct gathering of computational complexity " + "fields including dominant operation (heading alone is not sufficient)" + ) diff --git a/tests/contracts/test_skill_contracts.py b/tests/contracts/test_skill_contracts.py index 2d3e82fa3e..55eaf96e8c 100644 --- a/tests/contracts/test_skill_contracts.py +++ b/tests/contracts/test_skill_contracts.py @@ -2,6 +2,7 @@ from __future__ import annotations +import re from pathlib import Path import pytest @@ -98,3 +99,79 @@ def test_every_skill_with_patterns_has_examples(skills): + "\n".join(f" - {s}" for s in sorted(missing)) + "\nAdd pattern_examples to skill_contracts.yaml." ) + + +VALID_EXPERIMENT_TYPES = frozenset( + { + "benchmark", + "configuration_study", + "causal_inference", + "robustness_audit", + "exploratory", + } +) + + +def test_skill_contracts_pattern_examples_use_valid_experiment_types() -> None: + """pattern_examples in skill_contracts.yaml must use only valid experiment_type values. + + 'controlled' is not a valid experiment type. Invalid examples mislead + developers writing new skills and create false documentation contracts. + """ + contracts_text = _CONTRACTS_YAML.read_text() + # Use [^\s\\]+ to stop at backslash, since YAML string literals use \n (two chars) + for m in re.finditer(r"experiment_type\s*=\s*([^\s\\]+)", contracts_text): + value = m.group(1).strip("\"'") + assert value in VALID_EXPERIMENT_TYPES, ( + f"skill_contracts.yaml contains invalid experiment_type in pattern_examples: " + f"{value!r}. Valid values: {sorted(VALID_EXPERIMENT_TYPES)}" + ) + + +def test_review_design_experiment_type_output_has_allowed_values() -> None: + """review-design contract must declare allowed_values for experiment_type output. + + Without this constraint, invalid values (e.g. 'controlled') can propagate + silently through capture and downstream recipe steps. + """ + contracts = yaml.safe_load(_CONTRACTS_YAML.read_text()) + review_design = contracts["skills"]["review-design"] + outputs = {o["name"]: o for o in review_design["outputs"]} + et_output = outputs.get("experiment_type") + assert et_output is not None, "review-design must declare experiment_type output" + assert "allowed_values" in et_output, ( + "experiment_type output must have allowed_values constraint. " + "Without it, invalid values propagate silently." + ) + assert set(et_output["allowed_values"]) == VALID_EXPERIMENT_TYPES + + +def test_all_exp_lens_skills_have_contracts(skills): + """Every exp-lens skill must have an entry in skill_contracts.yaml.""" + from autoskillit.workspace.skills import DefaultSkillResolver + + resolver = DefaultSkillResolver() + exp_lens = [ + s.name + for s in resolver.list_all() + if "exp-lens" in s.categories and s.name.startswith("exp-lens-") + ] + missing = [name for name in exp_lens if name not in skills] + assert not missing, f"exp-lens skills missing contracts: {sorted(missing)}" + + +def test_skill_contracts_yaml_includes_prepare_research_pr(skills): + """prepare-research-pr must be registered with prep_path output pattern.""" + _assert_skill_has_patterns(skills, "prepare-research-pr", r"prep_path\s*=\s*/.+") + + +def test_skill_contracts_yaml_includes_compose_research_pr(skills): + """compose-research-pr must be registered with pr_url output pattern.""" + _assert_skill_has_patterns( + skills, "compose-research-pr", r"pr_url\s*=\s*(https://github\.com/.*/pull/\d+)?" + ) + + +def test_skill_contracts_yaml_open_research_pr_removed(skills): + """open-research-pr must no longer be registered — it has been retired.""" + assert "open-research-pr" not in skills diff --git a/tests/contracts/test_sous_chef_quota_protocol.py b/tests/contracts/test_sous_chef_quota_protocol.py new file mode 100644 index 0000000000..12238ae2bc --- /dev/null +++ b/tests/contracts/test_sous_chef_quota_protocol.py @@ -0,0 +1,17 @@ +"""Contract test: sous-chef SKILL.md must contain QUOTA WAIT PROTOCOL section.""" + +from pathlib import Path + + +def test_sous_chef_contains_quota_wait_protocol(): + """sous-chef/SKILL.md contains QUOTA WAIT PROTOCOL section.""" + skill_md = ( + Path(__file__).resolve().parent.parent.parent + / "src" + / "autoskillit" + / "skills" + / "sous-chef" + / "SKILL.md" + ) + content = skill_md.read_text() + assert "QUOTA WAIT PROTOCOL" in content diff --git a/tests/contracts/test_sous_chef_routing.py b/tests/contracts/test_sous_chef_routing.py index 5c3ced777f..fa07208c3d 100644 --- a/tests/contracts/test_sous_chef_routing.py +++ b/tests/contracts/test_sous_chef_routing.py @@ -72,3 +72,34 @@ def test_stale_routing_uses_subtype_discriminant(self) -> None: "sous-chef/SKILL.md must contain 'subtype: stale' or 'subtype=stale' as a " "compound routing discriminant, not just the words 'stale' and 'subtype' separately" ) + + +def _extract_merge_phase_section(skill_md: str) -> str: + """Extract text from '## MERGE PHASE' up to the next top-level '## ' heading.""" + lines = skill_md.splitlines() + in_section = False + extracted: list[str] = [] + for line in lines: + if line.startswith("## MERGE PHASE"): + in_section = True + extracted.append(line) + continue + if in_section and line.startswith("## ") and "MERGE PHASE" not in line: + break + if in_section: + extracted.append(line) + return "\n".join(extracted) + + +def test_sous_chef_merge_phase_documents_queue_no_auto_path() -> None: + """MERGE PHASE section must document the queue_enqueue_no_auto routing cell.""" + skill_md = _sous_chef_text() + merge_phase = _extract_merge_phase_section(skill_md) + assert merge_phase, "MERGE PHASE section not found in sous-chef/SKILL.md" + assert "queue_enqueue_no_auto" in merge_phase, ( + "MERGE PHASE section must document the queue_enqueue_no_auto step" + ) + assert "queue_available == true and auto_merge_available == false" in merge_phase, ( + "MERGE PHASE section must document the condition " + "'queue_available == true and auto_merge_available == false'" + ) diff --git a/tests/contracts/test_stage_data_contracts.py b/tests/contracts/test_stage_data_contracts.py new file mode 100644 index 0000000000..2bb4d8cba4 --- /dev/null +++ b/tests/contracts/test_stage_data_contracts.py @@ -0,0 +1,69 @@ +"""Contract tests for stage-data SKILL.md — pre-flight resource feasibility gate.""" + +from pathlib import Path + +import pytest + +SKILL_PATH = ( + Path(__file__).resolve().parent.parent.parent + / "src" + / "autoskillit" + / "skills_extended" + / "stage-data" + / "SKILL.md" +) + + +@pytest.fixture(scope="module") +def skill_text() -> str: + return SKILL_PATH.read_text() + + +def test_stage_data_skill_exists() -> None: + assert SKILL_PATH.exists() + + +def test_stage_data_emits_verdict_token(skill_text: str) -> None: + assert "verdict =" in skill_text + + +def test_stage_data_emits_resource_report_token(skill_text: str) -> None: + assert "resource_report =" in skill_text + + +def test_stage_data_reads_data_manifest(skill_text: str) -> None: + assert "data_manifest" in skill_text + + +def test_stage_data_checks_disk_space(skill_text: str) -> None: + lower = skill_text.lower() + assert "disk" in lower + assert "df" in lower or "disk space" in lower + + +def test_stage_data_checks_network_connectivity(skill_text: str) -> None: + lower = skill_text.lower() + assert "network" in lower or "connectivity" in lower or "reachab" in lower + + +def test_stage_data_creates_directory_structure(skill_text: str) -> None: + lower = skill_text.lower() + assert "mkdir" in lower or "directory structure" in lower or "create" in lower + assert "data dir" in lower + + +def test_stage_data_documents_pass_verdict(skill_text: str) -> None: + assert "PASS" in skill_text + + +def test_stage_data_documents_warn_verdict(skill_text: str) -> None: + assert "WARN" in skill_text + + +def test_stage_data_documents_fail_verdict(skill_text: str) -> None: + assert "FAIL" in skill_text + + +def test_stage_data_categories_include_research(skill_text: str) -> None: + assert "categories" in skill_text + assert "research" in skill_text diff --git a/tests/contracts/test_sub_skill_refusal_contracts.py b/tests/contracts/test_sub_skill_refusal_contracts.py new file mode 100644 index 0000000000..1d4d517067 --- /dev/null +++ b/tests/contracts/test_sub_skill_refusal_contracts.py @@ -0,0 +1,85 @@ +""" +Cross-skill contract: every SKILL.md that invokes sub-skills via the Skill tool must contain +explicit refusal handling language. Parametrized over all qualifying skills — self-updating +as new skills are added to skills_extended/. +""" + +import re +from pathlib import Path + +import pytest + +_SKILLS_DIR = Path(__file__).parents[2] / "src/autoskillit/skills_extended" + +# Identifies a SKILL.md as invoking sub-skills via the Skill tool +_SUB_SKILL_CALL_PATTERN = re.compile( + r"Skill tool.{0,200}/autoskillit:|" + r"/autoskillit:.{0,200}Skill tool|" + r"LOAD.{0,100}/autoskillit:|" + r"Load.{0,100}/autoskillit:", +) + +# Refusal detection language +_REFUSAL_SIGNAL_PATTERN = re.compile( + r"disable-model-invocation|cannot be used|Skill tool returns.{0,50}error|" + r"refused|Skill tool fails|skill.{0,50}unavailable", + re.IGNORECASE, +) + +# Required action on refusal — specific phrases unlikely to appear in non-refusal contexts +_ACTION_SIGNAL_PATTERN = re.compile( + r"proceed without|discard|log.{0,30}warning|fail.{0,30}clean|abort.{0,20}step", + re.IGNORECASE, +) + + +def _find_sub_skill_calling_skills() -> list[tuple[str, Path]]: + results = [] + for skill_dir in sorted(_SKILLS_DIR.iterdir()): + skill_md = skill_dir / "SKILL.md" + if not skill_md.exists(): + continue + text = skill_md.read_text(encoding="utf-8") + if _SUB_SKILL_CALL_PATTERN.search(text): + results.append((skill_dir.name, skill_md)) + return results + + +_SUB_SKILL_CALLERS = _find_sub_skill_calling_skills() + + +@pytest.mark.parametrize( + "skill_name,skill_md", + _SUB_SKILL_CALLERS, + ids=[s[0] for s in _SUB_SKILL_CALLERS], +) +def test_sub_skill_calling_skill_has_refusal_handler(skill_name: str, skill_md: Path): + """ + Structural ratchet: any skill that invokes sub-skills via the Skill tool must + document what to do when the Skill tool refuses the invocation. New qualifying + skills without this handler fail CI immediately without requiring code review. + """ + text = skill_md.read_text(encoding="utf-8") + has_refusal = bool(_REFUSAL_SIGNAL_PATTERN.search(text)) + has_action = bool(_ACTION_SIGNAL_PATTERN.search(text)) + assert has_refusal, ( + f"{skill_name}/SKILL.md invokes sub-skills via the Skill tool but contains no " + f"documentation of what to do when the Skill tool refuses the invocation. " + f"Add a refusal handler near the Skill tool call: describe what happens when the " + f"tool returns 'cannot be used' or 'disable-model-invocation', and what action follows." + ) + assert has_action, ( + f"{skill_name}/SKILL.md has refusal detection language but no prescribed action. " + f"Specify: proceed without, discard, fail clean, log warning, or abort step." + ) + + +def test_mermaid_skill_itself_not_a_sub_skill_caller(): + """ + Sanity: the mermaid skill is a leaf and should not appear in the parametrized list. + Confirms the detector does not over-fire on leaf skills. + """ + caller_names = {s[0] for s in _SUB_SKILL_CALLERS} + assert "mermaid" not in caller_names, ( + "mermaid/SKILL.md was detected as a sub-skill caller — review the detection pattern." + ) diff --git a/tests/contracts/test_target_skill_invocability.py b/tests/contracts/test_target_skill_invocability.py index 38a0277274..9876ba0787 100644 --- a/tests/contracts/test_target_skill_invocability.py +++ b/tests/contracts/test_target_skill_invocability.py @@ -1,6 +1,6 @@ """Contract: the target skill of a run_skill call must be invocable after session setup. -Verifies that the invocation chain (init_session → activate_tier2 → resolve namespace) +Verifies that the invocation chain (init_session → activate_skill_deps → resolve namespace) leaves the target skill invocable and all other Tier 2 skills gated. """ @@ -16,7 +16,7 @@ from autoskillit.recipe.io import builtin_recipes_dir from autoskillit.workspace import ( DefaultSessionSkillManager, - SkillResolver, + DefaultSkillResolver, SkillsDirectoryProvider, ) @@ -42,7 +42,7 @@ def _make_session( ) tier2 = frozenset(config.skills.tier2) if target_skill in tier2: - mgr.activate_tier2(session_id, target_skill) + mgr.activate_skill_deps(session_id, target_skill) return mgr, session_id, str(tmp_path) @@ -95,7 +95,7 @@ class TestResolvedNamespaceMatchesSkillLocation: """Namespace resolution must match physical skill location.""" def test_bundled_extended_skill_uses_bare_namespace(self) -> None: - resolver = SkillResolver() + resolver = DefaultSkillResolver() info = resolver.resolve("make-plan") assert info is not None assert info.source == SkillSource.BUNDLED_EXTENDED @@ -104,7 +104,7 @@ def test_bundled_extended_skill_uses_bare_namespace(self) -> None: assert resolved == "/make-plan arg1" def test_bundled_skill_uses_autoskillit_namespace(self) -> None: - resolver = SkillResolver() + resolver = DefaultSkillResolver() info = resolver.resolve("open-kitchen") assert info is not None assert info.source == SkillSource.BUNDLED @@ -113,18 +113,52 @@ def test_bundled_skill_uses_autoskillit_namespace(self) -> None: assert resolved == "/autoskillit:open-kitchen" def test_already_correct_namespace_is_preserved(self) -> None: - resolver = SkillResolver() + resolver = DefaultSkillResolver() resolved, name = resolve_target_skill("/make-plan arg1 arg2", resolver) assert name == "make-plan" assert resolved == "/make-plan arg1 arg2" def test_non_slash_command_passes_through(self) -> None: - resolver = SkillResolver() + resolver = DefaultSkillResolver() resolved, name = resolve_target_skill("Fix the bug", resolver) assert name is None assert resolved == "Fix the bug" +class TestDepSkillsNotGatedAfterActivation: + """After activating a target with activate_deps, dependency skills are also ungated.""" + + def test_dep_skills_not_gated_after_activation(self, tmp_path: Path) -> None: + """After activating make-plan, arch-lens-* and mermaid skills are ungated.""" + config = load_config() + provider = SkillsDirectoryProvider() + mgr = DefaultSessionSkillManager(provider, tmp_path) + session_id = "test-dep-activation" + mgr.init_session(session_id, cook_session=False, config=config) + mgr.activate_skill_deps(session_id, "make-plan") + + skills_base = tmp_path / session_id / ".claude" / "skills" + # Check arch-lens skills are ungated + for skill_dir in sorted(skills_base.iterdir()): + if not skill_dir.is_dir(): + continue + name = skill_dir.name + if not name.startswith("arch-lens-"): + continue + content = (skill_dir / "SKILL.md").read_text() + assert "disable-model-invocation: true" not in content, ( + f"arch-lens skill '{name}' should be ungated after activating make-plan" + ) + + # Check mermaid is ungated + mermaid_md = skills_base / "mermaid" / "SKILL.md" + assert mermaid_md.exists(), "mermaid skill dir should exist after init_session" + content = mermaid_md.read_text() + assert "disable-model-invocation: true" not in content, ( + "mermaid should be ungated via transitive dependency from make-plan" + ) + + class TestAllRecipeSkillCommandsInvocable: """Every run_skill step in bundled recipes must resolve to an invocable form.""" @@ -133,7 +167,7 @@ def test_all_bundled_recipes_skill_commands_invocable_after_init_session( ) -> None: config = load_config() tier2 = frozenset(config.skills.tier2) - resolver = SkillResolver() + resolver = DefaultSkillResolver() provider = SkillsDirectoryProvider() for yaml_path in sorted(builtin_recipes_dir().glob("*.yaml")): @@ -168,12 +202,12 @@ def test_all_bundled_recipes_skill_commands_invocable_after_init_session( f"'{resolved}' (should use /autoskillit: namespace)" ) - # Verify activation: after init_session + activate_tier2, target is invocable + # Verify activation: after init_session + activate_skill_deps, target is invocable session_id = f"test-{yaml_path.stem}-{step_name}" mgr = DefaultSessionSkillManager(provider, tmp_path) mgr.init_session(session_id, cook_session=False, config=config) if name in tier2: - mgr.activate_tier2(session_id, name) + mgr.activate_skill_deps(session_id, name) skill_md_path = tmp_path / session_id / ".claude" / "skills" / name / "SKILL.md" if skill_md_path.exists(): content = skill_md_path.read_text() diff --git a/tests/contracts/test_triage_issues_contracts.py b/tests/contracts/test_triage_issues_contracts.py new file mode 100644 index 0000000000..6ce9b92965 --- /dev/null +++ b/tests/contracts/test_triage_issues_contracts.py @@ -0,0 +1,33 @@ +"""Contract tests for triage-issues body-file safety (gh issue edit --body-file).""" + +from __future__ import annotations + +from pathlib import Path + +SKILL_DIR = Path(__file__).parents[2] / "src/autoskillit/skills_extended/triage-issues" +SKILL_MD = SKILL_DIR / "SKILL.md" + + +def test_triage_issues_skill_exists(): + assert SKILL_MD.exists(), f"SKILL.md not found at {SKILL_MD}" + + +def test_triage_issues_gh_issue_edit_uses_body_file(): + """triage-issues gh issue edit must use --body-file, not inline --body shell substitution.""" + text = SKILL_MD.read_text() + edit_pos = text.find("gh issue edit") + assert edit_pos != -1, "Sanity: 'gh issue edit' not found in triage-issues" + edit_context = text[edit_pos : edit_pos + 400] + assert "--body-file" in edit_context, ( + "triage-issues 'gh issue edit' must use --body-file to prevent shell-substitution " + "truncation and LLM body recomposition" + ) + + +def test_triage_issues_body_file_uses_autoskillit_temp(): + """triage-issues must write edit body to AUTOSKILLIT_TEMP/triage-issues/.""" + text = SKILL_MD.read_text() + assert "AUTOSKILLIT_TEMP" in text, ( + "triage-issues must write issue body to {{AUTOSKILLIT_TEMP}}/triage-issues/ " + "before calling gh issue edit --body-file" + ) diff --git a/tests/core/test_claude_env.py b/tests/core/test_claude_env.py new file mode 100644 index 0000000000..b34112cb31 --- /dev/null +++ b/tests/core/test_claude_env.py @@ -0,0 +1,132 @@ +"""Unit tests for build_claude_env() — IDE env scrubbing at the subprocess launch boundary.""" + +from __future__ import annotations + +from types import MappingProxyType + +import pytest + +from autoskillit.core import build_claude_env +from autoskillit.core._claude_env import ( + IDE_ENV_ALWAYS_EXTRAS, + IDE_ENV_DENYLIST, + IDE_ENV_PREFIX_DENYLIST, +) + + +def test_build_claude_env_strips_sse_port() -> None: + base = {"CLAUDE_CODE_SSE_PORT": "23270", "HOME": "/tmp", "PATH": "/usr/bin"} + result = build_claude_env(base=base) + assert "CLAUDE_CODE_SSE_PORT" not in result + assert result["HOME"] == "/tmp" + assert result["PATH"] == "/usr/bin" + + +@pytest.mark.parametrize( + "key", + [ + "CLAUDE_CODE_IDE_HOST_OVERRIDE", + "CLAUDE_CODE_IDE_SKIP_AUTO_INSTALL", + "CLAUDE_CODE_IDE_SKIP_VALID_CHECK", + "CLAUDE_CODE_SSE_TOKEN", + "CLAUDE_CODE_SSE_HOST", + ], +) +def test_build_claude_env_strips_ide_prefix(key: str) -> None: + result = build_claude_env(base={key: "value", "HOME": "/tmp"}) + assert key not in result + assert "HOME" in result + + +@pytest.mark.parametrize( + "key", + [ + "CLAUDE_CODE_SSE_PORT", + "ENABLE_IDE_INTEGRATION", + "CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR", + "VSCODE_GIT_ASKPASS_MAIN", + "CURSOR_TRACE_ID", + "ZED_TERM", + ], +) +def test_build_claude_env_strips_expanded_denylist(key: str) -> None: + result = build_claude_env(base={key: "value", "HOME": "/tmp"}) + assert key not in result + assert "HOME" in result + + +def test_build_claude_env_preserves_unrelated_claude_vars() -> None: + base = { + "CLAUDE_CONFIG_DIR": "/home/user/.claude", + "ANTHROPIC_API_KEY": "sk-...", + "ANTHROPIC_LOG": "debug", + } + result = build_claude_env(base=base) + assert result["CLAUDE_CONFIG_DIR"] == "/home/user/.claude" + assert result["ANTHROPIC_API_KEY"] == "sk-..." + assert result["ANTHROPIC_LOG"] == "debug" + + +def test_build_claude_env_injects_auto_connect_off() -> None: + result = build_claude_env(base={}) + assert result["CLAUDE_CODE_AUTO_CONNECT_IDE"] == "0" + + +def test_build_claude_env_caller_extras_can_override_auto_connect() -> None: + result = build_claude_env(base={}, extras={"CLAUDE_CODE_AUTO_CONNECT_IDE": "1"}) + assert result["CLAUDE_CODE_AUTO_CONNECT_IDE"] == "1" + + +def test_build_claude_env_applies_extras() -> None: + result = build_claude_env(base={}, extras={"AUTOSKILLIT_HEADLESS": "1"}) + assert result["AUTOSKILLIT_HEADLESS"] == "1" + + +def test_build_claude_env_extras_override_base() -> None: + result = build_claude_env(base={"FOO": "original"}, extras={"FOO": "overridden"}) + assert result["FOO"] == "overridden" + + +def test_build_claude_env_defaults_to_os_environ(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("AUTOSKILLIT_TEST_DEFAULT_ENV_MARKER", "present") + monkeypatch.setenv("CLAUDE_CODE_SSE_PORT", "23270") + result = build_claude_env() + assert result.get("AUTOSKILLIT_TEST_DEFAULT_ENV_MARKER") == "present" + assert "CLAUDE_CODE_SSE_PORT" not in result + + +def test_build_claude_env_returns_mappingproxy() -> None: + result = build_claude_env(base={"HOME": "/tmp"}) + assert isinstance(result, MappingProxyType) + with pytest.raises(TypeError): + result["X"] = "Y" # type: ignore[index] + + +def test_ide_env_denylist_contains_expected_names() -> None: + assert "CLAUDE_CODE_SSE_PORT" in IDE_ENV_DENYLIST + assert "ENABLE_IDE_INTEGRATION" in IDE_ENV_DENYLIST + assert "CLAUDE_CODE_WEBSOCKET_AUTH_FILE_DESCRIPTOR" in IDE_ENV_DENYLIST + assert "VSCODE_GIT_ASKPASS_MAIN" in IDE_ENV_DENYLIST + assert "CURSOR_TRACE_ID" in IDE_ENV_DENYLIST + assert "ZED_TERM" in IDE_ENV_DENYLIST + + +def test_ide_env_prefix_denylist_covers_ide_and_sse() -> None: + assert "CLAUDE_CODE_IDE_" in IDE_ENV_PREFIX_DENYLIST + assert "CLAUDE_CODE_SSE" in IDE_ENV_PREFIX_DENYLIST + + +def test_ide_env_always_extras_includes_auto_connect_off() -> None: + assert IDE_ENV_ALWAYS_EXTRAS["CLAUDE_CODE_AUTO_CONNECT_IDE"] == "0" + + +def test_ide_env_denylist_contains_max_mcp_output_tokens() -> None: + """MAX_MCP_OUTPUT_TOKENS must be in IDE_ENV_DENYLIST.""" + assert "MAX_MCP_OUTPUT_TOKENS" in IDE_ENV_DENYLIST + + +def test_build_claude_env_strips_max_mcp_output_tokens() -> None: + """MAX_MCP_OUTPUT_TOKENS must be stripped from base env by build_claude_env.""" + result = build_claude_env(base={"MAX_MCP_OUTPUT_TOKENS": "99999", "HOME": "/tmp"}) + assert "MAX_MCP_OUTPUT_TOKENS" not in result + assert result["HOME"] == "/tmp" diff --git a/tests/core/test_ensure_project_temp_with_config.py b/tests/core/test_ensure_project_temp_with_config.py new file mode 100644 index 0000000000..7652f02a79 --- /dev/null +++ b/tests/core/test_ensure_project_temp_with_config.py @@ -0,0 +1,63 @@ +"""Tests for ensure_project_temp with configurable override.""" + +from __future__ import annotations + +from pathlib import Path + +from autoskillit.core.io import ensure_project_temp + + +def test_ensure_project_temp_default_writes_self_gitignore(tmp_path: Path) -> None: + result = ensure_project_temp(tmp_path) + assert result == tmp_path / ".autoskillit" / "temp" + gitignore = result / ".gitignore" + assert gitignore.exists() + assert "*" in gitignore.read_text() + assert not (tmp_path / ".gitignore").exists() + + +def test_ensure_project_temp_relative_override_writes_self_gitignore( + tmp_path: Path, +) -> None: + result = ensure_project_temp(tmp_path, override="build/temp") + assert result == tmp_path / "build" / "temp" + gitignore = result / ".gitignore" + assert gitignore.exists() + assert "*" in gitignore.read_text() + assert not (tmp_path / ".gitignore").exists() + + +def test_ensure_project_temp_absolute_override_writes_self_gitignore( + tmp_path: Path, +) -> None: + abs_target = tmp_path / "external" / "scratch" + result = ensure_project_temp(tmp_path, override=str(abs_target)) + assert result == abs_target + gitignore = result / ".gitignore" + assert gitignore.exists() + assert "*" in gitignore.read_text() + assert not (tmp_path / ".gitignore").exists() + + +def test_ensure_project_temp_gitignore_written_before_other_content( + tmp_path: Path, +) -> None: + """The self-gitignore must exist immediately after ensure_project_temp returns, + even though no session content has been written yet.""" + result = ensure_project_temp(tmp_path) + children = sorted(p.name for p in result.iterdir()) + assert children == [".gitignore"], ( + f"only .gitignore should exist after ensure_project_temp: {children}" + ) + + +def test_ensure_project_temp_idempotent_on_existing_gitignore(tmp_path: Path) -> None: + target = tmp_path / ".autoskillit" / "temp" + target.mkdir(parents=True) + custom = "# custom user content\n*\n!keep.txt\n" + (target / ".gitignore").write_text(custom) + + ensure_project_temp(tmp_path) + ensure_project_temp(tmp_path) + + assert (target / ".gitignore").read_text() == custom diff --git a/tests/core/test_io.py b/tests/core/test_io.py index 880d8efa01..f8ba57ea85 100644 --- a/tests/core/test_io.py +++ b/tests/core/test_io.py @@ -99,25 +99,6 @@ def test_only_yaml_imports_yaml_directly(self): assert not violations, f"Direct yaml imports found outside core/io.py: {violations}" -# --------------------------------------------------------------------------- -# T1 — _parse_issue_ref importable from core -# --------------------------------------------------------------------------- - - -def test_parse_issue_ref_importable_from_core(): - from autoskillit.core import _parse_issue_ref - - owner, repo, number = _parse_issue_ref("https://github.com/acme/proj/issues/42") - assert owner == "acme" and repo == "proj" and number == 42 - - -def test_parse_issue_ref_not_in_io(): - import autoskillit.core.io as io_mod - - assert not hasattr(io_mod, "_parse_issue_ref") - assert "_parse_issue_ref" not in io_mod.__all__ - - def test_atomic_write_is_canonical_public_name(): """_atomic_write must not appear in core.io.__all__; atomic_write must.""" import autoskillit.core.io as io_mod @@ -137,3 +118,56 @@ def test_atomic_write_private_alias_removed(): import autoskillit.core.io as io_mod assert not hasattr(io_mod, "_atomic_write") + + +# --------------------------------------------------------------------------- +# write_versioned_json — schema version envelope helper +# --------------------------------------------------------------------------- + + +def test_write_versioned_json_enriches_payload_with_schema_version(tmp_path): + import json + + from autoskillit.core.io import write_versioned_json + + target = tmp_path / "f.json" + write_versioned_json(target, {"a": 1}, schema_version=2) + assert json.loads(target.read_text(encoding="utf-8")) == {"a": 1, "schema_version": 2} + + +def test_write_versioned_json_preserves_existing_keys_atomically(tmp_path, monkeypatch): + """Asserts the helper routes through ``atomic_write`` (no partial-file + fallout on a simulated mid-write crash).""" + import json + + from autoskillit.core import io as io_mod + from autoskillit.core.io import write_versioned_json + + calls: list[tuple[str, str]] = [] + real_atomic_write = io_mod.atomic_write + + def spy(path, content): + calls.append((str(path), content)) + return real_atomic_write(path, content) + + monkeypatch.setattr(io_mod, "atomic_write", spy) + + target = tmp_path / "nested.json" + payload = {"outer": {"inner": [1, 2, 3]}, "name": "demo"} + write_versioned_json(target, payload, schema_version=7) + + assert len(calls) == 1 + assert calls[0][0] == str(target) + decoded = json.loads(target.read_text(encoding="utf-8")) + assert decoded == {"outer": {"inner": [1, 2, 3]}, "name": "demo", "schema_version": 7} + + +def test_write_versioned_json_rejects_non_dict_payload(tmp_path): + import pytest + + from autoskillit.core.io import write_versioned_json + + target = tmp_path / "bad.json" + with pytest.raises(TypeError, match="dict payload"): + write_versioned_json(target, [1, 2, 3], schema_version=1) # type: ignore[arg-type] + assert not target.exists() diff --git a/tests/core/test_resolve_temp_dir.py b/tests/core/test_resolve_temp_dir.py new file mode 100644 index 0000000000..62e5acc35d --- /dev/null +++ b/tests/core/test_resolve_temp_dir.py @@ -0,0 +1,65 @@ +"""Tests for autoskillit.core.io.resolve_temp_dir.""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import pytest + +from autoskillit.core.io import resolve_temp_dir + + +def test_resolve_temp_dir_default_returns_project_relative() -> None: + assert resolve_temp_dir(Path("/proj"), None) == Path("/proj/.autoskillit/temp") + + +def test_resolve_temp_dir_relative_override_anchored_to_project() -> None: + assert resolve_temp_dir(Path("/proj"), ".build/scratch") == Path("/proj/.build/scratch") + + +def test_resolve_temp_dir_absolute_override_passthrough() -> None: + assert resolve_temp_dir(Path("/proj"), "/mnt/ramdisk/at") == Path("/mnt/ramdisk/at") + + +def test_resolve_temp_dir_empty_string_raises_value_error() -> None: + with pytest.raises(ValueError, match="empty string"): + resolve_temp_dir(Path("/proj"), "") + + +def test_resolve_temp_dir_no_autoskillit_imports() -> None: + """core.io must not transitively import any non-core autoskillit module. + + Runs in an isolated subprocess so the destructive ``sys.modules`` clear + cannot leak into other xdist tests sharing the same worker process. + """ + import subprocess + import textwrap + + script = textwrap.dedent( + """ + import sys + for m in list(sys.modules): + if m == "autoskillit" or m.startswith("autoskillit."): + del sys.modules[m] + import autoskillit.core.io # noqa: F401 + leaked = [ + m + for m in sys.modules + if m.startswith("autoskillit.") + and not m.startswith("autoskillit.core") + and m != "autoskillit" + ] + if leaked: + print("LEAKED:" + ",".join(sorted(leaked))) + sys.exit(1) + sys.exit(0) + """ + ) + result = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, f"core.io leaked imports outside core/: {result.stdout.strip()}" diff --git a/tests/core/test_types.py b/tests/core/test_types.py index 94d78b1823..49f9d7c276 100644 --- a/tests/core/test_types.py +++ b/tests/core/test_types.py @@ -7,6 +7,7 @@ from autoskillit.core.types import ( ChannelConfirmation, + CIRunScope, MergeFailedStep, MergeState, RestartScope, @@ -29,6 +30,7 @@ def test_retry_reason_values(): RetryReason.PATH_CONTAMINATION, RetryReason.CONTRACT_RECOVERY, RetryReason.STALE, + RetryReason.CLONE_CONTAMINATION, } assert RetryReason.NONE.value == "none" @@ -82,10 +84,12 @@ def test_channel_confirmation_values(): ChannelConfirmation.CHANNEL_A, ChannelConfirmation.CHANNEL_B, ChannelConfirmation.UNMONITORED, + ChannelConfirmation.DIR_MISSING, } assert ChannelConfirmation.CHANNEL_A.value == "channel_a" assert ChannelConfirmation.CHANNEL_B.value == "channel_b" assert ChannelConfirmation.UNMONITORED.value == "unmonitored" + assert ChannelConfirmation.DIR_MISSING.value == "dir_missing" def test_skill_command_prefix_constant_exists(): @@ -336,3 +340,66 @@ def test_run_managed_async_pty_mode_default_false(): sig = inspect.signature(run_managed_async) assert sig.parameters["pty_mode"].default is False + + +# --------------------------------------------------------------------------- +# CIRunScope event field +# --------------------------------------------------------------------------- + + +def test_ci_run_scope_event_field(): + """CIRunScope must accept and store an event field.""" + scope = CIRunScope(event="push") + assert scope.event == "push" + assert scope.workflow is None + assert scope.head_sha is None + + +def test_ci_run_scope_event_defaults_to_none(): + """CIRunScope.event defaults to None when not specified.""" + scope = CIRunScope() + assert scope.event is None + + +def test_pr_state_enum_members_are_locked(): + """PRState enum has exactly the expected members — prevents silent addition/removal.""" + from autoskillit.core.types import PRState + + assert set(PRState) == { + PRState.MERGED, + PRState.EJECTED, + PRState.EJECTED_CI_FAILURE, + PRState.STALLED, + PRState.DROPPED_HEALTHY, + PRState.TIMEOUT, + PRState.ERROR, + } + assert PRState.DROPPED_HEALTHY.value == "dropped_healthy" + + +class TestSkillResultCrashedFactory: + def test_crashed_returns_skill_result_with_correct_fields(self): + result = SkillResult.crashed( + exception=RuntimeError("boom"), + skill_command="/investigate test", + ) + assert result.success is False + assert result.subtype == "crashed" + assert result.is_error is True + assert result.exit_code == -1 + assert result.needs_retry is False + assert result.retry_reason == RetryReason.NONE + assert "RuntimeError: boom" in result.result + assert result.session_id == "" + assert result.stderr == "" + + def test_crashed_to_json_produces_valid_envelope(self): + result = SkillResult.crashed( + exception=RuntimeError("boom"), + skill_command="/investigate test", + ) + data = json.loads(result.to_json()) + assert "needs_retry" in data + assert "session_id" in data + assert "subtype" in data + assert data["subtype"] == "crashed" diff --git a/tests/core/test_types_structure.py b/tests/core/test_types_structure.py index fd4d3c9911..a7b967a579 100644 --- a/tests/core/test_types_structure.py +++ b/tests/core/test_types_structure.py @@ -12,10 +12,10 @@ def test_enums_importable_from_sub_module(): def test_protocols_importable_from_sub_module(): - from autoskillit.core._type_protocols import GatePolicy, HeadlessExecutor + from autoskillit.core._type_protocols import GateState, HeadlessExecutor - assert callable(GatePolicy) - assert GatePolicy.__module__ == "autoskillit.core._type_protocols" + assert callable(GateState) + assert GateState.__module__ == "autoskillit.core._type_protocols" assert callable(HeadlessExecutor) assert HeadlessExecutor.__module__ == "autoskillit.core._type_protocols" @@ -23,12 +23,13 @@ def test_protocols_importable_from_sub_module(): def test_types_hub_backward_compat(): """All symbols must still be importable from autoskillit.core.types.""" import dataclasses + from typing import Protocol as TypingProtocol from autoskillit.core.types import ( FREE_RANGE_TOOLS, GATED_TOOLS, FailureRecord, - GatePolicy, + GateState, HeadlessExecutor, LoadResult, RetryReason, @@ -40,13 +41,13 @@ def test_types_hub_backward_compat(): assert issubclass(RetryReason, str) # _type_enums — StrEnum assert dataclasses.is_dataclass(SubprocessResult) # _type_subprocess - assert callable(SubprocessRunner) # _type_subprocess — Protocol + assert issubclass(SubprocessRunner, TypingProtocol) # _type_subprocess — Protocol assert isinstance(GATED_TOOLS, frozenset) # _type_constants assert isinstance(FREE_RANGE_TOOLS, frozenset) # _type_constants assert dataclasses.is_dataclass(LoadResult) # _type_results assert dataclasses.is_dataclass(SkillResult) # _type_results assert dataclasses.is_dataclass(FailureRecord) # _type_results - assert callable(GatePolicy) # _type_protocols — Protocol + assert callable(GateState) # _type_protocols — Protocol assert callable(HeadlessExecutor) # _type_protocols — Protocol assert callable(extract_skill_name) # _type_helpers — function diff --git a/tests/docs/__init__.py b/tests/docs/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/docs/test_banned_phrases.py b/tests/docs/test_banned_phrases.py new file mode 100644 index 0000000000..a849236a15 --- /dev/null +++ b/tests/docs/test_banned_phrases.py @@ -0,0 +1,69 @@ +"""Reject AI-tone banned phrases in every doc. + +Phrases derived from REQ-DOC-070. Code spans (backticks), fenced blocks, +file paths, and quoted strings are stripped before matching so a literal +example cannot trigger a false positive. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[2] +DOCS_DIR = REPO_ROOT / "docs" +ROOT_README = REPO_ROOT / "README.md" + +BANNED_PHRASES = [ + r"under the hood", + r"sensible defaults", + r"fills in the rest", + r"best technical approach", + r"magically", + r"seamlessly", + r"effortlessly", + r"works like magic", + r"just works", + r"deep dive", + r"super easy", + r"out of the box", + r"battle[- ]tested", + r"painlessly", +] + +# Files exempt from banned-phrase checking. The glossary intentionally lists +# the canonical and banned spellings of every term it covers. +EXEMPT_FILES = {"glossary.md"} + +CODE_BLOCK_RE = re.compile(r"```.*?```", re.DOTALL) +INLINE_CODE_RE = re.compile(r"`[^`]*`") +QUOTED_RE = re.compile(r'"[^"]*"|\'[^\']*\'') + + +def _strip_examples(text: str) -> str: + text = CODE_BLOCK_RE.sub("", text) + text = INLINE_CODE_RE.sub("", text) + text = QUOTED_RE.sub("", text) + return text + + +def _doc_files() -> list[Path]: + files = [p for p in DOCS_DIR.rglob("*.md") if p.name not in EXEMPT_FILES] + if ROOT_README.exists(): + files.append(ROOT_README) + return sorted(files) + + +@pytest.mark.parametrize("md", _doc_files(), ids=lambda p: p.relative_to(REPO_ROOT).as_posix()) +def test_no_banned_phrases(md: Path) -> None: + text = _strip_examples(md.read_text(encoding="utf-8")) + hits: list[tuple[str, int]] = [] + for line_no, line in enumerate(text.splitlines(), start=1): + for phrase in BANNED_PHRASES: + if re.search(phrase, line, flags=re.IGNORECASE): + hits.append((phrase, line_no)) + assert not hits, f"{md.relative_to(REPO_ROOT)} contains banned phrases: " + ", ".join( + f"{phrase!r} on line {line}" for phrase, line in hits + ) diff --git a/tests/docs/test_doc_counts.py b/tests/docs/test_doc_counts.py new file mode 100644 index 0000000000..7746ba43fd --- /dev/null +++ b/tests/docs/test_doc_counts.py @@ -0,0 +1,330 @@ +"""Verify every numerical claim in every doc file matches source of truth. + +Each assertion reads the doc file(s) it covers and the source it derives from, +then compares. A failure prints which doc has the stale value and what the +canonical value is. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest +import yaml + +REPO_ROOT = Path(__file__).resolve().parents[2] +SRC_DIR = REPO_ROOT / "src" / "autoskillit" +DOCS_DIR = REPO_ROOT / "docs" +ROOT_README = REPO_ROOT / "README.md" +CLAUDE_MD = REPO_ROOT / "CLAUDE.md" + + +# ----- helpers ---------------------------------------------------------------- + + +def _read(path: Path) -> str: + return path.read_text(encoding="utf-8") + + +def _doc_files() -> list[Path]: + return sorted(DOCS_DIR.rglob("*.md")) + + +def _docs_containing(pattern: str) -> list[Path]: + rx = re.compile(pattern) + return [p for p in _doc_files() if rx.search(_read(p))] + + +# ----- canonical source-of-truth getters -------------------------------------- + + +def _count_mcp_tools() -> int: + total = 0 + for f in (SRC_DIR / "server").glob("tools_*.py"): + total += sum(1 for line in _read(f).splitlines() if line.strip().startswith("@mcp.tool")) + return total + + +def _count_kitchen_tools() -> int: + total = 0 + for f in (SRC_DIR / "server").glob("tools_*.py"): + text = _read(f) + for line in text.splitlines(): + if line.strip().startswith("@mcp.tool") and '"kitchen"' in line: + total += 1 + return total + + +def _count_free_range_tools() -> int: + total = 0 + for f in (SRC_DIR / "server").glob("tools_*.py"): + for line in _read(f).splitlines(): + stripped = line.strip() + if stripped.startswith("@mcp.tool") and '"kitchen"' not in stripped: + total += 1 + return total + + +def _count_headless_tools() -> int: + total = 0 + for f in (SRC_DIR / "server").glob("tools_*.py"): + for line in _read(f).splitlines(): + if line.strip().startswith("@mcp.tool") and '"headless"' in line: + total += 1 + return total + + +def _count_skills_total() -> int: + tier1 = sum(1 for p in (SRC_DIR / "skills").iterdir() if p.is_dir()) + tier23 = sum(1 for p in (SRC_DIR / "skills_extended").iterdir() if p.is_dir()) + return tier1 + tier23 + + +def _count_arch_lens_skills() -> int: + return sum( + 1 + for p in (SRC_DIR / "skills_extended").iterdir() + if p.is_dir() and p.name.startswith("arch-lens-") + ) + + +def _count_exp_lens_skills() -> int: + return sum( + 1 + for p in (SRC_DIR / "skills_extended").iterdir() + if p.is_dir() and p.name.startswith("exp-lens-") + ) + + +def _count_vis_lens_skills() -> int: + return sum( + 1 + for p in (SRC_DIR / "skills_extended").iterdir() + if p.is_dir() and p.name.startswith("vis-lens-") + ) + + +def _hook_files() -> list[Path]: + return sorted(f for f in (SRC_DIR / "hooks").glob("*.py") if f.name not in {"__init__.py"}) + + +def _count_hooks_by_event() -> dict[str, int]: + """Group unique hook scripts by their PreToolUse / PostToolUse / SessionStart event. + + Imports HOOK_REGISTRY and counts the distinct script files referenced by + each event type — duplicates (e.g. branch_protection_guard registered for + both merge_worktree and push_to_remote) collapse to a single entry. + """ + from autoskillit.hook_registry import HOOK_REGISTRY # local import to avoid hard dep + + by_event: dict[str, set[str]] = { + "PreToolUse": set(), + "PostToolUse": set(), + "SessionStart": set(), + } + for hook_def in HOOK_REGISTRY: + for script in hook_def.scripts: + by_event[hook_def.event_type].add(script) + return {event: len(scripts) for event, scripts in by_event.items()} + + +def _quota_thresholds_default() -> tuple[float, float]: + data = yaml.safe_load(_read(SRC_DIR / "config" / "defaults.yaml")) + quota = data.get("quota_guard") + assert quota is not None, "quota_guard key missing from config/defaults.yaml" + short = quota.get("short_window_threshold") + long_ = quota.get("long_window_threshold") + assert short is not None, ( + "quota_guard.short_window_threshold key missing from config/defaults.yaml" + ) + assert long_ is not None, ( + "quota_guard.long_window_threshold key missing from config/defaults.yaml" + ) + return float(short), float(long_) + + +def _count_doctor_checks() -> int: + """Count doctor checks inside ``run_doctor``: numbered + lettered sub-checks (4b, 7b). + + Helper functions earlier in the module use the same ``# Check N:`` comment + style for their internal sub-steps; we restrict the count to the body of + ``run_doctor`` so those comments do not double-count. + """ + text = _read(SRC_DIR / "cli" / "_doctor.py") + body = re.search(r"def run_doctor\(.*?\n((?: .*\n|\n)+)", text, re.DOTALL) + assert body, "run_doctor not found in _doctor.py" + body_text = body.group(1) + numbered = len(re.findall(r"# Check \d+:", body_text)) + lettered = len(re.findall(r"# Check \d+[a-z]:", body_text)) + return numbered + lettered + + +def _bundled_recipes() -> list[str]: + return sorted(p.stem for p in (SRC_DIR / "recipes").glob("*.yaml")) + + +def _retry_reason_values() -> list[str]: + text = _read(SRC_DIR / "core" / "_type_enums.py") + block = re.search(r"class RetryReason\(StrEnum\):(.*?)\nclass ", text, re.DOTALL) + assert block, "RetryReason enum not found" + return re.findall(r'"([a-z_]+)"', block.group(1)) + + +def _count_semantic_rule_files() -> int: + return sum(1 for p in (SRC_DIR / "recipe").glob("rules_*.py")) + + +# ----- tests ------------------------------------------------------------------ + + +def test_kitchen_tagged_tool_count_is_41() -> None: + assert _count_kitchen_tools() == 41, ( + f"Expected 41 kitchen-tagged tools; found {_count_kitchen_tools()}" + ) + + +def test_free_range_tool_count_is_3() -> None: + assert _count_free_range_tools() == 3, ( + f"Expected 3 free-range tools; found {_count_free_range_tools()}" + ) + + +def test_headless_tool_count_is_1() -> None: + assert _count_headless_tools() == 1, ( + f"Expected 1 headless-tagged tool; found {_count_headless_tools()}" + ) + + +def test_arch_lens_count_is_13() -> None: + assert _count_arch_lens_skills() == 13 + + +def test_exp_lens_count_is_18() -> None: + assert _count_exp_lens_skills() == 18 + + +def test_vis_lens_count_is_12() -> None: + assert _count_vis_lens_skills() == 12 + + +def test_quota_thresholds_defaults() -> None: + short, long_ = _quota_thresholds_default() + assert short == pytest.approx(85.0) + assert long_ == pytest.approx(98.0) + + +def test_doctor_check_count_is_22() -> None: + # _count_doctor_checks() counts every "# Check N:" and "# Check Nb:" marker + # in run_doctor() — 17 numbered base markers + 5 lettered sub-check markers + # (2b, 2c, 2d, 4b, 7b) = 22 total. test_installation_states_17_doctor_checks + # checks the *user-visible* count from docs/installation.md ("15 numbered + 2 + # lettered sub-checks 4b and 7b = 17"). The gap of 5 is intentional: Check 2, + # Check 4, and Check 7 each appear as separate implementation markers but the + # docs present them as single numbered entries that subsume their sub-variants. + # Update both tests whenever a new doctor check is added. + assert _count_doctor_checks() == 22, ( + f"Expected 22 doctor checks; found {_count_doctor_checks()}" + ) + + +def test_bundled_recipe_count_is_5() -> None: + recipes = _bundled_recipes() + expected = ["implementation", "implementation-groups", "merge-prs", "remediation", "research"] + assert recipes == expected, f"Recipes drifted: {recipes}" + + +def test_retry_reason_value_count_is_11() -> None: + values = _retry_reason_values() + assert len(values) == 11, f"RetryReason has {len(values)} values: {values}" + + +def test_semantic_rule_family_count_is_20() -> None: + assert _count_semantic_rule_files() == 20 + + +# ----- per-doc count assertions (run once docs exist) ------------------------- + + +def _assert_doc_states_number(doc: Path, label: str, expected: int) -> None: + if not doc.exists(): + pytest.skip(f"{doc.relative_to(REPO_ROOT)} not yet present") + text = _read(doc) + if not re.search(rf"\b{expected}\b", text): + pytest.fail(f"{doc.relative_to(REPO_ROOT)}: missing canonical {label}={expected}") + + +@pytest.mark.parametrize( + "doc_path", + [ + DOCS_DIR / "execution" / "architecture.md", + DOCS_DIR / "execution" / "tool-access.md", + ], +) +def test_docs_state_43_mcp_tools(doc_path: Path) -> None: + _assert_doc_states_number(doc_path, "MCP tools", 43) + + +@pytest.mark.parametrize( + "doc_path", + [ + DOCS_DIR / "execution" / "architecture.md", + DOCS_DIR / "execution" / "tool-access.md", + ], +) +def test_docs_state_41_kitchen_tools(doc_path: Path) -> None: + _assert_doc_states_number(doc_path, "kitchen tools", 41) + + +def test_skill_visibility_states_109_skills() -> None: + _assert_doc_states_number(DOCS_DIR / "skills" / "visibility.md", "skills total", 109) + + +def test_safety_hooks_states_13_hooks() -> None: + _assert_doc_states_number(DOCS_DIR / "safety" / "hooks.md", "hooks total", 13) + + +def test_configuration_states_quota_thresholds() -> None: + doc = DOCS_DIR / "configuration.md" + if not doc.exists(): + pytest.skip("docs/configuration.md not present") + text = _read(doc) + assert "85.0" in text, ( + "docs/configuration.md does not state quota_guard.short_window_threshold = 85.0" + ) + assert "98.0" in text, ( + "docs/configuration.md does not state quota_guard.long_window_threshold = 98.0" + ) + + +def test_installation_states_17_doctor_checks() -> None: + _assert_doc_states_number(DOCS_DIR / "installation.md", "doctor checks", 17) + + +def test_recipes_overview_states_5_recipes() -> None: + _assert_doc_states_number(DOCS_DIR / "recipes" / "overview.md", "bundled recipes", 5) + + +def test_orchestration_states_11_retry_reasons() -> None: + _assert_doc_states_number(DOCS_DIR / "execution" / "orchestration.md", "retry reasons", 11) + + +def test_authoring_states_17_rule_families() -> None: + _assert_doc_states_number(DOCS_DIR / "recipes" / "authoring.md", "rule families", 17) + + +def test_catalog_states_arch_and_exp_lens_counts() -> None: + catalog = DOCS_DIR / "skills" / "catalog.md" + if not catalog.exists(): + pytest.skip("docs/skills/catalog.md not present") + text = _read(catalog) + assert "13" in text, "skills/catalog.md does not state 13 arch-lens skills" + assert "18" in text, "skills/catalog.md does not state 18 exp-lens skills" + + +def test_catalog_states_vis_lens_count_is_12() -> None: + catalog = DOCS_DIR / "skills" / "catalog.md" + if not catalog.exists(): + pytest.skip("docs/skills/catalog.md not present") + text = _read(catalog) + assert "12" in text, "skills/catalog.md does not state 12 vis-lens skills" diff --git a/tests/docs/test_doc_index.py b/tests/docs/test_doc_index.py new file mode 100644 index 0000000000..f3142e8efa --- /dev/null +++ b/tests/docs/test_doc_index.py @@ -0,0 +1,121 @@ +"""Verify every doc is reachable from docs/README.md and every subdir has a README.""" + +from __future__ import annotations + +import re +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[2] +DOCS_DIR = REPO_ROOT / "docs" +DOCS_README = DOCS_DIR / "README.md" +ROOT_README = REPO_ROOT / "README.md" + +EXPECTED_SUBDIRS = { + "examples", + "recipes", + "skills", + "execution", + "safety", + "operations", + "developer", +} + +LINK_RE = re.compile(r"\[[^\]]*\]\(([^)#]+)(?:#[^)]*)?\)") + + +def _all_md_files() -> list[Path]: + return sorted(p for p in DOCS_DIR.rglob("*.md")) + + +def _links_in(md_path: Path) -> list[Path]: + """Return absolute resolved paths for every local .md link in md_path.""" + text = md_path.read_text(encoding="utf-8") + out: list[Path] = [] + for raw in LINK_RE.findall(text): + if raw.startswith(("http://", "https://", "mailto:")): + continue + if not raw.endswith(".md"): + continue + target = (md_path.parent / raw).resolve() + out.append(target) + return out + + +def test_docs_readme_exists() -> None: + assert DOCS_README.exists(), "docs/README.md is missing" + + +def test_every_subdirectory_has_readme() -> None: + missing = [] + for sub in EXPECTED_SUBDIRS: + readme = DOCS_DIR / sub / "README.md" + if not readme.exists(): + missing.append(str(readme.relative_to(REPO_ROOT))) + assert not missing, f"Missing subdirectory READMEs: {missing}" + + +def test_every_doc_reachable_from_index() -> None: + """BFS from docs/README.md through .md links; every docs/**.md must be visited.""" + if not DOCS_README.exists(): + import pytest + + pytest.skip("docs/README.md not present yet") + + visited: set[Path] = {DOCS_README.resolve()} + queue: list[Path] = [DOCS_README] + while queue: + current = queue.pop() + for link in _links_in(current): + if link in visited: + continue + if not link.exists() or link.suffix != ".md": + continue + try: + link.relative_to(DOCS_DIR.resolve()) + except ValueError: + continue + visited.add(link) + queue.append(link) + + expected = {p.resolve() for p in _all_md_files()} + unreachable = expected - visited + assert not unreachable, "Unreachable from docs/README.md: " + ", ".join( + sorted(p.relative_to(REPO_ROOT).as_posix() for p in unreachable) + ) + + +def test_subdir_readme_lists_each_sibling() -> None: + """Each subdirectory README must mention every sibling .md file by name.""" + for sub in EXPECTED_SUBDIRS: + sub_dir = DOCS_DIR / sub + if not sub_dir.exists(): + continue + readme = sub_dir / "README.md" + if not readme.exists(): + continue + readme_text = readme.read_text(encoding="utf-8") + siblings = sorted(p.name for p in sub_dir.glob("*.md") if p.name != "README.md") + for sib in siblings: + assert sib in readme_text, ( + f"{readme.relative_to(REPO_ROOT)} does not list sibling {sib}" + ) + + +def test_docs_readme_line_count_under_80() -> None: + if not DOCS_README.exists(): + import pytest + + pytest.skip("docs/README.md not present yet") + line_count = len(DOCS_README.read_text(encoding="utf-8").splitlines()) + assert line_count <= 80, f"docs/README.md has {line_count} lines (max 80)" + + +def test_root_readme_line_count_at_least_30() -> None: + if not ROOT_README.exists(): + import pytest + + pytest.skip("README.md not present yet") + line_count = len(ROOT_README.read_text(encoding="utf-8").splitlines()) + assert line_count >= 30, ( + f"README.md has {line_count} lines (expected >= 30 to guard against accidental truncation)" + ) diff --git a/tests/docs/test_doc_links.py b/tests/docs/test_doc_links.py new file mode 100644 index 0000000000..5147fb5538 --- /dev/null +++ b/tests/docs/test_doc_links.py @@ -0,0 +1,110 @@ +"""Verify every local markdown link resolves and no old flat-layout link survives. + +The four `spectral-init` archive PR pairs in +``docs/examples/research-pipeline.md`` are checked against an explicit +allowlist so the example never silently loses one. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[2] +DOCS_DIR = REPO_ROOT / "docs" +ROOT_README = REPO_ROOT / "README.md" +CLAUDE_MD = REPO_ROOT / "CLAUDE.md" + +LINK_RE = re.compile(r"\[[^\]]*\]\(([^)]+)\)") + +# Old flat-layout paths that must never appear in any link. +FORBIDDEN_OLD_PATHS = { + "docs/recipes.md", + "docs/sub-recipe-composition.md", + "docs/skill-visibility.md", + "docs/project-local-overrides.md", + "docs/subset-categories.md", + "docs/architecture.md", + "docs/mcp-tool-access.md", + "docs/hooks-and-safety.md", + "docs/cli-reference.md", + "docs/developer/session-diagnostics.md", + # In-subdirectory bare names that map to old flat layout: + "recipes.md", + "sub-recipe-composition.md", + "skill-visibility.md", + "project-local-overrides.md", + "subset-categories.md", + "mcp-tool-access.md", + "hooks-and-safety.md", + "cli-reference.md", + "session-diagnostics.md", +} + +# Spectral-init research/archive PR allowlist for the examples doc. Each entry +# must appear at least once in research-pipeline.md. +SPECTRAL_INIT_ALLOWLIST = [ + "https://github.com/TalonT-Org/spectral-init/pull/233", + "https://github.com/TalonT-Org/spectral-init/pull/234", + "https://github.com/TalonT-Org/spectral-init/pull/238", + "https://github.com/TalonT-Org/spectral-init/pull/239", + "https://github.com/TalonT-Org/spectral-init/pull/256", + "https://github.com/TalonT-Org/spectral-init/pull/257", + "https://github.com/TalonT-Org/spectral-init/pull/263", + "https://github.com/TalonT-Org/spectral-init/pull/264", + "https://github.com/TalonT-Org/spectral-init/tree/main/research/2026-03-baseline", + "https://github.com/TalonT-Org/spectral-init/tree/main/research/2026-03-comparator", + "https://github.com/TalonT-Org/spectral-init/tree/main/research/2026-03-variance", + "https://github.com/TalonT-Org/spectral-init/tree/main/research/2026-04-sensitivity", +] + + +def _all_md_files() -> list[Path]: + files: list[Path] = list(DOCS_DIR.rglob("*.md")) + if ROOT_README.exists(): + files.append(ROOT_README) + return sorted(files) + + +def _link_targets(md: Path) -> list[str]: + return LINK_RE.findall(md.read_text(encoding="utf-8")) + + +@pytest.mark.parametrize("md", _all_md_files(), ids=lambda p: p.relative_to(REPO_ROOT).as_posix()) +def test_local_links_resolve(md: Path) -> None: + failures: list[str] = [] + for raw in _link_targets(md): + if raw.startswith(("http://", "https://", "mailto:", "#")): + continue + target = raw.split("#", 1)[0] + if not target or not target.endswith(".md"): + continue + resolved = (md.parent / target).resolve() + if not resolved.exists(): + failures.append(f"broken link {raw} -> {resolved}") + assert not failures, f"{md.relative_to(REPO_ROOT)}:\n " + "\n ".join(failures) + + +@pytest.mark.parametrize("md", _all_md_files(), ids=lambda p: p.relative_to(REPO_ROOT).as_posix()) +def test_no_old_flat_layout_links(md: Path) -> None: + bad: list[str] = [] + for raw in _link_targets(md): + if raw.startswith(("http://", "https://", "mailto:", "#")): + continue + target = raw.split("#", 1)[0] + # Strip leading ./ and ../ to compare against forbidden bare names. + normalised = target.lstrip("./") + if normalised in FORBIDDEN_OLD_PATHS: + bad.append(raw) + assert not bad, f"{md.relative_to(REPO_ROOT)} links to forbidden old paths: {bad}" + + +def test_spectral_init_allowlist_present() -> None: + examples = DOCS_DIR / "examples" / "research-pipeline.md" + if not examples.exists(): + pytest.skip("research-pipeline.md not present") + text = examples.read_text(encoding="utf-8") + missing = [url for url in SPECTRAL_INIT_ALLOWLIST if url not in text] + assert not missing, f"research-pipeline.md missing allowlisted URLs: {missing}" diff --git a/tests/docs/test_filename_naming.py b/tests/docs/test_filename_naming.py new file mode 100644 index 0000000000..413bbd0edd --- /dev/null +++ b/tests/docs/test_filename_naming.py @@ -0,0 +1,83 @@ +"""Encode the 7 naming rules from REQ-DOC-085 as predicates over docs/ filenames.""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[2] +DOCS_DIR = REPO_ROOT / "docs" + +KEBAB_RE = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*\.md$") + +# Files allow-listed against specific rules. Each entry: rule -> {filenames}. +ALLOWLIST = { + "ing_suffix": {"getting-started.md", "contributing.md", "authoring.md"}, + "segment_count": {"getting-started.md", "end-turn-hazards.md", "research-pipeline.md"}, +} + +# overrides.md is a list-like file (collection of override sites) and is exempt; +# subsets.md and catalog.md are explicitly list files per REQ-DOC-085 rule 5. +CONCEPT_FILES_MUST_BE_SINGULAR = { + "visibility", + "composition", + "architecture", + "orchestration", +} + + +def _all_md_files() -> list[Path]: + return sorted(p for p in DOCS_DIR.rglob("*.md") if p.name != "README.md") + + +@pytest.mark.parametrize("md", _all_md_files(), ids=lambda p: p.relative_to(REPO_ROOT).as_posix()) +def test_rule_1_kebab_case(md: Path) -> None: + assert KEBAB_RE.match(md.name), f"{md.name} is not kebab-case" + + +@pytest.mark.parametrize("md", _all_md_files(), ids=lambda p: p.relative_to(REPO_ROOT).as_posix()) +def test_rule_2_noun_phrase(md: Path) -> None: + if md.name in ALLOWLIST["ing_suffix"]: + return + stem = md.stem + assert not stem.endswith("ing"), f"{md.name} ends in -ing (verb form)" + + +@pytest.mark.parametrize("md", _all_md_files(), ids=lambda p: p.relative_to(REPO_ROOT).as_posix()) +def test_rule_3_drop_topic_prefix_in_subdirs(md: Path) -> None: + parent = md.parent.name + if parent in {"recipes", "skills", "execution", "safety", "operations"}: + first_segment = md.stem.split("-", 1)[0] + assert first_segment != parent, ( + f"{md.relative_to(REPO_ROOT)}: filename starts with parent dir name '{parent}'" + ) + + +@pytest.mark.parametrize("md", _all_md_files(), ids=lambda p: p.relative_to(REPO_ROOT).as_posix()) +def test_rule_4_max_three_segments(md: Path) -> None: + if md.name in ALLOWLIST["segment_count"]: + return + segments = md.stem.split("-") + assert len(segments) <= 3, f"{md.name} has {len(segments)} kebab segments (max 3)" + + +@pytest.mark.parametrize("md", _all_md_files(), ids=lambda p: p.relative_to(REPO_ROOT).as_posix()) +def test_rule_5_singular_for_concepts(md: Path) -> None: + if md.stem in CONCEPT_FILES_MUST_BE_SINGULAR: + assert not md.stem.endswith("s"), f"{md.name} is a concept file but uses plural form" + + +@pytest.mark.parametrize("md", _all_md_files(), ids=lambda p: p.relative_to(REPO_ROOT).as_posix()) +def test_rule_6_no_coordinating_conjunctions(md: Path) -> None: + assert "-and-" not in md.stem, f"{md.name} contains -and-" + assert "-or-" not in md.stem, f"{md.name} contains -or-" + + +@pytest.mark.parametrize("md", _all_md_files(), ids=lambda p: p.relative_to(REPO_ROOT).as_posix()) +def test_rule_7_no_mcp_prefix_in_execution(md: Path) -> None: + if md.parent.name == "execution": + assert not md.stem.startswith("mcp-"), ( + f"{md.relative_to(REPO_ROOT)}: starts with redundant 'mcp-' prefix" + ) diff --git a/tests/docs/test_glossary_spelling.py b/tests/docs/test_glossary_spelling.py new file mode 100644 index 0000000000..62e32f6d08 --- /dev/null +++ b/tests/docs/test_glossary_spelling.py @@ -0,0 +1,66 @@ +"""Reject banned variants of glossary terms across every doc. + +The glossary itself is exempt because it intentionally lists each canonical +form alongside its common-mistake variants. +""" + +from __future__ import annotations + +import re +from pathlib import Path + +import pytest + +REPO_ROOT = Path(__file__).resolve().parents[2] +DOCS_DIR = REPO_ROOT / "docs" +GLOSSARY = DOCS_DIR / "glossary.md" + +# Each entry: (banned regex, canonical form). Matching is case-insensitive +# unless the regex carries an explicit flag. +BANNED_VARIANTS: list[tuple[str, str]] = [ + (r"free-range tool", "free range tools"), + (r"sous chef\b", "sous-chef"), + (r"\bRecify\b", "Rectify"), + (r"\bwork tree\b", "worktree"), + (r"\btier-1\b", "Tier 1"), + (r"\btier-2\b", "Tier 2"), + (r"\btier-3\b", "Tier 3"), + (r"retry reason\b", "retry_reason"), +] + +CODE_BLOCK_RE = re.compile(r"```.*?```", re.DOTALL) +INLINE_CODE_RE = re.compile(r"`[^`]*`") + + +def _strip_examples(text: str) -> str: + text = CODE_BLOCK_RE.sub("", text) + text = INLINE_CODE_RE.sub("", text) + return text + + +def _doc_files() -> list[Path]: + return sorted(p for p in DOCS_DIR.rglob("*.md") if p.name != "glossary.md") + + +def test_glossary_exists() -> None: + assert GLOSSARY.exists(), "docs/glossary.md is missing" + + +def test_glossary_has_at_least_17_terms() -> None: + if not GLOSSARY.exists(): + pytest.skip("glossary not present") + headings = re.findall(r"^### .+$", GLOSSARY.read_text(encoding="utf-8"), flags=re.MULTILINE) + assert len(headings) >= 17, f"Glossary has {len(headings)} terms (need >= 17)" + + +@pytest.mark.parametrize("md", _doc_files(), ids=lambda p: p.relative_to(REPO_ROOT).as_posix()) +def test_no_banned_variants(md: Path) -> None: + text = _strip_examples(md.read_text(encoding="utf-8")) + hits: list[tuple[str, str, int]] = [] + for line_no, line in enumerate(text.splitlines(), start=1): + for pat, canonical in BANNED_VARIANTS: + if re.search(pat, line, flags=re.IGNORECASE): + hits.append((pat, canonical, line_no)) + assert not hits, f"{md.relative_to(REPO_ROOT)} contains banned variants: " + ", ".join( + f"/{pat}/ (use {canonical!r}) on line {line}" for pat, canonical, line in hits + ) diff --git a/tests/execution/conftest.py b/tests/execution/conftest.py new file mode 100644 index 0000000000..921d173ec8 --- /dev/null +++ b/tests/execution/conftest.py @@ -0,0 +1,69 @@ +"""Shared fixtures and helpers for tests/execution/.""" + +from __future__ import annotations + +import pathlib +import textwrap +from typing import Any + +import pytest + +from autoskillit.config.settings import LinuxTracingConfig + +# Simulates Claude CLI process that writes a result line then hangs. +# Used by test_process_channel_b.py and test_process_monitor.py. +WRITE_RESULT_THEN_HANG_SCRIPT = textwrap.dedent("""\ + import sys, time, json + result = {"type": "result", "subtype": "success", "is_error": False, + "result": "done", "session_id": "s1"} + sys.stdout.write(json.dumps(result, separators=(",", ":")) + "\\n") + sys.stdout.flush() + time.sleep(3600) +""") + +# Shared helper script used by PTY-tracing and session-log integration tests. +# Allocates 60 MB resident memory then sleeps so the tracer can observe it. +_ALLOCATE_60MB_SCRIPT = """\ +import time +data = bytearray(60 * 1024 * 1024) # 60 MB resident allocation +time.sleep(3) +""" + + +@pytest.fixture +def isolated_tracing_config(tmp_path: pathlib.Path) -> LinuxTracingConfig: + """Pre-isolated LinuxTracingConfig for tracing tests. + Always writes to a tmp_path subdir, never to the real /dev/shm. + Use this fixture for all new tests that need a LinuxTracingConfig.""" + shm = tmp_path / "shm" + shm.mkdir(parents=True, exist_ok=True) + return LinuxTracingConfig(enabled=True, proc_interval=0.05, tmpfs_path=str(shm)) + + +@pytest.fixture +def merge_group_only_repo_state() -> dict[str, Any]: + """A fixture modelling a repo whose CI only triggers on merge_group. + + Forces the merge-group-only scenario to exist as a first-class test input. + Used by reachability tests and test_check_repo_merge_state_returns_merge_group_as_ci_event. + """ + return { + "graphql_response": { + "data": { + "repository": { + "mergeQueue": None, + "autoMergeAllowed": True, + "object": { + "entries": [ + { + "name": "tests.yml", + "object": {"text": "on: [merge_group]\njobs: {}"}, + }, + ] + }, + } + } + }, + "rest_completed_runs": {"workflow_runs": []}, + "rest_active_runs": {"workflow_runs": []}, + } diff --git a/tests/execution/test_anomaly_detection.py b/tests/execution/test_anomaly_detection.py index f181254546..ff7bdcd4d1 100644 --- a/tests/execution/test_anomaly_detection.py +++ b/tests/execution/test_anomaly_detection.py @@ -2,7 +2,10 @@ from __future__ import annotations +import pytest + from autoskillit.execution.anomaly_detection import ( + BENIGN_WCHANS, AnomalyKind, AnomalySeverity, detect_anomalies, @@ -23,6 +26,7 @@ def _snap( wchan: str = "", ctx_switches_voluntary: int = 500, ctx_switches_involuntary: int = 20, + cpu_percent: float = 0.0, ) -> dict[str, object]: return { "state": state, @@ -37,6 +41,7 @@ def _snap( "wchan": wchan, "ctx_switches_voluntary": ctx_switches_voluntary, "ctx_switches_involuntary": ctx_switches_involuntary, + "cpu_percent": cpu_percent, } @@ -137,3 +142,192 @@ def test_anomaly_record_structure(): assert "detail" in anomaly assert "snapshot" in anomaly assert anomaly["pid"] == 1234 + + +# --------------------------------------------------------------------------- +# REQ-ENUM-001, REQ-ENUM-002 +# --------------------------------------------------------------------------- + + +def test_anomaly_kind_has_d_state_sustained(): + """AnomalyKind.D_STATE_SUSTAINED is defined with the correct string value.""" + assert AnomalyKind.D_STATE_SUSTAINED == "d_state_sustained" + + +def test_anomaly_kind_has_high_cpu_sustained(): + """AnomalyKind.HIGH_CPU_SUSTAINED is defined with the correct string value.""" + assert AnomalyKind.HIGH_CPU_SUSTAINED == "high_cpu_sustained" + + +def test_benign_wchans_is_central_frozenset(): + """BENIGN_WCHANS is a frozenset containing the three issue-cited values.""" + assert isinstance(BENIGN_WCHANS, frozenset) + assert "do_nanosleep" in BENIGN_WCHANS + assert "do_epoll_wait" in BENIGN_WCHANS + assert "schedule_hrtimeout_range" in BENIGN_WCHANS + + +def test_d_state_sustained_fires_on_two_consecutive(): + """Two consecutive disk-sleep snapshots with a non-benign wchan fire exactly one anomaly.""" + snaps = [ + _snap(state="disk-sleep", wchan="ext4_file_write_iter"), + _snap(state="disk-sleep", wchan="ext4_file_write_iter"), + ] + anomalies = detect_anomalies(snaps, pid=999) + d_state = [a for a in anomalies if a["kind"] == AnomalyKind.D_STATE_SUSTAINED] + assert len(d_state) == 1 + assert d_state[0]["seq"] == 1 + + +def test_d_state_sustained_no_fire_on_single_snapshot(): + """A single disk-sleep snapshot yields zero D_STATE_SUSTAINED anomalies.""" + snaps = [_snap(state="disk-sleep", wchan="ext4_file_write_iter")] + anomalies = detect_anomalies(snaps, pid=999) + d_state = [a for a in anomalies if a["kind"] == AnomalyKind.D_STATE_SUSTAINED] + assert len(d_state) == 0 + + +def test_d_state_sustained_counter_resets_on_intervening_sleep(): + """Sequence [disk-sleep, sleeping, disk-sleep] yields zero D_STATE_SUSTAINED anomalies.""" + snaps = [ + _snap(state="disk-sleep", wchan="ext4_file_write_iter"), + _snap(state="sleeping"), + _snap(state="disk-sleep", wchan="ext4_file_write_iter"), + ] + anomalies = detect_anomalies(snaps, pid=999) + d_state = [a for a in anomalies if a["kind"] == AnomalyKind.D_STATE_SUSTAINED] + assert len(d_state) == 0 + + +# --------------------------------------------------------------------------- +# REQ-WCHAN-002, REQ-TEST-005 — benign wchans are skipped +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("wchan", ["do_nanosleep", "do_epoll_wait", "schedule_hrtimeout_range"]) +def test_d_state_sustained_benign_wchan_skipped(wchan: str) -> None: + """Two disk-sleep snapshots with a benign wchan yield no D_STATE_SUSTAINED anomaly.""" + snaps = [ + _snap(state="disk-sleep", wchan=wchan), + _snap(state="disk-sleep", wchan=wchan), + ] + anomalies = detect_anomalies(snaps, pid=999) + d_state = [a for a in anomalies if a["kind"] == AnomalyKind.D_STATE_SUSTAINED] + assert len(d_state) == 0 + + +def test_d_state_sustained_detail_includes_wchan(): + """The emitted D_STATE_SUSTAINED anomaly detail contains the triggering wchan value.""" + wchan_val = "ext4_file_write_iter" + snaps = [ + _snap(state="disk-sleep", wchan=wchan_val), + _snap(state="disk-sleep", wchan=wchan_val), + ] + anomalies = detect_anomalies(snaps, pid=999) + d_state = [a for a in anomalies if a["kind"] == AnomalyKind.D_STATE_SUSTAINED] + assert len(d_state) == 1 + assert d_state[0]["detail"]["wchan"] == wchan_val + + +def test_high_cpu_sustained_fires_on_two_consecutive(): + """Two consecutive snapshots with cpu_percent=95.0 produce exactly one HIGH_CPU_SUSTAINED.""" + snaps = [_snap(cpu_percent=95.0), _snap(cpu_percent=95.0)] + anomalies = detect_anomalies(snaps, pid=999) + high_cpu = [a for a in anomalies if a["kind"] == AnomalyKind.HIGH_CPU_SUSTAINED] + assert len(high_cpu) == 1 + + +def test_high_cpu_sustained_no_fire_on_single_snapshot(): + """A single high-CPU snapshot yields zero HIGH_CPU_SUSTAINED anomalies.""" + snaps = [_snap(cpu_percent=95.0)] + anomalies = detect_anomalies(snaps, pid=999) + high_cpu = [a for a in anomalies if a["kind"] == AnomalyKind.HIGH_CPU_SUSTAINED] + assert len(high_cpu) == 0 + + +def test_high_cpu_sustained_fires_at_exact_threshold(): + """cpu_percent=90.0 fires; cpu_percent=89.9 does not.""" + snaps_at = [_snap(cpu_percent=90.0), _snap(cpu_percent=90.0)] + anomalies_at = detect_anomalies(snaps_at, pid=999) + high_cpu_at = [a for a in anomalies_at if a["kind"] == AnomalyKind.HIGH_CPU_SUSTAINED] + assert len(high_cpu_at) == 1 + + snaps_below = [_snap(cpu_percent=89.9), _snap(cpu_percent=89.9)] + anomalies_below = detect_anomalies(snaps_below, pid=999) + high_cpu_below = [a for a in anomalies_below if a["kind"] == AnomalyKind.HIGH_CPU_SUSTAINED] + assert len(high_cpu_below) == 0 + + +def test_high_cpu_sustained_counter_resets_on_intervening_idle(): + """Sequence [95%, 10%, 95%] yields zero HIGH_CPU_SUSTAINED anomalies.""" + snaps = [_snap(cpu_percent=95.0), _snap(cpu_percent=10.0), _snap(cpu_percent=95.0)] + anomalies = detect_anomalies(snaps, pid=999) + high_cpu = [a for a in anomalies if a["kind"] == AnomalyKind.HIGH_CPU_SUSTAINED] + assert len(high_cpu) == 0 + + +def test_high_cpu_sustained_detail_includes_cpu_percent(): + """The emitted HIGH_CPU_SUSTAINED anomaly detail contains the cpu_percent value.""" + snaps = [_snap(cpu_percent=95.5), _snap(cpu_percent=95.5)] + anomalies = detect_anomalies(snaps, pid=999) + high_cpu = [a for a in anomalies if a["kind"] == AnomalyKind.HIGH_CPU_SUSTAINED] + assert len(high_cpu) == 1 + assert high_cpu[0]["detail"]["cpu_percent"] == 95.5 + + +# --------------------------------------------------------------------------- +# Test 1.7 — Anomaly-detection liveness canary +# --------------------------------------------------------------------------- + + +def test_anomaly_canary_fires_on_synthetic_stream(): + """detect_anomalies fires OOM_CRITICAL on a stream with oom_score=100→900 spike. + + Test 1.7: liveness canary — fails loudly if anomaly detection is silently gutted. + Universal anomaly_count==0 across production sessions was unreadable before #806. + """ + snaps = [ + _snap(oom_score=100), + _snap(oom_score=900), # exceeds OOM_CRITICAL threshold (>=800) + ] + anomalies = detect_anomalies(snaps, pid=999) + oom_critical = [a for a in anomalies if a["kind"] == AnomalyKind.OOM_CRITICAL] + assert len(oom_critical) >= 1, ( + "detect_anomalies must fire OOM_CRITICAL when oom_score >= 800. " + "If this test fails, anomaly detection has been silently disabled." + ) + + +# --------------------------------------------------------------------------- +# Test 1.8 — Identity-drift detection fires when comm disagrees +# --------------------------------------------------------------------------- + + +def test_identity_drift_anomaly_fires_when_comm_mismatches(): + """detect_identity_drift fires IDENTITY_DRIFT when snap.comm != expected_comm. + + Test 1.8: architectural immunity check. If PTY wrapping ever bypasses the + resolver, the drift detector surfaces it rather than letting it rot for months. + """ + from autoskillit.execution.anomaly_detection import AnomalyKind, detect_identity_drift + + # Use plain dicts (as flush_session_log passes to detect_anomalies) + # Simulate: expected process is 'claude' but every snapshot has comm='script' + snap_dicts = [{"comm": "script", "vm_rss_kb": 2048, "oom_score": 10} for _ in range(2)] + anomalies = detect_identity_drift(snap_dicts, expected_comm="claude") + assert len(anomalies) >= 1, ( + "detect_identity_drift must fire when snap.comm != expected_comm. " + "This is the architectural immunity check for PTY wrapper tracer drift." + ) + drift_anomalies = [a for a in anomalies if a["kind"] == AnomalyKind.IDENTITY_DRIFT] + assert drift_anomalies, ( + f"Expected IDENTITY_DRIFT anomaly kind. Got: {[a['kind'] for a in anomalies]}" + ) + + +def test_identity_drift_kind_exists(): + """AnomalyKind.IDENTITY_DRIFT must exist as a StrEnum member.""" + assert hasattr(AnomalyKind, "IDENTITY_DRIFT"), ( + "AnomalyKind must have IDENTITY_DRIFT member for PTY wrapper drift detection" + ) + assert AnomalyKind.IDENTITY_DRIFT == "identity_drift" diff --git a/tests/execution/test_check_repo_merge_state.py b/tests/execution/test_check_repo_merge_state.py new file mode 100644 index 0000000000..4bef40b87c --- /dev/null +++ b/tests/execution/test_check_repo_merge_state.py @@ -0,0 +1,157 @@ +"""Round-trip budget tests for fetch_repo_merge_state. + +Mirrors test_single_graphql_call_per_poll_cycle at the consolidated-tool layer. +All three booleans (queue_available, merge_group_trigger, auto_merge_available) +must come from a single HTTP round-trip to the GitHub GraphQL endpoint. +""" + +from __future__ import annotations + +import pytest + +from autoskillit.execution.merge_queue import fetch_repo_merge_state + +# Reminder: fetch_repo_merge_state now returns ci_event in addition to the +# three boolean fields. Tests below check for the ci_event field explicitly. + + +@pytest.mark.anyio +async def test_check_repo_merge_state_uses_single_graphql_call(httpx_mock): + """All three booleans come from one HTTP round-trip. + + Mirrors test_single_graphql_call_per_poll_cycle but at the MCP-tool layer. + """ + httpx_mock.add_response( + url="https://api.github.com/graphql", + json={ + "data": { + "repository": { + "mergeQueue": None, + "autoMergeAllowed": True, + "object": { + "entries": [ + { + "name": "tests.yml", + "object": {"text": "on: [push, merge_group]"}, + }, + ] + }, + } + } + }, + ) + result = await fetch_repo_merge_state(owner="o", repo="r", branch="main", token=None) + assert result["queue_available"] is False + assert result["merge_group_trigger"] is True + assert result["auto_merge_available"] is True + # ci_event: both push and merge_group present — prefer push for historical compat + assert result["ci_event"] == "push" + assert len(httpx_mock.get_requests()) == 1 # NOT 3, NOT N+2 + + +@pytest.mark.anyio +async def test_check_repo_merge_state_handles_null_blob_text(httpx_mock): + """Blob.text is null for binary files / files >512KB. Must treat as 'no match'.""" + httpx_mock.add_response( + url="https://api.github.com/graphql", + json={ + "data": { + "repository": { + "mergeQueue": {"id": "MQ_abc"}, + "autoMergeAllowed": False, + "object": { + "entries": [ + {"name": "tests.yml", "object": {"text": None}}, + ] + }, + } + } + }, + ) + result = await fetch_repo_merge_state(owner="o", repo="r", branch="main", token=None) + assert result["merge_group_trigger"] is False + assert result["queue_available"] is True + assert result["ci_event"] is None # no parseable trigger in null blobs + + +@pytest.mark.anyio +async def test_check_repo_merge_state_handles_missing_workflows_dir(httpx_mock): + """object is null when .github/workflows does not exist. + + merge_group_trigger must be false, not an error. + """ + httpx_mock.add_response( + url="https://api.github.com/graphql", + json={ + "data": { + "repository": { + "mergeQueue": None, + "autoMergeAllowed": False, + "object": None, + } + } + }, + ) + result = await fetch_repo_merge_state(owner="o", repo="r", branch="main", token=None) + assert result["merge_group_trigger"] is False + assert result["queue_available"] is False + assert result["ci_event"] is None # null object → no workflows → no trigger + + +def test_repo_state_query_is_distinct_module_constant_from_pr_state_query(): + """_REPO_STATE_QUERY and _QUERY must be distinct module-level constants. + + Prevents a future DRY refactor from merging them (they operate on different + scopes: repo-level vs. PR-level). + """ + from autoskillit.execution import merge_queue + + assert hasattr(merge_queue, "_REPO_STATE_QUERY") + assert hasattr(merge_queue, "_QUERY") + assert merge_queue._REPO_STATE_QUERY is not merge_queue._QUERY + assert "mergeQueue(branch" in merge_queue._REPO_STATE_QUERY + assert "autoMergeAllowed" in merge_queue._REPO_STATE_QUERY + assert "object(expression:" in merge_queue._REPO_STATE_QUERY + + +@pytest.mark.anyio +async def test_check_repo_merge_state_returns_merge_group_as_ci_event( + httpx_mock, merge_group_only_repo_state +): + """check_repo_merge_state must derive ci_event='merge_group' when the only + workflow trigger is merge_group. This capture is what ci_watch reads to avoid + the event='push' timeout on repos that only trigger on merge_group.""" + httpx_mock.add_response( + url="https://api.github.com/graphql", + json=merge_group_only_repo_state["graphql_response"], + ) + result = await fetch_repo_merge_state(owner="o", repo="r", branch="main", token=None) + assert result["ci_event"] == "merge_group" + assert result["merge_group_trigger"] is True + + +@pytest.mark.anyio +async def test_check_repo_merge_state_returns_null_ci_event_for_no_trigger(httpx_mock): + """When no push or merge_group trigger is found (e.g. schedule-only), ci_event + must be None — the ci.py default (scope.event=None) matches any trigger.""" + httpx_mock.add_response( + url="https://api.github.com/graphql", + json={ + "data": { + "repository": { + "mergeQueue": None, + "autoMergeAllowed": False, + "object": { + "entries": [ + { + "name": "nightly.yml", + "object": {"text": "on:\n schedule:\n - cron: '0 0 * * *'"}, + }, + ] + }, + } + } + }, + ) + result = await fetch_repo_merge_state(owner="o", repo="r", branch="main", token=None) + assert result["ci_event"] is None diff --git a/tests/execution/test_ci.py b/tests/execution/test_ci.py index 909a8f2358..4b62e2ddc9 100644 --- a/tests/execution/test_ci.py +++ b/tests/execution/test_ci.py @@ -25,6 +25,7 @@ def _run( status: str = "completed", conclusion: str = "success", head_sha: str = "abc123", + event: str = "push", updated_at: str | None = None, ) -> dict: """Build a mock workflow run dict.""" @@ -33,6 +34,7 @@ def _run( "status": status, "conclusion": conclusion, "head_sha": head_sha, + "event": event, "updated_at": updated_at or _NOW.isoformat(), } @@ -51,16 +53,18 @@ def _jobs_response(*jobs: tuple[str, str]) -> dict: # --------------------------------------------------------------------------- -def test_jittered_sleep_bounded(): - for attempt in range(10): - val = _jittered_sleep(attempt) - assert 0 <= val <= 30 # cap is 30 +@pytest.mark.parametrize("attempt", range(10)) +def test_jittered_sleep_bounded(attempt: int) -> None: + val = _jittered_sleep(attempt) + assert 0 <= val <= 30 # cap is 30 def test_jittered_sleep_variance(): """Two calls should not produce identical results (statistical check).""" - values = {_jittered_sleep(2) for _ in range(20)} - assert len(values) > 1 + values = [_jittered_sleep(2) for _ in range(20)] + assert max(values) - min(values) > 1.0, ( + "Jitter variance is too low — values are nearly constant" + ) # --------------------------------------------------------------------------- @@ -151,8 +155,14 @@ async def test_lookback_without_head_sha_matches_any(): @pytest.mark.anyio -async def test_lookback_window_filters_old_runs(): - """Runs older than lookback_seconds should be filtered by the service.""" +async def test_wait_returns_no_runs_when_fetch_returns_empty(): + """wait() returns no_runs or timed_out when _fetch_completed_runs returns []. + + _fetch_completed_runs is mocked to return [] (no completed runs found). + asyncio.sleep is mocked to return immediately. With timeout_seconds=1 the + test may exit via either "no_runs" (poll exhausted) or "timed_out" + (wall-clock exceeded); both are valid outcomes for this empty-fetch scenario. + """ watcher = DefaultCIWatcher(token="tok") # Look-back returns old run — will be filtered by cutoff time watcher._fetch_completed_runs = AsyncMock( # type: ignore[method-assign] @@ -341,6 +351,36 @@ async def test_status_by_run_id(httpx_mock): assert result["runs"][0]["failed_jobs"] == ["deploy"] +# --------------------------------------------------------------------------- +# Event discrimination — regression test for issue #662 +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +async def test_event_filtering_selects_correct_event(): + """With scope.event='push', a passing pull_request run must not mask a failing push run. + + This is the core regression test for GitHub issue #662. + """ + watcher = DefaultCIWatcher(token="tok") + watcher._fetch_completed_runs = AsyncMock( # type: ignore[method-assign] + return_value=[ + _run(run_id=1, conclusion="success", event="pull_request"), + _run(run_id=2, conclusion="failure", event="push"), + ] + ) + watcher._fetch_failed_jobs = AsyncMock(return_value=["test"]) # type: ignore[method-assign] + + result = await watcher.wait( + "main", + repo="owner/repo", + scope=CIRunScope(event="push"), + timeout_seconds=60, + ) + assert result["conclusion"] == "failure" # push run, not pull_request + assert result["run_id"] == 2 + + # --------------------------------------------------------------------------- # TOOL-2: Billing-error (action_required) coverage # --------------------------------------------------------------------------- diff --git a/tests/execution/test_ci_params.py b/tests/execution/test_ci_params.py index 8183373424..7a64ce3055 100644 --- a/tests/execution/test_ci_params.py +++ b/tests/execution/test_ci_params.py @@ -9,10 +9,11 @@ from datetime import UTC, datetime +import httpx import pytest from autoskillit.core import CIRunScope -from autoskillit.execution.ci import DefaultCIWatcher +from autoskillit.execution.ci import DefaultCIWatcher, _validate_run_matches_scope def _now() -> str: @@ -231,3 +232,94 @@ async def test_wait_calls_fetch_jobs_for_timed_out_run(httpx_mock): result = await watcher.wait("main", repo="owner/repo", timeout_seconds=60) assert result["conclusion"] == "timed_out" assert "unit" in result["failed_jobs"] + + +# --------------------------------------------------------------------------- +# _fetch_completed_runs — event param +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +async def test_completed_runs_includes_event(httpx_mock): + """When scope.event='push', event must appear in API query params.""" + httpx_mock.add_response(json={"workflow_runs": []}) + watcher = DefaultCIWatcher(token="tok") + async with httpx.AsyncClient() as client: + await watcher._fetch_completed_runs( + client, + watcher._headers(), + "owner/repo", + "main", + scope=CIRunScope(event="push"), + lookback_seconds=300, + ) + req = httpx_mock.get_requests()[0] + assert httpx.URL(str(req.url)).params["event"] == "push" + + +@pytest.mark.anyio +async def test_completed_runs_omits_event_when_none(httpx_mock): + """When scope.event is None, event must be absent from API params.""" + httpx_mock.add_response(json={"workflow_runs": []}) + watcher = DefaultCIWatcher(token="tok") + async with httpx.AsyncClient() as client: + await watcher._fetch_completed_runs( + client, + watcher._headers(), + "owner/repo", + "main", + scope=CIRunScope(), + lookback_seconds=300, + ) + req = httpx_mock.get_requests()[0] + assert "event" not in httpx.URL(str(req.url)).params + + +@pytest.mark.anyio +async def test_active_runs_includes_event(httpx_mock): + """When scope.event='push', event must appear in active runs params.""" + httpx_mock.add_response(json={"workflow_runs": []}) + watcher = DefaultCIWatcher(token="tok") + async with httpx.AsyncClient() as client: + await watcher._fetch_active_runs( + client, + watcher._headers(), + "owner/repo", + "main", + scope=CIRunScope(event="push"), + ) + req = httpx_mock.get_requests()[0] + assert httpx.URL(str(req.url)).params["event"] == "push" + + +# --------------------------------------------------------------------------- +# _validate_run_matches_scope +# --------------------------------------------------------------------------- + + +def test_validate_run_matches_scope_event_match(): + """Run with matching event passes validation.""" + run = {"event": "push", "head_sha": "abc123"} + scope = CIRunScope(event="push", head_sha="abc123") + assert _validate_run_matches_scope(run, scope) is True + + +def test_validate_run_matches_scope_event_mismatch(): + """Run with non-matching event fails validation.""" + run = {"event": "pull_request", "head_sha": "abc123"} + scope = CIRunScope(event="push", head_sha="abc123") + assert _validate_run_matches_scope(run, scope) is False + + +def test_validate_run_matches_scope_none_event_accepts_all(): + """When scope.event is None, any event is accepted.""" + run = {"event": "pull_request", "head_sha": "abc123"} + scope = CIRunScope(event=None) + assert _validate_run_matches_scope(run, scope) is True + + +def test_validate_run_matches_scope_sha_mismatch(): + """Run with non-matching head_sha fails validation.""" + run = {"event": "push", "head_sha": "def456"} + scope = CIRunScope(head_sha="abc123") + assert _validate_run_matches_scope(run, scope) is False diff --git a/tests/execution/test_clone_guard.py b/tests/execution/test_clone_guard.py new file mode 100644 index 0000000000..55d853261f --- /dev/null +++ b/tests/execution/test_clone_guard.py @@ -0,0 +1,403 @@ +"""Tests for clone contamination guard — detect and revert direct changes.""" + +from __future__ import annotations + +import json + +import pytest + +from autoskillit.core.types import ( + RetryReason, + SkillResult, + SubprocessResult, + TerminationReason, +) +from autoskillit.execution.clone_guard import ( + CloneSnapshot, + check_and_revert_clone_contamination, + detect_contamination, + is_worktree_skill, + revert_contamination, + snapshot_clone_state, +) +from autoskillit.execution.headless import _build_skill_result +from autoskillit.pipeline.audit import DefaultAuditLog +from tests.conftest import MockSubprocessRunner + + +def _git_result(stdout: str = "", returncode: int = 0) -> SubprocessResult: + """Build a minimal SubprocessResult simulating a git command.""" + return SubprocessResult( + returncode=returncode, + stdout=stdout, + stderr="", + termination=TerminationReason.NATURAL_EXIT, + pid=99999, + ) + + +def _make_skill_result( + success: bool = False, + needs_retry: bool = True, + worktree_path: str | None = None, + exit_code: int = 1, +) -> SkillResult: + """Build a minimal SkillResult for guard tests.""" + return SkillResult( + success=success, + result="test result", + session_id="test-session", + subtype="error", + is_error=not success, + exit_code=exit_code, + needs_retry=needs_retry, + retry_reason=RetryReason.RESUME if needs_retry else RetryReason.NONE, + stderr="", + worktree_path=worktree_path, + ) + + +# --------------------------------------------------------------------------- +# T1: is_worktree_skill positive cases +# --------------------------------------------------------------------------- +class TestIsWorktreeSkillPositive: + def test_slash_command_implement(self): + assert is_worktree_skill("/autoskillit:implement-worktree-no-merge /path/to/plan.md") + + def test_slash_command_retry(self): + assert is_worktree_skill("/autoskillit:retry-worktree /path/to/worktree") + + def test_bare_name(self): + assert is_worktree_skill("implement-worktree-no-merge") + + def test_full_path(self): + assert is_worktree_skill( + "/path/to/skills_extended/implement-worktree-no-merge/SKILL.md some args" + ) + + +# --------------------------------------------------------------------------- +# T2: is_worktree_skill negative cases +# --------------------------------------------------------------------------- +class TestIsWorktreeSkillNegative: + def test_investigate(self): + assert not is_worktree_skill("/autoskillit:investigate") + + def test_make_plan(self): + assert not is_worktree_skill("/autoskillit:make-plan") + + def test_open_pr(self): + assert not is_worktree_skill("/autoskillit:open-pr") + + def test_implement_worktree_without_no_merge(self): + assert not is_worktree_skill("implement-worktree") + + +# --------------------------------------------------------------------------- +# T3: snapshot_clone_state captures SHA +# --------------------------------------------------------------------------- +@pytest.mark.anyio +async def test_snapshot_clone_state_captures_sha(tmp_path): + runner = MockSubprocessRunner() + runner.push(_git_result(stdout="abc123\n")) + snapshot = await snapshot_clone_state(str(tmp_path), runner) + assert snapshot is not None + assert snapshot.head_sha == "abc123" + + +# --------------------------------------------------------------------------- +# T4: snapshot_clone_state returns None on failure +# --------------------------------------------------------------------------- +@pytest.mark.anyio +async def test_snapshot_clone_state_returns_none_on_failure(tmp_path): + runner = MockSubprocessRunner() + runner.push(_git_result(returncode=128)) + snapshot = await snapshot_clone_state(str(tmp_path), runner) + assert snapshot is None + + +# --------------------------------------------------------------------------- +# T4b: snapshot_clone_state returns None when stdout is empty after rc=0 +# --------------------------------------------------------------------------- +@pytest.mark.anyio +async def test_snapshot_clone_state_returns_none_on_empty_stdout(tmp_path): + runner = MockSubprocessRunner() + runner.push(_git_result(stdout="", returncode=0)) + snapshot = await snapshot_clone_state(str(tmp_path), runner) + assert snapshot is None + + +# --------------------------------------------------------------------------- +# T5: detect_contamination — uncommitted changes +# --------------------------------------------------------------------------- +@pytest.mark.anyio +async def test_detect_contamination_uncommitted_changes(tmp_path): + runner = MockSubprocessRunner() + runner.push(_git_result(stdout="abc123\n")) # git rev-parse HEAD (same) + runner.push(_git_result(stdout=" M src/main.py\n?? new_file.txt\n")) # git status + snapshot = CloneSnapshot(head_sha="abc123") + report = await detect_contamination(snapshot, str(tmp_path), runner) + assert report is not None + assert len(report.uncommitted_files) == 2 + assert not report.direct_commits + + +# --------------------------------------------------------------------------- +# T6: detect_contamination — direct commits +# --------------------------------------------------------------------------- +@pytest.mark.anyio +async def test_detect_contamination_direct_commits(tmp_path): + runner = MockSubprocessRunner() + runner.push(_git_result(stdout="def456\n")) # HEAD moved + runner.push(_git_result(stdout="")) # clean status + snapshot = CloneSnapshot(head_sha="abc123") + report = await detect_contamination(snapshot, str(tmp_path), runner) + assert report is not None + assert report.direct_commits + assert len(report.uncommitted_files) == 0 + + +# --------------------------------------------------------------------------- +# T7: detect_contamination — both +# --------------------------------------------------------------------------- +@pytest.mark.anyio +async def test_detect_contamination_both(tmp_path): + runner = MockSubprocessRunner() + runner.push(_git_result(stdout="def456\n")) # HEAD moved + runner.push(_git_result(stdout=" M dirty.py\n")) # dirty + snapshot = CloneSnapshot(head_sha="abc123") + report = await detect_contamination(snapshot, str(tmp_path), runner) + assert report is not None + assert report.direct_commits + assert len(report.uncommitted_files) == 1 + + +# --------------------------------------------------------------------------- +# T8: detect_contamination — clean +# --------------------------------------------------------------------------- +@pytest.mark.anyio +async def test_detect_contamination_clean(tmp_path): + runner = MockSubprocessRunner() + runner.push(_git_result(stdout="abc123\n")) # same HEAD + runner.push(_git_result(stdout="")) # clean status + snapshot = CloneSnapshot(head_sha="abc123") + report = await detect_contamination(snapshot, str(tmp_path), runner) + assert report is None + + +# --------------------------------------------------------------------------- +# T9: revert_contamination — uncommitted only +# --------------------------------------------------------------------------- +@pytest.mark.anyio +async def test_revert_uncommitted_only(tmp_path): + runner = MockSubprocessRunner() + snapshot = CloneSnapshot(head_sha="abc123") + from autoskillit.execution.clone_guard import ContaminationReport + + report = ContaminationReport( + pre_sha="abc123", + post_sha="abc123", + uncommitted_files=[" M src/main.py"], + direct_commits=False, + reverted=False, + ) + result = await revert_contamination(snapshot, report, str(tmp_path), runner) + assert result.reverted + cmds = [call[0] for call in runner.call_args_list] + assert len(cmds) == 2 + assert ["git", "reset", "--hard", "abc123"] in cmds + assert ["git", "clean", "-fd"] in cmds + + +# --------------------------------------------------------------------------- +# T9b: revert_contamination — git commands fail → reverted=False +# --------------------------------------------------------------------------- +@pytest.mark.anyio +async def test_revert_contamination_returns_false_when_git_fails(tmp_path): + runner = MockSubprocessRunner() + runner.push(_git_result(returncode=128)) # git reset --hard fails + runner.push(_git_result(returncode=0)) # git clean succeeds (still reverted=False) + snapshot = CloneSnapshot(head_sha="abc123") + from autoskillit.execution.clone_guard import ContaminationReport + + report = ContaminationReport( + pre_sha="abc123", + post_sha="def456", + uncommitted_files=[], + direct_commits=True, + reverted=False, + ) + result = await revert_contamination(snapshot, report, str(tmp_path), runner) + assert not result.reverted + + +# --------------------------------------------------------------------------- +# T10: revert_contamination — direct commits +# --------------------------------------------------------------------------- +@pytest.mark.anyio +async def test_revert_direct_commits(tmp_path): + runner = MockSubprocessRunner() + snapshot = CloneSnapshot(head_sha="abc123") + from autoskillit.execution.clone_guard import ContaminationReport + + report = ContaminationReport( + pre_sha="abc123", + post_sha="def456", + uncommitted_files=[], + direct_commits=True, + reverted=False, + ) + result = await revert_contamination(snapshot, report, str(tmp_path), runner) + assert result.reverted + cmds = [call[0] for call in runner.call_args_list] + assert ["git", "reset", "--hard", "abc123"] in cmds + assert ["git", "clean", "-fd"] in cmds + + +# --------------------------------------------------------------------------- +# T11: guard full flow — contamination detected +# --------------------------------------------------------------------------- +@pytest.mark.anyio +async def test_guard_full_flow_contamination_detected(tmp_path): + runner = MockSubprocessRunner() + # detect_contamination: rev-parse HEAD (moved), status (dirty) + runner.push(_git_result(stdout="def456\n")) + runner.push(_git_result(stdout=" M file.py\n")) + # revert_contamination: reset --hard, clean -fd + runner.push(_git_result()) + runner.push(_git_result()) + + snapshot = CloneSnapshot(head_sha="abc123") + skill_result = _make_skill_result(success=False, worktree_path=None) + audit = DefaultAuditLog() + + result, reverted = await check_and_revert_clone_contamination( + snapshot, + skill_result, + str(tmp_path), + runner, + audit, + skill_command="/autoskillit:implement-worktree-no-merge plan.md", + ) + assert reverted + assert len(runner.call_args_list) == 4 # 2 detect + 2 revert + assert len(audit.get_report()) == 1 + record = audit.get_report()[0] + assert record.subtype == "clone_contamination" + assert "pre_sha=abc123" in record.stderr + assert "post_sha=def456" in record.stderr + + +# --------------------------------------------------------------------------- +# T12: guard skipped when success +# --------------------------------------------------------------------------- +@pytest.mark.anyio +async def test_guard_skipped_when_success(tmp_path): + runner = MockSubprocessRunner() + snapshot = CloneSnapshot(head_sha="abc123") + skill_result = _make_skill_result(success=True, worktree_path=None) + + result, reverted = await check_and_revert_clone_contamination( + snapshot, skill_result, str(tmp_path), runner, None + ) + assert not reverted + assert len(runner.call_args_list) == 0 + + +# --------------------------------------------------------------------------- +# T13: guard skipped when worktree created +# --------------------------------------------------------------------------- +@pytest.mark.anyio +async def test_guard_skipped_when_worktree_created(tmp_path): + runner = MockSubprocessRunner() + snapshot = CloneSnapshot(head_sha="abc123") + skill_result = _make_skill_result(success=False, worktree_path="/some/worktree") + + result, reverted = await check_and_revert_clone_contamination( + snapshot, skill_result, str(tmp_path), runner, None + ) + assert not reverted + assert len(runner.call_args_list) == 0 + + +# --------------------------------------------------------------------------- +# T14: guard skipped when no snapshot +# --------------------------------------------------------------------------- +@pytest.mark.anyio +async def test_guard_skipped_when_no_snapshot(tmp_path): + runner = MockSubprocessRunner() + skill_result = _make_skill_result(success=False, worktree_path=None) + + result, reverted = await check_and_revert_clone_contamination( + None, skill_result, str(tmp_path), runner, None + ) + assert not reverted + assert len(runner.call_args_list) == 0 + + +# --------------------------------------------------------------------------- +# T15: worktree_path always extracted (even when needs_retry=False) +# --------------------------------------------------------------------------- +def test_worktree_path_always_extracted(): + """worktree_path should be extracted regardless of needs_retry status.""" + assistant = json.dumps( + { + "type": "assistant", + "message": { + "role": "assistant", + "content": "worktree_path = /tmp/wt\nbranch_name = impl-test", + }, + } + ) + result_json = json.dumps( + { + "type": "result", + "subtype": "success", + "result": "Task completed.", + "session_id": "test-session", + "is_error": False, + } + ) + stdout = f"{assistant}\n{result_json}\n" + sr = SubprocessResult( + returncode=0, + stdout=stdout, + stderr="", + termination=TerminationReason.NATURAL_EXIT, + pid=12345, + ) + skill = _build_skill_result(sr) + assert skill.worktree_path == "/tmp/wt" + + +# --------------------------------------------------------------------------- +# T16: audit log records contamination +# --------------------------------------------------------------------------- +@pytest.mark.anyio +async def test_audit_log_records_contamination(tmp_path): + runner = MockSubprocessRunner() + runner.push(_git_result(stdout="def456\n")) + runner.push(_git_result(stdout=" M a.py\n M b.py\n")) + + snapshot = CloneSnapshot(head_sha="abc123") + skill_result = _make_skill_result(success=False, worktree_path=None) + audit = DefaultAuditLog() + + await check_and_revert_clone_contamination( + snapshot, + skill_result, + str(tmp_path), + runner, + audit, + skill_command="/autoskillit:implement-worktree-no-merge plan.md", + ) + + records = audit.get_report() + assert len(records) == 1 + record = records[0] + assert record.subtype == "clone_contamination" + assert record.retry_reason == RetryReason.CLONE_CONTAMINATION.value + assert "pre_sha=abc123" in record.stderr + assert "post_sha=def456" in record.stderr + assert "files=2" in record.stderr + assert "direct_commits=True" in record.stderr diff --git a/tests/execution/test_commands.py b/tests/execution/test_commands.py index 4c0cc1866c..26d43b8fdb 100644 --- a/tests/execution/test_commands.py +++ b/tests/execution/test_commands.py @@ -4,12 +4,16 @@ from pathlib import Path +import pytest + from autoskillit.core import ClaudeFlags from autoskillit.execution.commands import ( + _MAX_MCP_OUTPUT_TOKENS_VALUE, ClaudeHeadlessCmd, ClaudeInteractiveCmd, build_full_headless_cmd, build_headless_cmd, + build_headless_resume_cmd, build_interactive_cmd, ) @@ -35,9 +39,13 @@ def test_starts_with_claude(self) -> None: result = build_interactive_cmd() assert result.cmd[0] == "claude" - def test_env_is_empty(self) -> None: + def test_env_is_populated_and_scrubbed(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("CLAUDE_CODE_SSE_PORT", "23270") + monkeypatch.setenv("HOME", "/tmp/home") result = build_interactive_cmd() - assert result.env == {} + assert "CLAUDE_CODE_SSE_PORT" not in result.env + assert result.env.get("HOME") == "/tmp/home" + assert result.env["CLAUDE_CODE_AUTO_CONNECT_IDE"] == "0" def test_accepts_model(self) -> None: result = build_interactive_cmd(model="claude-opus-4-6") @@ -76,6 +84,16 @@ def test_resume_placed_before_initial_prompt(self) -> None: prompt_idx = result.cmd.index("hello") assert resume_idx < prompt_idx + def test_env_has_max_mcp_output_tokens(self) -> None: + """build_interactive_cmd must inject MAX_MCP_OUTPUT_TOKENS even with no env_extras.""" + spec = build_interactive_cmd() + assert spec.env["MAX_MCP_OUTPUT_TOKENS"] == _MAX_MCP_OUTPUT_TOKENS_VALUE + + def test_caller_extras_override_baseline(self) -> None: + """Caller-supplied env_extras must override the baseline default.""" + spec = build_interactive_cmd(env_extras={"MAX_MCP_OUTPUT_TOKENS": "99999"}) + assert spec.env["MAX_MCP_OUTPUT_TOKENS"] == "99999" + class TestBuildInteractiveCmdExtended: def test_accepts_plugin_dir(self, tmp_path: Path) -> None: @@ -143,9 +161,13 @@ def test_does_not_include_allow_dangerously_skip_permissions(self) -> None: result = build_headless_cmd("some prompt") assert ClaudeFlags.ALLOW_DANGEROUSLY_SKIP_PERMISSIONS not in result.cmd - def test_env_is_empty(self) -> None: + def test_env_is_populated_and_scrubbed(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("CLAUDE_CODE_SSE_PORT", "23270") + monkeypatch.setenv("HOME", "/tmp/home") result = build_headless_cmd("some prompt") - assert result.env == {} + assert "CLAUDE_CODE_SSE_PORT" not in result.env + assert result.env.get("HOME") == "/tmp/home" + assert result.env["CLAUDE_CODE_AUTO_CONNECT_IDE"] == "0" def test_accepts_model(self) -> None: result = build_headless_cmd("some prompt", model="claude-sonnet-4-6") @@ -154,6 +176,45 @@ def test_accepts_model(self) -> None: assert result.cmd[idx + 1] == "claude-sonnet-4-6" +class TestBuildHeadlessResumeCmd: + def test_basic_cmd_structure(self) -> None: + result = build_headless_resume_cmd(resume_session_id="abc-123", prompt="Emit token") + assert result.cmd[0] == "claude" + assert ClaudeFlags.PRINT in result.cmd + assert ClaudeFlags.RESUME in result.cmd + assert result.cmd[result.cmd.index(ClaudeFlags.RESUME) + 1] == "abc-123" + assert ClaudeFlags.DANGEROUSLY_SKIP_PERMISSIONS in result.cmd + assert ClaudeFlags.OUTPUT_FORMAT in result.cmd + assert result.cmd[result.cmd.index(ClaudeFlags.OUTPUT_FORMAT) + 1] == "json" + prompt_idx = result.cmd.index(ClaudeFlags.PRINT) + 1 + assert result.cmd[prompt_idx] == "Emit token" + + def test_env_is_populated_with_ide_suppression(self) -> None: + from collections.abc import Mapping + + result = build_headless_resume_cmd(resume_session_id="abc-123", prompt="Emit token") + assert isinstance(result.env, Mapping) + assert len(result.env) > 0 + assert result.env.get("CLAUDE_CODE_AUTO_CONNECT_IDE") == "0" + + def test_env_has_max_mcp_output_tokens(self) -> None: + """build_headless_resume_cmd must inject MAX_MCP_OUTPUT_TOKENS even with no env_extras.""" + spec = build_headless_resume_cmd(resume_session_id="abc", prompt="Emit token") + assert spec.env["MAX_MCP_OUTPUT_TOKENS"] == _MAX_MCP_OUTPUT_TOKENS_VALUE + + def test_no_plugin_dir_by_default(self) -> None: + result = build_headless_resume_cmd(resume_session_id="abc-123", prompt="Emit token") + assert ClaudeFlags.PLUGIN_DIR not in result.cmd + + def test_with_plugin_dir(self) -> None: + result = build_headless_resume_cmd( + resume_session_id="abc-123", prompt="Emit token", plugin_dir=Path("/tmp/plugin") + ) + assert ClaudeFlags.PLUGIN_DIR in result.cmd + idx = result.cmd.index(ClaudeFlags.PLUGIN_DIR) + assert result.cmd[idx + 1] == "/tmp/plugin" + + class TestBuildFullHeadlessCmd: BASE = dict( cwd="/repo", @@ -163,85 +224,185 @@ class TestBuildFullHeadlessCmd: output_format_value="stream-json", output_format_required_flags=["--verbose"], add_dirs=[], - exit_after_stop_delay_ms=120000, + exit_after_stop_delay_ms=2000, ) - def test_env_prefix_present(self): - """cmd must start with ['env', 'AUTOSKILLIT_HEADLESS=1', ...]""" - cmd = build_full_headless_cmd("/investigate foo", **self.BASE) - assert cmd[0] == "env" - assert "AUTOSKILLIT_HEADLESS=1" in cmd - - def test_exit_delay_appended_when_positive(self): - cmd = build_full_headless_cmd("/investigate foo", **self.BASE) - assert "CLAUDE_CODE_EXIT_AFTER_STOP_DELAY=120000" in cmd - - def test_exit_delay_omitted_when_zero(self): + def test_returns_claude_headless_cmd(self): + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + assert isinstance(spec, ClaudeHeadlessCmd) + + def test_cmd_starts_with_claude_not_env(self): + """Argv no longer carries a leading ['env', ...] prefix.""" + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + assert spec.cmd[0] == "claude" + assert "env" != spec.cmd[0] + assert not any(tok.startswith("AUTOSKILLIT_HEADLESS=") for tok in spec.cmd) + assert not any(tok.startswith("CLAUDE_CODE_EXIT_AFTER_STOP_DELAY=") for tok in spec.cmd) + assert not any(tok.startswith("SCENARIO_STEP_NAME=") for tok in spec.cmd) + + def test_env_has_autoskillit_headless(self): + """AUTOSKILLIT_HEADLESS=1 now lives on spec.env, not in argv.""" + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + assert spec.env["AUTOSKILLIT_HEADLESS"] == "1" + + def test_env_has_exit_delay_when_positive(self): + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + assert spec.env["CLAUDE_CODE_EXIT_AFTER_STOP_DELAY"] == "2000" + + def test_env_omits_exit_delay_when_zero(self): params = {**self.BASE, "exit_after_stop_delay_ms": 0} - cmd = build_full_headless_cmd("/investigate foo", **params) - assert not any("CLAUDE_CODE_EXIT_AFTER_STOP_DELAY" in s for s in cmd) + spec = build_full_headless_cmd("/investigate foo", **params) + assert "CLAUDE_CODE_EXIT_AFTER_STOP_DELAY" not in spec.env + + def test_env_strips_sse_port(self, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("CLAUDE_CODE_SSE_PORT", "23270") + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + assert "CLAUDE_CODE_SSE_PORT" not in spec.env + + def test_headless_exclusive_vars_stripped_from_host_env_exit_delay( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """CLAUDE_CODE_EXIT_AFTER_STOP_DELAY in host env must be stripped even when ms=0.""" + monkeypatch.setenv("CLAUDE_CODE_EXIT_AFTER_STOP_DELAY", "99999") + params = {**self.BASE, "exit_after_stop_delay_ms": 0} + spec = build_full_headless_cmd("/investigate foo", **params) + assert "CLAUDE_CODE_EXIT_AFTER_STOP_DELAY" not in spec.env + + def test_headless_exclusive_vars_stripped_from_host_env_scenario_step( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """SCENARIO_STEP_NAME in host env must be stripped even when no step name is given.""" + monkeypatch.setenv("SCENARIO_STEP_NAME", "outer-step") + params = {**self.BASE, "scenario_step_name": ""} + spec = build_full_headless_cmd("/investigate foo", **params) + assert "SCENARIO_STEP_NAME" not in spec.env + + def test_env_has_auto_connect_off(self): + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + assert spec.env["CLAUDE_CODE_AUTO_CONNECT_IDE"] == "0" def test_plugin_dir_present(self): - cmd = build_full_headless_cmd("/investigate foo", **self.BASE) - assert "--plugin-dir" in cmd - idx = cmd.index("--plugin-dir") - assert cmd[idx + 1] == "/plugins" + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + assert "--plugin-dir" in spec.cmd + idx = spec.cmd.index("--plugin-dir") + assert spec.cmd[idx + 1] == "/plugins" def test_output_format_present(self): - cmd = build_full_headless_cmd("/investigate foo", **self.BASE) - assert "--output-format" in cmd - idx = cmd.index("--output-format") - assert cmd[idx + 1] == "stream-json" + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + assert "--output-format" in spec.cmd + idx = spec.cmd.index("--output-format") + assert spec.cmd[idx + 1] == "stream-json" def test_output_format_required_flags_appended(self): - cmd = build_full_headless_cmd("/investigate foo", **self.BASE) - assert "--verbose" in cmd + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + assert "--verbose" in spec.cmd def test_output_format_required_flags_not_duplicated(self): """If a required flag is already present it must not be added twice.""" params = {**self.BASE, "output_format_required_flags": ["--output-format"]} - cmd = build_full_headless_cmd("/investigate foo", **params) - assert cmd.count("--output-format") == 1 + spec = build_full_headless_cmd("/investigate foo", **params) + assert spec.cmd.count("--output-format") == 1 def test_add_dirs_injected(self): from autoskillit.core import ValidatedAddDir d = ValidatedAddDir(path="/skills/custom") params = {**self.BASE, "add_dirs": [d]} - cmd = build_full_headless_cmd("/investigate foo", **params) - assert "--add-dir" in cmd - idx = cmd.index("--add-dir") - assert cmd[idx + 1] == "/skills/custom" + spec = build_full_headless_cmd("/investigate foo", **params) + assert "--add-dir" in spec.cmd + idx = spec.cmd.index("--add-dir") + assert spec.cmd[idx + 1] == "/skills/custom" def test_no_add_dirs_emits_no_flag(self): - cmd = build_full_headless_cmd("/investigate foo", **self.BASE) - assert "--add-dir" not in cmd + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + assert "--add-dir" not in spec.cmd def test_skill_prefix_injected(self): """Slash commands must be prefixed with 'Use '.""" - cmd = build_full_headless_cmd("/investigate foo", **self.BASE) + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + cmd = spec.cmd prompt_idx = cmd.index("-p") + 1 if "-p" in cmd else cmd.index("--print") + 1 assert cmd[prompt_idx].startswith("Use /investigate") def test_completion_marker_appended(self): """Completion directive must appear in the prompt.""" - cmd = build_full_headless_cmd("/investigate foo", **self.BASE) + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + cmd = spec.cmd prompt_idx = cmd.index("-p") + 1 if "-p" in cmd else cmd.index("--print") + 1 assert "DONE" in cmd[prompt_idx] def test_cwd_anchor_appended(self): """Working-directory anchor must appear in the prompt.""" - cmd = build_full_headless_cmd("/investigate foo", **self.BASE) + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + cmd = spec.cmd prompt_idx = cmd.index("-p") + 1 if "-p" in cmd else cmd.index("--print") + 1 assert "/repo" in cmd[prompt_idx] def test_model_injected_when_provided(self): params = {**self.BASE, "model": "claude-opus-4-6"} - cmd = build_full_headless_cmd("/investigate foo", **params) - assert "--model" in cmd - idx = cmd.index("--model") - assert cmd[idx + 1] == "claude-opus-4-6" + spec = build_full_headless_cmd("/investigate foo", **params) + assert "--model" in spec.cmd + idx = spec.cmd.index("--model") + assert spec.cmd[idx + 1] == "claude-opus-4-6" def test_model_omitted_when_none(self): - cmd = build_full_headless_cmd("/investigate foo", **self.BASE) - assert "--model" not in cmd + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + assert "--model" not in spec.cmd + + def test_narration_suppression_directive_in_prompt(self): + """EFFICIENCY DIRECTIVE must appear in the assembled prompt.""" + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + cmd = spec.cmd + prompt_idx = cmd.index("-p") + 1 if "-p" in cmd else cmd.index("--print") + 1 + assert "EFFICIENCY DIRECTIVE" in cmd[prompt_idx] + + def test_env_has_max_mcp_output_tokens(self): + """MAX_MCP_OUTPUT_TOKENS=50000 must be present in headless session env.""" + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + assert spec.env["MAX_MCP_OUTPUT_TOKENS"] == _MAX_MCP_OUTPUT_TOKENS_VALUE + + def test_max_mcp_output_tokens_not_in_argv(self): + """MAX_MCP_OUTPUT_TOKENS must live in spec.env, not in argv.""" + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + assert not any(tok.startswith("MAX_MCP_OUTPUT_TOKENS=") for tok in spec.cmd) + + def test_headless_exclusive_vars_strips_host_max_mcp_output_tokens( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Host-env MAX_MCP_OUTPUT_TOKENS must be stripped and replaced by the hardcoded value.""" + monkeypatch.setenv("MAX_MCP_OUTPUT_TOKENS", "99999") + spec = build_full_headless_cmd("/investigate foo", **self.BASE) + assert spec.env["MAX_MCP_OUTPUT_TOKENS"] == _MAX_MCP_OUTPUT_TOKENS_VALUE + + +def test_headless_exclusive_vars_contains_max_mcp_output_tokens() -> None: + """MAX_MCP_OUTPUT_TOKENS must be in _HEADLESS_EXCLUSIVE_VARS.""" + from autoskillit.execution.commands import _HEADLESS_EXCLUSIVE_VARS + + assert "MAX_MCP_OUTPUT_TOKENS" in _HEADLESS_EXCLUSIVE_VARS + + +# MAINTENANCE: When adding a new session builder to commands.py, +# add it to this parametrize list. test_no_raw_claude_env ensures +# env routing; this test ensures env CONTENT. +@pytest.mark.parametrize( + "builder_call", + [ + lambda: build_interactive_cmd(), + lambda: build_full_headless_cmd( + "/investigate foo", + cwd="/tmp", + completion_marker="%%DONE%%", + model=None, + plugin_dir=None, + output_format_value="stream-json", + ), + lambda: build_headless_resume_cmd(resume_session_id="abc", prompt="Emit"), + ], + ids=["interactive", "full_headless", "headless_resume"], +) +def test_all_session_builders_inject_max_mcp_output_tokens(builder_call) -> None: + """Every session command builder must produce env with MAX_MCP_OUTPUT_TOKENS.""" + spec = builder_call() + assert "MAX_MCP_OUTPUT_TOKENS" in spec.env + assert spec.env["MAX_MCP_OUTPUT_TOKENS"] == _MAX_MCP_OUTPUT_TOKENS_VALUE diff --git a/tests/execution/test_github.py b/tests/execution/test_github.py index 882cf3b2c2..26f3689a67 100644 --- a/tests/execution/test_github.py +++ b/tests/execution/test_github.py @@ -596,18 +596,6 @@ async def test_ensure_label_returns_error_on_network_failure(httpx_mock): # --------------------------------------------------------------------------- -def test_github_fetcher_protocol_has_add_labels(): - assert hasattr(GitHubFetcher, "add_labels") - - -def test_github_fetcher_protocol_has_remove_label(): - assert hasattr(GitHubFetcher, "remove_label") - - -def test_github_fetcher_protocol_has_ensure_label(): - assert hasattr(GitHubFetcher, "ensure_label") - - def test_default_github_fetcher_implements_full_protocol(): fetcher = DefaultGitHubFetcher(token=None) assert isinstance(fetcher, GitHubFetcher) diff --git a/tests/execution/test_github_headers.py b/tests/execution/test_github_headers.py index 1129996a33..fb52a8d855 100644 --- a/tests/execution/test_github_headers.py +++ b/tests/execution/test_github_headers.py @@ -6,7 +6,7 @@ from __future__ import annotations -import asyncio +import pytest from autoskillit.execution.github import github_headers from autoskillit.execution.merge_queue import DefaultMergeQueueWatcher @@ -48,26 +48,27 @@ def test_github_headers_returns_new_dict_each_call(): # --------------------------------------------------------------------------- -def test_merge_queue_watcher_includes_user_agent_in_client_headers(): +@pytest.mark.anyio +async def test_merge_queue_watcher_includes_user_agent_in_client_headers(): """DefaultMergeQueueWatcher must include User-Agent: autoskillit in its client. - This is the regression guard for the P6-5 bug: merge_queue.py built headers - inline in __init__ and omitted User-Agent. + Regression guard for P6-5 bug: merge_queue.py built headers inline in __init__ + and omitted User-Agent. """ watcher = DefaultMergeQueueWatcher(token=None) try: - # httpx.AsyncClient merges headers case-insensitively; check both cases client_headers = dict(watcher._client.headers) assert client_headers.get("user-agent") == "autoskillit" finally: - asyncio.run(watcher.aclose()) + await watcher.aclose() -def test_merge_queue_watcher_includes_user_agent_with_token(): +@pytest.mark.anyio +async def test_merge_queue_watcher_includes_user_agent_with_token(): """User-Agent must be present even when a token is provided.""" watcher = DefaultMergeQueueWatcher(token="tok") try: client_headers = dict(watcher._client.headers) assert client_headers.get("user-agent") == "autoskillit" finally: - asyncio.run(watcher.aclose()) + await watcher.aclose() diff --git a/tests/execution/test_headless.py b/tests/execution/test_headless.py index 6f54326875..83605b28f0 100644 --- a/tests/execution/test_headless.py +++ b/tests/execution/test_headless.py @@ -2,6 +2,7 @@ import json from pathlib import Path +from unittest.mock import patch import pytest @@ -9,12 +10,14 @@ CONTEXT_EXHAUSTION_MARKER, ChannelConfirmation, RetryReason, + SkillResult, SubprocessResult, TerminationReason, ) from autoskillit.execution.commands import _ensure_skill_prefix from autoskillit.execution.headless import ( _build_skill_result, + _extract_missing_token_hints, _extract_worktree_path, _scan_jsonl_write_paths, ) @@ -125,9 +128,9 @@ def test_warns_when_dir_missing(self, tmp_path, monkeypatch): with structlog.testing.capture_logs() as logs: _session_log_dir(cwd) assert any( - e.get("event") == "session_log_dir_missing" + e.get("event") == "session_log_dir_precreating" for e in logs - if e.get("log_level") == "warning" + if e.get("log_level") == "info" ) def test_no_warning_when_dir_present(self, tmp_path, monkeypatch): @@ -175,7 +178,8 @@ def test_logs_path_when_dir_missing(self, tmp_path, monkeypatch): assert any(e.get("event") == "session_log_dir_computed" for e in info_entries) computed = next(e for e in info_entries if e.get("event") == "session_log_dir_computed") assert computed.get("path") == str(result) - assert any(e.get("event") == "session_log_dir_missing" for e in logs) + assert any(e.get("event") == "session_log_dir_precreating" for e in info_entries) + assert not any(e.get("event") == "session_log_dir_missing" for e in logs) def test_headless_session_log_dir_uses_shared_util(self): from autoskillit.core.paths import claude_code_project_dir @@ -184,6 +188,19 @@ def test_headless_session_log_dir_uses_shared_util(self): cwd = "/home/user/project" assert _session_log_dir(cwd) == claude_code_project_dir(cwd) + def test_session_log_dir_creates_missing_directory(self, tmp_path, monkeypatch): + """_session_log_dir must create the directory if absent, so Channel B + always has a directory to poll.""" + from autoskillit.execution.headless import _session_log_dir + + fake_home = tmp_path / "home" + fake_home.mkdir() + monkeypatch.setattr("pathlib.Path.home", lambda: fake_home) + cwd = "/some/fresh/clone/path" + result = _session_log_dir(cwd) + assert result.exists() + assert result.is_dir() + class TestResolveSessionId: """Unit tests for _resolve_skill_session_id — the session UUID resolution helper.""" @@ -307,8 +324,17 @@ def test_build_skill_result_stale_path_uses_channel_b_session_id(self): cwd="/tmp", ) assert skill_result.session_id == "b077addc-926d-4869-b27a-7465a4c0fda4" - assert skill_result.success is False - assert skill_result.needs_retry is True + + def test_build_skill_result_idle_stall_is_retriable(self): + """IDLE_STALL termination → success=False, needs_retry=True, subtype=idle_stall.""" + from autoskillit.execution.headless import _build_skill_result + + skill = _build_skill_result( + _sr(returncode=-15, stdout="", termination=TerminationReason.IDLE_STALL) + ) + assert skill.success is False + assert skill.needs_retry is True + assert skill.subtype == "idle_stall" def test_build_skill_result_timeout_empty_stdout_uses_channel_b_session_id(self): """_build_skill_result must use Channel B session_id on TIMED_OUT with empty stdout.""" @@ -814,6 +840,7 @@ class TestBuildSkillResultCrossValidation: "cli_subtype", "is_error", "exit_code", + "kill_reason", "needs_retry", "retry_reason", "stderr", @@ -1675,6 +1702,8 @@ def test_termination_reason_completed_without_marker_fails(self): (TerminationReason.NATURAL_EXIT, 0, MARKER, False), # marker-only (TerminationReason.COMPLETED, 0, f"Done.\n\n{MARKER}", True), (TerminationReason.COMPLETED, -15, f"Done.\n\n{MARKER}", True), + (TerminationReason.COMPLETED, -9, f"Done.\n\n{MARKER}", True), + (TerminationReason.COMPLETED, -9, "No marker here", False), (TerminationReason.COMPLETED, 0, "No marker here", False), (TerminationReason.STALE, -15, f"Done.\n\n{MARKER}", False), (TerminationReason.TIMED_OUT, -1, f"Done.\n\n{MARKER}", False), @@ -1685,6 +1714,8 @@ def test_termination_reason_completed_without_marker_fails(self): "natural_exit+marker_only=failure", "completed+marker=success", "completed_sigterm+marker=success", + "completed_sigkill+marker=success", + "completed_sigkill+no_marker=failure", "completed+no_marker=failure", "stale+marker=failure", "timed_out+marker=failure", @@ -1710,6 +1741,37 @@ def test_cross_validation_matrix(self, termination, returncode, result_text, exp is expected ) + def test_build_skill_result_channel_a_win_preserves_success_with_minus_9(self): + """COMPLETED + CHANNEL_A + returncode=-9 + content → success=True (1d). + + Verifies that the adjudicator correctly marks a SIGKILL'd session as + successful when Channel A confirmed completion and the result has content + with the marker. This is the key assertion that the -9 bug existed at the + kill level, not the adjudication level. + """ + ndjson = ( + '{"type":"result","subtype":"success",' + f'"result":"Work done.\\n\\n{self.MARKER}",' + '"session_id":"s1","is_error":false}\n' + ) + result = _build_skill_result( + SubprocessResult( + returncode=-9, + stdout=ndjson, + stderr="", + termination=TerminationReason.COMPLETED, + pid=1, + channel_confirmation=ChannelConfirmation.CHANNEL_A, + ), + completion_marker=self.MARKER, + skill_command="test-skill", + audit=None, + ) + assert result.success is True, ( + f"Expected success=True for COMPLETED+CHANNEL_A+rc=-9, got success={result.success}, " + f"subtype={result.subtype!r}" + ) + def test_build_skill_result_recovers_when_marker_in_separate_assistant_message(self): """ If the model emits substantive content in an assistant record and %%ORDER_UP%% @@ -2088,13 +2150,64 @@ async def raising_runner(*args: object, **kwargs: object) -> None: tool_ctx.runner = raising_runner # type: ignore[assignment] - with pytest.raises(RuntimeError, match="simulated crash"): - await run_headless_core("/investigate test", cwd=str(tmp_path), ctx=tool_ctx) + skill_result = await run_headless_core( + "/investigate test", cwd=str(tmp_path), ctx=tool_ctx + ) + assert isinstance(skill_result, SkillResult) + assert skill_result.success is False + assert skill_result.subtype == "crashed" + assert skill_result.is_error is True + assert skill_result.exit_code == -1 + assert skill_result.needs_retry is False + assert "simulated crash" in skill_result.result crash_calls = [f for f in flushed if f.get("termination_reason") == "CRASHED"] assert len(crash_calls) >= 1 assert crash_calls[0]["success"] is False + @pytest.mark.anyio + async def test_crash_exception_text_passed_to_flush(self, monkeypatch, tool_ctx, tmp_path): + """flush_session_log receives exception_text with the traceback on crash.""" + from autoskillit.execution.headless import run_headless_core + + flushed: list[dict] = [] + + def fake_flush(**kwargs: object) -> None: + flushed.append(dict(kwargs)) + + monkeypatch.setattr("autoskillit.execution.flush_session_log", fake_flush) + + async def raising_runner(*args: object, **kwargs: object) -> None: + raise OSError("disk full") + + tool_ctx.runner = raising_runner # type: ignore[assignment] + + await run_headless_core("/investigate test", cwd=str(tmp_path), ctx=tool_ctx) + + crash_calls = [f for f in flushed if f.get("termination_reason") == "CRASHED"] + assert len(crash_calls) >= 1 + assert "exception_text" in crash_calls[0] + assert "OSError: disk full" in crash_calls[0]["exception_text"] + + @pytest.mark.anyio + async def test_crash_logs_exception_with_logger_error(self, monkeypatch, tool_ctx, tmp_path): + """Runner crash is logged at ERROR level with exc_info.""" + from autoskillit.execution.headless import run_headless_core + + monkeypatch.setattr("autoskillit.execution.flush_session_log", lambda **kw: None) + + async def raising_runner(*args: object, **kwargs: object) -> None: + raise ValueError("bad input") + + tool_ctx.runner = raising_runner # type: ignore[assignment] + + with patch("autoskillit.execution.headless.logger") as mock_logger: + result = await run_headless_core("/investigate test", cwd=str(tmp_path), ctx=tool_ctx) + mock_logger.error.assert_called_once() + call_kwargs = mock_logger.error.call_args + assert call_kwargs[1].get("exc_info") + assert result.success is False + class TestRetryBudgetEnforcement: """_build_skill_result enforces max_consecutive_retries budget.""" @@ -2232,6 +2345,40 @@ def test_skips_when_cwd_relative(self): assert result == "cmd" +# --------------------------------------------------------------------------- +# Test: _inject_narration_suppression +# --------------------------------------------------------------------------- + + +class TestInjectNarrationSuppression: + def test_appends_efficiency_directive(self): + from autoskillit.execution.commands import _inject_narration_suppression + + result = _inject_narration_suppression("Use /make-plan foo") + assert "EFFICIENCY DIRECTIVE" in result + + def test_preserves_original_command(self): + from autoskillit.execution.commands import _inject_narration_suppression + + original = "Use /autoskillit:investigate problem" + result = _inject_narration_suppression(original) + assert result.startswith(original) + + def test_directive_targets_inter_tool_prose(self): + from autoskillit.execution.commands import _inject_narration_suppression + + result = _inject_narration_suppression("cmd") + # Directive must reference tool calls specifically + assert "between tool calls" in result + + def test_directive_exempts_final_response(self): + from autoskillit.execution.commands import _inject_narration_suppression + + result = _inject_narration_suppression("cmd") + # Must not suppress the final response where structured output tokens live + assert "final response" in result + + # --------------------------------------------------------------------------- # Test: _extract_output_paths (Step 1b) # --------------------------------------------------------------------------- @@ -2943,6 +3090,74 @@ def test_bold_wrapped_tokens_in_assistant_messages_recovery_succeeds( assert sr.needs_retry is False +class TestBuildSkillResultDirMissingRecovery: + """DIR_MISSING channel confirmation does not silently pass — it attempts + late-bind recovery when conditions allow.""" + + def test_dir_missing_with_recoverable_subtype_attempts_recovery(self): + """When channel_confirmation is DIR_MISSING and subtype is recoverable, + the recovery gate must attempt marker-based recovery. + + Setup: termination=COMPLETED (bypasses stale branch), subtype=empty_output + (in _CHANNEL_B_RECOVERABLE_SUBTYPES), marker on a standalone line in the + assistant message (required by _marker_is_standalone). + """ + import structlog.testing + + marker = "===DONE===" + # Marker must appear as a standalone line for _marker_is_standalone to match + assistant_line = json.dumps( + { + "type": "assistant", + "message": { + "content": [{"type": "text", "text": f"Task complete.\n\n{marker}"}], + }, + } + ) + # subtype=empty_output places the session in _CHANNEL_B_RECOVERABLE_SUBTYPES, + # triggering the DIR_MISSING recovery guard in _build_skill_result + result_line = json.dumps( + { + "type": "result", + "subtype": "empty_output", + "is_error": True, + "result": "", + "session_id": "s1", + "errors": [], + } + ) + stdout = assistant_line + "\n" + result_line + # termination=COMPLETED skips the stale-branch early return so execution + # reaches the Channel B / DIR_MISSING recovery gate + sub_result = SubprocessResult( + returncode=0, + stdout=stdout, + stderr="", + termination=TerminationReason.COMPLETED, + pid=12345, + channel_confirmation=ChannelConfirmation.DIR_MISSING, + ) + with structlog.testing.capture_logs() as logs: + skill = _build_skill_result(sub_result, completion_marker=marker) + # Recovery should succeed — marker found as standalone line in assistant_messages + assert skill.success is True + # Verify the recovery code path was taken, not just the outcome + assert any(e.get("event") == "dir_missing_late_bind_recovery" for e in logs) + + def test_dir_missing_without_marker_does_not_recover(self): + """DIR_MISSING with no completion marker must not silently succeed.""" + sub_result = SubprocessResult( + returncode=0, + stdout="", + stderr="", + termination=TerminationReason.STALE, + pid=12345, + channel_confirmation=ChannelConfirmation.DIR_MISSING, + ) + skill = _build_skill_result(sub_result) + assert skill.success is False + + class TestTimedOutSessionPreservesState: """TIMED_OUT branch must parse stdout to preserve tool_uses and assistant_messages.""" @@ -3025,6 +3240,8 @@ class TestOutputPathTokensDerivedFromContracts: "conflict_report_path", "diagnosis_path", "diagram_path", + "evaluation_dashboard", + "experiment_plan", "group_files", "groups_path", "investigation_path", @@ -3032,12 +3249,21 @@ class TestOutputPathTokensDerivedFromContracts: "plan_parts", "plan_path", "pr_order_file", + "prep_path", "recipe_path", "remediation_path", + "report_path", + "report_plan_path", + "results_path", "review_path", + "revision_guidance", + "scope_report", "summary_path", "triage_manifest", "triage_report", + "visualization_plan_path", + "html_path", + "resource_report", } ) @@ -3442,3 +3668,421 @@ def test_context_exhaustion_session_id_from_subprocess_result(self) -> None: ) sr = _build_skill_result(result) assert sr.session_id == "ch-b-uuid-5678" + + +class TestHeadlessExecutorCompletionMarker: + """Protocol conformance: DefaultHeadlessExecutor.run accepts completion_marker.""" + + def test_headless_executor_accepts_completion_marker(self) -> None: + import inspect + + from autoskillit.execution.headless import DefaultHeadlessExecutor + + sig = inspect.signature(DefaultHeadlessExecutor.run) + assert "completion_marker" in sig.parameters + param = sig.parameters["completion_marker"] + assert param.default == "" + + +class TestHeadlessExecutorIdleOutputTimeout: + """Protocol conformance and resolution logic for idle_output_timeout.""" + + def test_headless_executor_accepts_idle_output_timeout(self) -> None: + import inspect + + from autoskillit.execution.headless import DefaultHeadlessExecutor + + sig = inspect.signature(DefaultHeadlessExecutor.run) + assert "idle_output_timeout" in sig.parameters + param = sig.parameters["idle_output_timeout"] + assert param.default is None + + def _success_payload(self, marker: str) -> SubprocessResult: + payload = json.dumps( + { + "type": "result", + "subtype": "success", + "is_error": False, + "result": f"Done. {marker}", + "session_id": "sess-iot", + } + ) + return SubprocessResult(0, payload, "", TerminationReason.NATURAL_EXIT, pid=1) + + @pytest.mark.anyio + async def test_default_headless_executor_uses_per_step_idle_output_timeout( + self, tool_ctx + ) -> None: + """idle_output_timeout=120 is converted to float and passed to the runner.""" + from autoskillit.execution.headless import run_headless_core + + marker = tool_ctx.config.run_skill.completion_marker + tool_ctx.runner.push(self._success_payload(marker)) + await run_headless_core( + "/investigate foo", cwd="/tmp", ctx=tool_ctx, idle_output_timeout=120.0 + ) + _, _cwd, _timeout, kwargs = tool_ctx.runner.call_args_list[0] + assert kwargs["idle_output_timeout"] == 120.0 + + @pytest.mark.anyio + async def test_default_headless_executor_converts_zero_to_none(self, tool_ctx) -> None: + """idle_output_timeout=0 is converted to None (disabled) before passing to runner.""" + from autoskillit.execution.headless import run_headless_core + + marker = tool_ctx.config.run_skill.completion_marker + tool_ctx.runner.push(self._success_payload(marker)) + await run_headless_core( + "/investigate foo", cwd="/tmp", ctx=tool_ctx, idle_output_timeout=0.0 + ) + _, _cwd, _timeout, kwargs = tool_ctx.runner.call_args_list[0] + assert kwargs["idle_output_timeout"] is None + + @pytest.mark.anyio + async def test_default_headless_executor_falls_back_to_cfg_idle_output_timeout( + self, tool_ctx + ) -> None: + """idle_output_timeout=None falls back to float(cfg.idle_output_timeout).""" + from autoskillit.execution.headless import run_headless_core + + marker = tool_ctx.config.run_skill.completion_marker + tool_ctx.runner.push(self._success_payload(marker)) + await run_headless_core( + "/investigate foo", cwd="/tmp", ctx=tool_ctx, idle_output_timeout=None + ) + _, _cwd, _timeout, kwargs = tool_ctx.runner.call_args_list[0] + assert kwargs["idle_output_timeout"] == 600.0 + + +def _ndjson_with_write(result_text: str, file_paths: list[str], session_id: str = "test-session"): + """Build NDJSON stdout with Write tool_use entries and a result record.""" + records = [] + if file_paths: + content = [ + { + "type": "tool_use", + "name": "Write", + "id": f"t{i}", + "input": {"file_path": fp}, + } + for i, fp in enumerate(file_paths) + ] + records.append(json.dumps({"type": "assistant", "message": {"content": content}})) + records.append( + json.dumps( + { + "type": "result", + "subtype": "success", + "is_error": False, + "result": result_text, + "session_id": session_id, + } + ) + ) + return "\n".join(records) + + +class TestExtractMissingTokenHints: + def test_extracts_token_and_path(self): + stdout = _ndjson_with_write("plan summary\n%%ORDER_UP%%", ["/tmp/out.md"]) + hints = _extract_missing_token_hints(stdout, [r"plan_path\s*=\s*/.+"]) + assert hints == [("plan_path", "/tmp/out.md")] + + def test_returns_empty_when_pattern_satisfied(self): + stdout = _ndjson_with_write("plan_path = /tmp/out.md\n%%ORDER_UP%%", ["/tmp/out.md"]) + hints = _extract_missing_token_hints(stdout, [r"plan_path\s*=\s*/.+"]) + assert hints == [] + + def test_returns_empty_for_non_path_patterns(self): + stdout = _ndjson_with_write("%%ORDER_UP%%", ["/tmp/out.md"]) + hints = _extract_missing_token_hints(stdout, [r"verdict\s*=\s*\w+"]) + assert hints == [] + + def test_uses_last_write_path(self): + stdout = _ndjson_with_write("%%ORDER_UP%%", ["/tmp/first.md", "/tmp/final.md"]) + hints = _extract_missing_token_hints(stdout, [r"plan_path\s*=\s*/.+"]) + assert hints == [("plan_path", "/tmp/final.md")] + + +class TestContractNudge: + """Integration tests for the contract recovery nudge in run_headless_core. + + The nudge fires when CONTRACT_RECOVERY is triggered with a valid session_id. + CONTRACT_RECOVERY requires synthesis to have failed first. For CHANNEL_A/B + sessions, synthesis is skipped (gated on UNMONITORED), so Write evidence + with file_path triggers CONTRACT_RECOVERY while _extract_missing_token_hints + can still find the file_path for hints. + """ + + def _main_session_ndjson( + self, marker: str, *, include_token: bool = False, session_id: str = "sess-main" + ) -> str: + """Build NDJSON for a CHANNEL_A-confirmed session with Write evidence.""" + result_text = "plan summary\n" + if include_token: + result_text += "plan_path = /tmp/out.md\n" + result_text += marker + return _ndjson_with_write(result_text, ["/tmp/out.md"], session_id=session_id) + + def _main_subprocess_result( + self, marker: str, *, session_id: str = "sess-main" + ) -> SubprocessResult: + """Build a SubprocessResult with CHANNEL_A confirmation to bypass synthesis.""" + return SubprocessResult( + returncode=0, + stdout=self._main_session_ndjson(marker, session_id=session_id), + stderr="", + termination=TerminationReason.NATURAL_EXIT, + pid=1, + channel_confirmation=ChannelConfirmation.CHANNEL_A, + ) + + def _nudge_response_ndjson(self, marker: str, *, include_token: bool = True) -> str: + """Build NDJSON for a nudge response.""" + if include_token: + result_text = f"plan_path = /tmp/out.md\n{marker}" + else: + result_text = f"I cannot do that.\n{marker}" + return json.dumps( + { + "type": "result", + "subtype": "success", + "is_error": False, + "result": result_text, + "session_id": "sess-main", + "usage": {"input_tokens": 100, "output_tokens": 50}, + } + ) + + @pytest.mark.anyio + async def test_nudge_fires_on_contract_recovery(self, tool_ctx): + from autoskillit.execution.headless import run_headless_core + + marker = tool_ctx.config.run_skill.completion_marker + tool_ctx.runner.push(self._main_subprocess_result(marker)) + tool_ctx.runner.push( + SubprocessResult( + 0, self._nudge_response_ndjson(marker), "", TerminationReason.NATURAL_EXIT, pid=2 + ) + ) + result = await run_headless_core( + "/autoskillit:make-plan foo", + cwd="/tmp", + ctx=tool_ctx, + expected_output_patterns=[r"plan_path\s*=\s*/.+"], + ) + assert result.success is True + assert result.needs_retry is False + assert "plan_path = /tmp/out.md" in result.result + + @pytest.mark.anyio + async def test_nudge_failure_falls_through(self, tool_ctx): + from autoskillit.execution.headless import run_headless_core + + marker = tool_ctx.config.run_skill.completion_marker + tool_ctx.runner.push(self._main_subprocess_result(marker)) + tool_ctx.runner.push( + SubprocessResult( + 0, + self._nudge_response_ndjson(marker, include_token=False), + "", + TerminationReason.NATURAL_EXIT, + pid=2, + ) + ) + result = await run_headless_core( + "/autoskillit:make-plan foo", + cwd="/tmp", + ctx=tool_ctx, + expected_output_patterns=[r"plan_path\s*=\s*/.+"], + ) + assert result.retry_reason == RetryReason.CONTRACT_RECOVERY + assert result.needs_retry is True + + @pytest.mark.anyio + async def test_nudge_timeout_falls_through(self, tool_ctx): + from autoskillit.execution.headless import run_headless_core + + marker = tool_ctx.config.run_skill.completion_marker + tool_ctx.runner.push(self._main_subprocess_result(marker)) + tool_ctx.runner.push( + SubprocessResult(1, "", "timeout", TerminationReason.TIMED_OUT, pid=2) + ) + result = await run_headless_core( + "/autoskillit:make-plan foo", + cwd="/tmp", + ctx=tool_ctx, + expected_output_patterns=[r"plan_path\s*=\s*/.+"], + ) + assert result.retry_reason == RetryReason.CONTRACT_RECOVERY + assert result.needs_retry is True + + @pytest.mark.anyio + async def test_nudge_skips_when_budget_exhausted(self, tool_ctx): + from datetime import UTC, datetime + + from autoskillit.core import FailureRecord + from autoskillit.execution.headless import run_headless_core + from autoskillit.pipeline.audit import DefaultAuditLog + + marker = tool_ctx.config.run_skill.completion_marker + audit = DefaultAuditLog() + for _ in range(4): + audit.record_failure( + FailureRecord( # type: ignore[arg-type] + timestamp=datetime.now(UTC).isoformat(), + skill_command="/autoskillit:make-plan foo", + exit_code=-1, + subtype="stale", + needs_retry=True, + retry_reason="stale", + stderr="", + ) + ) + tool_ctx.audit = audit + tool_ctx.runner.push(self._main_subprocess_result(marker)) + result = await run_headless_core( + "/autoskillit:make-plan foo", + cwd="/tmp", + ctx=tool_ctx, + expected_output_patterns=[r"plan_path\s*=\s*/.+"], + ) + assert result.retry_reason == RetryReason.BUDGET_EXHAUSTED + assert len(tool_ctx.runner.call_args_list) == 1 + + @pytest.mark.anyio + async def test_nudge_skips_when_no_session_id(self, tool_ctx): + from autoskillit.execution.headless import run_headless_core + + marker = tool_ctx.config.run_skill.completion_marker + ndjson = _ndjson_with_write(f"plan summary\n{marker}", ["/tmp/out.md"], session_id="") + tool_ctx.runner.push( + SubprocessResult( + 0, + ndjson, + "", + TerminationReason.NATURAL_EXIT, + pid=1, + channel_confirmation=ChannelConfirmation.CHANNEL_A, + ) + ) + result = await run_headless_core( + "/autoskillit:make-plan foo", + cwd="/tmp", + ctx=tool_ctx, + expected_output_patterns=[r"plan_path\s*=\s*/.+"], + ) + assert result.retry_reason == RetryReason.CONTRACT_RECOVERY + assert len(tool_ctx.runner.call_args_list) == 1 + + @pytest.mark.anyio + async def test_nudge_resume_cmd_uses_correct_session_id(self, tool_ctx): + from autoskillit.execution.headless import run_headless_core + + marker = tool_ctx.config.run_skill.completion_marker + tool_ctx.runner.push(self._main_subprocess_result(marker, session_id="sess-abc-123")) + tool_ctx.runner.push( + SubprocessResult( + 0, self._nudge_response_ndjson(marker), "", TerminationReason.NATURAL_EXIT, pid=2 + ) + ) + await run_headless_core( + "/autoskillit:make-plan foo", + cwd="/tmp", + ctx=tool_ctx, + expected_output_patterns=[r"plan_path\s*=\s*/.+"], + ) + assert len(tool_ctx.runner.call_args_list) == 2 + nudge_cmd = tool_ctx.runner.call_args_list[1][0] + assert "--resume" in nudge_cmd + resume_idx = nudge_cmd.index("--resume") + assert nudge_cmd[resume_idx + 1] == "sess-abc-123" + + @pytest.mark.anyio + async def test_nudge_token_usage_merged(self, tool_ctx): + from autoskillit.execution.headless import run_headless_core + + marker = tool_ctx.config.run_skill.completion_marker + main_ndjson_records = [ + json.dumps( + { + "type": "assistant", + "message": { + "content": [ + { + "type": "tool_use", + "name": "Write", + "id": "t0", + "input": {"file_path": "/tmp/out.md"}, + } + ] + }, + } + ), + json.dumps( + { + "type": "result", + "subtype": "success", + "is_error": False, + "result": f"plan summary\n{marker}", + "session_id": "sess-tok", + "usage": {"input_tokens": 1000, "output_tokens": 500}, + } + ), + ] + main_ndjson = "\n".join(main_ndjson_records) + + nudge_ndjson = json.dumps( + { + "type": "result", + "subtype": "success", + "is_error": False, + "result": f"plan_path = /tmp/out.md\n{marker}", + "session_id": "sess-tok", + "usage": {"input_tokens": 200, "output_tokens": 100}, + } + ) + + tool_ctx.runner.push( + SubprocessResult( + 0, + main_ndjson, + "", + TerminationReason.NATURAL_EXIT, + pid=1, + channel_confirmation=ChannelConfirmation.CHANNEL_A, + ) + ) + tool_ctx.runner.push( + SubprocessResult(0, nudge_ndjson, "", TerminationReason.NATURAL_EXIT, pid=2) + ) + + result = await run_headless_core( + "/autoskillit:make-plan foo", + cwd="/tmp", + ctx=tool_ctx, + expected_output_patterns=[r"plan_path\s*=\s*/.+"], + step_name="test-step", + ) + assert result.success is True + assert result.token_usage is not None + assert result.token_usage.get("input_tokens", 0) >= 1200 + assert result.token_usage.get("output_tokens", 0) >= 600 + + @pytest.mark.anyio + async def test_nudge_exception_falls_through(self, tool_ctx): + from autoskillit.execution.headless import run_headless_core + + marker = tool_ctx.config.run_skill.completion_marker + tool_ctx.runner.push(self._main_subprocess_result(marker)) + # Empty stdout nudge → patterns not found → falls through + tool_ctx.runner.push( + SubprocessResult(1, "", "RuntimeError", TerminationReason.NATURAL_EXIT, pid=2) + ) + result = await run_headless_core( + "/autoskillit:make-plan foo", + cwd="/tmp", + ctx=tool_ctx, + expected_output_patterns=[r"plan_path\s*=\s*/.+"], + ) + assert result.retry_reason == RetryReason.CONTRACT_RECOVERY + assert result.needs_retry is True diff --git a/tests/execution/test_headless_env_injection.py b/tests/execution/test_headless_env_injection.py index d98025e87c..c1d3dade64 100644 --- a/tests/execution/test_headless_env_injection.py +++ b/tests/execution/test_headless_env_injection.py @@ -46,8 +46,11 @@ async def test_headless_command_includes_headless_env_var(tmp_path: Path) -> Non await run_headless_core("/investigate foo", str(tmp_path), ctx) assert mock_runner.call_args_list, "runner was never called" - cmd, *_ = mock_runner.call_args_list[0] - assert "AUTOSKILLIT_HEADLESS=1" in cmd, ( - "run_headless_core must inject AUTOSKILLIT_HEADLESS=1 into the subprocess command " + cmd, _cwd, _timeout, kwargs = mock_runner.call_args_list[0] + env = kwargs.get("env") + assert env is not None + assert env["AUTOSKILLIT_HEADLESS"] == "1", ( + "run_headless_core must inject AUTOSKILLIT_HEADLESS=1 via the env kwarg " "so PreToolUse hooks can identify headless sessions." ) + assert cmd[0] != "env", "argv must no longer carry a leading ['env', ...] prefix" diff --git a/tests/execution/test_headless_env_scrub.py b/tests/execution/test_headless_env_scrub.py new file mode 100644 index 0000000000..4f31ee397b --- /dev/null +++ b/tests/execution/test_headless_env_scrub.py @@ -0,0 +1,45 @@ +"""Launch-site env-scrub contract test for run_headless_core. + +Asserts that ``CLAUDE_CODE_SSE_PORT`` and other IDE discovery vars are +stripped from the env passed to the subprocess runner, and that the +auto-connect suppressor is always present. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from tests.conftest import MockSubprocessRunner, _make_result + + +@pytest.mark.anyio +async def test_run_headless_core_env_excludes_ide_vars( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.setenv("CLAUDE_CODE_SSE_PORT", "23270") + monkeypatch.setenv("ENABLE_IDE_INTEGRATION", "true") + monkeypatch.setenv("CLAUDE_CODE_IDE_HOST_OVERRIDE", "host") + + from autoskillit.config import AutomationConfig + from autoskillit.execution.headless import run_headless_core + from autoskillit.pipeline import DefaultGateState + from autoskillit.server._factory import make_context + + mock_runner = MockSubprocessRunner() + mock_runner.set_default(_make_result()) + ctx = make_context(AutomationConfig(), runner=mock_runner, plugin_dir=str(tmp_path)) + ctx.gate = DefaultGateState(enabled=True) + + await run_headless_core("/investigate foo", str(tmp_path), ctx) + + assert mock_runner.call_args_list, "runner was never called" + _cmd, _cwd, _timeout, kwargs = mock_runner.call_args_list[0] + env = kwargs.get("env") + assert env is not None + assert "CLAUDE_CODE_SSE_PORT" not in env + assert "ENABLE_IDE_INTEGRATION" not in env + assert "CLAUDE_CODE_IDE_HOST_OVERRIDE" not in env + assert env["CLAUDE_CODE_AUTO_CONNECT_IDE"] == "0" + assert env["AUTOSKILLIT_HEADLESS"] == "1" diff --git a/tests/execution/test_linux_tracing.py b/tests/execution/test_linux_tracing.py index b00aabee95..45b3c3f501 100644 --- a/tests/execution/test_linux_tracing.py +++ b/tests/execution/test_linux_tracing.py @@ -72,23 +72,26 @@ def test_read_proc_snapshot_has_all_fields(): # context switches (psutil-sourced) assert snap.ctx_switches_voluntary >= 0 assert snap.ctx_switches_involuntary >= 0 + # cpu_percent field + assert isinstance(snap.cpu_percent, float) + assert snap.cpu_percent >= 0.0 @pytest.mark.anyio -async def test_tracing_handle_accumulates_snapshots(): +async def test_tracing_handle_accumulates_snapshots(tmp_path): """LinuxTracingHandle accumulates snapshots during monitoring.""" import subprocess import anyio from autoskillit.config import LinuxTracingConfig - from autoskillit.execution.linux_tracing import start_linux_tracing + from autoskillit.execution.linux_tracing import start_linux_tracing, trace_target_from_pid proc = subprocess.Popen(["sleep", "2"]) - cfg = LinuxTracingConfig(enabled=True, proc_interval=0.1) + cfg = LinuxTracingConfig(enabled=True, proc_interval=0.1, tmpfs_path=str(tmp_path)) async with anyio.create_task_group() as tg: - handle = start_linux_tracing(pid=proc.pid, config=cfg, tg=tg) + handle = start_linux_tracing(target=trace_target_from_pid(proc.pid), config=cfg, tg=tg) assert handle is not None await anyio.sleep(0.5) snapshots = handle.stop() @@ -101,19 +104,19 @@ async def test_tracing_handle_accumulates_snapshots(): @pytest.mark.anyio -async def test_tracing_handle_stop_returns_snapshots(): +async def test_tracing_handle_stop_returns_snapshots(tmp_path): """stop() returns the accumulated snapshot list.""" import os import anyio from autoskillit.config import LinuxTracingConfig - from autoskillit.execution.linux_tracing import start_linux_tracing + from autoskillit.execution.linux_tracing import start_linux_tracing, trace_target_from_pid - cfg = LinuxTracingConfig(enabled=True, proc_interval=0.1) + cfg = LinuxTracingConfig(enabled=True, proc_interval=0.1, tmpfs_path=str(tmp_path)) async with anyio.create_task_group() as tg: - handle = start_linux_tracing(pid=os.getpid(), config=cfg, tg=tg) + handle = start_linux_tracing(target=trace_target_from_pid(os.getpid()), config=cfg, tg=tg) assert handle is not None await anyio.sleep(0.3) result = handle.stop() @@ -123,24 +126,32 @@ async def test_tracing_handle_stop_returns_snapshots(): assert len(result) >= 1 -def test_linux_tracing_available_flag(): - """LINUX_TRACING_AVAILABLE is True on Linux, False elsewhere.""" +@pytest.mark.skipif(sys.platform != "linux", reason="Linux only") +def test_linux_tracing_available_on_linux(): + from autoskillit.execution.linux_tracing import LINUX_TRACING_AVAILABLE + + assert LINUX_TRACING_AVAILABLE is True + + +@pytest.mark.skipif(sys.platform == "linux", reason="Non-Linux only") +def test_linux_tracing_unavailable_on_non_linux(): from autoskillit.execution.linux_tracing import LINUX_TRACING_AVAILABLE - if sys.platform == "linux": - assert LINUX_TRACING_AVAILABLE is True - else: - assert LINUX_TRACING_AVAILABLE is False + assert LINUX_TRACING_AVAILABLE is False -def test_noop_on_non_linux(monkeypatch): +def test_noop_on_non_linux(monkeypatch, tmp_path): """start_linux_tracing is a no-op when LINUX_TRACING_AVAILABLE is False.""" + import os + from autoskillit.config import LinuxTracingConfig from autoskillit.execution import linux_tracing monkeypatch.setattr(linux_tracing, "LINUX_TRACING_AVAILABLE", False) - cfg = LinuxTracingConfig(enabled=True, proc_interval=1.0) - result = linux_tracing.start_linux_tracing(pid=1, config=cfg, tg=None) + cfg = LinuxTracingConfig(enabled=True, proc_interval=1.0, tmpfs_path=str(tmp_path)) + result = linux_tracing.start_linux_tracing( + target=linux_tracing.trace_target_from_pid(os.getpid()), config=cfg, tg=None + ) assert result is None @@ -161,17 +172,6 @@ async def test_proc_monitor_detects_death(): # --- captured_at tests --- -def test_proc_snapshot_has_captured_at(): - """read_proc_snapshot stamps captured_at on the returned snapshot.""" - from autoskillit.execution.linux_tracing import read_proc_snapshot - - snap = read_proc_snapshot(os.getpid()) - assert snap is not None - assert snap.captured_at != "" - # Must be a valid ISO-8601 UTC timestamp - datetime.fromisoformat(snap.captured_at) - - @pytest.mark.anyio async def test_proc_monitor_stamps_unique_captured_at(): """Each snapshot from proc_monitor has a distinct captured_at.""" @@ -192,11 +192,11 @@ async def test_proc_monitor_stamps_unique_captured_at(): async def test_start_linux_tracing_creates_trace_file(tmp_path): """When tmpfs_path is configured, start_linux_tracing opens a trace file.""" from autoskillit.config import LinuxTracingConfig - from autoskillit.execution.linux_tracing import start_linux_tracing + from autoskillit.execution.linux_tracing import start_linux_tracing, trace_target_from_pid config = LinuxTracingConfig(enabled=True, proc_interval=0.01, tmpfs_path=str(tmp_path)) async with anyio.create_task_group() as tg: - handle = start_linux_tracing(os.getpid(), config, tg) + handle = start_linux_tracing(trace_target_from_pid(os.getpid()), config, tg) assert handle is not None await anyio.sleep(0.05) tg.cancel_scope.cancel() @@ -212,20 +212,25 @@ async def test_streaming_writes_each_snapshot_as_jsonl(tmp_path): import subprocess from autoskillit.config import LinuxTracingConfig - from autoskillit.execution.linux_tracing import start_linux_tracing + from autoskillit.execution.linux_tracing import start_linux_tracing, trace_target_from_pid proc = subprocess.Popen(["sleep", "2"]) config = LinuxTracingConfig(enabled=True, proc_interval=0.05, tmpfs_path=str(tmp_path)) async with anyio.create_task_group() as tg: - handle = start_linux_tracing(proc.pid, config, tg) + handle = start_linux_tracing(trace_target_from_pid(proc.pid), config, tg) assert handle is not None await anyio.sleep(0.2) tg.cancel_scope.cancel() + # Save trace path and flush before stop() deletes the file on clean exit + trace_path = handle._trace_path + assert trace_path is not None + if handle._trace_file is not None: + handle._trace_file.flush() + content = trace_path.read_text() snapshots = handle.stop() - assert handle._trace_path is not None - lines = handle._trace_path.read_text().strip().split("\n") + lines = content.strip().split("\n") assert len(lines) >= 1 for line in lines: record = json.loads(line) @@ -267,7 +272,7 @@ def test_stop_idempotent(tmp_path): async def test_streaming_graceful_when_tmpfs_missing(tmp_path): """If tmpfs_path does not exist, tracing still works in-memory.""" from autoskillit.config import LinuxTracingConfig - from autoskillit.execution.linux_tracing import start_linux_tracing + from autoskillit.execution.linux_tracing import start_linux_tracing, trace_target_from_pid config = LinuxTracingConfig( enabled=True, @@ -275,7 +280,7 @@ async def test_streaming_graceful_when_tmpfs_missing(tmp_path): tmpfs_path=str(tmp_path / "nonexistent"), ) async with anyio.create_task_group() as tg: - handle = start_linux_tracing(os.getpid(), config, tg) + handle = start_linux_tracing(trace_target_from_pid(os.getpid()), config, tg) assert handle is not None await anyio.sleep(0.05) tg.cancel_scope.cancel() @@ -290,7 +295,6 @@ async def test_streaming_graceful_when_tmpfs_missing(tmp_path): def test_proc_snapshot_has_captured_at_field(): """ProcSnapshot must have a captured_at field populated at creation time.""" import os - from datetime import datetime from autoskillit.execution.linux_tracing import read_proc_snapshot @@ -304,21 +308,198 @@ def test_proc_snapshot_has_captured_at_field(): @pytest.mark.anyio -async def test_proc_monitor_snapshots_have_distinct_timestamps(): +async def test_proc_monitor_snapshots_have_distinct_timestamps(tmp_path): """Consecutive snapshots from proc_monitor must have distinct captured_at values.""" import os import anyio from autoskillit.config import LinuxTracingConfig - from autoskillit.execution.linux_tracing import start_linux_tracing + from autoskillit.execution.linux_tracing import start_linux_tracing, trace_target_from_pid - config = LinuxTracingConfig(proc_interval=0.05) + config = LinuxTracingConfig(proc_interval=0.05, tmpfs_path=str(tmp_path)) async with anyio.create_task_group() as tg: - handle = start_linux_tracing(os.getpid(), config, tg) + handle = start_linux_tracing(trace_target_from_pid(os.getpid()), config, tg) await anyio.sleep(0.2) result = handle.stop() tg.cancel_scope.cancel() assert len(result) >= 2 timestamps = [s.captured_at for s in result] assert len(set(timestamps)) == len(timestamps), "All captured_at must be unique" + + +@pytest.mark.anyio +async def test_proc_monitor_persists_psutil_process_for_cpu_percent(): + """proc_monitor reports cpu_percent > 0 for a CPU-bound subprocess. + + This is only possible when a single psutil.Process is reused across iterations + and its baseline is primed before the loop. A fresh Process per iteration always + returns 0.0 on the first cpu_percent(interval=0) call. + """ + import subprocess + + from autoskillit.execution.linux_tracing import proc_monitor + + proc = subprocess.Popen( + [sys.executable, "-c", "while True: pass"], + ) + try: + snaps = [] + with anyio.fail_after(10): + async for snap in proc_monitor(proc.pid, interval=0.1): + snaps.append(snap) + if len(snaps) >= 5: + break + assert len(snaps) >= 3, "Need at least 3 snapshots" + assert any(s.cpu_percent > 0.0 for s in snaps), ( + "At least one snapshot must show cpu_percent > 0.0 for a CPU-bound process" + ) + finally: + proc.kill() + proc.wait() + + +@pytest.mark.anyio +async def test_start_linux_tracing_writes_enrollment_sidecar(tmp_path): + """start_linux_tracing must write autoskillit_enrollment_{pid}.json immediately.""" + import anyio + + from autoskillit.config import LinuxTracingConfig + from autoskillit.execution.linux_tracing import start_linux_tracing, trace_target_from_pid + + cfg = LinuxTracingConfig(enabled=True, proc_interval=0.1, tmpfs_path=str(tmp_path)) + async with anyio.create_task_group() as tg: + proc = await anyio.open_process(["sleep", "2"]) + handle = start_linux_tracing(trace_target_from_pid(proc.pid), cfg, tg) + assert handle is not None + enrollment = tmp_path / f"autoskillit_enrollment_{proc.pid}.json" + assert enrollment.exists() + data = json.loads(enrollment.read_text()) + assert data["schema_version"] == 2 + assert data["pid"] == proc.pid + try: + handle.stop() + finally: + proc.kill() + assert not enrollment.exists(), "Enrollment must be deleted by stop()" + + +# --- LinuxTracingConfig guard tests --- + + +def test_tracing_config_rejects_dev_shm_in_test_env(monkeypatch): + """LinuxTracingConfig.__post_init__ must raise when tmpfs_path is /dev/shm + and PYTEST_CURRENT_TEST env var is set.""" + from autoskillit.config import LinuxTracingConfig + + monkeypatch.setenv( + "PYTEST_CURRENT_TEST", + "tests/execution/test_linux_tracing.py::fake_test", + ) + with pytest.raises(RuntimeError, match="tmpfs_path|PYTEST_CURRENT_TEST"): + LinuxTracingConfig(tmpfs_path="/dev/shm") + + +def test_tracing_config_allows_custom_tmpfs_in_test_env(monkeypatch, tmp_path): + """LinuxTracingConfig must not raise when a non-/dev/shm path is provided.""" + from autoskillit.config import LinuxTracingConfig + + monkeypatch.setenv( + "PYTEST_CURRENT_TEST", + "tests/execution/test_linux_tracing.py::fake_test", + ) + cfg = LinuxTracingConfig(tmpfs_path=str(tmp_path)) # must not raise + assert cfg.tmpfs_path == str(tmp_path) + + +def test_tracing_config_allows_dev_shm_outside_test_env(monkeypatch): + """LinuxTracingConfig must not raise for /dev/shm when not running under pytest.""" + from autoskillit.config import LinuxTracingConfig + + monkeypatch.delenv("PYTEST_CURRENT_TEST", raising=False) + cfg = LinuxTracingConfig(tmpfs_path="/dev/shm") # production path — must not raise + assert cfg.tmpfs_path == "/dev/shm" + + +def test_isolated_tracing_config_fixture_returns_non_dev_shm(isolated_tracing_config): + """The isolated_tracing_config fixture must return a config pointing to a + temp dir, not /dev/shm.""" + from pathlib import Path + + assert isolated_tracing_config.tmpfs_path != "/dev/shm" + assert Path(isolated_tracing_config.tmpfs_path).is_dir() + + +# --- Test 1.2: ProcSnapshot carries a comm field --- + + +def test_proc_snapshot_has_comm_field(): + """ProcSnapshot.comm is populated from /proc/{pid}/comm on every snapshot. + + Test 1.2: guards against regression of the self-identifying snapshot invariant. + comm provides identity anchoring so every snapshot in proc_trace.jsonl can be + cross-checked against the expected workload process. + """ + import os + + from autoskillit.execution.linux_tracing import read_proc_snapshot + + snap = read_proc_snapshot(os.getpid()) + assert snap is not None + assert hasattr(snap, "comm"), ( + "ProcSnapshot must have a 'comm' field populated from /proc/{pid}/comm" + ) + assert isinstance(snap.comm, str) and snap.comm, "ProcSnapshot.comm must be a non-empty string" + # /proc/self/comm contains the process name (typically 'python' or 'pytest') + expected_comm = open(f"/proc/{os.getpid()}/comm").read().strip() # noqa: SIM115 + assert snap.comm == expected_comm, ( + f"snap.comm {snap.comm!r} must match /proc/{os.getpid()}/comm {expected_comm!r}" + ) + + +# --- Test 1.5: start_linux_tracing rejects raw int --- + + +def test_start_linux_tracing_requires_trace_target(): + """start_linux_tracing(target=...) must accept TraceTarget, reject raw int. + + Test 1.5: locks the type contract. Any future caller that passes an int gets + a hard failure rather than silent wrong-process observation. + """ + from autoskillit.execution.linux_tracing import start_linux_tracing + + # Annotation must reference TraceTarget by name (from __future__ import annotations + # makes annotations lazy strings; verify the string contains "TraceTarget") + ann = start_linux_tracing.__annotations__.get("target", "") + assert "TraceTarget" in str(ann), ( + f"start_linux_tracing 'target' parameter must be annotated as TraceTarget, " + f"got annotation {ann!r}" + ) + + # Passing a raw int as target must raise TypeError at runtime + with pytest.raises(TypeError): + start_linux_tracing(target=123, config=None, tg=None) # type: ignore[arg-type] + + +@pytest.mark.anyio +async def test_stop_unlinks_trace_and_enrollment(tmp_path): + """stop() must delete both trace JSONL and enrollment sidecar on clean exit.""" + import anyio + + from autoskillit.config import LinuxTracingConfig + from autoskillit.execution.linux_tracing import start_linux_tracing, trace_target_from_pid + + cfg = LinuxTracingConfig(enabled=True, proc_interval=0.1, tmpfs_path=str(tmp_path)) + async with anyio.create_task_group() as tg: + proc = await anyio.open_process(["sleep", "2"]) + handle = start_linux_tracing(trace_target_from_pid(proc.pid), cfg, tg) + assert handle is not None + trace = tmp_path / f"autoskillit_trace_{proc.pid}.jsonl" + enrollment = tmp_path / f"autoskillit_enrollment_{proc.pid}.json" + assert trace.exists() + try: + handle.stop() + finally: + proc.kill() + assert not trace.exists(), "Trace file must be deleted on clean stop()" + assert not enrollment.exists(), "Enrollment sidecar must be deleted on clean stop()" diff --git a/tests/execution/test_linux_tracing_pty_integration.py b/tests/execution/test_linux_tracing_pty_integration.py new file mode 100644 index 0000000000..4fef51cad2 --- /dev/null +++ b/tests/execution/test_linux_tracing_pty_integration.py @@ -0,0 +1,136 @@ +"""Integration test: PTY-wrapped command is traced at the workload level, not the wrapper. + +Regression test for issue #806: anyio.open_process([script, ...]) returns the PID +of the script(1) PTY wrapper, not the intended workload binary. Before the fix, +every snapshot in proc_trace.jsonl described script(1) (~2 MB RSS, 1 thread, +do_sys_poll wchan) instead of the actual workload. + +After the fix (TraceTarget resolver), the tracer resolves from the spawn PID to +the workload PID by walking descendants and matching on the command basename. +""" + +from __future__ import annotations + +import json +import shutil +import sys + +import pytest + +from tests.execution.conftest import _ALLOCATE_60MB_SCRIPT + +pytestmark = pytest.mark.skipif( + sys.platform != "linux", + reason="Linux only — tests PTY wrapping + /proc tracing", +) + +# Skip the entire module when script(1) is absent; no stub needed. +pytestmark_script = pytest.mark.skipif( + shutil.which("script") is None, + reason="script(1) not available on this system", +) + + +@pytestmark_script +@pytest.mark.anyio +async def test_pty_wrapped_command_is_traced_as_grandchild(isolated_tracing_config, tmp_path): + """run_managed_async(pty_mode=True, tracing) observes the workload, not script(1). + + Test 1.1 — reproduces the exact production combination that no pre-#806 test + exercised: pty_mode=True + linux_tracing_config together. + + Failure signal: + - peak_rss_kb ≤ 30_000 → tracer is watching script(1) (~2 MB) + - comm == 'script' in snapshots → tracer is watching script(1) by name + """ + from autoskillit.execution.process import run_managed_async + + helper = tmp_path / "allocate_60mb.py" + helper.write_text(_ALLOCATE_60MB_SCRIPT) + + result = await run_managed_async( + ["python3", str(helper)], + cwd=tmp_path, + timeout=30.0, + pty_mode=True, + linux_tracing_config=isolated_tracing_config, + ) + + assert result.proc_snapshots is not None, ( + "proc_snapshots must be collected when linux_tracing_config is provided" + ) + snapshots = result.proc_snapshots + assert len(snapshots) >= 1, "At least one snapshot must be captured" + + # No snapshot should describe script(1) — only the workload + comms = [s.get("comm", "") for s in snapshots] + assert "script" not in comms, ( + f"Found script(1) comm in snapshots — tracer is still observing the PTY wrapper. " + f"comms={comms}. This is issue #806." + ) + + # At least one snapshot must show the workload's elevated RSS + peak_rss = max((s.get("vm_rss_kb", 0) for s in snapshots), default=0) + assert peak_rss > 30_000, ( + f"Peak RSS is {peak_rss} KB — too low for a 60 MB allocation. " + "If the tracer is watching script(1) it would see ~2 MB RSS. " + "This is the exact fingerprint of issue #806." + ) + + # At least one snapshot must self-identify as the python workload + workload_comms = [c for c in comms if "python" in c.lower()] + assert workload_comms, ( + f"No python comm found in snapshots. comms={comms}. " + "The workload process should have comm containing 'python'." + ) + + +@pytestmark_script +@pytest.mark.anyio +async def test_pty_wrapped_tracing_produces_no_script_snapshots_in_proc_trace_jsonl( + isolated_tracing_config, tmp_path +): + """proc_trace.jsonl must not contain any rows with comm='script'. + + Test 1.10 (partial): after the fix, every row in proc_trace.jsonl self-identifies + the tracked process, and 'script' must never appear there. + """ + from autoskillit.execution.process import run_managed_async + from autoskillit.execution.session_log import flush_session_log + + helper = tmp_path / "allocate_60mb.py" + helper.write_text(_ALLOCATE_60MB_SCRIPT) + + result = await run_managed_async( + ["python3", str(helper)], + cwd=tmp_path, + timeout=30.0, + pty_mode=True, + linux_tracing_config=isolated_tracing_config, + ) + + assert result.proc_snapshots is not None + + flush_session_log( + log_dir=str(tmp_path / "logs"), + cwd=str(tmp_path), + session_id="pty-trace-test-001", + pid=result.pid, + skill_command="/test", + success=result.returncode == 0, + subtype="completed", + exit_code=result.returncode if result.returncode is not None else -1, + start_ts=result.start_ts or "2026-01-01T00:00:00+00:00", + proc_snapshots=result.proc_snapshots, + ) + + trace_path = tmp_path / "logs" / "sessions" / "pty-trace-test-001" / "proc_trace.jsonl" + assert trace_path.exists(), "proc_trace.jsonl must be written" + rows = [json.loads(line) for line in trace_path.read_text().splitlines()] + assert rows, "proc_trace.jsonl must have at least one row" + + for row in rows: + assert "comm" in row, f"Every row must have a 'comm' field. Row: {row}" + assert row["comm"] != "script", ( + f"Found comm='script' in proc_trace.jsonl — tracer observed PTY wrapper. Row: {row}" + ) diff --git a/tests/execution/test_merge_queue.py b/tests/execution/test_merge_queue.py index b7cd26d7a0..0537898a3e 100644 --- a/tests/execution/test_merge_queue.py +++ b/tests/execution/test_merge_queue.py @@ -8,7 +8,13 @@ import httpx import pytest -from autoskillit.execution.merge_queue import DefaultMergeQueueWatcher, PRFetchState +import autoskillit.execution.merge_queue as _mq +from autoskillit.core.types import PRState +from autoskillit.execution.merge_queue import ( + ClassifierInconclusive, + DefaultMergeQueueWatcher, + PRFetchState, +) def _make_watcher() -> DefaultMergeQueueWatcher: @@ -19,7 +25,9 @@ def _queue_state( *, merged: bool = False, state: str = "OPEN", + mergeable: str = "MERGEABLE", merge_state_status: str = "CLEAN", + auto_merge_present: bool = False, auto_merge_enabled_at: datetime | None = None, pr_node_id: str = "PR_kwDO_test", in_queue: bool = False, @@ -29,7 +37,9 @@ def _queue_state( return { "merged": merged, "state": state, + "mergeable": mergeable, "merge_state_status": merge_state_status, + "auto_merge_present": auto_merge_present, "auto_merge_enabled_at": auto_merge_enabled_at, "pr_node_id": pr_node_id, "in_queue": in_queue, @@ -67,14 +77,14 @@ async def test_returns_merged_when_pr_closed_and_merged(self): assert result["pr_state"] == "merged" @pytest.mark.anyio - async def test_returns_ejected_when_not_in_queue_not_stuck(self): - """Two consecutive 'open, not in queue, no auto_merge' cycles → ejected.""" + async def test_returns_ejected_when_mergeable_conflicting_and_not_in_queue(self): + """mergeable=CONFLICTING + not in queue → ejected via positive conflicting signal.""" watcher = _make_watcher() watcher._fetch_pr_and_queue_state = AsyncMock( # type: ignore[method-assign] return_value=_queue_state( merged=False, in_queue=False, - auto_merge_enabled_at=None, + mergeable="CONFLICTING", merge_state_status="BLOCKED", ) ) @@ -274,10 +284,10 @@ async def test_no_false_ejection_when_pr_merges_between_cycles(self): @pytest.mark.anyio async def test_confirmation_window_delays_ejection_by_one_cycle(self): - """Two consecutive 'not in queue' cycles with no auto_merge → ejected, not on cycle 1.""" + """Two consecutive not-in-queue cycles required before acting on CONFLICTING ejection.""" watcher = _make_watcher() state = _queue_state( - merged=False, in_queue=False, auto_merge_enabled_at=None, merge_state_status="BLOCKED" + merged=False, in_queue=False, mergeable="CONFLICTING", merge_state_status="BLOCKED" ) watcher._fetch_pr_and_queue_state = AsyncMock(return_value=state) # type: ignore[method-assign] with patch("autoskillit.execution.merge_queue.asyncio.sleep", new_callable=AsyncMock): @@ -679,13 +689,37 @@ async def _fetch(*_a, **_kw): assert call_count >= 3 @pytest.mark.anyio - async def test_returns_ejected_when_checks_terminal_and_not_in_queue(self): - """checks_state=SUCCESS + not in queue → genuine ejection (guard must not block it).""" + async def test_returns_dropped_healthy_when_checks_success_and_mergeable(self): + """Healthy PR (SUCCESS + MERGEABLE + CLEAN + auto_merge cleared) → dropped_healthy. + + This is the exact issue #802 failure mode: the old elimination classifier returned + 'ejected' for this state because no other gate matched. The new classifier returns + DROPPED_HEALTHY via positive signal — auto_merge was cleared while the PR was healthy. + """ watcher = _make_watcher() watcher._fetch_pr_and_queue_state = AsyncMock( # type: ignore[method-assign] return_value=_queue_state( in_queue=False, - auto_merge_enabled_at=None, + mergeable="MERGEABLE", + merge_state_status="CLEAN", + checks_state="SUCCESS", + auto_merge_present=False, + ) + ) + with patch("autoskillit.execution.merge_queue.asyncio.sleep", new_callable=AsyncMock): + result = await watcher.wait(pr_number=1, target_branch="main", repo="owner/repo") + + assert result["success"] is False + assert result["pr_state"] == "dropped_healthy" + + @pytest.mark.anyio + async def test_returns_ejected_when_checks_success_but_mergeable_conflicting(self): + """checks_state=SUCCESS + mergeable=CONFLICTING → ejected via positive CONFLICTING gate.""" + watcher = _make_watcher() + watcher._fetch_pr_and_queue_state = AsyncMock( # type: ignore[method-assign] + return_value=_queue_state( + in_queue=False, + mergeable="CONFLICTING", merge_state_status="BLOCKED", checks_state="SUCCESS", ) @@ -697,12 +731,18 @@ async def test_returns_ejected_when_checks_terminal_and_not_in_queue(self): assert result["pr_state"] == "ejected" @pytest.mark.anyio - async def test_returns_ejected_when_no_status_checks_configured(self): - """checks_state=None (no required checks) → ejected; unchanged for repos without CI.""" + async def test_returns_ejected_when_no_checks_configured_but_conflicting(self): + """checks_state=None + mergeable=CONFLICTING → ejected via positive CONFLICTING signal. + + For repos without required CI checks, ejection requires a positive mergeable=CONFLICTING + signal rather than the absence of checks. ClassifierInconclusive handles the ambiguous + case (no CI, no conflict signal) by continuing to poll. + """ watcher = _make_watcher() watcher._fetch_pr_and_queue_state = AsyncMock( # type: ignore[method-assign] return_value=_queue_state( in_queue=False, + mergeable="CONFLICTING", merge_state_status="BLOCKED", checks_state=None, ) @@ -752,6 +792,262 @@ def test_implements_merge_queue_watcher_protocol(self): assert isinstance(_make_watcher(), MergeQueueWatcher) +class TestInconclusiveBudget: + """Tests for the split inconclusive budget: CIStillRunning vs NoPositiveSignal.""" + + @pytest.mark.anyio + async def test_pending_ci_does_not_exhaust_inconclusive_budget(self): + """CIStillRunning must not consume inconclusive_count. + Six PENDING cycles with budget=3 must NOT trigger budget ceiling. + timeout_seconds=99999 ensures outer deadline is not the cause. + """ + watcher = DefaultMergeQueueWatcher(token=None) + call_count = 0 + + async def _fetch(*_a, **_kw): + nonlocal call_count + call_count += 1 + if call_count > 6: + return _queue_state(merged=True) + return _queue_state( + merged=False, + in_queue=False, + checks_state="PENDING", + merge_state_status="BLOCKED", + auto_merge_enabled_at=None, + ) + + watcher._fetch_pr_and_queue_state = _fetch # type: ignore[method-assign] + with patch("autoskillit.execution.merge_queue.asyncio.sleep", new_callable=AsyncMock): + result = await watcher.wait( + pr_number=42, + target_branch="main", + repo="owner/repo", + poll_interval=1, + timeout_seconds=99999, + ) + + assert result["success"] is True + assert result["pr_state"] == "merged" + + @pytest.mark.anyio + async def test_expected_ci_does_not_exhaust_inconclusive_budget(self): + """CIStillRunning (EXPECTED) must not consume inconclusive_count. + Six EXPECTED cycles with budget=3 must NOT trigger budget ceiling. + """ + watcher = DefaultMergeQueueWatcher(token=None) + call_count = 0 + + async def _fetch(*_a, **_kw): + nonlocal call_count + call_count += 1 + if call_count > 6: + return _queue_state(merged=True) + return _queue_state( + merged=False, + in_queue=False, + checks_state="EXPECTED", + merge_state_status="BLOCKED", + auto_merge_enabled_at=None, + ) + + watcher._fetch_pr_and_queue_state = _fetch # type: ignore[method-assign] + with patch("autoskillit.execution.merge_queue.asyncio.sleep", new_callable=AsyncMock): + result = await watcher.wait( + pr_number=42, + target_branch="main", + repo="owner/repo", + poll_interval=1, + timeout_seconds=99999, + ) + + assert result["success"] is True + assert result["pr_state"] == "merged" + + @pytest.mark.anyio + async def test_no_positive_signal_exhausts_budget_returns_timeout(self): + """NoPositiveSignal must still exhaust the bounded budget. + Unknown state with no positive classifier match × (window + N) cycles + → pr_state='timeout'. Reason must contain 'Inconclusive after'. + """ + watcher = DefaultMergeQueueWatcher(token=None) + watcher._fetch_pr_and_queue_state = AsyncMock( # type: ignore[method-assign] + return_value=_queue_state( + merged=False, + in_queue=False, + checks_state="SUCCESS", + mergeable="UNKNOWN", + merge_state_status="UNKNOWN", + auto_merge_enabled_at=None, + ) + ) + with patch("autoskillit.execution.merge_queue.asyncio.sleep", new_callable=AsyncMock): + result = await watcher.wait( + pr_number=42, + target_branch="main", + repo="owner/repo", + poll_interval=1, + timeout_seconds=99999, + ) + + assert result["success"] is False + assert result["pr_state"] == "timeout" + assert "Inconclusive after" in result["reason"] + + @pytest.mark.anyio + async def test_inconclusive_count_resets_on_queue_reentry(self): + """inconclusive_count must reset when in_queue becomes True. + Scenario: out(PENDING×5) → in_queue → out(PENDING×5) → merged. + Budget=3. Without reset: second phase exhausts budget immediately. + With reset: both phases are tolerated independently. + """ + watcher = DefaultMergeQueueWatcher(token=None) + call_count = 0 + + async def _fetch(*_a, **_kw): + nonlocal call_count + call_count += 1 + if call_count <= 5: + return _queue_state( + merged=False, + in_queue=False, + checks_state="PENDING", + merge_state_status="BLOCKED", + auto_merge_enabled_at=None, + ) + if call_count == 6: + return _queue_state(merged=False, in_queue=True) + if call_count <= 11: + return _queue_state( + merged=False, + in_queue=False, + checks_state="PENDING", + merge_state_status="BLOCKED", + auto_merge_enabled_at=None, + ) + return _queue_state(merged=True) + + watcher._fetch_pr_and_queue_state = _fetch # type: ignore[method-assign] + with patch("autoskillit.execution.merge_queue.asyncio.sleep", new_callable=AsyncMock): + result = await watcher.wait( + pr_number=42, + target_branch="main", + repo="owner/repo", + poll_interval=1, + timeout_seconds=99999, + ) + + assert result["success"] is True + assert result["pr_state"] == "merged" + + @pytest.mark.anyio + async def test_confirmation_window_does_not_consume_inconclusive_budget(self): + """CIStillRunning (PENDING) must never consume the inconclusive budget at any cycle. + confirmation_cycles=4, budget=3: all 7 PENDING cycles complete without budget exhaustion + because PENDING raises CIStillRunning (exempt from budget). Merged on call 8. + """ + watcher = DefaultMergeQueueWatcher(token=None) + call_count = 0 + + async def _fetch(*_a, **_kw): + nonlocal call_count + call_count += 1 + if call_count > 7: + return _queue_state(merged=True) + return _queue_state( + merged=False, + in_queue=False, + checks_state="PENDING", + merge_state_status="BLOCKED", + auto_merge_enabled_at=None, + ) + + watcher._fetch_pr_and_queue_state = _fetch # type: ignore[method-assign] + with patch("autoskillit.execution.merge_queue.asyncio.sleep", new_callable=AsyncMock): + result = await watcher.wait( + pr_number=42, + target_branch="main", + repo="owner/repo", + poll_interval=1, + timeout_seconds=99999, + not_in_queue_confirmation_cycles=4, + ) + + assert result["success"] is True + assert result["pr_state"] == "merged" + assert call_count == 8 + + @pytest.mark.anyio + async def test_wait_accepts_max_inconclusive_retries_per_call_param(self): + """max_inconclusive_retries must be a wait() parameter, not constructor-only. + Passing it must not raise TypeError. Passing a small value (1) must cause + budget exhaustion after 1 NoPositiveSignal cycle beyond the confirmation window. + """ + watcher = _make_watcher() + # State: unknown — no positive classifier fires → NoPositiveSignal + watcher._fetch_pr_and_queue_state = AsyncMock( # type: ignore[method-assign] + return_value=_queue_state( + merged=False, + in_queue=False, + checks_state="SUCCESS", + mergeable="UNKNOWN", + merge_state_status="UNKNOWN", + auto_merge_enabled_at=None, + ) + ) + with patch("autoskillit.execution.merge_queue.asyncio.sleep", new_callable=AsyncMock): + result = await watcher.wait( + pr_number=42, + target_branch="main", + repo="owner/repo", + poll_interval=1, + timeout_seconds=99999, + max_inconclusive_retries=1, # ← per-call override + ) + + assert result["success"] is False + assert result["pr_state"] == "timeout" + assert "Inconclusive after 1 retries" in result["reason"] + + @pytest.mark.anyio + async def test_per_call_max_inconclusive_retries_overrides_constructor_default(self): + """Per-call value must take precedence over the constructor default of 5. + budget=2 per call, constructor default would be 5. Budget exhaustion must + occur after 2 ambiguous cycles (+ confirmation window), not 5. + """ + watcher = _make_watcher() # constructor default = 5 + call_count = 0 + + async def _fetch(*_a, **_kw): + nonlocal call_count + call_count += 1 + return _queue_state( + merged=False, + in_queue=False, + checks_state="SUCCESS", + mergeable="UNKNOWN", + merge_state_status="UNKNOWN", + auto_merge_enabled_at=None, + ) + + watcher._fetch_pr_and_queue_state = _fetch # type: ignore[method-assign] + with patch("autoskillit.execution.merge_queue.asyncio.sleep", new_callable=AsyncMock): + result = await watcher.wait( + pr_number=42, + target_branch="main", + repo="owner/repo", + poll_interval=1, + timeout_seconds=99999, + max_inconclusive_retries=2, # ← per-call override + ) + + assert result["success"] is False + assert result["pr_state"] == "timeout" + # confirmation_cycles=2 (default): cycle 1 is window, cycles 2-3 consume budget + # budget=2: exhausted on call 3 → total calls = 3 + assert call_count == 3 + + class TestRelatedCoverage: """Coverage for related untested paths found during investigation.""" @@ -803,3 +1099,412 @@ async def test_returns_error_when_repo_has_no_slash(self): assert result["success"] is False assert result["pr_state"] == "error" assert "Invalid repo format" in result["reason"] + + +class TestEjectionEnrichment: + """Tests ejection response enrichment with CI failure cause.""" + + @pytest.mark.anyio + async def test_ejected_ci_failure_when_checks_state_is_failure(self): + """When checks_state=FAILURE, wait() returns pr_state='ejected_ci_failure'.""" + watcher = _make_watcher() + watcher._fetch_pr_and_queue_state = AsyncMock( # type: ignore[method-assign] + return_value=_queue_state( + merged=False, + in_queue=False, + checks_state="FAILURE", + merge_state_status="BLOCKED", + auto_merge_enabled_at=None, + ) + ) + with patch("autoskillit.execution.merge_queue.asyncio.sleep", new_callable=AsyncMock): + result = await watcher.wait( + pr_number=42, + target_branch="main", + repo="owner/repo", + poll_interval=1, + not_in_queue_confirmation_cycles=2, + ) + assert result["success"] is False + assert result["pr_state"] == "ejected_ci_failure" + assert result.get("ejection_cause") == "ci_failure" + + @pytest.mark.anyio + async def test_ejected_when_checks_state_is_none(self): + """checks_state=None + mergeable=CONFLICTING → pr_state='ejected', no ejection_cause.""" + watcher = _make_watcher() + watcher._fetch_pr_and_queue_state = AsyncMock( # type: ignore[method-assign] + return_value=_queue_state( + merged=False, + in_queue=False, + checks_state=None, + merge_state_status="BLOCKED", + mergeable="CONFLICTING", + auto_merge_enabled_at=None, + ) + ) + with patch("autoskillit.execution.merge_queue.asyncio.sleep", new_callable=AsyncMock): + result = await watcher.wait( + pr_number=42, + target_branch="main", + repo="owner/repo", + poll_interval=1, + not_in_queue_confirmation_cycles=2, + ) + assert result["success"] is False + assert result["pr_state"] == "ejected" + assert "ejection_cause" not in result + + @pytest.mark.anyio + async def test_ejected_when_checks_state_is_success(self): + """checks_state=SUCCESS + mergeable=CONFLICTING → pr_state='ejected', no enrichment.""" + watcher = _make_watcher() + watcher._fetch_pr_and_queue_state = AsyncMock( # type: ignore[method-assign] + return_value=_queue_state( + merged=False, + in_queue=False, + checks_state="SUCCESS", + merge_state_status="BLOCKED", + mergeable="CONFLICTING", + auto_merge_enabled_at=None, + ) + ) + with patch("autoskillit.execution.merge_queue.asyncio.sleep", new_callable=AsyncMock): + result = await watcher.wait( + pr_number=42, + target_branch="main", + repo="owner/repo", + poll_interval=1, + not_in_queue_confirmation_cycles=2, + ) + assert result["success"] is False + assert result["pr_state"] == "ejected" + assert "ejection_cause" not in result + + @pytest.mark.anyio + async def test_ejected_ci_failure_on_closed_pr_with_failure_checks(self): + """CLOSED state with checks_state=FAILURE → ejected_ci_failure.""" + watcher = _make_watcher() + watcher._fetch_pr_and_queue_state = AsyncMock( # type: ignore[method-assign] + return_value=_queue_state( + state="CLOSED", + merged=False, + checks_state="FAILURE", + ) + ) + result = await watcher.wait( + pr_number=42, target_branch="main", repo="owner/repo", poll_interval=1 + ) + assert result["success"] is False + assert result["pr_state"] == "ejected_ci_failure" + assert result.get("ejection_cause") == "ci_failure" + + @pytest.mark.anyio + async def test_ejected_ci_failure_after_in_queue_to_not_in_queue_transition(self): + """in_queue=True on first poll, then in_queue=False+FAILURE → ejected_ci_failure.""" + watcher = _make_watcher() + watcher._fetch_pr_and_queue_state = AsyncMock( # type: ignore[method-assign] + side_effect=[ + _queue_state(in_queue=True, checks_state=None), + _queue_state( + in_queue=False, + checks_state="FAILURE", + merge_state_status="BLOCKED", + auto_merge_enabled_at=None, + ), + _queue_state( + in_queue=False, + checks_state="FAILURE", + merge_state_status="BLOCKED", + auto_merge_enabled_at=None, + ), + ] + ) + with patch("autoskillit.execution.merge_queue.asyncio.sleep", new_callable=AsyncMock): + result = await watcher.wait( + pr_number=42, + target_branch="main", + repo="owner/repo", + poll_interval=1, + not_in_queue_confirmation_cycles=2, + ) + assert result["success"] is False + assert result["pr_state"] == "ejected_ci_failure" + assert result.get("ejection_cause") == "ci_failure" + + +# --------------------------------------------------------------------------- +# Part A: New classifier immunity tests (T1–T6) +# --------------------------------------------------------------------------- + + +class TestClassifierImmunity: + """Positive-signal immunity tests for the extracted _classify_pr_state function.""" + + # --- T1: Reproduces the reported bug --- + + def test_classifier_returns_dropped_healthy_when_auto_merge_cleared_on_healthy_pr(self): + """Exact issue #802 state: healthy PR with auto_merge cleared → DROPPED_HEALTHY.""" + state = _queue_state( + merged=False, + state="OPEN", + mergeable="MERGEABLE", + merge_state_status="CLEAN", + checks_state="SUCCESS", + in_queue=False, + auto_merge_present=False, + ) + result = _mq._classify_pr_state(state) + assert result.terminal == PRState.DROPPED_HEALTHY + + # --- T2: Positive-signal contract: EJECTED requires positive signal --- + + @pytest.mark.parametrize( + "state", + [ + # open + MERGEABLE + CLEAN + PENDING checks + _queue_state( + mergeable="MERGEABLE", + merge_state_status="CLEAN", + checks_state="PENDING", + auto_merge_present=True, + ), + # open + UNKNOWN mergeable + CLEAN + SUCCESS + _queue_state( + mergeable="UNKNOWN", + merge_state_status="CLEAN", + checks_state="SUCCESS", + ), + # open + MERGEABLE + HAS_HOOKS + SUCCESS + auto_merge_present=True + _queue_state( + mergeable="MERGEABLE", + merge_state_status="HAS_HOOKS", + checks_state="SUCCESS", + auto_merge_present=True, + ), + ], + ) + def test_classifier_never_returns_ejected_without_positive_signal(self, state): + """For ambiguous-but-healthy states, classifier must NOT return EJECTED.""" + try: + result = _mq._classify_pr_state(state) + assert result.terminal != PRState.EJECTED, ( + f"Classifier returned EJECTED without a positive signal for state: {state}" + ) + except ClassifierInconclusive: + pass # expected — no positive signal matched + + # --- T3: Classifier raises ClassifierInconclusive — no silent fall-through --- + + def test_classifier_raises_inconclusive_when_no_positive_signal_matches(self): + """ClassifierInconclusive raised when no positive gate matches; .state exposes fields.""" + state = _queue_state( + merged=False, + state="OPEN", + mergeable="UNKNOWN", + merge_state_status="BEHIND", + checks_state=None, + auto_merge_present=True, + in_queue=False, + ) + with pytest.raises(ClassifierInconclusive) as exc_info: + _mq._classify_pr_state(state) + assert exc_info.value.state is state + assert exc_info.value.reason + + # --- T4: Exhaustive PRState coverage --- + + @pytest.mark.parametrize( + "expected_terminal,state", + [ + ( + PRState.MERGED, + _queue_state(merged=True), + ), + ( + PRState.EJECTED, + _queue_state( + merged=False, + state="OPEN", + mergeable="CONFLICTING", + in_queue=False, + ), + ), + ( + PRState.EJECTED_CI_FAILURE, + _queue_state( + merged=False, + state="OPEN", + checks_state="FAILURE", + in_queue=False, + ), + ), + ( + PRState.STALLED, + _queue_state( + merged=False, + state="OPEN", + mergeable="MERGEABLE", + merge_state_status="CLEAN", + auto_merge_enabled_at=datetime.now(UTC) - timedelta(seconds=120), + auto_merge_present=True, + in_queue=False, + ), + ), + ( + PRState.DROPPED_HEALTHY, + _queue_state( + merged=False, + state="OPEN", + mergeable="MERGEABLE", + merge_state_status="CLEAN", + checks_state="SUCCESS", + auto_merge_present=False, + in_queue=False, + ), + ), + ], + ) + def test_classifier_returns_expected_terminal_for_canonical_fixture( + self, expected_terminal, state + ): + """Every classifier-reachable PRState terminal has at least one positive fixture.""" + result = _mq._classify_pr_state(state) + assert result.terminal == expected_terminal + + # --- T5: Import-time schema round-trip guard --- + + def test_query_field_map_matches_prfetchstate_required_keys(self): + """_QUERY_FIELD_MAP keys must exactly match PRFetchState required+optional keys.""" + all_keys = PRFetchState.__required_keys__ | PRFetchState.__optional_keys__ + assert set(_mq._QUERY_FIELD_MAP) == all_keys, ( + f"Mismatch — missing from map: {all_keys - set(_mq._QUERY_FIELD_MAP)}, " + f"extra in map: {set(_mq._QUERY_FIELD_MAP) - all_keys}" + ) + + # --- T6: Fixture immunity --- + + def test_queue_state_fixture_populates_all_prfetchstate_fields(self): + """_queue_state() must cover every PRFetchState key so new fields are caught at once.""" + all_keys = PRFetchState.__required_keys__ | PRFetchState.__optional_keys__ + fixture_keys = set(_queue_state().keys()) + assert fixture_keys == all_keys, ( + f"_queue_state() missing keys: {all_keys - fixture_keys}, " + f"extra keys: {fixture_keys - all_keys}" + ) + + +# --------------------------------------------------------------------------- +# fetch_repo_merge_state rate-limit retry +# --------------------------------------------------------------------------- + + +_SUCCESS_BODY = { + "data": { + "repository": { + "mergeQueue": None, + "autoMergeAllowed": False, + "object": None, + } + } +} + + +class TestFetchRepoMergeStateRetry: + """Tests for HTTP 429 / secondary-rate-limit 403 retry behaviour.""" + + @pytest.mark.anyio + async def test_retries_on_429(self, httpx_mock, monkeypatch): + """Retries on HTTP 429, succeeds on second attempt.""" + sleep_calls: list[float] = [] + + async def fake_sleep(secs: float) -> None: + sleep_calls.append(secs) + + monkeypatch.setattr(_mq.asyncio, "sleep", fake_sleep) + + httpx_mock.add_response( + url="https://api.github.com/graphql", + status_code=429, + headers={"Retry-After": "1"}, + ) + httpx_mock.add_response( + url="https://api.github.com/graphql", + json=_SUCCESS_BODY, + ) + + from autoskillit.execution.merge_queue import fetch_repo_merge_state + + result = await fetch_repo_merge_state(owner="o", repo="r", branch="main", token=None) + assert result["queue_available"] is False + assert len(sleep_calls) == 1 + assert sleep_calls[0] == 1.0 # Retry-After header value is '1' + + @pytest.mark.anyio + async def test_retries_on_secondary_rate_limit_403(self, httpx_mock, monkeypatch): + """Retries on 403 whose body contains 'secondary rate limit'.""" + sleep_calls: list[float] = [] + + async def fake_sleep(secs: float) -> None: + sleep_calls.append(secs) + + monkeypatch.setattr(_mq.asyncio, "sleep", fake_sleep) + monkeypatch.setattr(_mq.random, "uniform", lambda a, b: 0.42) + + httpx_mock.add_response( + url="https://api.github.com/graphql", + status_code=403, + text="You have exceeded a secondary rate limit", + ) + httpx_mock.add_response( + url="https://api.github.com/graphql", + json=_SUCCESS_BODY, + ) + + from autoskillit.execution.merge_queue import fetch_repo_merge_state + + result = await fetch_repo_merge_state(owner="o", repo="r", branch="main", token=None) + assert result["queue_available"] is False + assert len(sleep_calls) == 1 + assert sleep_calls[0] == 0.42 # jitter backoff via patched random.uniform + + @pytest.mark.anyio + async def test_raises_on_non_rate_limit_403(self, httpx_mock): + """Non-secondary-rate-limit 403 propagates immediately without retry.""" + httpx_mock.add_response( + url="https://api.github.com/graphql", + status_code=403, + text="Bad credentials", + ) + + from autoskillit.execution.merge_queue import fetch_repo_merge_state + + with pytest.raises(httpx.HTTPStatusError) as exc_info: + await fetch_repo_merge_state(owner="o", repo="r", branch="main", token=None) + assert exc_info.value.response.status_code == 403 + # Only one request was made (no retry) + assert len(httpx_mock.get_requests()) == 1 + + @pytest.mark.anyio + async def test_exhausts_retries_and_raises(self, httpx_mock, monkeypatch): + """After max_attempts of 429, raises HTTPStatusError.""" + sleep_calls: list[float] = [] + + async def fake_sleep(secs: float) -> None: + sleep_calls.append(secs) + + monkeypatch.setattr(_mq.asyncio, "sleep", fake_sleep) + + for _ in range(_mq._RATE_LIMIT_MAX_ATTEMPTS): + httpx_mock.add_response( + url="https://api.github.com/graphql", + status_code=429, + headers={"Retry-After": "1"}, + ) + + from autoskillit.execution.merge_queue import fetch_repo_merge_state + + with pytest.raises(httpx.HTTPStatusError) as exc_info: + await fetch_repo_merge_state(owner="o", repo="r", branch="main", token=None) + assert exc_info.value.response.status_code == 429 + assert len(httpx_mock.get_requests()) == _mq._RATE_LIMIT_MAX_ATTEMPTS diff --git a/tests/execution/test_pr_analysis.py b/tests/execution/test_pr_analysis.py index a7e380a783..47b41b328e 100644 --- a/tests/execution/test_pr_analysis.py +++ b/tests/execution/test_pr_analysis.py @@ -151,3 +151,129 @@ def test_domain_paths_has_no_duplicates() -> None: for prefixes in DOMAIN_PATHS.values(): all_prefixes.extend(prefixes) assert len(all_prefixes) == len(set(all_prefixes)) + + +# --------------------------------------------------------------------------- +# extract_linked_issues — additional coverage (migrated from pipeline/test_fidelity.py) +# --------------------------------------------------------------------------- + + +def test_extract_linked_issues_case_insensitive() -> None: + """Extraction is case-insensitive: CLOSES, fixes, Resolves all match.""" + result = extract_linked_issues("CLOSES #10\nfixes #20\nResolves #30") + assert sorted(result, key=int) == ["10", "20", "30"] + + +def test_extract_linked_issues_commit_concatenation() -> None: + """PR body and commit messages concatenated together yield combined results.""" + pr_body = "Closes #100" + commits = "Fixes #200" + combined = f"{pr_body}\n{commits}" + result = extract_linked_issues(combined) + assert sorted(result, key=int) == ["100", "200"] + + +# --------------------------------------------------------------------------- +# is_valid_fidelity_finding — edge cases (migrated from pipeline/test_fidelity.py) +# --------------------------------------------------------------------------- + + +def test_fidelity_gap_with_empty_file_and_zero_line() -> None: + """Gap finding with file='' and line=0 is valid (unpostable — summary only).""" + gap = { + "file": "", + "line": 0, + "dimension": "fidelity", + "severity": "critical", + "message": "Gap: entire feature section 'notifications' not implemented.", + "requires_decision": False, + } + assert is_valid_fidelity_finding(gap) is True + + +def test_fidelity_skipped_when_no_linked_issues() -> None: + """extract_linked_issues returns [] for PRs with no Closes/Fixes/Resolves refs. + + The fidelity skip condition is len(linked_issues) == 0. This test confirms + that a PR body without issue references produces an empty list, which is the + signal the review-pr skill uses to skip fidelity subagent launch. + """ + pr_body = "This PR adds a minor cleanup, no issue references." + linked = extract_linked_issues(pr_body) + assert linked == [] + + +# --------------------------------------------------------------------------- +# partition_files_by_domain — domain-key coverage +# (migrated from pipeline/test_pr_domain_partitioner.py) +# --------------------------------------------------------------------------- + + +def test_partition_files_execution_prefix() -> None: + result = partition_files_by_domain(["src/autoskillit/execution/headless.py"]) + assert "Pipeline/Execution" in result + assert "src/autoskillit/execution/headless.py" in result["Pipeline/Execution"] + + +def test_partition_files_pipeline_prefix() -> None: + result = partition_files_by_domain(["src/autoskillit/pipeline/pr_gates.py"]) + assert "Pipeline/Execution" in result + assert "src/autoskillit/pipeline/pr_gates.py" in result["Pipeline/Execution"] + + +def test_partition_files_recipe_prefix() -> None: + result = partition_files_by_domain(["src/autoskillit/recipe/schema.py"]) + assert "Recipe/Validation" in result + + +def test_partition_files_cli_prefix() -> None: + result = partition_files_by_domain(["src/autoskillit/cli/app.py"]) + assert "CLI/Workspace" in result + + +def test_partition_files_workspace_prefix() -> None: + result = partition_files_by_domain(["src/autoskillit/workspace/skills.py"]) + assert "CLI/Workspace" in result + + +def test_partition_files_skills_prefix() -> None: + result = partition_files_by_domain(["src/autoskillit/skills_extended/open-pr/SKILL.md"]) + assert "Skills" in result + + +def test_partition_files_core_prefix() -> None: + result = partition_files_by_domain(["src/autoskillit/core/types.py"]) + assert "Core/Config/Infra" in result + + +def test_partition_files_config_prefix() -> None: + result = partition_files_by_domain(["src/autoskillit/config/settings.py"]) + assert "Core/Config/Infra" in result + + +def test_partition_files_hooks_prefix() -> None: + result = partition_files_by_domain(["src/autoskillit/hooks/quota_check.py"]) + assert "Core/Config/Infra" in result + + +def test_partition_files_empty_input() -> None: + result = partition_files_by_domain([]) + assert result == {} + + +def test_partition_files_only_non_empty_domains_returned() -> None: + result = partition_files_by_domain(["src/autoskillit/server/tools_execution.py"]) + assert "Tests" not in result + assert "Skills" not in result + + +def test_partition_files_mixed_domains() -> None: + files = [ + "src/autoskillit/server/tools_execution.py", + "src/autoskillit/execution/headless.py", + "tests/test_something.py", + ] + result = partition_files_by_domain(files) + assert "Server/MCP Tools" in result + assert "Pipeline/Execution" in result + assert "Tests" in result diff --git a/tests/execution/test_process_channel_b.py b/tests/execution/test_process_channel_b.py index 1d59e6be32..bc153460a3 100644 --- a/tests/execution/test_process_channel_b.py +++ b/tests/execution/test_process_channel_b.py @@ -9,20 +9,7 @@ from autoskillit.core.types import ChannelConfirmation, SubprocessResult, TerminationReason from autoskillit.execution.process import run_managed_async - -# --------------------------------------------------------------------------- -# Helper scripts — small Python programs that reproduce specific scenarios -# --------------------------------------------------------------------------- - -# Script that writes a JSON result line then hangs (simulates Claude CLI completed-but-hung) -WRITE_RESULT_THEN_HANG_SCRIPT = textwrap.dedent("""\ - import sys, time, json - result = {"type": "result", "subtype": "success", "is_error": False, - "result": "done", "session_id": "s1"} - sys.stdout.write(json.dumps(result, separators=(",", ":")) + "\\n") - sys.stdout.flush() - time.sleep(3600) -""") +from tests.execution.conftest import WRITE_RESULT_THEN_HANG_SCRIPT # Script that: # (1) writes %%ORDER_UP%% to a JSONL session file (Channel B fires) @@ -162,6 +149,11 @@ async def test_channel_b_wins_drain_timeout_still_kills(self, tmp_path): t=0.16s Channel B fires → drain wait starts with 0.5s timeout t=0.66s drain times out (script never wrote to stdout) t=0.66s process killed with empty stdout + + timeout=60s: guards against the outer wall-clock expiring under xdist -n 4 load. + _watch_session_log waits up to 1s for stdout_session_id_ready before Phase 1 starts; + under CI load both the preamble and Phase 1 polls can overrun, so the outer + timeout must exceed 1s + _phase1_timeout (30s default) + drain (0.5s) = 31.5s. """ session_dir = tmp_path / "session" session_dir.mkdir() @@ -171,7 +163,7 @@ async def test_channel_b_wins_drain_timeout_still_kills(self, tmp_path): result = await run_managed_async( [sys.executable, str(script), str(session_dir)], cwd=tmp_path, - timeout=30, + timeout=60, session_log_dir=session_dir, completion_marker="%%ORDER_UP%%", completion_drain_timeout=0.5, @@ -485,3 +477,63 @@ async def test_drain_window_times_out_when_no_session_jsonl(self, tmp_path): ) assert result.channel_confirmation == ChannelConfirmation.UNMONITORED + + +# Script that: +# (1) writes static %%ORDER_UP%% to JSONL (simulating sub-skill emission) +# (2) later writes %%ORDER_UP::{unique}%% to JSONL (the parent's real marker) +# (3) writes type=result to stdout within the drain window +# (4) hangs until killed +# Pass session_dir as sys.argv[1], unique marker as sys.argv[2]. +CHANNEL_B_SUB_SKILL_COLLISION_SCRIPT = textwrap.dedent("""\ + import sys, time, json, os + session_dir = sys.argv[1] + unique_marker = sys.argv[2] + os.makedirs(session_dir, exist_ok=True) + time.sleep(0.1) + with open(os.path.join(session_dir, "session.jsonl"), "w") as f: + # Sub-skill emits static marker — should NOT trigger completion + sub_skill_record = {"type": "assistant", "message": {"role": "assistant", + "content": "%%ORDER_UP%%"}} + f.write(json.dumps(sub_skill_record) + "\\n") + f.flush() + time.sleep(0.3) + # Parent emits its unique marker — SHOULD trigger completion + parent_record = {"type": "assistant", "message": {"role": "assistant", + "content": unique_marker}} + f.write(json.dumps(parent_record) + "\\n") + f.flush() + time.sleep(0.15) + result = {"type": "result", "subtype": "success", "is_error": False, + "result": "done", "session_id": "s1"} + sys.stdout.write(json.dumps(result, separators=(",", ":")) + "\\n") + sys.stdout.flush() + time.sleep(3600) +""") + + +class TestChannelBSubSkillCollision: + """Channel B ignores static markers when monitoring for a unique marker.""" + + @pytest.mark.anyio + async def test_channel_b_ignores_sub_skill_marker(self, tmp_path): + session_dir = tmp_path / "session" + session_dir.mkdir() + unique_marker = "%%ORDER_UP::test1234%%" + script = tmp_path / "sub_skill_collision.py" + script.write_text(CHANNEL_B_SUB_SKILL_COLLISION_SCRIPT) + + result = await run_managed_async( + [sys.executable, str(script), str(session_dir), unique_marker], + cwd=tmp_path, + timeout=15, + session_log_dir=session_dir, + completion_marker=unique_marker, + completion_drain_timeout=2.0, + _phase1_poll=0.05, + _phase2_poll=0.05, + _heartbeat_poll=0.05, + ) + + assert result.termination == TerminationReason.COMPLETED + assert result.channel_confirmation == ChannelConfirmation.CHANNEL_B diff --git a/tests/execution/test_process_debug_logging.py b/tests/execution/test_process_debug_logging.py index 7bddfac23d..95cb3e648d 100644 --- a/tests/execution/test_process_debug_logging.py +++ b/tests/execution/test_process_debug_logging.py @@ -110,7 +110,7 @@ async def test_watch_process_logs_exit(tmp_path): @pytest.mark.anyio async def test_kill_decision_logs_natural_exit(tmp_path): - """Kill decision logs 'natural_exit' when process exits on its own.""" + """Kill decision logs 'no_kill' reason when process exits on its own.""" from autoskillit.execution.process import run_managed_async cmd = ["python3", "-c", "pass"] @@ -119,12 +119,12 @@ async def test_kill_decision_logs_natural_exit(tmp_path): kill_logs = [r for r in logs if r.get("event") == "kill_decision"] assert kill_logs, f"Expected kill_decision log, got events: {[r.get('event') for r in logs]}" - assert kill_logs[0]["reason"] == "natural_exit" + assert kill_logs[0]["reason"] == "no_kill" @pytest.mark.anyio async def test_kill_decision_logs_timeout(tmp_path): - """Kill decision logs 'timeout' when process exceeds timeout.""" + """Kill decision logs 'immediate_kill' reason when process exceeds timeout.""" from autoskillit.execution.process import run_managed_async cmd = [ @@ -141,4 +141,4 @@ async def test_kill_decision_logs_timeout(tmp_path): assert result.termination == TerminationReason.TIMED_OUT kill_logs = [r for r in logs if r.get("event") == "kill_decision"] assert kill_logs, f"Expected kill_decision log, got events: {[r.get('event') for r in logs]}" - assert kill_logs[0]["reason"] == "timeout" + assert kill_logs[0]["reason"] == "immediate_kill" diff --git a/tests/execution/test_process_idle_watchdog.py b/tests/execution/test_process_idle_watchdog.py new file mode 100644 index 0000000000..7ae6c34905 --- /dev/null +++ b/tests/execution/test_process_idle_watchdog.py @@ -0,0 +1,132 @@ +"""Tests for the stdout idle watchdog coroutine (_watch_stdout_idle).""" + +from __future__ import annotations + +import sys +import textwrap +import time + +import anyio +import pytest + +from autoskillit.execution._process_race import ( + RaceAccumulator, + _watch_stdout_idle, +) + +WRITE_BURST_THEN_STALL_SCRIPT = textwrap.dedent("""\ + import sys, time, json + for i in range(3): + sys.stdout.write(json.dumps({"type": "assistant", "i": i}) + "\\n") + sys.stdout.flush() + time.sleep(9999) +""") + +WRITE_CONTINUOUS_SCRIPT = textwrap.dedent("""\ + import sys, time, json + for i in range(10): + sys.stdout.write(json.dumps({"type": "assistant", "i": i}) + "\\n") + sys.stdout.flush() + time.sleep(0.5) +""") + + +@pytest.mark.anyio +async def test_watch_stdout_idle_fires_on_silence(tmp_path: anyio.Path) -> None: + """Watchdog fires IDLE_STALL when stdout stops growing.""" + script = tmp_path / "burst_then_stall.py" + await anyio.Path(script).write_text(WRITE_BURST_THEN_STALL_SCRIPT) + stdout_file = tmp_path / "stdout.txt" + + acc = RaceAccumulator() + trigger = anyio.Event() + + async with anyio.create_task_group() as tg: + proc = await anyio.open_process( + [sys.executable, str(script)], + stdout=await anyio.Path(stdout_file).open("wb"), + stderr=None, + ) + + async def run_watchdog() -> None: + await _watch_stdout_idle( + stdout_file, + idle_output_timeout=2.0, + acc=acc, + trigger=trigger, + _poll_interval=0.2, + ) + + start = time.monotonic() + with anyio.fail_after(5.0): + tg.start_soon(run_watchdog) + await trigger.wait() + + elapsed = time.monotonic() - start + assert acc.idle_stall is True + assert 2.0 <= elapsed < 4.0 + tg.cancel_scope.cancel() + proc.kill() + + +@pytest.mark.anyio +async def test_watch_stdout_idle_resets_on_continuous_output(tmp_path: anyio.Path) -> None: + """Watchdog does NOT fire when stdout keeps growing.""" + script = tmp_path / "continuous.py" + await anyio.Path(script).write_text(WRITE_CONTINUOUS_SCRIPT) + stdout_file = tmp_path / "stdout.txt" + + acc = RaceAccumulator() + trigger = anyio.Event() + + with anyio.fail_after(8.0): + async with anyio.create_task_group() as tg: + proc = await anyio.open_process( + [sys.executable, str(script)], + stdout=await anyio.Path(stdout_file).open("wb"), + stderr=None, + ) + + tg.start_soon( + _watch_stdout_idle, + stdout_file, + 3.0, + acc, + trigger, + 0.2, + ) + + await proc.wait() + # Script ran to completion — cancel the watchdog + tg.cancel_scope.cancel() + + assert acc.idle_stall is False + + +@pytest.mark.anyio +async def test_watch_stdout_idle_handles_missing_file(tmp_path: anyio.Path) -> None: + """Watchdog tolerates missing stdout file until it appears.""" + stdout_file = tmp_path / "stdout.txt" + + acc = RaceAccumulator() + trigger = anyio.Event() + + async def create_file_after_delay() -> None: + await anyio.sleep(1.0) + await anyio.Path(stdout_file).write_bytes(b"some data\n") + await anyio.sleep(3.0) + + with anyio.fail_after(5.0): + async with anyio.create_task_group() as tg: + tg.start_soon(create_file_after_delay) + tg.start_soon( + _watch_stdout_idle, + stdout_file, + 2.0, + acc, + trigger, + 0.2, + ) + await trigger.wait() + + assert acc.idle_stall is True diff --git a/tests/execution/test_process_jsonl.py b/tests/execution/test_process_jsonl.py index 3b6bb82ec5..6f100420b1 100644 --- a/tests/execution/test_process_jsonl.py +++ b/tests/execution/test_process_jsonl.py @@ -316,3 +316,48 @@ def test_marker_must_be_standalone_line_in_result(self): assert not _jsonl_has_record_type( line, frozenset({"result"}), completion_marker="%%ORDER_UP%%" ) + + +class TestMarkerDiscrimination: + """Regression guards: per-invocation markers are structurally incompatible with static ones.""" + + def test_session_marker_does_not_match_global_marker(self): + """A JSONL record with static %%ORDER_UP%% must NOT match a per-invocation marker.""" + content = ( + json.dumps( + { + "type": "assistant", + "message": {"content": [{"type": "text", "text": "%%ORDER_UP%%"}]}, + } + ) + + "\n" + ) + assert not _jsonl_contains_marker( + content, "%%ORDER_UP::abc12345%%", frozenset({"assistant"}) + ) + + def test_session_marker_matches_itself(self): + """A per-invocation marker matches itself in JSONL detection.""" + content = ( + json.dumps( + { + "type": "assistant", + "message": {"content": [{"type": "text", "text": "%%ORDER_UP::abc12345%%"}]}, + } + ) + + "\n" + ) + assert _jsonl_contains_marker(content, "%%ORDER_UP::abc12345%%", frozenset({"assistant"})) + + def test_different_session_markers_dont_collide(self): + """Two different per-invocation markers do not cross-match.""" + content = ( + json.dumps( + { + "type": "assistant", + "message": {"content": [{"type": "text", "text": "%%ORDER_UP::aaa%%"}]}, + } + ) + + "\n" + ) + assert not _jsonl_contains_marker(content, "%%ORDER_UP::bbb%%", frozenset({"assistant"})) diff --git a/tests/execution/test_process_kill.py b/tests/execution/test_process_kill.py index a6f75e27e5..a3c6cc1c34 100644 --- a/tests/execution/test_process_kill.py +++ b/tests/execution/test_process_kill.py @@ -9,6 +9,7 @@ from __future__ import annotations +import os import sys import textwrap @@ -115,6 +116,9 @@ async def test_cancellation_kills_process(self, tmp_path): script = tmp_path / "sleep.py" script.write_text("import time; time.sleep(3600)") + parent = psutil.Process(os.getpid()) + children_before = set(c.pid for c in parent.children(recursive=True)) + async with anyio.create_task_group() as tg: async def _run() -> None: @@ -131,6 +135,10 @@ async def _run() -> None: # Give the kernel a moment await anyio.sleep(0.5) + children_after = set(c.pid for c in parent.children(recursive=True)) + leaked = children_after - children_before + assert not leaked, f"Child processes not cleaned up after cancellation: {leaked}" + class TestAsyncKillDoesNotBlockLoop: """async_kill_process_tree doesn't block the event loop.""" diff --git a/tests/execution/test_process_monitor.py b/tests/execution/test_process_monitor.py index 697f980fb4..99d0349826 100644 --- a/tests/execution/test_process_monitor.py +++ b/tests/execution/test_process_monitor.py @@ -4,34 +4,23 @@ import sys import time -from unittest.mock import patch +from unittest.mock import MagicMock, patch import anyio +import psutil import pytest -from autoskillit.core.types import TerminationReason +from autoskillit.core.types import ChannelBStatus, TerminationReason from autoskillit.execution.process import ( RaceAccumulator, _has_active_api_connection, + _has_active_child_processes, _heartbeat, _session_log_monitor, _watch_session_log, run_managed_async, ) - -# --------------------------------------------------------------------------- -# Helper scripts — small Python programs that reproduce specific scenarios -# --------------------------------------------------------------------------- - -# Script that writes a JSON result line then hangs (simulates Claude CLI completed-but-hung) -WRITE_RESULT_THEN_HANG_SCRIPT = ( - "import sys, time, json\n" - 'result = {"type": "result", "subtype": "success", "is_error": False,\n' - ' "result": "done", "session_id": "s1"}\n' - 'sys.stdout.write(json.dumps(result, separators=(",", ":")) + "\\n")\n' - "sys.stdout.flush()\n" - "time.sleep(3600)\n" -) +from tests.execution.conftest import WRITE_RESULT_THEN_HANG_SCRIPT # Script that writes non-matching output then hangs PARTIAL_OUTPUT_THEN_HANG_SCRIPT = ( @@ -596,6 +585,121 @@ def test_skips_zombie_child_gracefully(self): assert _has_active_api_connection(12345) is True +class TestHasActiveChildProcesses: + """Unit tests for _has_active_child_processes. + + The function caches psutil.Process objects so cpu_percent(interval=0) + returns meaningful deltas on the second call. First call primes the + baseline (always returns False); second call with the same child PIDs + uses the cached objects. + """ + + @pytest.fixture(autouse=True) + def _clear_cache(self, monkeypatch): + """Reset the module-level Process cache between tests.""" + from autoskillit.execution import _process_monitor + + monkeypatch.setattr(_process_monitor, "_child_process_cache", {}) + + def _make_child(self, cpu: float | type[Exception], *, pid: int = 999) -> MagicMock: + """Build a mock psutil child process.""" + child = MagicMock() + child.pid = pid + if isinstance(cpu, type) and issubclass(cpu, Exception): + child.cpu_percent.side_effect = cpu(pid=pid) + else: + child.cpu_percent.return_value = cpu + return child + + def _patch_children(self, children, monkeypatch, parent_raises=None): + mock_proc = MagicMock() + if parent_raises: + monkeypatch.setattr( + "autoskillit.execution._process_monitor.psutil.Process", + MagicMock(side_effect=parent_raises(pid=1234)), + ) + return + mock_proc.children.return_value = children + monkeypatch.setattr( + "autoskillit.execution._process_monitor.psutil.Process", + MagicMock(return_value=mock_proc), + ) + + def test_returns_true_when_child_exceeds_threshold(self, monkeypatch): + child = self._make_child(15.0, pid=100) + self._patch_children([child], monkeypatch) + # First call primes baseline; second call returns meaningful delta. + _has_active_child_processes(1234) + # Cache now holds the child object; second call uses cached.cpu_percent. + from autoskillit.execution._process_monitor import _child_process_cache + + _child_process_cache[100] = child + assert _has_active_child_processes(1234) is True + + def test_returns_false_when_all_children_below_threshold(self, monkeypatch): + children = [ + self._make_child(0.0, pid=100), + self._make_child(5.0, pid=101), + self._make_child(9.9, pid=102), + ] + self._patch_children(children, monkeypatch) + # Prime baseline + _has_active_child_processes(1234) + from autoskillit.execution._process_monitor import _child_process_cache + + for c in children: + _child_process_cache[c.pid] = c + assert _has_active_child_processes(1234) is False + + def test_returns_false_when_no_children(self, monkeypatch): + self._patch_children([], monkeypatch) + assert _has_active_child_processes(1234) is False + + def test_returns_false_on_parent_nosuchprocess(self, monkeypatch): + self._patch_children([], monkeypatch, parent_raises=psutil.NoSuchProcess) + assert _has_active_child_processes(1234) is False + + def test_skips_dead_child_gracefully(self, monkeypatch): + children = [ + self._make_child(psutil.NoSuchProcess, pid=100), + self._make_child(5.0, pid=101), + ] + self._patch_children(children, monkeypatch) + _has_active_child_processes(1234) + from autoskillit.execution._process_monitor import _child_process_cache + + for c in children: + if c.pid in _child_process_cache: + pass # Already cached by prime call + _child_process_cache[c.pid] = c + assert _has_active_child_processes(1234) is False + + def test_skips_zombie_child_then_finds_active(self, monkeypatch): + children = [ + self._make_child(psutil.ZombieProcess, pid=100), + self._make_child(20.0, pid=101), + ] + self._patch_children(children, monkeypatch) + # Prime baseline + _has_active_child_processes(1234) + from autoskillit.execution._process_monitor import _child_process_cache + + for c in children: + _child_process_cache[c.pid] = c + assert _has_active_child_processes(1234) is True + + def test_skips_access_denied_gracefully(self, monkeypatch): + self._patch_children( + [self._make_child(psutil.AccessDenied, pid=100)], + monkeypatch, + ) + _has_active_child_processes(1234) + from autoskillit.execution._process_monitor import _child_process_cache + + _child_process_cache[100] = self._make_child(psutil.AccessDenied, pid=100) + assert _has_active_child_processes(1234) is False + + class TestSessionLogMonitorStaleSuppressionGate: """_session_log_monitor suppresses stale when process has an active port-443 connection.""" @@ -717,6 +821,144 @@ def side_effect(pid): "Suppression warning must appear in structlog capture or stdout" ) + @pytest.mark.anyio + async def test_suppresses_stale_when_child_cpu_active_no_api_connection( + self, tmp_path, monkeypatch + ): + """Child CPU activity suppresses stale kill even when no port-443 connection.""" + session_file = tmp_path / "session.jsonl" + session_file.write_text("") + spawn_time = time.time() - 10 # wall time — compared against st_ctime in phase 1 + call_count: dict[str, int] = {"cpu": 0} + + def fake_api_conn(pid): + return False # No port-443 connection + + def fake_child_cpu(pid): + call_count["cpu"] += 1 + return call_count["cpu"] == 1 # True first, False second + + monkeypatch.setattr( + "autoskillit.execution._process_monitor._has_active_api_connection", + fake_api_conn, + ) + monkeypatch.setattr( + "autoskillit.execution._process_monitor._has_active_child_processes", + fake_child_cpu, + ) + result = await _session_log_monitor( + tmp_path, + "DONE", + stale_threshold=0.05, + spawn_time=spawn_time, + pid=9999, + _phase1_poll=0.01, + _phase2_poll=0.05, + ) + assert result.status == ChannelBStatus.STALE + assert call_count["cpu"] == 2 # suppressed once, then fired + + +class TestStaleSuppressionBounded: + """Bounded suppression: max_suppression_seconds caps stale deferral.""" + + @pytest.mark.anyio + async def test_stale_suppression_bounded_by_max_duration(self, tmp_path, monkeypatch): + """Stale fires after max_suppression_seconds despite ESTABLISHED connection.""" + session_file = tmp_path / "session.jsonl" + session_file.write_text("") + spawn_time = time.time() - 10 + + monkeypatch.setattr( + "autoskillit.execution._process_monitor._has_active_api_connection", + lambda pid: True, + ) + + with anyio.fail_after(8.0): + result = await _session_log_monitor( + tmp_path, + "DONE", + stale_threshold=0.05, + spawn_time=spawn_time, + pid=9999, + _phase1_poll=0.01, + _phase2_poll=0.05, + max_suppression_seconds=1.0, + ) + assert result.status == ChannelBStatus.STALE + + @pytest.mark.anyio + async def test_stale_suppression_resets_on_genuine_activity(self, tmp_path, monkeypatch): + """Suppression counter resets when JSONL file grows.""" + session_file = tmp_path / "session.jsonl" + session_file.write_text("") + spawn_time = time.time() - 10 + + monkeypatch.setattr( + "autoskillit.execution._process_monitor._has_active_api_connection", + lambda pid: True, + ) + + async def write_activity() -> None: + import json as _json + + for i in range(6): + await anyio.sleep(0.5) + with session_file.open("a") as f: + record = {"type": "assistant", "message": {"content": f"msg-{i}"}} + f.write(_json.dumps(record) + "\n") + + with anyio.fail_after(10.0): + async with anyio.create_task_group() as tg: + tg.start_soon(write_activity) + result = await _session_log_monitor( + tmp_path, + "DONE", + stale_threshold=0.05, + spawn_time=spawn_time, + pid=9999, + _phase1_poll=0.01, + _phase2_poll=0.05, + max_suppression_seconds=2.0, + ) + tg.cancel_scope.cancel() + + assert result.status == ChannelBStatus.STALE + + @pytest.mark.anyio + async def test_stale_suppression_logs_warning_on_bounded_kill( + self, tmp_path, monkeypatch, capsys + ): + """Warning log emitted when bounded suppression fires.""" + import structlog.testing + + session_file = tmp_path / "session.jsonl" + session_file.write_text("") + spawn_time = time.time() - 10 + + monkeypatch.setattr( + "autoskillit.execution._process_monitor._has_active_api_connection", + lambda pid: True, + ) + + with anyio.fail_after(8.0): + with structlog.testing.capture_logs() as logs: + result = await _session_log_monitor( + tmp_path, + "DONE", + stale_threshold=0.05, + spawn_time=spawn_time, + pid=9999, + _phase1_poll=0.01, + _phase2_poll=0.05, + max_suppression_seconds=1.0, + ) + assert result.status == ChannelBStatus.STALE + captured = capsys.readouterr().out + capsys.readouterr().err + bounded_in_logs = any("Suppression bounded" in str(log.get("event", "")) for log in logs) + bounded_in_stdout = "Suppression bounded" in captured + assert bounded_in_logs or bounded_in_stdout + class TestHeartbeatMarkerAwareness: """_heartbeat respects completion_marker when configured.""" @@ -1005,3 +1247,26 @@ async def test_session_id_falls_back_to_recency_when_no_match(self, tmp_path): ) assert result.status == "completion" assert result.session_id == session_b + + +class TestSessionLogMonitorDirMissing: + """DIR_MISSING: _session_log_monitor returns immediately when dir is absent.""" + + @pytest.mark.anyio + async def test_session_log_monitor_returns_dir_missing_when_dir_absent(self, tmp_path): + """When session_log_dir does not exist, monitor returns DIR_MISSING immediately + instead of burning phase1_timeout absorbing OSError.""" + nonexistent = tmp_path / "does_not_exist" # NOT created + t0 = time.monotonic() + result = await _session_log_monitor( + nonexistent, + "MARKER", + stale_threshold=10.0, + spawn_time=time.time() - 1, + _phase1_timeout=5.0, + _phase1_poll=0.01, # fast poll so DIR_MISSING returns within one cycle + ) + elapsed = time.monotonic() - t0 + assert result.status == ChannelBStatus.DIR_MISSING + assert elapsed < 0.1 # FileNotFoundError is immediate after the poll sleep + assert result.session_id == "" diff --git a/tests/execution/test_process_pty.py b/tests/execution/test_process_pty.py index 09f2f80965..5ea77ce86e 100644 --- a/tests/execution/test_process_pty.py +++ b/tests/execution/test_process_pty.py @@ -7,6 +7,7 @@ from __future__ import annotations +import json import shutil import sys import textwrap @@ -15,6 +16,7 @@ from autoskillit.core.types import ( ChannelConfirmation, + CliSubtype, RetryReason, SubprocessResult, TerminationReason, @@ -468,6 +470,7 @@ class TestAdjudicationCoverageMatrix: TerminationReason.NATURAL_EXIT, # TestSTOPDelayPipelineAdjudication TerminationReason.STALE, # TestStaleRecoveryPipelineAdjudication TerminationReason.TIMED_OUT, # TestTimedOutPipelineAdjudication + TerminationReason.IDLE_STALL, # TestIdleStallWatchdog in test_process_run.py } ) @@ -495,8 +498,6 @@ def _result_ndjson( session_id: str = "s1", ) -> str: """Build a minimal NDJSON string with a single type=result record.""" - import json - return json.dumps( { "type": "result", @@ -632,6 +633,190 @@ def test_t3_does_not_fire_when_no_messages(self) -> None: assert recovered is None +# --------------------------------------------------------------------------- +# Channel B drain-race recovery — integration through _build_skill_result +# --------------------------------------------------------------------------- + + +def _assistant_content_ndjson(text: str) -> str: + """Build an assistant NDJSON record with text content (no type=result).""" + return json.dumps( + { + "type": "assistant", + "message": { + "role": "assistant", + "content": [{"type": "text", "text": text}], + }, + } + ) + + +class TestChannelBDrainRaceRecovery: + """Verify pre-gate Channel B drain-race recovery in _build_skill_result. + + When Claude Code defers the type=result NDJSON record until all background + agents finish, killing the process tree after Channel B fires means the + deferred record is never flushed to stdout. These tests cover the recovery + block that reconstructs the result from assistant_messages. + """ + + def test_channel_b_drain_race_recovery_promotes_unparseable(self) -> None: + """CHANNEL_B + UNPARSEABLE + marker standalone in assistant_messages → success. + + Simulates the background-agent deferred-result scenario: Channel B confirmed + completion, assistant_messages contain the marker with substantive content, + but type=result was never flushed to stdout. + """ + stdout = _assistant_content_ndjson( + "Plan completed.\n\nplan_path = /tmp/plan.md\n%%ORDER_UP%%" + ) + result = SubprocessResult( + returncode=0, + stdout=stdout, + stderr="", + termination=TerminationReason.NATURAL_EXIT, + pid=12345, + channel_confirmation=ChannelConfirmation.CHANNEL_B, + ) + skill_result = _build_skill_result( + result, + completion_marker="%%ORDER_UP%%", + skill_command="/make-plan", + audit=None, + expected_output_patterns=[r"plan_path\s*=\s*/.+"], + ) + assert skill_result.success is True + assert skill_result.needs_retry is False + assert "plan_path = /tmp/plan.md" in skill_result.result + + def test_channel_b_drain_race_no_marker_in_messages_not_rescued(self) -> None: + """CHANNEL_B + UNPARSEABLE + marker absent from assistant_messages → not rescued. + + When Channel B fired but assistant_messages don't contain the marker as a + standalone line, recovery must not fire. The session remains UNPARSEABLE + (is_error=True) which the dead-end guard classifies as SESSION_ERROR — + a terminal failure, not a retriable DRAIN_RACE. + """ + stdout = _assistant_content_ndjson("Working on the task...") + result = SubprocessResult( + returncode=0, + stdout=stdout, + stderr="", + termination=TerminationReason.NATURAL_EXIT, + pid=12345, + channel_confirmation=ChannelConfirmation.CHANNEL_B, + ) + skill_result = _build_skill_result( + result, + completion_marker="%%ORDER_UP%%", + skill_command="/test", + audit=None, + expected_output_patterns=[r"plan_path\s*=\s*/.+"], + ) + assert skill_result.success is False + assert skill_result.needs_retry is False + + def test_channel_b_drain_race_recovery_empty_output( + self, monkeypatch: pytest.MonkeyPatch + ) -> None: + """CHANNEL_B + EMPTY_OUTPUT + marker in assistant_messages → success. + + Same deferred-result scenario but stdout is completely empty. + Monkeypatches parse_session_result to inject assistant_messages since + an empty stdout produces no NDJSON records to accumulate from. + """ + from autoskillit.execution import headless as headless_mod + + fake_session = ClaudeSessionResult( + subtype=CliSubtype.EMPTY_OUTPUT, + is_error=True, + result="", + session_id="test", + assistant_messages=["Done.\n%%ORDER_UP%%"], + ) + monkeypatch.setattr(headless_mod, "parse_session_result", lambda _: fake_session) + result = SubprocessResult( + returncode=0, + stdout="", + stderr="", + termination=TerminationReason.NATURAL_EXIT, + pid=12345, + channel_confirmation=ChannelConfirmation.CHANNEL_B, + ) + skill_result = _build_skill_result( + result, + completion_marker="%%ORDER_UP%%", + skill_command="/test", + audit=None, + ) + assert skill_result.success is True + + def test_channel_a_unparseable_no_drain_race_recovery(self) -> None: + """CHANNEL_A + UNPARSEABLE must not trigger the new Channel B recovery. + + The pre-gate recovery is strictly for CHANNEL_B. CHANNEL_A sessions with + UNPARSEABLE subtype should continue to be handled by existing mechanisms. + """ + stdout = _assistant_content_ndjson( + "Plan completed.\n\nplan_path = /tmp/plan.md\n%%ORDER_UP%%" + ) + result = SubprocessResult( + returncode=0, + stdout=stdout, + stderr="", + termination=TerminationReason.NATURAL_EXIT, + pid=12345, + channel_confirmation=ChannelConfirmation.CHANNEL_A, + ) + skill_result = _build_skill_result( + result, + completion_marker="%%ORDER_UP%%", + skill_command="/test", + audit=None, + ) + assert skill_result.success is False + + def test_unmonitored_unparseable_no_drain_race_recovery(self) -> None: + """UNMONITORED + UNPARSEABLE: no channel recovery, existing behavior preserved.""" + stdout = _assistant_content_ndjson( + "Plan completed.\n\nplan_path = /tmp/plan.md\n%%ORDER_UP%%" + ) + result = SubprocessResult( + returncode=0, + stdout=stdout, + stderr="", + termination=TerminationReason.NATURAL_EXIT, + pid=12345, + channel_confirmation=ChannelConfirmation.UNMONITORED, + ) + skill_result = _build_skill_result( + result, + completion_marker="%%ORDER_UP%%", + skill_command="/test", + audit=None, + ) + assert skill_result.success is False + + def test_channel_b_timeout_not_recovered(self) -> None: + """CHANNEL_B + TIMEOUT: timeout is not a recoverable subtype.""" + result = SubprocessResult( + returncode=-1, + stdout="", + stderr="", + termination=TerminationReason.TIMED_OUT, + pid=12345, + channel_confirmation=ChannelConfirmation.CHANNEL_B, + ) + skill_result = _build_skill_result( + result, + completion_marker="%%ORDER_UP%%", + skill_command="/test", + audit=None, + expected_output_patterns=[r"plan_path\s*=\s*/.+"], + ) + assert skill_result.success is False + + # --------------------------------------------------------------------------- # Adjudication guards — integration through _build_skill_result # --------------------------------------------------------------------------- diff --git a/tests/execution/test_process_race.py b/tests/execution/test_process_race.py index de16efea28..9543a4b9d0 100644 --- a/tests/execution/test_process_race.py +++ b/tests/execution/test_process_race.py @@ -2,6 +2,8 @@ from __future__ import annotations +import dataclasses + import pytest from autoskillit.core.types import ( @@ -32,6 +34,11 @@ class TestChannelBStatusExhaustiveCoverage: TerminationReason.STALE, ChannelConfirmation.UNMONITORED, ), + ( + ChannelBStatus.DIR_MISSING, + TerminationReason.STALE, + ChannelConfirmation.DIR_MISSING, + ), ], ) def test_each_channel_b_status_produces_defined_pair( @@ -54,11 +61,26 @@ def test_each_channel_b_status_produces_defined_pair( def test_sentinel_member_count(self) -> None: """Breaks when a new ChannelBStatus member is added, forcing test update.""" - assert len(ChannelBStatus) == 2, ( - f"ChannelBStatus has {len(ChannelBStatus)} members (expected 2). " + assert len(ChannelBStatus) == 3, ( + f"ChannelBStatus has {len(ChannelBStatus)} members (expected 3). " "Update the parametrized test above to cover the new member." ) + def test_resolve_termination_dir_missing_is_not_unmonitored(self) -> None: + """DIR_MISSING must NOT collapse to UNMONITORED — it gets its own + ChannelConfirmation value so downstream gates can distinguish.""" + signals = RaceSignals( + process_exited=True, + process_returncode=0, + channel_a_confirmed=False, + channel_b_status=ChannelBStatus.DIR_MISSING, + channel_b_session_id="", + stdout_session_id=None, + ) + termination, channel = resolve_termination(signals) + assert channel != ChannelConfirmation.UNMONITORED + assert channel == ChannelConfirmation.DIR_MISSING + class TestResolveTerminationPriority: """Verify priority ordering: process exit > stale > channel win.""" @@ -172,3 +194,124 @@ def test_session_id_empty_when_both_sources_empty(self) -> None: from autoskillit.execution.process import _resolve_session_id assert _resolve_session_id("", "") == "" + + +class TestResolveTerminationIdleStall: + """Idle stall priority in resolve_termination.""" + + def test_resolve_termination_idle_stall_priority(self) -> None: + signals = RaceSignals( + process_exited=False, + process_returncode=None, + channel_a_confirmed=False, + channel_b_status=None, + channel_b_session_id="", + stdout_session_id=None, + idle_stall=True, + ) + termination, channel = resolve_termination(signals) + assert termination == TerminationReason.IDLE_STALL + assert channel == ChannelConfirmation.UNMONITORED + + def test_resolve_termination_process_exit_beats_idle_stall(self) -> None: + signals = RaceSignals( + process_exited=True, + process_returncode=0, + channel_a_confirmed=False, + channel_b_status=None, + channel_b_session_id="", + stdout_session_id=None, + idle_stall=True, + ) + termination, _ = resolve_termination(signals) + assert termination == TerminationReason.NATURAL_EXIT + + def test_resolve_termination_idle_stall_beats_stale(self) -> None: + signals = RaceSignals( + process_exited=False, + process_returncode=None, + channel_a_confirmed=False, + channel_b_status=ChannelBStatus.STALE, + channel_b_session_id="s1", + stdout_session_id=None, + idle_stall=True, + ) + termination, _ = resolve_termination(signals) + assert termination == TerminationReason.IDLE_STALL + + +class TestRaceSignalsFieldCount: + """Sentinel test: breaks when RaceSignals fields change.""" + + def test_race_signals_field_count(self) -> None: + assert len(dataclasses.fields(RaceSignals)) == 8, ( + f"RaceSignals has {len(dataclasses.fields(RaceSignals))} fields (expected 8). " + "Update tests to cover the new field." + ) + + +class TestProcessExitedEvent: + """process_exited_event on RaceAccumulator / RaceSignals (1h).""" + + @pytest.mark.anyio + async def test_watch_process_sets_both_event_and_flag(self, tmp_path) -> None: + """_watch_process must set acc.process_exited=True AND process_exited_event.""" + import sys + + import anyio + + from autoskillit.execution._process_race import _watch_process + + acc = RaceAccumulator() + trigger = anyio.Event() + + proc = await anyio.open_process( + [sys.executable, "-c", "import time; time.sleep(0.2)"], + start_new_session=True, + ) + + async with anyio.create_task_group() as tg: + tg.start_soon(_watch_process, proc, acc, trigger) + await trigger.wait() + tg.cancel_scope.cancel() + + assert acc.process_exited is True + assert acc.process_exited_event.is_set() is True + + @pytest.mark.anyio + async def test_process_exited_event_fires_before_trigger(self, tmp_path) -> None: + """When trigger fires due to process exit, process_exited_event must already be set.""" + import sys + + import anyio + + from autoskillit.execution._process_race import _watch_process + + acc = RaceAccumulator() + trigger = anyio.Event() + + proc = await anyio.open_process( + [sys.executable, "-c", "import time; time.sleep(0.1)"], + start_new_session=True, + ) + + async with anyio.create_task_group() as tg: + tg.start_soon(_watch_process, proc, acc, trigger) + await trigger.wait() + # trigger just fired — process_exited_event must already be set + event_was_set = acc.process_exited_event.is_set() + tg.cancel_scope.cancel() + + assert event_was_set, "process_exited_event was not set before trigger fired" + + def test_process_exited_event_propagates_to_signals(self) -> None: + """process_exited_event propagates to RaceSignals via to_race_signals().""" + + acc = RaceAccumulator() + signals = acc.to_race_signals() + # The event object is shared (same reference) + assert signals.process_exited_event is acc.process_exited_event + + # After setting the event, it is set on both + acc.process_exited_event.set() + assert signals.process_exited_event.is_set() diff --git a/tests/execution/test_process_run.py b/tests/execution/test_process_run.py index bc564c503e..f85eb9be89 100644 --- a/tests/execution/test_process_run.py +++ b/tests/execution/test_process_run.py @@ -15,6 +15,7 @@ import time from pathlib import Path +import anyio import psutil import pytest @@ -361,3 +362,40 @@ async def test_run_managed_async_outer_cancel_no_attribute_error(self, tmp_path) assert caught_exc is None or not isinstance(caught_exc, AttributeError), ( f"timeout_scope None dereference — got AttributeError: {caught_exc}" ) + + +class TestIdleStallWatchdog: + """Integration test: idle_output_timeout kills a hanging process.""" + + @pytest.mark.anyio + async def test_run_managed_async_idle_stall_kills_hanging_process(self, tmp_path, monkeypatch): + """Process writes burst then stalls — IDLE_STALL kills it promptly.""" + script = tmp_path / "burst_stall.py" + script.write_text( + textwrap.dedent("""\ + import sys, time, json + for i in range(3): + sys.stdout.write(json.dumps({"type": "assistant", "i": i}) + "\\n") + sys.stdout.flush() + time.sleep(9999) + """) + ) + + monkeypatch.setattr( + "autoskillit.execution._process_monitor._has_active_api_connection", + lambda pid: True, + ) + + start = time.monotonic() + with anyio.fail_after(15.0): + result = await run_managed_async( + [sys.executable, str(script)], + cwd=tmp_path, + timeout=30, + idle_output_timeout=2.0, + stale_threshold=60, + ) + + elapsed = time.monotonic() - start + assert result.termination == TerminationReason.IDLE_STALL + assert elapsed < 12.0 diff --git a/tests/execution/test_process_submodules.py b/tests/execution/test_process_submodules.py index 3d2b167523..dcfbfaebba 100644 --- a/tests/execution/test_process_submodules.py +++ b/tests/execution/test_process_submodules.py @@ -76,9 +76,7 @@ def test_process_race_exports(): resolve_termination, ) - assert RaceAccumulator is not None assert RaceAccumulator.__module__ == "autoskillit.execution._process_race" - assert RaceSignals is not None assert RaceSignals.__module__ == "autoskillit.execution._process_race" assert callable(resolve_termination) assert resolve_termination.__module__ == "autoskillit.execution._process_race" diff --git a/tests/execution/test_quota.py b/tests/execution/test_quota.py index 27c98fe8d3..54519be171 100644 --- a/tests/execution/test_quota.py +++ b/tests/execution/test_quota.py @@ -9,6 +9,8 @@ import pytest +from autoskillit.config.settings import QuotaGuardConfig + class TestReadCredentials: def test_reads_access_token(self, tmp_path): @@ -51,10 +53,20 @@ def test_fresh_cache_returns_status(self, tmp_path): now = datetime.now(UTC) cache_data = { + "schema_version": 3, "fetched_at": (now - timedelta(seconds=30)).isoformat(), - "five_hour": { + "windows": { + "five_hour": { + "utilization": 87.3, + "resets_at": "2026-02-27T20:15:00+00:00", + } + }, + "binding": { + "window_name": "five_hour", "utilization": 87.3, "resets_at": "2026-02-27T20:15:00+00:00", + "should_block": True, + "effective_threshold": 85.0, }, } cache_path = tmp_path / "usage_cache.json" @@ -90,26 +102,99 @@ def test_corrupted_cache_returns_none(self, tmp_path): cache_path.write_text("not valid json{{") assert _read_cache(str(cache_path), max_age=120) is None + def test_read_cache_null_utilization_returns_none(self, tmp_path): + """Cache with utilization: null in binding must return None (fail-open).""" + from autoskillit.execution.quota import _read_cache + + cache_path = tmp_path / "usage_cache.json" + payload = { + "fetched_at": datetime.now(UTC).isoformat(), + "binding": {"utilization": None, "resets_at": None, "window_name": "five_hour"}, + } + cache_path.write_text(json.dumps(payload)) + assert _read_cache(str(cache_path), max_age=300) is None + + def test_read_cache_typeerror_returns_none(self, tmp_path): + """_read_cache must catch TypeError (e.g., float(None)) and return None.""" + from autoskillit.execution.quota import _read_cache + + cache_path = tmp_path / "usage_cache.json" + payload = { + "fetched_at": datetime.now(UTC).isoformat(), + "binding": {"utilization": None, "resets_at": None}, + } + cache_path.write_text(json.dumps(payload)) + # With __post_init__, constructing QuotaStatus with None raises TypeError. + # _read_cache must catch it and return None. + assert _read_cache(str(cache_path), max_age=300) is None + + +class TestQuotaDataclassPostInit: + """QuotaStatus and QuotaWindowEntry must enforce types at construction.""" + + def test_quota_window_entry_rejects_none_utilization(self): + from autoskillit.execution.quota import QuotaWindowEntry + + with pytest.raises(TypeError, match="utilization"): + QuotaWindowEntry(utilization=None, resets_at=None) + + def test_quota_status_rejects_none_utilization(self): + from autoskillit.execution.quota import QuotaStatus + + with pytest.raises(TypeError, match="utilization"): + QuotaStatus(utilization=None, resets_at=None) + + def test_quota_window_entry_coerces_string_utilization(self): + from autoskillit.execution.quota import QuotaWindowEntry + + entry = QuotaWindowEntry(utilization="85.5", resets_at=None) + assert entry.utilization == 85.5 + assert isinstance(entry.utilization, float) + + def test_quota_status_coerces_string_utilization(self): + from autoskillit.execution.quota import QuotaStatus + + status = QuotaStatus(utilization="42.0", resets_at=None) + assert status.utilization == 42.0 + assert isinstance(status.utilization, float) + class TestWriteCache: def test_writes_readable_cache(self, tmp_path): - from autoskillit.execution.quota import QuotaStatus, _read_cache, _write_cache + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + _read_cache, + _write_cache, + ) resets_at = datetime(2026, 2, 27, 20, 15, tzinfo=UTC) - status = QuotaStatus(utilization=75.0, resets_at=resets_at) + result = QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=75.0, resets_at=resets_at)}, + binding=QuotaStatus(utilization=75.0, resets_at=resets_at, window_name="five_hour"), + ) cache_path = tmp_path / "usage_cache.json" - _write_cache(str(cache_path), status) + _write_cache(str(cache_path), result) recovered = _read_cache(str(cache_path), max_age=60) assert recovered is not None assert recovered.utilization == pytest.approx(75.0) def test_write_failure_does_not_raise(self, tmp_path): - from autoskillit.execution.quota import QuotaStatus, _write_cache + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + _write_cache, + ) resets_at = datetime(2026, 2, 27, 20, 15, tzinfo=UTC) - status = QuotaStatus(utilization=50.0, resets_at=resets_at) + result = QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=50.0, resets_at=resets_at)}, + binding=QuotaStatus(utilization=50.0, resets_at=resets_at, window_name="five_hour"), + ) # Nonexistent parent directory — should log warning, not raise - _write_cache("/nonexistent/dir/cache.json", status) + _write_cache("/nonexistent/dir/cache.json", result) class TestCheckAndSleepIfNeeded: @@ -133,18 +218,27 @@ async def mock_fetch(*a, **kw): @pytest.mark.anyio async def test_below_threshold_returns_should_sleep_false(self, monkeypatch, tmp_path): from autoskillit.config.settings import QuotaGuardConfig - from autoskillit.execution.quota import QuotaStatus, check_and_sleep_if_needed + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + check_and_sleep_if_needed, + ) resets_at = datetime.now(UTC) + timedelta(hours=2) config = QuotaGuardConfig( enabled=True, - threshold=80.0, credentials_path=str(tmp_path / ".credentials.json"), cache_path=str(tmp_path / "cache.json"), ) - async def mock_fetch(path): - return QuotaStatus(utilization=50.0, resets_at=resets_at) + async def mock_fetch(path, **kwargs): + return QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=50.0, resets_at=resets_at)}, + binding=QuotaStatus( + utilization=50.0, resets_at=resets_at, window_name="five_hour" + ), + ) monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", mock_fetch) result = await check_and_sleep_if_needed(config) @@ -156,20 +250,34 @@ async def test_above_threshold_returns_should_sleep_true(self, monkeypatch, tmp_ from unittest.mock import AsyncMock from autoskillit.config.settings import QuotaGuardConfig - from autoskillit.execution.quota import QuotaStatus, check_and_sleep_if_needed + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + check_and_sleep_if_needed, + ) resets_at = datetime.now(UTC) + timedelta(hours=2) config = QuotaGuardConfig( enabled=True, - threshold=80.0, buffer_seconds=0, credentials_path=str(tmp_path / ".credentials.json"), cache_path=str(tmp_path / "cache.json"), ) - first_status = QuotaStatus(utilization=90.0, resets_at=resets_at) - second_status = QuotaStatus(utilization=91.0, resets_at=resets_at) - mock_fetch = AsyncMock(side_effect=[first_status, second_status]) + def _make_result(util: float) -> QuotaFetchResult: + return QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=util, resets_at=resets_at)}, + binding=QuotaStatus( + utilization=util, + resets_at=resets_at, + window_name="five_hour", + should_block=util >= 85.0, + effective_threshold=85.0, + ), + ) + + mock_fetch = AsyncMock(side_effect=[_make_result(90.0), _make_result(91.0)]) monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", mock_fetch) result = await check_and_sleep_if_needed(config) assert result["should_sleep"] is True @@ -180,17 +288,26 @@ async def test_above_threshold_returns_should_sleep_true(self, monkeypatch, tmp_ async def test_uses_fresh_cache_skips_fetch(self, monkeypatch, tmp_path): from autoskillit.config.settings import QuotaGuardConfig from autoskillit.execution.quota import ( + QuotaFetchResult, QuotaStatus, + QuotaWindowEntry, _write_cache, check_and_sleep_if_needed, ) resets_at = datetime.now(UTC) + timedelta(hours=1) cache_path = tmp_path / "cache.json" - _write_cache(str(cache_path), QuotaStatus(utilization=40.0, resets_at=resets_at)) + _write_cache( + str(cache_path), + QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=40.0, resets_at=resets_at)}, + binding=QuotaStatus( + utilization=40.0, resets_at=resets_at, window_name="five_hour" + ), + ), + ) config = QuotaGuardConfig( enabled=True, - threshold=80.0, cache_max_age=120, credentials_path=str(tmp_path / ".credentials.json"), cache_path=str(cache_path), @@ -199,7 +316,7 @@ async def test_uses_fresh_cache_skips_fetch(self, monkeypatch, tmp_path): async def mock_fetch(path): fetch_called.append(1) - return QuotaStatus(utilization=99.9, resets_at=resets_at) + raise AssertionError("should not fetch when cache is fresh") monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", mock_fetch) result = await check_and_sleep_if_needed(config) @@ -236,7 +353,7 @@ async def test_network_error_returns_error_dict(self, monkeypatch, tmp_path): json.dumps({"claudeAiOauth": {"accessToken": "tok", "expiresAt": expires_ms}}) ) - async def mock_fetch(path): + async def mock_fetch(path, **kwargs): raise OSError("network down") monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", mock_fetch) @@ -255,22 +372,43 @@ async def test_resets_at_none_after_refetch_logs_warning_with_fallback( import structlog.testing from autoskillit.config.settings import QuotaGuardConfig - from autoskillit.execution.quota import QuotaStatus, check_and_sleep_if_needed + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + check_and_sleep_if_needed, + ) config = QuotaGuardConfig( enabled=True, - threshold=80.0, credentials_path=str(tmp_path / ".credentials.json"), cache_path=str(tmp_path / "cache.json"), ) + resets = datetime.now(UTC) + timedelta(hours=1) # First fetch: above threshold, has resets_at so Gate 1 passes - first_status = QuotaStatus( - utilization=90.0, resets_at=datetime.now(UTC) + timedelta(hours=1) + first_result = QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=90.0, resets_at=resets)}, + binding=QuotaStatus( + utilization=90.0, + resets_at=resets, + window_name="five_hour", + should_block=True, + effective_threshold=85.0, + ), ) # Second fetch (re-fetch): above threshold, resets_at is None → Gate 2 fires - second_status = QuotaStatus(utilization=90.0, resets_at=None) + second_result = QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=90.0, resets_at=None)}, + binding=QuotaStatus( + utilization=90.0, + resets_at=None, + window_name="five_hour", + should_block=True, + effective_threshold=85.0, + ), + ) - mock_fetch = AsyncMock(side_effect=[first_status, second_status]) + mock_fetch = AsyncMock(side_effect=[first_result, second_result]) monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", mock_fetch) with structlog.testing.capture_logs() as cap: @@ -291,18 +429,31 @@ class TestCheckAndSleepResetAtNoneBlocks: @pytest.mark.anyio async def test_above_threshold_resets_at_none_first_fetch_blocks(self, monkeypatch, tmp_path): from autoskillit.config.settings import QuotaGuardConfig - from autoskillit.execution.quota import QuotaStatus, check_and_sleep_if_needed + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + check_and_sleep_if_needed, + ) config = QuotaGuardConfig( enabled=True, - threshold=80.0, buffer_seconds=60, credentials_path=str(tmp_path / ".credentials.json"), cache_path=str(tmp_path / "cache.json"), ) - async def mock_fetch(path): - return QuotaStatus(utilization=90.0, resets_at=None) + async def mock_fetch(path, **kwargs): + return QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=90.0, resets_at=None)}, + binding=QuotaStatus( + utilization=90.0, + resets_at=None, + window_name="five_hour", + should_block=True, + effective_threshold=85.0, + ), + ) monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", mock_fetch) result = await check_and_sleep_if_needed(config) @@ -314,20 +465,42 @@ async def test_above_threshold_resets_at_none_second_fetch_blocks(self, monkeypa from unittest.mock import AsyncMock from autoskillit.config.settings import QuotaGuardConfig - from autoskillit.execution.quota import QuotaStatus, check_and_sleep_if_needed + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + check_and_sleep_if_needed, + ) resets_at = datetime.now(UTC) + timedelta(hours=2) config = QuotaGuardConfig( enabled=True, - threshold=80.0, buffer_seconds=60, credentials_path=str(tmp_path / ".credentials.json"), cache_path=str(tmp_path / "cache.json"), ) # First fetch has resets_at (passes first None guard), second fetch has None - first_status = QuotaStatus(utilization=90.0, resets_at=resets_at) - second_status = QuotaStatus(utilization=90.0, resets_at=None) - mock_fetch = AsyncMock(side_effect=[first_status, second_status]) + first_result = QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=90.0, resets_at=resets_at)}, + binding=QuotaStatus( + utilization=90.0, + resets_at=resets_at, + window_name="five_hour", + should_block=True, + effective_threshold=85.0, + ), + ) + second_result = QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=90.0, resets_at=None)}, + binding=QuotaStatus( + utilization=90.0, + resets_at=None, + window_name="five_hour", + should_block=True, + effective_threshold=85.0, + ), + ) + mock_fetch = AsyncMock(side_effect=[first_result, second_result]) monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", mock_fetch) result = await check_and_sleep_if_needed(config) assert result["should_sleep"] is True @@ -337,17 +510,30 @@ async def test_above_threshold_resets_at_none_second_fetch_blocks(self, monkeypa async def test_cache_hit_resets_at_none_above_threshold_blocks(self, monkeypatch, tmp_path): from autoskillit.config.settings import QuotaGuardConfig from autoskillit.execution.quota import ( + QuotaFetchResult, QuotaStatus, + QuotaWindowEntry, _write_cache, check_and_sleep_if_needed, ) cache_path = tmp_path / "cache.json" # Write a cache entry with resets_at=None and above-threshold utilization - _write_cache(str(cache_path), QuotaStatus(utilization=90.0, resets_at=None)) + _write_cache( + str(cache_path), + QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=90.0, resets_at=None)}, + binding=QuotaStatus( + utilization=90.0, + resets_at=None, + window_name="five_hour", + should_block=True, + effective_threshold=85.0, + ), + ), + ) config = QuotaGuardConfig( enabled=True, - threshold=80.0, buffer_seconds=60, cache_max_age=120, credentials_path=str(tmp_path / ".credentials.json"), @@ -367,18 +553,31 @@ async def mock_fetch(path): @pytest.mark.anyio async def test_fallback_sleep_uses_at_least_buffer_seconds(self, monkeypatch, tmp_path): from autoskillit.config.settings import QuotaGuardConfig - from autoskillit.execution.quota import QuotaStatus, check_and_sleep_if_needed + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + check_and_sleep_if_needed, + ) config = QuotaGuardConfig( enabled=True, - threshold=80.0, buffer_seconds=120, credentials_path=str(tmp_path / ".credentials.json"), cache_path=str(tmp_path / "cache.json"), ) - async def mock_fetch(path): - return QuotaStatus(utilization=90.0, resets_at=None) + async def mock_fetch(path, **kwargs): + return QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=90.0, resets_at=None)}, + binding=QuotaStatus( + utilization=90.0, + resets_at=None, + window_name="five_hour", + should_block=True, + effective_threshold=85.0, + ), + ) monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", mock_fetch) result = await check_and_sleep_if_needed(config) @@ -390,19 +589,34 @@ async def test_above_threshold_with_buffer_seconds_default(self, monkeypatch, tm from unittest.mock import AsyncMock from autoskillit.config.settings import QuotaGuardConfig - from autoskillit.execution.quota import QuotaStatus, check_and_sleep_if_needed + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + check_and_sleep_if_needed, + ) resets_at = datetime.now(UTC) + timedelta(hours=2) # Do NOT override buffer_seconds — exercises the real default (60) config = QuotaGuardConfig( enabled=True, - threshold=80.0, credentials_path=str(tmp_path / ".credentials.json"), cache_path=str(tmp_path / "cache.json"), ) - first_status = QuotaStatus(utilization=90.0, resets_at=resets_at) - second_status = QuotaStatus(utilization=90.0, resets_at=resets_at) - mock_fetch = AsyncMock(side_effect=[first_status, second_status]) + + def _r(util: float) -> QuotaFetchResult: + return QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=util, resets_at=resets_at)}, + binding=QuotaStatus( + utilization=util, + resets_at=resets_at, + window_name="five_hour", + should_block=util >= 85.0, + effective_threshold=85.0, + ), + ) + + mock_fetch = AsyncMock(side_effect=[_r(90.0), _r(90.0)]) monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", mock_fetch) result = await check_and_sleep_if_needed(config) assert result["should_sleep"] is True @@ -410,10 +624,10 @@ async def test_above_threshold_with_buffer_seconds_default(self, monkeypatch, tm class TestIntegration: - """Integration tests: write/read contract between execution.quota and hooks.quota_check.""" + """Integration tests: write/read contract between execution.quota and hooks.quota_guard.""" def test_write_cache_then_quota_check_main_reads_it(self, tmp_path, monkeypatch): - """Cache written by _write_cache must be readable and actionable by quota_check.main(). + """Cache written by _write_cache must be readable and actionable by quota_guard.main(). T-INT-1: Catches format drift between _write_cache (execution layer) and _read_quota_cache (hook subprocess layer). @@ -421,11 +635,28 @@ def test_write_cache_then_quota_check_main_reads_it(self, tmp_path, monkeypatch) import io from contextlib import redirect_stdout - from autoskillit.execution.quota import QuotaStatus, _write_cache - from autoskillit.hooks.quota_check import main + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + _write_cache, + ) + from autoskillit.hooks.quota_guard import main cache_path = tmp_path / "quota_cache.json" - _write_cache(str(cache_path), QuotaStatus(utilization=95.0, resets_at=None)) + _write_cache( + str(cache_path), + QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=95.0, resets_at=None)}, + binding=QuotaStatus( + utilization=95.0, + resets_at=None, + window_name="five_hour", + should_block=True, + effective_threshold=85.0, + ), + ), + ) stdin_text = json.dumps({"tool_name": "run_skill"}) buf = io.StringIO() @@ -439,3 +670,1058 @@ def test_write_cache_then_quota_check_main_reads_it(self, tmp_path, monkeypatch) out = buf.getvalue() data = json.loads(out) assert data["hookSpecificOutput"]["permissionDecision"] == "deny" + + +class TestMultiWindowSelection: + """Verifies _compute_binding selects the worst-case window and full-snapshot cache I/O.""" + + # T-MW-1: one_hour exhausted, five_hour fine → binding = one_hour + def test_binding_window_one_hour_exhausted(self): + from autoskillit.execution.quota import QuotaWindowEntry, _compute_binding + + now = datetime.now(UTC) + resets_one_hour = now + timedelta(minutes=45) + windows = { + "one_hour": QuotaWindowEntry(utilization=91.0, resets_at=resets_one_hour), + "five_hour": QuotaWindowEntry(utilization=35.0, resets_at=now + timedelta(hours=4)), + } + binding = _compute_binding( + windows, + short_threshold=85.0, + long_threshold=98.0, + long_patterns=["weekly", "sonnet", "opus"], + ) + assert binding.utilization == pytest.approx(91.0) + assert binding.resets_at == resets_one_hour + assert binding.window_name == "one_hour" + + # T-MW-2: multiple windows exhausted → binding = window with latest resets_at + def test_binding_window_latest_resets_at_governs(self): + from autoskillit.execution.quota import QuotaWindowEntry, _compute_binding + + now = datetime.now(UTC) + resets_one_hour = now + timedelta(minutes=45) + resets_one_day = now + timedelta(hours=18) + windows = { + "one_hour": QuotaWindowEntry(utilization=91.0, resets_at=resets_one_hour), + "one_day": QuotaWindowEntry(utilization=97.0, resets_at=resets_one_day), + "five_hour": QuotaWindowEntry(utilization=35.0, resets_at=now + timedelta(hours=4)), + } + binding = _compute_binding( + windows, + short_threshold=85.0, + long_threshold=98.0, + long_patterns=["weekly", "sonnet", "opus"], + ) + assert binding.window_name == "one_day" + assert binding.resets_at == resets_one_day + + # T-MW-3: all windows fine → should_sleep=False, binding = highest utilization + def test_all_windows_fine_binding_is_highest_utilization(self): + from autoskillit.execution.quota import QuotaWindowEntry, _compute_binding + + now = datetime.now(UTC) + five_hour_resets = now + timedelta(hours=4) + windows = { + "one_hour": QuotaWindowEntry(utilization=40.0, resets_at=now + timedelta(hours=1)), + "five_hour": QuotaWindowEntry(utilization=60.0, resets_at=five_hour_resets), + "one_day": QuotaWindowEntry(utilization=30.0, resets_at=now + timedelta(days=1)), + } + binding = _compute_binding( + windows, + short_threshold=85.0, + long_threshold=98.0, + long_patterns=["weekly", "sonnet", "opus"], + ) + assert binding.utilization == pytest.approx(60.0) + assert binding.window_name == "five_hour" + assert binding.resets_at == five_hour_resets + + # T-MW-3b: empty windows dict → returns zero-utilization sentinel, no ValueError + def test_empty_windows_returns_zero_sentinel(self): + from autoskillit.execution.quota import _compute_binding + + binding = _compute_binding( + {}, + short_threshold=85.0, + long_threshold=98.0, + long_patterns=["weekly", "sonnet", "opus"], + ) + assert binding.utilization == pytest.approx(0.0) + assert binding.resets_at is None + + # T-MW-4: _write_cache stores full windows dict + binding key + def test_write_cache_stores_all_windows(self, tmp_path): + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + _write_cache, + ) + + now = datetime.now(UTC) + resets = now + timedelta(hours=1) + windows = { + "one_hour": QuotaWindowEntry(utilization=91.0, resets_at=resets), + "five_hour": QuotaWindowEntry(utilization=35.0, resets_at=now + timedelta(hours=4)), + } + binding = QuotaStatus(utilization=91.0, resets_at=resets, window_name="one_hour") + result = QuotaFetchResult(windows=windows, binding=binding) + cache_path = tmp_path / "cache.json" + _write_cache(str(cache_path), result) + data = json.loads(cache_path.read_text()) + assert "windows" in data + assert "one_hour" in data["windows"] + assert "five_hour" in data["windows"] + assert "binding" in data + assert data["binding"]["window_name"] == "one_hour" + assert data["binding"]["utilization"] == pytest.approx(91.0) + + # T-MW-5: _read_cache with old-format cache (missing "binding") returns None + def test_read_cache_old_format_returns_none(self, tmp_path): + from autoskillit.execution.quota import _read_cache + + old_cache = { + "fetched_at": datetime.now(UTC).isoformat(), + "five_hour": {"utilization": 87.0, "resets_at": None}, + } + cache_path = tmp_path / "old_cache.json" + cache_path.write_text(json.dumps(old_cache)) + result = _read_cache(str(cache_path), max_age=120) + assert result is None + + # T-MW-6: _read_cache with new format returns QuotaStatus from binding + def test_read_cache_new_format_returns_binding(self, tmp_path): + from autoskillit.execution.quota import _read_cache + + new_cache = { + "schema_version": 3, + "fetched_at": datetime.now(UTC).isoformat(), + "windows": { + "one_hour": { + "utilization": 91.0, + "resets_at": "2026-04-10T09:45:00+00:00", + }, + "five_hour": { + "utilization": 35.0, + "resets_at": "2026-04-10T13:00:00+00:00", + }, + }, + "binding": { + "window_name": "one_hour", + "utilization": 91.0, + "resets_at": "2026-04-10T09:45:00+00:00", + "should_block": True, + "effective_threshold": 85.0, + }, + } + cache_path = tmp_path / "new_cache.json" + cache_path.write_text(json.dumps(new_cache)) + status = _read_cache(str(cache_path), max_age=120) + assert status is not None + assert status.utilization == pytest.approx(91.0) + assert status.window_name == "one_hour" + + +class TestPerWindowThresholds: + """Per-window threshold classification: short windows block at 85%, long at 98%.""" + + _LONG_PATTERNS = ["weekly", "sonnet", "opus"] + + def test_threshold_for_window_short_default(self): + from autoskillit.execution.quota import _threshold_for_window + + assert ( + _threshold_for_window( + "five_hour", + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + ) + == 85.0 + ) + + def test_threshold_for_window_long_weekly(self): + from autoskillit.execution.quota import _threshold_for_window + + assert ( + _threshold_for_window( + "weekly", + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + ) + == 98.0 + ) + + def test_threshold_for_window_long_sonnet_substring(self): + from autoskillit.execution.quota import _threshold_for_window + + assert ( + _threshold_for_window( + "weekly_sonnet", + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + ) + == 98.0 + ) + + def test_threshold_for_window_case_insensitive(self): + from autoskillit.execution.quota import _threshold_for_window + + assert ( + _threshold_for_window( + "Weekly", + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + ) + == 98.0 + ) + + def test_threshold_for_window_unknown_uses_short(self): + from autoskillit.execution.quota import _threshold_for_window + + assert ( + _threshold_for_window( + "context", + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + ) + == 85.0 + ) + + def test_compute_binding_picks_short_when_only_short_exhausted(self): + from autoskillit.execution.quota import QuotaWindowEntry, _compute_binding + + now = datetime.now(UTC) + windows = { + "five_hour": QuotaWindowEntry(utilization=90.0, resets_at=now + timedelta(hours=1)), + "weekly": QuotaWindowEntry(utilization=80.0, resets_at=now + timedelta(days=4)), + } + binding = _compute_binding( + windows, + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + ) + assert binding.window_name == "five_hour" + assert binding.should_block is True + assert binding.effective_threshold == pytest.approx(85.0) + + def test_compute_binding_does_not_block_weekly_below_long_threshold(self): + """Regression test for issue #721: weekly at 86% must not block. + + Long-window quotas (weekly, sonnet, opus) reset across multi-day windows, + so 14% remaining headroom is comfortable, not exhausted. The pre-fix + behaviour blocked the pipeline for ~4 days at 86% weekly. + """ + from autoskillit.execution.quota import QuotaWindowEntry, _compute_binding + + now = datetime.now(UTC) + windows = { + "weekly": QuotaWindowEntry(utilization=86.0, resets_at=now + timedelta(days=4)), + "five_hour": QuotaWindowEntry(utilization=50.0, resets_at=now + timedelta(hours=1)), + } + binding = _compute_binding( + windows, + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + ) + assert binding.should_block is False + assert binding.effective_threshold == pytest.approx(98.0) + + def test_compute_binding_blocks_weekly_at_99_percent(self): + from autoskillit.execution.quota import QuotaWindowEntry, _compute_binding + + now = datetime.now(UTC) + windows = { + "weekly": QuotaWindowEntry(utilization=99.0, resets_at=now + timedelta(days=4)), + } + binding = _compute_binding( + windows, + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + ) + assert binding.should_block is True + assert binding.effective_threshold == pytest.approx(98.0) + + def test_compute_binding_picks_latest_resets_among_exhausted(self): + """Among exhausted windows, the one with the latest reset wins.""" + from autoskillit.execution.quota import QuotaWindowEntry, _compute_binding + + now = datetime.now(UTC) + weekly_resets = now + timedelta(days=4) + windows = { + "five_hour": QuotaWindowEntry(utilization=90.0, resets_at=now + timedelta(hours=1)), + "weekly": QuotaWindowEntry(utilization=99.0, resets_at=weekly_resets), + } + binding = _compute_binding( + windows, + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + ) + assert binding.window_name == "weekly" + assert binding.resets_at == weekly_resets + assert binding.should_block is True + + def test_write_cache_includes_should_block_and_effective_threshold(self, tmp_path): + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + _write_cache, + ) + + now = datetime.now(UTC) + weekly_resets = now + timedelta(days=4) + windows = { + "weekly": QuotaWindowEntry(utilization=86.0, resets_at=weekly_resets), + } + binding = QuotaStatus( + utilization=86.0, + resets_at=weekly_resets, + window_name="weekly", + should_block=False, + effective_threshold=98.0, + ) + result = QuotaFetchResult(windows=windows, binding=binding) + cache_path = tmp_path / "cache.json" + _write_cache(str(cache_path), result) + data = json.loads(cache_path.read_text()) + assert data["binding"]["should_block"] is False + assert data["binding"]["effective_threshold"] == pytest.approx(98.0) + + def test_read_cache_round_trip_should_block(self, tmp_path): + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + _read_cache, + _write_cache, + ) + + now = datetime.now(UTC) + weekly_resets = now + timedelta(days=4) + windows = { + "weekly": QuotaWindowEntry(utilization=99.0, resets_at=weekly_resets), + } + binding = QuotaStatus( + utilization=99.0, + resets_at=weekly_resets, + window_name="weekly", + should_block=True, + effective_threshold=98.0, + ) + cache_path = tmp_path / "cache.json" + _write_cache(str(cache_path), QuotaFetchResult(windows=windows, binding=binding)) + status = _read_cache(str(cache_path), max_age=300) + assert status is not None + assert status.should_block is True + assert status.effective_threshold == pytest.approx(98.0) + assert status.window_name == "weekly" + + @pytest.mark.anyio + async def test_check_and_sleep_returns_false_for_weekly_at_86_percent( + self, monkeypatch, tmp_path + ): + """End-to-end regression test for #721 — weekly at 86% must not sleep.""" + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaWindowEntry, + _compute_binding, + check_and_sleep_if_needed, + ) + + now = datetime.now(UTC) + windows = { + "weekly": QuotaWindowEntry(utilization=86.0, resets_at=now + timedelta(days=4)), + "five_hour": QuotaWindowEntry(utilization=2.0, resets_at=now + timedelta(hours=1)), + } + binding = _compute_binding( + windows, + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + ) + + async def fake_fetch(credentials_path, **kwargs): + return QuotaFetchResult(windows=windows, binding=binding) + + monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", fake_fetch) + config = QuotaGuardConfig( + cache_path=str(tmp_path / "cache.json"), + credentials_path=str(tmp_path / "creds.json"), + ) + result = await check_and_sleep_if_needed(config) + assert result["should_sleep"] is False + assert result["window_name"] == "weekly" + + @pytest.mark.anyio + async def test_check_and_sleep_returns_true_for_weekly_at_99_percent( + self, monkeypatch, tmp_path + ): + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaWindowEntry, + _compute_binding, + check_and_sleep_if_needed, + ) + + now = datetime.now(UTC) + weekly_resets = now + timedelta(days=4) + windows = { + "weekly": QuotaWindowEntry(utilization=99.0, resets_at=weekly_resets), + "five_hour": QuotaWindowEntry(utilization=2.0, resets_at=now + timedelta(hours=1)), + } + binding = _compute_binding( + windows, + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + ) + + async def fake_fetch(credentials_path, **kwargs): + return QuotaFetchResult(windows=windows, binding=binding) + + monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", fake_fetch) + config = QuotaGuardConfig( + cache_path=str(tmp_path / "cache.json"), + credentials_path=str(tmp_path / "creds.json"), + ) + result = await check_and_sleep_if_needed(config) + assert result["should_sleep"] is True + assert result["window_name"] == "weekly" + assert result["sleep_seconds"] > 0 + + +class TestRefreshQuotaCache: + """Tests for _refresh_quota_cache: unconditional fetch-and-write behavior.""" + + @pytest.mark.anyio + async def test_refresh_quota_cache_fetches_even_when_cache_is_fresh( + self, tmp_path, monkeypatch + ): + """_refresh_quota_cache calls _fetch_quota unconditionally, even if cache is fresh.""" + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + _refresh_quota_cache, + ) + + fresh_cache = tmp_path / "cache.json" + # Write a 10-second-old cache (well within 300s max_age) + fresh_cache.write_text( + json.dumps( + { + "fetched_at": (datetime.now(UTC) - timedelta(seconds=10)).isoformat(), + "five_hour": {"utilization": 0.3, "resets_at": None}, + } + ) + ) + fetch_called = [] + + async def fake_fetch(credentials_path, **kwargs): + fetch_called.append(True) + return QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=0.35, resets_at=None)}, + binding=QuotaStatus(utilization=0.35, resets_at=None, window_name="five_hour"), + ) + + monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", fake_fetch) + config = QuotaGuardConfig(cache_path=str(fresh_cache)) + await _refresh_quota_cache(config) + assert len(fetch_called) == 1 # must have fetched even though cache was fresh + + @pytest.mark.anyio + async def test_refresh_quota_cache_writes_new_cache(self, tmp_path, monkeypatch): + """_refresh_quota_cache writes a new cache file after fetching.""" + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + _refresh_quota_cache, + ) + + cache_path = tmp_path / "cache.json" + + async def fake_fetch(credentials_path, **kwargs): + return QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=0.5, resets_at=None)}, + binding=QuotaStatus(utilization=0.5, resets_at=None, window_name="five_hour"), + ) + + monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", fake_fetch) + config = QuotaGuardConfig(cache_path=str(cache_path)) + await _refresh_quota_cache(config) + assert cache_path.exists() + data = json.loads(cache_path.read_text()) + assert data["binding"]["utilization"] == pytest.approx(0.5) + + +class TestCacheSchemaVersion: + """Phase 4 (#711 Part B): quota cache schema versioning tests.""" + + def setup_method(self): + from autoskillit.execution.quota import _reset_schema_drift_logged_for_tests + + _reset_schema_drift_logged_for_tests() + + def test_write_cache_embeds_schema_version(self, tmp_path): + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + _write_cache, + ) + + result = QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=50.0, resets_at=None)}, + binding=QuotaStatus(utilization=50.0, resets_at=None, window_name="five_hour"), + ) + cache_path = tmp_path / "cache.json" + _write_cache(str(cache_path), result) + raw = json.loads(cache_path.read_text()) + assert raw["schema_version"] == 3 + + def test_write_cache_uses_write_versioned_json(self, tmp_path, monkeypatch): + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + _write_cache, + ) + + calls = [] + + def spy(path, payload, schema_version): + calls.append({"path": path, "schema_version": schema_version}) + # Call through to real impl + from autoskillit.core import write_versioned_json as real + + real(path, payload, schema_version) + + monkeypatch.setattr("autoskillit.execution.quota.write_versioned_json", spy) + + result = QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=50.0, resets_at=None)}, + binding=QuotaStatus(utilization=50.0, resets_at=None, window_name="five_hour"), + ) + cache_path = tmp_path / "cache.json" + _write_cache(str(cache_path), result) + assert len(calls) == 1 + assert calls[0]["schema_version"] == 3 + + def test_read_cache_schema_round_trip_returns_status(self, tmp_path): + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + _read_cache, + _write_cache, + ) + + resets_at = datetime(2026, 2, 27, 20, 15, tzinfo=UTC) + result = QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=60.0, resets_at=resets_at)}, + binding=QuotaStatus(utilization=60.0, resets_at=resets_at, window_name="five_hour"), + ) + cache_path = tmp_path / "cache.json" + _write_cache(str(cache_path), result) + status = _read_cache(str(cache_path), max_age=60) + assert status is not None + assert status.utilization == pytest.approx(60.0) + + def test_read_cache_missing_schema_version_returns_none(self, tmp_path): + from autoskillit.execution.quota import _read_cache + + cache_path = tmp_path / "cache.json" + old_data = { + "fetched_at": datetime.now(UTC).isoformat(), + "windows": {}, + "binding": {"utilization": 50.0, "resets_at": None, "window_name": "five_hour"}, + } + cache_path.write_text(json.dumps(old_data)) + assert _read_cache(str(cache_path), max_age=60) is None + + def test_read_cache_wrong_schema_version_returns_none(self, tmp_path): + from autoskillit.execution.quota import _read_cache + + cache_path = tmp_path / "cache.json" + old_data = { + "schema_version": 1, + "fetched_at": datetime.now(UTC).isoformat(), + "windows": {}, + "binding": {"utilization": 50.0, "resets_at": None, "window_name": "five_hour"}, + } + cache_path.write_text(json.dumps(old_data)) + assert _read_cache(str(cache_path), max_age=60) is None + + def test_read_cache_logs_drift_warning_on_schema_mismatch(self, tmp_path): + import structlog.testing + + from autoskillit.execution.quota import _read_cache + + cache_path = tmp_path / "cache.json" + old_data = { + "fetched_at": datetime.now(UTC).isoformat(), + "windows": {}, + "binding": {"utilization": 50.0, "resets_at": None, "window_name": "five_hour"}, + } + cache_path.write_text(json.dumps(old_data)) + + with structlog.testing.capture_logs() as cap: + _read_cache(str(cache_path), max_age=60) + + drift_logs = [r for r in cap if "quota_cache_schema_drift" in r.get("event", "")] + assert len(drift_logs) == 1 + assert "cache_path" in drift_logs[0] + assert drift_logs[0]["observed"] is None + + def test_read_cache_logs_drift_exactly_once_per_path_per_process(self, tmp_path): + import structlog.testing + + from autoskillit.execution.quota import _read_cache + + cache_path = tmp_path / "cache.json" + old_data = { + "fetched_at": datetime.now(UTC).isoformat(), + "windows": {}, + "binding": {"utilization": 50.0, "resets_at": None, "window_name": "five_hour"}, + } + cache_path.write_text(json.dumps(old_data)) + + with structlog.testing.capture_logs() as cap: + for _ in range(5): + _read_cache(str(cache_path), max_age=60) + + drift_logs = [r for r in cap if "quota_cache_schema_drift" in r.get("event", "")] + assert len(drift_logs) == 1 + + def test_read_cache_logs_drift_once_per_path_not_globally(self, tmp_path): + import structlog.testing + + from autoskillit.execution.quota import _read_cache + + for name in ("cache_a.json", "cache_b.json"): + path = tmp_path / name + path.write_text( + json.dumps( + { + "fetched_at": datetime.now(UTC).isoformat(), + "windows": {}, + "binding": {"utilization": 50.0}, + } + ) + ) + + with structlog.testing.capture_logs() as cap: + _read_cache(str(tmp_path / "cache_a.json"), max_age=60) + _read_cache(str(tmp_path / "cache_b.json"), max_age=60) + + drift_logs = [r for r in cap if "quota_cache_schema_drift" in r.get("event", "")] + assert len(drift_logs) == 2 + + def test_read_cache_drift_set_is_module_scoped_and_reset_helper_works(self, tmp_path): + import structlog.testing + + from autoskillit.execution.quota import ( + _read_cache, + _reset_schema_drift_logged_for_tests, + ) + + cache_path = tmp_path / "cache.json" + cache_path.write_text( + json.dumps( + { + "fetched_at": datetime.now(UTC).isoformat(), + "windows": {}, + "binding": {"utilization": 50.0}, + } + ) + ) + + with structlog.testing.capture_logs() as cap1: + _read_cache(str(cache_path), max_age=60) + assert len([r for r in cap1 if "quota_cache_schema_drift" in r.get("event", "")]) == 1 + + _reset_schema_drift_logged_for_tests() + + with structlog.testing.capture_logs() as cap2: + _read_cache(str(cache_path), max_age=60) + assert len([r for r in cap2 if "quota_cache_schema_drift" in r.get("event", "")]) == 1 + + @pytest.mark.anyio + async def test_old_format_cache_gets_rewritten_with_new_format_on_next_fetch( + self, tmp_path, monkeypatch + ): + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + check_and_sleep_if_needed, + ) + + cache_path = tmp_path / "cache.json" + # Write old-format cache (no schema_version) + old_data = { + "fetched_at": datetime.now(UTC).isoformat(), + "windows": {}, + "binding": {"utilization": 50.0, "resets_at": None, "window_name": "five_hour"}, + } + cache_path.write_text(json.dumps(old_data)) + + async def fake_fetch(credentials_path, **kwargs): + return QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=30.0, resets_at=None)}, + binding=QuotaStatus(utilization=30.0, resets_at=None, window_name="five_hour"), + ) + + monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", fake_fetch) + config = QuotaGuardConfig( + cache_path=str(cache_path), + credentials_path=str(tmp_path / "fake_creds.json"), + ) + await check_and_sleep_if_needed(config) + new_data = json.loads(cache_path.read_text()) + assert new_data["schema_version"] == 3 + + +class TestPerWindowToggles: + """Per-window enable/disable toggles for _compute_binding.""" + + _LONG_PATTERNS = ["weekly", "sonnet", "opus"] + + def _windows(self, five_hour_util: float, weekly_util: float) -> dict: + from autoskillit.execution.quota import QuotaWindowEntry + + now = datetime.now(UTC) + return { + "five_hour": QuotaWindowEntry( + utilization=five_hour_util, resets_at=now + timedelta(hours=3) + ), + "weekly": QuotaWindowEntry(utilization=weekly_util, resets_at=now + timedelta(days=4)), + } + + def test_compute_binding_defaults_both_enabled_preserves_behavior(self): + """Test 1: default call (no toggle kwargs) — five_hour at 90% is binding and blocks.""" + from autoskillit.execution.quota import _compute_binding + + binding = _compute_binding( + self._windows(90.0, 80.0), + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + ) + assert binding.window_name == "five_hour" + assert binding.should_block is True + assert binding.effective_threshold == pytest.approx(85.0) + + def test_compute_binding_short_disabled_drops_five_hour(self): + """Test 2: short_enabled=False — five_hour is dropped, weekly survives.""" + from autoskillit.execution.quota import _compute_binding + + binding = _compute_binding( + self._windows(90.0, 80.0), + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + short_enabled=False, + long_enabled=True, + ) + assert binding.window_name == "weekly" + assert binding.should_block is False + assert binding.effective_threshold == pytest.approx(98.0) + + def test_compute_binding_short_disabled_and_only_short_windows_present(self): + """Test 3: all windows are short class → all dropped → empty sentinel.""" + from autoskillit.execution.quota import QuotaWindowEntry, _compute_binding + + now = datetime.now(UTC) + windows = { + "one_hour": QuotaWindowEntry(utilization=95.0, resets_at=now + timedelta(minutes=45)), + "five_hour": QuotaWindowEntry(utilization=90.0, resets_at=now + timedelta(hours=3)), + } + binding = _compute_binding( + windows, + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + short_enabled=False, + ) + assert binding.utilization == pytest.approx(0.0) + assert binding.resets_at is None + assert binding.should_block is False + assert binding.effective_threshold == pytest.approx(100.0) + assert binding.window_name == "unknown" + + def test_compute_binding_long_disabled_drops_weekly(self): + """Test 4: long_enabled=False — weekly dropped, five_hour survives.""" + from autoskillit.execution.quota import _compute_binding + + binding = _compute_binding( + self._windows(80.0, 99.0), + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + long_enabled=False, + ) + assert binding.window_name == "five_hour" + assert binding.should_block is False + assert binding.effective_threshold == pytest.approx(85.0) + + def test_compute_binding_long_disabled_suppresses_weekly_block(self): + """Test 5: long_enabled=False — weekly at 99% is ignored, five_hour at 2% passes.""" + from autoskillit.execution.quota import _compute_binding + + binding = _compute_binding( + self._windows(2.0, 99.0), + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + long_enabled=False, + ) + assert binding.window_name == "five_hour" + assert binding.should_block is False + + def test_compute_binding_both_disabled_returns_sentinel(self): + """Test 6: both disabled → empty sentinel with should_block=False.""" + from autoskillit.execution.quota import _compute_binding + + binding = _compute_binding( + self._windows(90.0, 99.0), + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + short_enabled=False, + long_enabled=False, + ) + assert binding.utilization == pytest.approx(0.0) + assert binding.resets_at is None + assert binding.should_block is False + assert binding.effective_threshold == pytest.approx(100.0) + + def test_compute_binding_substring_classification_respects_long_patterns(self): + """Test 7: weekly_sonnet is classified as long via substring match and dropped.""" + from autoskillit.execution.quota import QuotaWindowEntry, _compute_binding + + now = datetime.now(UTC) + windows = { + "weekly_sonnet": QuotaWindowEntry(utilization=99.0, resets_at=now + timedelta(days=6)), + "five_hour": QuotaWindowEntry(utilization=90.0, resets_at=now + timedelta(hours=3)), + } + binding = _compute_binding( + windows, + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + long_enabled=False, + ) + assert binding.window_name == "five_hour" + + def test_compute_binding_both_enabled_matches_legacy_keyword_signature(self): + """Test 8: explicit True values produce identical output to implicit defaults.""" + from autoskillit.execution.quota import _compute_binding + + windows = self._windows(90.0, 80.0) + implicit = _compute_binding( + windows, + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + ) + explicit = _compute_binding( + windows, + short_threshold=85.0, + long_threshold=98.0, + long_patterns=self._LONG_PATTERNS, + short_enabled=True, + long_enabled=True, + ) + assert explicit.window_name == implicit.window_name + assert explicit.should_block == implicit.should_block + assert explicit.effective_threshold == pytest.approx(implicit.effective_threshold) + assert explicit.utilization == pytest.approx(implicit.utilization) + + @pytest.mark.anyio + async def test_check_and_sleep_respects_short_window_disabled(self, monkeypatch, tmp_path): + """Test 9: short_window_enabled=False — five_hour at 90% is ignored.""" + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + check_and_sleep_if_needed, + ) + + resets_at = datetime.now(UTC) + timedelta(hours=3) + config = QuotaGuardConfig( + short_window_enabled=False, + credentials_path=str(tmp_path / ".credentials.json"), + cache_path=str(tmp_path / "cache.json"), + ) + + captured_kwargs: dict = {} + + async def fake_fetch(credentials_path, **kwargs): + captured_kwargs.update(kwargs) + return QuotaFetchResult( + windows={ + "five_hour": QuotaWindowEntry(utilization=90.0, resets_at=resets_at), + "weekly": QuotaWindowEntry( + utilization=80.0, resets_at=datetime.now(UTC) + timedelta(days=4) + ), + }, + binding=QuotaStatus( + utilization=80.0, + resets_at=datetime.now(UTC) + timedelta(days=4), + window_name="weekly", + should_block=False, + effective_threshold=98.0, + ), + ) + + monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", fake_fetch) + result = await check_and_sleep_if_needed(config) + assert result["should_sleep"] is False + assert result["window_name"] == "weekly" + assert captured_kwargs.get("short_enabled") is False + + @pytest.mark.anyio + async def test_check_and_sleep_respects_long_window_disabled(self, monkeypatch, tmp_path): + """Test 10: long_window_enabled=False — weekly at 99% is ignored.""" + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + check_and_sleep_if_needed, + ) + + config = QuotaGuardConfig( + long_window_enabled=False, + credentials_path=str(tmp_path / ".credentials.json"), + cache_path=str(tmp_path / "cache.json"), + ) + + captured_kwargs: dict = {} + + async def fake_fetch(credentials_path, **kwargs): + captured_kwargs.update(kwargs) + return QuotaFetchResult( + windows={ + "weekly": QuotaWindowEntry( + utilization=99.0, resets_at=datetime.now(UTC) + timedelta(days=6) + ), + "five_hour": QuotaWindowEntry( + utilization=2.0, resets_at=datetime.now(UTC) + timedelta(hours=3) + ), + }, + binding=QuotaStatus( + utilization=2.0, + resets_at=datetime.now(UTC) + timedelta(hours=3), + window_name="five_hour", + should_block=False, + effective_threshold=85.0, + ), + ) + + monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", fake_fetch) + result = await check_and_sleep_if_needed(config) + assert result["should_sleep"] is False + assert result["window_name"] == "five_hour" + assert captured_kwargs.get("long_enabled") is False + + @pytest.mark.anyio + async def test_check_and_sleep_both_disabled_returns_sentinel_no_sleep( + self, monkeypatch, tmp_path + ): + """Test 11: both flags False → sentinel, no sleep, no error.""" + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + check_and_sleep_if_needed, + ) + + config = QuotaGuardConfig( + short_window_enabled=False, + long_window_enabled=False, + credentials_path=str(tmp_path / ".credentials.json"), + cache_path=str(tmp_path / "cache.json"), + ) + + async def fake_fetch(credentials_path, **kwargs): + return QuotaFetchResult( + windows={ + "weekly": QuotaWindowEntry( + utilization=99.0, resets_at=datetime.now(UTC) + timedelta(days=6) + ), + "five_hour": QuotaWindowEntry( + utilization=99.0, resets_at=datetime.now(UTC) + timedelta(hours=3) + ), + }, + binding=QuotaStatus(utilization=0.0, resets_at=None, effective_threshold=100.0), + ) + + monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", fake_fetch) + result = await check_and_sleep_if_needed(config) + assert result["should_sleep"] is False + assert result["utilization"] == pytest.approx(0.0) + assert result["resets_at"] is None + assert "error" not in result + + @pytest.mark.anyio + async def test_check_and_sleep_global_enabled_false_still_short_circuits( + self, monkeypatch, tmp_path + ): + """Test 12: global enabled=False short-circuits before _fetch_quota is called.""" + fetch_called = [] + + async def sentinel_fetch(*a, **kw): + fetch_called.append(1) + raise AssertionError("_fetch_quota must not be called when enabled=False") + + monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", sentinel_fetch) + from autoskillit.execution.quota import check_and_sleep_if_needed + + config = QuotaGuardConfig( + enabled=False, + short_window_enabled=True, + long_window_enabled=True, + ) + result = await check_and_sleep_if_needed(config) + assert result["should_sleep"] is False + assert fetch_called == [] + + @pytest.mark.anyio + async def test_refresh_quota_cache_forwards_per_window_toggles(self, monkeypatch, tmp_path): + """Test 13: _refresh_quota_cache passes short_enabled/long_enabled to _fetch_quota.""" + from autoskillit.execution.quota import ( + QuotaFetchResult, + QuotaStatus, + QuotaWindowEntry, + _refresh_quota_cache, + ) + + captured_kwargs: dict = {} + + async def fake_fetch(credentials_path, **kwargs): + captured_kwargs.update(kwargs) + return QuotaFetchResult( + windows={"five_hour": QuotaWindowEntry(utilization=0.1, resets_at=None)}, + binding=QuotaStatus(utilization=0.1, resets_at=None, window_name="five_hour"), + ) + + monkeypatch.setattr("autoskillit.execution.quota._fetch_quota", fake_fetch) + config = QuotaGuardConfig( + short_window_enabled=False, + cache_path=str(tmp_path / "cache.json"), + ) + await _refresh_quota_cache(config) + assert captured_kwargs["short_enabled"] is False + assert captured_kwargs["long_enabled"] is True diff --git a/tests/execution/test_quota_http.py b/tests/execution/test_quota_http.py new file mode 100644 index 0000000000..dbce6a2e28 --- /dev/null +++ b/tests/execution/test_quota_http.py @@ -0,0 +1,256 @@ +"""End-to-end HTTP tests for quota guard using api-simulator mock_http_server. + +These tests exercise the real httpx client path — no monkeypatching of _fetch_quota. +They complement the unit tests in test_quota.py which mock at the function level. +""" + +from __future__ import annotations + +import json +import time +from datetime import UTC, datetime, timedelta +from types import SimpleNamespace + +import pytest +from api_simulator.http import MockResponseSpec as PyResponseSpec + +from autoskillit.execution.quota import check_and_sleep_if_needed + +pytestmark = pytest.mark.anyio + +QUOTA_ENDPOINT = "/api/oauth/usage" + + +@pytest.fixture() +def credentials(tmp_path): + """Write a valid .credentials.json and return its path as a string.""" + creds_file = tmp_path / ".credentials.json" + creds_file.write_text( + json.dumps( + { + "claudeAiOauth": { + "accessToken": "test-token-abc123", + "expiresAt": (time.time() + 3600) * 1000, + } + } + ) + ) + return str(creds_file) + + +@pytest.fixture() +def quota_config(credentials, tmp_path): + """Minimal config namespace for check_and_sleep_if_needed.""" + return SimpleNamespace( + enabled=True, + short_window_enabled=True, + long_window_enabled=True, + credentials_path=credentials, + cache_path=str(tmp_path / "quota_cache.json"), + cache_max_age=120, + short_window_threshold=80.0, + long_window_threshold=98.0, + long_window_patterns=["weekly", "sonnet", "opus"], + buffer_seconds=60, + ) + + +@pytest.fixture(autouse=True) +def _reset_mock(mock_http_server): + """Reset mock_http_server before each test to clear routes and recordings.""" + mock_http_server.reset() + + +async def test_normal_utilization_returns_status_and_sends_correct_headers( + mock_http_server, quota_config +): + mock_http_server.register( + "GET", + QUOTA_ENDPOINT, + PyResponseSpec( + body={ + "five_hour": { + "utilization": 50.0, + "resets_at": "2026-04-05T00:00:00+00:00", + } + } + ), + ) + + result = await check_and_sleep_if_needed(quota_config, base_url=mock_http_server.url) + + assert result["should_sleep"] is False + assert result["utilization"] == 50.0 + assert result["resets_at"] == "2026-04-05T00:00:00+00:00" + + requests = mock_http_server.get_requests("GET", QUOTA_ENDPOINT) + assert len(requests) == 1 + assert requests[0]["headers"]["authorization"] == "Bearer test-token-abc123" + assert requests[0]["headers"]["anthropic-beta"] == "oauth-2025-04-20" + + +async def test_above_threshold_triggers_double_fetch(mock_http_server, quota_config): + resets_at = (datetime.now(UTC) + timedelta(hours=2)).isoformat() + mock_http_server.register_sequence( + "GET", + QUOTA_ENDPOINT, + [ + PyResponseSpec(body={"five_hour": {"utilization": 95.0, "resets_at": resets_at}}), + PyResponseSpec(body={"five_hour": {"utilization": 95.0, "resets_at": resets_at}}), + ], + ) + + result = await check_and_sleep_if_needed(quota_config, base_url=mock_http_server.url) + + assert result["should_sleep"] is True + assert result["sleep_seconds"] > 0 + assert mock_http_server.request_count("GET", QUOTA_ENDPOINT) == 2 + + +async def test_resets_at_null_blocks_with_fallback(mock_http_server, quota_config): + mock_http_server.register( + "GET", + QUOTA_ENDPOINT, + PyResponseSpec(body={"five_hour": {"utilization": 95.0, "resets_at": None}}), + ) + + result = await check_and_sleep_if_needed(quota_config, base_url=mock_http_server.url) + + assert result["should_sleep"] is True + assert result["sleep_seconds"] >= 60 + assert result["reason"] == "unknown_reset" + assert mock_http_server.request_count("GET", QUOTA_ENDPOINT) == 1 + + +async def test_http_429_fails_open(mock_http_server, quota_config): + mock_http_server.register("GET", QUOTA_ENDPOINT, PyResponseSpec(status=429)) + + result = await check_and_sleep_if_needed(quota_config, base_url=mock_http_server.url) + + assert result["should_sleep"] is False + assert "error" in result + + +async def test_http_503_fails_open(mock_http_server, quota_config): + mock_http_server.register("GET", QUOTA_ENDPOINT, PyResponseSpec(status=503)) + + result = await check_and_sleep_if_needed(quota_config, base_url=mock_http_server.url) + + assert result["should_sleep"] is False + assert "error" in result + + +async def test_network_timeout_fails_open(mock_http_server, quota_config): + mock_http_server.register("GET", QUOTA_ENDPOINT, PyResponseSpec(body={}, delay_ms=500)) + + result = await check_and_sleep_if_needed( + quota_config, base_url=mock_http_server.url, _httpx_timeout=0.1 + ) + + assert result["should_sleep"] is False + assert "error" in result + + +async def test_z_suffix_resets_at_parsed_correctly(mock_http_server, quota_config): + mock_http_server.register( + "GET", + QUOTA_ENDPOINT, + PyResponseSpec( + body={ + "five_hour": { + "utilization": 50.0, + "resets_at": "2026-04-05T00:00:00Z", + } + } + ), + ) + + result = await check_and_sleep_if_needed(quota_config, base_url=mock_http_server.url) + + assert result["resets_at"] == "2026-04-05T00:00:00+00:00" + + +# T-HTTP-MW-1: multi-window response, worst-case window governs +async def test_multi_window_worst_case_governs(mock_http_server, quota_config): + """When one_hour is exhausted but five_hour is fine, one_hour governs the sleep.""" + resets_at = (datetime.now(UTC) + timedelta(minutes=45)).isoformat() + five_hour_resets = (datetime.now(UTC) + timedelta(hours=4)).isoformat() + mock_http_server.register_sequence( + "GET", + QUOTA_ENDPOINT, + [ + PyResponseSpec( + body={ + "one_hour": {"utilization": 91.0, "resets_at": resets_at}, + "five_hour": {"utilization": 35.0, "resets_at": five_hour_resets}, + } + ), + PyResponseSpec( + body={ + "one_hour": {"utilization": 91.0, "resets_at": resets_at}, + "five_hour": {"utilization": 35.0, "resets_at": five_hour_resets}, + } + ), + ], + ) + result = await check_and_sleep_if_needed(quota_config, base_url=mock_http_server.url) + assert result["should_sleep"] is True + assert result["sleep_seconds"] == pytest.approx(45 * 60 + 60, abs=30) + assert result["window_name"] == "one_hour" + + +async def test_null_utilization_window_skipped(mock_http_server, quota_config): + """Windows with utilization: null must be skipped, not crash.""" + mock_http_server.register( + "GET", + QUOTA_ENDPOINT, + PyResponseSpec( + body={ + "five_hour": {"utilization": None, "resets_at": "2026-04-10T12:00:00Z"}, + "daily": {"utilization": 50.0, "resets_at": "2026-04-10T18:00:00Z"}, + } + ), + ) + result = await check_and_sleep_if_needed(quota_config, base_url=mock_http_server.url) + assert result["should_sleep"] is False + assert result["utilization"] == 50.0 + + +async def test_all_null_utilization_returns_zero(mock_http_server, quota_config): + """When all windows have null utilization, result should be 0.0 (below threshold).""" + mock_http_server.register( + "GET", + QUOTA_ENDPOINT, + PyResponseSpec( + body={ + "five_hour": {"utilization": None, "resets_at": None}, + } + ), + ) + result = await check_and_sleep_if_needed(quota_config, base_url=mock_http_server.url) + assert result["should_sleep"] is False + assert result["utilization"] == 0.0 + + +# T-HTTP-MW-2: unknown/extra window keys are tolerated (forward compat) +async def test_unknown_window_keys_tolerated(mock_http_server, quota_config): + """Extra unknown window keys in API response are tolerated without error.""" + mock_http_server.register( + "GET", + QUOTA_ENDPOINT, + PyResponseSpec( + body={ + "five_hour": { + "utilization": 50.0, + "resets_at": "2026-04-05T00:00:00+00:00", + }, + "ten_year": { + "utilization": 1.0, + "resets_at": "2036-04-05T00:00:00+00:00", + }, + } + ), + ) + result = await check_and_sleep_if_needed(quota_config, base_url=mock_http_server.url) + assert result["should_sleep"] is False + assert result["utilization"] == pytest.approx(50.0) diff --git a/tests/execution/test_readiness_helper_contract.py b/tests/execution/test_readiness_helper_contract.py new file mode 100644 index 0000000000..0c917d374f --- /dev/null +++ b/tests/execution/test_readiness_helper_contract.py @@ -0,0 +1,98 @@ +"""AST lint guard: no inline stderr/stdout readline loops used as subprocess readiness polls. + +Any test that spawns a subprocess and polls its stderr/stdout line-by-line to +wait for a readiness token is a structural race — the string-parse window is +outside the try: block of the lifespan's cancel scope. The approved pattern is +`wait_for_subprocess_ready` from `tests._subprocess_ready`. + +This test walks every .py file under tests/ and rejects any file that: + - contains a `.stderr.readline()` or `.stdout.readline()` call inside a + while/for loop, AND + - also contains a `send_signal` or `Popen` call in the same function, AND + - does NOT import from tests._subprocess_ready (the approved helper). + +Files that only readline for unrelated reasons (e.g., reading output after +the process is done) are not caught by this guard because they lack a loop +enclosing the call or lack a send_signal/Popen usage. +""" + +from __future__ import annotations + +import ast +from pathlib import Path + +_TESTS_ROOT = Path(__file__).parent.parent + + +def _has_subprocess_signal(func_node: ast.FunctionDef | ast.AsyncFunctionDef) -> bool: + """Return True if the function calls send_signal or Popen.""" + for node in ast.walk(func_node): + if not isinstance(node, ast.Call): + continue + func = node.func + if isinstance(func, ast.Attribute) and func.attr in ("send_signal", "Popen"): + return True + if isinstance(func, ast.Name) and func.id == "Popen": + return True + return False + + +def _has_inline_readline_loop(func_node: ast.FunctionDef | ast.AsyncFunctionDef) -> bool: + """Return True if the function has a readline() call inside a while/for loop.""" + for loop in ast.walk(func_node): + if not isinstance(loop, (ast.While, ast.For)): + continue + for node in ast.walk(loop): + if not isinstance(node, ast.Call): + continue + func = node.func + if isinstance(func, ast.Attribute) and func.attr == "readline": + # Check it's .stderr.readline or .stdout.readline + value = func.value + if isinstance(value, ast.Attribute) and value.attr in ("stderr", "stdout"): + return True + return False + + +def _imports_subprocess_ready(tree: ast.Module) -> bool: + """Return True if the file imports from tests._subprocess_ready.""" + for node in ast.walk(tree): + if isinstance(node, ast.ImportFrom): + if node.module and "_subprocess_ready" in node.module: + return True + if isinstance(node, ast.Import): + for alias in node.names: + if "_subprocess_ready" in alias.name: + return True + return False + + +class TestReadinessHelperContract: + def test_no_inline_readline_loops_in_tests(self): + """No test file may use inline stderr/stdout readline loops as readiness polls.""" + violations: list[str] = [] + for py_file in _TESTS_ROOT.rglob("*.py"): + try: + source = py_file.read_text(encoding="utf-8") + tree = ast.parse(source) + except SyntaxError: + continue + + # Files that import the approved helper are exempt + if _imports_subprocess_ready(tree): + continue + + for node in ast.walk(tree): + if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + continue + if _has_inline_readline_loop(node) and _has_subprocess_signal(node): + violations.append( + f"{py_file.relative_to(_TESTS_ROOT)}:{node.lineno}: " + f"function {node.name!r} has inline stderr/stdout readline loop" + ) + + assert not violations, ( + "Found inline stderr/stdout readline readiness polls in test functions:\n" + + "\n".join(f" {v}" for v in violations) + + "\nUse `from tests._subprocess_ready import wait_for_subprocess_ready` instead." + ) diff --git a/tests/execution/test_recording.py b/tests/execution/test_recording.py new file mode 100644 index 0000000000..1aefd09ecd --- /dev/null +++ b/tests/execution/test_recording.py @@ -0,0 +1,627 @@ +"""Tests for RecordingSubprocessRunner and related helpers.""" + +from __future__ import annotations + +from collections import deque +from dataclasses import dataclass +from pathlib import Path +from unittest.mock import Mock, patch + +import pytest + +from autoskillit.core.types import SubprocessRunner, TerminationReason +from autoskillit.execution.commands import build_full_headless_cmd +from autoskillit.execution.recording import ( + RecordingSubprocessRunner, + ReplayingSubprocessRunner, + ScenarioReplayError, + _extract_model, +) +from tests.conftest import MockSubprocessRunner, _make_result + + +@dataclass +class FakeStepResult: + cassette_exit_code: int + cassette_path: str + cassette_duration_ms: int + + +@dataclass +class FakeSessionResult: + returncode: int + stdout: str + + +class FakeCLI: + def __init__(self, stdout: str = "", returncode: int = 0) -> None: + self._result = FakeSessionResult(returncode, stdout) + + def run(self, args: object = None, env: object = None) -> FakeSessionResult: + return self._result + + +@dataclass +class FakeMeta: + exit_code: int + model: str = "test" + duration_ms: int = 1000 + + +# --- T0: RecordingSubprocessRunner must NOT call atexit.register --- + + +def test_recording_runner_does_not_register_atexit(): + """ + RecordingSubprocessRunner must not register atexit hooks. + Teardown is owned by the FastMCP server lifespan, not the constructor. + Regression guard for issue #745. + """ + mock_recorder = Mock() + with patch("atexit.register") as mock_atexit: + RecordingSubprocessRunner(recorder=mock_recorder, inner=Mock()) + mock_atexit.assert_not_called() + + +# --- T1: Protocol compliance --- + + +def test_recording_runner_satisfies_protocol(): + """RecordingSubprocessRunner is a valid SubprocessRunner.""" + mock_recorder = Mock() + runner = RecordingSubprocessRunner(recorder=mock_recorder) + assert isinstance(runner, SubprocessRunner) + + +# --- T2: Session call routes to record_step --- + + +@pytest.mark.anyio +async def test_session_call_routes_to_record_step(tmp_path): + """pty_mode=True + SCENARIO_STEP_NAME in env kwarg → record_step(), not inner runner.""" + mock_recorder = Mock() + mock_recorder.record_step.return_value = FakeStepResult( + cassette_exit_code=0, + cassette_path=str(tmp_path / "cassette"), + cassette_duration_ms=5000, + ) + inner = MockSubprocessRunner() + runner = RecordingSubprocessRunner(recorder=mock_recorder, inner=inner) + + cmd = ["claude", "--model", "sonnet", "--print", "do stuff"] + env = { + "AUTOSKILLIT_HEADLESS": "1", + "SCENARIO_STEP_NAME": "investigate", + } + + result = await runner(cmd, cwd=Path("/tmp"), timeout=300, env=env, pty_mode=True) + + mock_recorder.record_step.assert_called_once_with( + step_name="investigate", + tool="run_skill", + args=["claude", "--model", "sonnet", "--print", "do stuff"], + model="sonnet", + session_log_dir=None, + ) + assert inner.call_args_list == [] # inner NOT called + assert result.returncode == 0 + assert result.termination == TerminationReason.NATURAL_EXIT + + +# --- T3: Non-session call delegates to inner runner + records summary --- + + +@pytest.mark.anyio +async def test_non_session_call_delegates_and_records(): + """pty_mode=False → inner runner called, then record_non_session_step().""" + mock_recorder = Mock() + inner = MockSubprocessRunner() + inner.set_default(_make_result(returncode=0)) + runner = RecordingSubprocessRunner(recorder=mock_recorder, inner=inner) + + cmd = ["pytest", "tests/"] + env = {"SCENARIO_STEP_NAME": "test-check"} + + result = await runner(cmd, cwd=Path("/tmp"), timeout=60, env=env, pty_mode=False) + + assert len(inner.call_args_list) == 1 # inner WAS called + mock_recorder.record_non_session_step.assert_called_once_with( + step_name="test-check", + tool="run_cmd", + result_summary={"exit_code": 0, "stdout_head": result.stdout[:500]}, + ) + + +# --- T4: No step_name skips recording --- + + +@pytest.mark.anyio +async def test_no_step_name_skips_recording(): + """Calls without SCENARIO_STEP_NAME go through inner runner unrecorded.""" + mock_recorder = Mock() + inner = MockSubprocessRunner() + inner.set_default(_make_result(returncode=0)) + runner = RecordingSubprocessRunner(recorder=mock_recorder, inner=inner) + + cmd = ["claude", "--print", "test"] + env = {"AUTOSKILLIT_HEADLESS": "1"} + + await runner(cmd, cwd=Path("/tmp"), timeout=300, env=env, pty_mode=True) + + assert len(inner.call_args_list) == 1 # inner called (no recording intercept) + mock_recorder.record_step.assert_not_called() + mock_recorder.record_non_session_step.assert_not_called() + + +# --- T6: _extract_model from args --- + + +def test_extract_model(): + args = ["claude", "--print", "hello", "--model", "sonnet"] + assert _extract_model(args) == "sonnet" + + +def test_extract_model_missing(): + args = ["claude", "--print", "hello"] + assert _extract_model(args) == "" + + +# --- T7: SCENARIO_STEP_NAME in cmd from build_full_headless_cmd --- + +_BASE_CMD_ARGS = dict( + cwd="/tmp", + completion_marker="DONE", + model=None, + plugin_dir="/plugins", + output_format_value="stream-json", +) + + +def test_build_full_headless_cmd_injects_scenario_step_name(): + spec = build_full_headless_cmd( + "/investigate foo", + scenario_step_name="investigate", + **_BASE_CMD_ARGS, + ) + assert spec.env["SCENARIO_STEP_NAME"] == "investigate" + assert not any("SCENARIO_STEP_NAME" in tok for tok in spec.cmd) + + +# --- T8: build_full_headless_cmd without scenario_step_name --- + + +def test_build_full_headless_cmd_no_scenario_step_name(): + spec = build_full_headless_cmd( + "/investigate foo", + **_BASE_CMD_ARGS, + ) + assert "SCENARIO_STEP_NAME" not in spec.env + assert not any("SCENARIO_STEP_NAME" in tok for tok in spec.cmd) + + +# --- T9: run_headless_core passes scenario_step_name through --- + + +@pytest.mark.anyio +async def test_run_headless_core_injects_scenario_step_name(tmp_path): + """run_headless_core passes step_name as scenario_step_name and routes it via env kwarg.""" + from autoskillit.config import AutomationConfig + from autoskillit.execution.headless import run_headless_core + from autoskillit.pipeline import DefaultGateState + from autoskillit.server._factory import make_context + + mock_runner = MockSubprocessRunner() + mock_runner.set_default(_make_result()) + ctx = make_context(AutomationConfig(), runner=mock_runner, plugin_dir=str(tmp_path)) + ctx.gate = DefaultGateState(enabled=True) + + await run_headless_core("/investigate foo", str(tmp_path), ctx, step_name="investigate") + + cmd, _cwd, _timeout, kwargs = mock_runner.call_args_list[0] + assert cmd[0] != "env" + env = kwargs.get("env") + assert env is not None + assert env["SCENARIO_STEP_NAME"] == "investigate" + + +# --- T-DERIVE: _derive_step_name_from_skill_command --- + + +def test_derive_step_name_from_namespaced_skill(): + """Extract skill name from /autoskillit:skill-name args form.""" + from autoskillit.execution.headless import _derive_step_name_from_skill_command + + assert ( + _derive_step_name_from_skill_command("/autoskillit:smoke-task arg1 arg2") == "smoke-task" + ) + assert _derive_step_name_from_skill_command("/autoskillit:investigate foo") == "investigate" + assert _derive_step_name_from_skill_command(" /autoskillit:make-plan ") == "make-plan" + + +def test_derive_step_name_from_plain_skill(): + """Extract skill name from /skill-name args form (no namespace prefix).""" + from autoskillit.execution.headless import _derive_step_name_from_skill_command + + assert _derive_step_name_from_skill_command("/investigate foo") == "investigate" + assert _derive_step_name_from_skill_command("/smoke-task") == "smoke-task" + assert _derive_step_name_from_skill_command("plain text no slash") == "plain" + assert _derive_step_name_from_skill_command("") == "" + + +# --- T-AUTO-DERIVE: run_headless_core auto-derives step name --- + + +@pytest.mark.anyio +async def test_run_headless_core_auto_derives_step_name_when_recording(tmp_path): + """When runner is RecordingSubprocessRunner and step_name is empty, + run_headless_core auto-derives step_name from the skill command.""" + from autoskillit.config import AutomationConfig + from autoskillit.execution.headless import run_headless_core + from autoskillit.pipeline import DefaultGateState + from autoskillit.server._factory import make_context + + mock_recorder = Mock() + mock_recorder.record_step.return_value = FakeStepResult( + cassette_exit_code=0, + cassette_path="", + cassette_duration_ms=100, + ) + inner = MockSubprocessRunner() + inner.set_default(_make_result()) + recording_runner = RecordingSubprocessRunner(recorder=mock_recorder, inner=inner) + + ctx = make_context(AutomationConfig(), runner=recording_runner, plugin_dir=str(tmp_path)) + ctx.gate = DefaultGateState(enabled=True) + ctx.config.linux_tracing.log_dir = str(tmp_path / "logs") + + # Call WITHOUT step_name — auto-derivation should kick in + await run_headless_core("/autoskillit:smoke-task", str(tmp_path), ctx) + + # record_step must be called with the derived step name + mock_recorder.record_step.assert_called_once() + call_kwargs = mock_recorder.record_step.call_args.kwargs + assert call_kwargs["step_name"] == "smoke-task", ( + f"Expected derived step_name 'smoke-task', got {call_kwargs['step_name']!r}" + ) + + +# --- T10: make_context wraps runner when RECORD_SCENARIO set --- + + +def test_make_context_wraps_runner_when_record_scenario(monkeypatch, tmp_path): + scenario_dir = tmp_path / "scenario" + scenario_dir.mkdir() + monkeypatch.setenv("RECORD_SCENARIO", "1") + monkeypatch.setenv("RECORD_SCENARIO_DIR", str(scenario_dir)) + monkeypatch.setenv("RECORD_SCENARIO_RECIPE", "smoke-test") + mock_recorder = Mock() + import api_simulator.claude as _api_sim_claude + + monkeypatch.setattr( + _api_sim_claude, "make_scenario_recorder", Mock(return_value=mock_recorder), raising=False + ) + mock_atexit = Mock() + monkeypatch.setattr("atexit.register", mock_atexit) + + from autoskillit.config import AutomationConfig + from autoskillit.server._factory import make_context + + ctx = make_context(AutomationConfig(), plugin_dir=str(tmp_path)) + assert isinstance(ctx.runner, RecordingSubprocessRunner) + mock_atexit.assert_not_called() + + +# --- T11: make_context default runner unchanged without env var --- + + +def test_make_context_default_runner_without_record_scenario(monkeypatch, tmp_path): + monkeypatch.delenv("RECORD_SCENARIO", raising=False) + monkeypatch.delenv("REPLAY_SCENARIO", raising=False) + + from autoskillit.config import AutomationConfig + from autoskillit.execution.process import DefaultSubprocessRunner + from autoskillit.server._factory import make_context + + ctx = make_context(AutomationConfig(), plugin_dir=str(tmp_path)) + assert isinstance(ctx.runner, DefaultSubprocessRunner) + + +# --- T12: Protocol conformance --- + + +def test_sequencing_runner_satisfies_protocol(): + """ReplayingSubprocessRunner is a valid SubprocessRunner.""" + runner = ReplayingSubprocessRunner({}, {}) + assert isinstance(runner, SubprocessRunner) + + +# --- T13: Session step dispatch via FakeClaudeCLI replay --- + + +@pytest.mark.anyio +async def test_sequencing_session_step_dispatch(tmp_path): + """Step in session_map → popleft, cli.run(), return SubprocessResult from meta.""" + cli = FakeCLI(stdout="session output", returncode=0) + meta = FakeMeta(exit_code=0, duration_ms=2000) + session_map: dict[str, deque] = {"implement": deque([(cli, meta)])} + runner = ReplayingSubprocessRunner(session_map, {}) + + cmd = ["claude", "--print", "do stuff"] + env = {"SCENARIO_STEP_NAME": "implement"} + result = await runner(cmd, cwd=tmp_path, timeout=60, env=env) + + assert result.returncode == meta.exit_code + assert result.stdout == "session output" + assert result.termination == TerminationReason.NATURAL_EXIT + assert result.elapsed_seconds == meta.duration_ms / 1000.0 + + +# --- T14: Non-session step dispatch via result stub --- + + +@pytest.mark.anyio +async def test_sequencing_non_session_step_dispatch(tmp_path): + """Step in non_session_results → return SubprocessResult from summary.""" + non_session = { + "test-check": { + "exit_code": 1, + "stdout_head": "FAILED", + "stderr": "error output", + } + } + runner = ReplayingSubprocessRunner({}, non_session) + + cmd = ["task", "test-check"] + env = {"SCENARIO_STEP_NAME": "test-check"} + result = await runner(cmd, cwd=tmp_path, timeout=60, env=env) + + assert result.returncode == 1 + assert result.stdout == "FAILED" + assert result.stderr == "error output" + assert result.termination == TerminationReason.NATURAL_EXIT + + +# --- T15: Missing step name raises ValueError --- + + +@pytest.mark.anyio +async def test_sequencing_missing_step_name_raises(tmp_path): + """No SCENARIO_STEP_NAME in env kwarg → ValueError.""" + runner = ReplayingSubprocessRunner({}, {}) + cmd = ["claude", "--print", "test"] + with pytest.raises(ValueError, match="SCENARIO_STEP_NAME"): + await runner(cmd, cwd=tmp_path, timeout=60) + + +# --- T16: Unknown step raises ScenarioReplayError --- + + +@pytest.mark.anyio +async def test_sequencing_unknown_step_raises(tmp_path): + """Step not in session_map or non_session → ScenarioReplayError with guidance.""" + runner = ReplayingSubprocessRunner( + {"known": deque([(FakeCLI(), FakeMeta(exit_code=0))])}, {"other": {}} + ) + cmd = ["claude", "--print", "test"] + env = {"SCENARIO_STEP_NAME": "unknown-step"} + with pytest.raises(ScenarioReplayError) as exc_info: + await runner(cmd, cwd=tmp_path, timeout=60, env=env) + msg = str(exc_info.value) + assert "unknown-step" in msg + assert "known" in msg + assert "other" in msg + + +# --- T17: call_log records all dispatches --- + + +@pytest.mark.anyio +async def test_sequencing_call_log(tmp_path): + """Each __call__ appends (step_name, cmd) to call_log.""" + cli = FakeCLI(stdout="session", returncode=0) + meta = FakeMeta(exit_code=0, duration_ms=500) + non_session = {"check": {"exit_code": 0, "stdout_head": "ok", "stderr": ""}} + session_map: dict[str, deque] = {"run": deque([(cli, meta)])} + runner = ReplayingSubprocessRunner(session_map, non_session) + + cmd1 = ["claude", "--print", "go"] + env1 = {"SCENARIO_STEP_NAME": "run"} + cmd2 = ["task", "test"] + env2 = {"SCENARIO_STEP_NAME": "check"} + + await runner(cmd1, cwd=tmp_path, timeout=60, env=env1) + await runner(cmd2, cwd=tmp_path, timeout=60, env=env2) + + assert len(runner.call_log) == 2 + assert runner.call_log[0] == ("run", cmd1) + assert runner.call_log[1] == ("check", cmd2) + + +# --- T18: Multiple calls to same step advance the deque --- + + +@pytest.mark.anyio +async def test_sequencing_multiple_calls_advance_queue(tmp_path): + """Successive calls to same step popleft through the deque.""" + cli1 = FakeCLI(stdout="first", returncode=0) + cli2 = FakeCLI(stdout="second", returncode=0) + meta1 = FakeMeta(exit_code=0, duration_ms=100) + meta2 = FakeMeta(exit_code=0, duration_ms=200) + session_map: dict[str, deque] = {"implement": deque([(cli1, meta1), (cli2, meta2)])} + runner = ReplayingSubprocessRunner(session_map, {}) + + cmd = ["claude", "--print", "go"] + env = {"SCENARIO_STEP_NAME": "implement"} + result1 = await runner(cmd, cwd=tmp_path, timeout=60, env=env) + result2 = await runner(cmd, cwd=tmp_path, timeout=60, env=env) + + assert result1.stdout == "first" + assert result2.stdout == "second" + + +# --- T19: Exhausted session deque falls through to non-session --- + + +@pytest.mark.anyio +async def test_sequencing_exhausted_session_falls_to_non_session(tmp_path): + """When session deque is empty but non_session has entry, use non_session.""" + non_session = {"test": {"exit_code": 2, "stdout_head": "non-session result", "stderr": ""}} + session_map: dict[str, deque] = {"test": deque()} + runner = ReplayingSubprocessRunner(session_map, non_session) + + cmd = ["task", "test"] + env = {"SCENARIO_STEP_NAME": "test"} + result = await runner(cmd, cwd=tmp_path, timeout=60, env=env) + + assert result.returncode == 2 + assert result.stdout == "non-session result" + + +# --- T20: make_context wires ReplayingSubprocessRunner when REPLAY_SCENARIO set --- + + +def test_make_context_wires_sequencing_runner_when_replay_scenario(monkeypatch, tmp_path): + """REPLAY_SCENARIO=1 + valid dir → ctx.runner is ReplayingSubprocessRunner.""" + replay_dir = tmp_path / "replay" + replay_dir.mkdir() + monkeypatch.setenv("REPLAY_SCENARIO", "1") + monkeypatch.setenv("REPLAY_SCENARIO_DIR", str(replay_dir)) + monkeypatch.delenv("RECORD_SCENARIO", raising=False) + + mock_scenario = Mock() + mock_scenario.step_sequence = [] + mock_player = Mock() + mock_player.scenario.return_value = mock_scenario + mock_player.build_session_map.return_value = {} + mock_make_player = Mock(return_value=mock_player) + + import api_simulator.claude as _api_sim_claude + + monkeypatch.setattr(_api_sim_claude, "make_scenario_player", mock_make_player, raising=False) + + from autoskillit.config import AutomationConfig + from autoskillit.server._factory import make_context + + ctx = make_context(AutomationConfig(), plugin_dir=str(tmp_path)) + assert isinstance(ctx.runner, ReplayingSubprocessRunner) + mock_make_player.assert_called_once() + call_kwargs = mock_make_player.call_args.kwargs + assert call_kwargs.get("scenario_dir") == str(replay_dir) + + +# --- T21: REPLAY_SCENARIO takes precedence over RECORD_SCENARIO --- + + +def test_replay_takes_precedence_over_record(monkeypatch, tmp_path): + """When both REPLAY and RECORD env vars set, REPLAY wins.""" + replay_dir = tmp_path / "replay" + replay_dir.mkdir() + monkeypatch.setenv("REPLAY_SCENARIO", "1") + monkeypatch.setenv("REPLAY_SCENARIO_DIR", str(replay_dir)) + monkeypatch.setenv("RECORD_SCENARIO", "1") + monkeypatch.setenv("RECORD_SCENARIO_DIR", str(replay_dir)) + + mock_scenario = Mock() + mock_scenario.step_sequence = [] + mock_player = Mock() + mock_player.scenario.return_value = mock_scenario + mock_player.build_session_map.return_value = {} + mock_recorder = Mock() + mock_make_recorder = Mock(return_value=mock_recorder) + + import api_simulator.claude as _api_sim_claude + + monkeypatch.setattr( + _api_sim_claude, "make_scenario_player", Mock(return_value=mock_player), raising=False + ) + monkeypatch.setattr( + _api_sim_claude, "make_scenario_recorder", mock_make_recorder, raising=False + ) + mock_atexit = Mock() + monkeypatch.setattr("atexit.register", mock_atexit) + + from autoskillit.config import AutomationConfig + from autoskillit.server._factory import make_context + + ctx = make_context(AutomationConfig(), plugin_dir=str(tmp_path)) + assert isinstance(ctx.runner, ReplayingSubprocessRunner) + mock_make_recorder.assert_not_called() # REPLAY takes precedence over RECORD + mock_atexit.assert_not_called() + + +# --- T22: Cross-scenario session override (integration, requires api-simulator) --- + + +@pytest.mark.anyio +async def test_cross_scenario_override(tmp_path): + """Cross-scenario session injection → ReplayingSubprocessRunner replays override.""" + # Simulate two scenarios providing the same step; override with a controlled FakeCLI + # to verify that ReplayingSubprocessRunner uses whatever session_map it is given, + # regardless of which scenario recorded a given step name. + override_cli = FakeCLI(stdout="from-overridden-scenario2", returncode=0) + override_meta = FakeMeta(exit_code=0, duration_ms=500) + session_map: dict[str, deque] = {"implement": deque([(override_cli, override_meta)])} + + runner = ReplayingSubprocessRunner(session_map, {}) + cmd = ["claude", "--print", "go"] + env = {"SCENARIO_STEP_NAME": "implement"} + result = await runner(cmd, cwd=tmp_path, timeout=60, env=env) + + assert result.stdout == "from-overridden-scenario2" + assert result.returncode == 0 + assert result.elapsed_seconds == pytest.approx(0.5) + + +# --- T-REC-PUBLIC: recorder is a public attribute --- + + +def test_recording_runner_recorder_is_public(): + """RecordingSubprocessRunner exposes recorder as a public attribute.""" + mock_recorder = Mock() + runner = RecordingSubprocessRunner(recorder=mock_recorder) + assert runner.recorder is mock_recorder + + +# --- T-REPLAY-PLAYER: player attribute stored --- + + +def test_replaying_runner_stores_player_attribute(): + """ReplayingSubprocessRunner stores player when provided.""" + mock_player = Mock() + runner = ReplayingSubprocessRunner({}, {}, player=mock_player) + assert runner.player is mock_player + + +# --- T-REPLAY-PLAYER-NONE: player defaults to None --- + + +def test_replaying_runner_player_defaults_to_none(): + """ReplayingSubprocessRunner.player is None when not provided.""" + runner = ReplayingSubprocessRunner({}, {}) + assert runner.player is None + + +# --- T-BUILD-REPLAY-PLAYER: build_replay_runner stores player on runner --- + + +def test_build_replay_runner_stores_player_on_runner(tmp_path, monkeypatch): + """build_replay_runner() passes the ScenarioPlayer to ReplayingSubprocessRunner.player.""" + from autoskillit.execution.recording import build_replay_runner + + mock_scenario = Mock() + mock_scenario.step_sequence = [] + mock_player = Mock() + mock_player.scenario.return_value = mock_scenario + mock_player.build_session_map.return_value = {} + + import api_simulator.claude as _api_sim_claude + + monkeypatch.setattr( + _api_sim_claude, "make_scenario_player", Mock(return_value=mock_player), raising=False + ) + mock_atexit = Mock() + monkeypatch.setattr("atexit.register", mock_atexit) + + result = build_replay_runner(str(tmp_path)) + assert result.player is mock_player + mock_atexit.assert_not_called() diff --git a/tests/execution/test_recording_sigterm.py b/tests/execution/test_recording_sigterm.py new file mode 100644 index 0000000000..0aaa21276c --- /dev/null +++ b/tests/execution/test_recording_sigterm.py @@ -0,0 +1,82 @@ +"""Integration test: autoskillit serve subprocess receives SIGTERM and writes scenario.json. + +Regression guard for issue #745. Synchronizes with the subprocess via the +filesystem sentinel written by the lifespan (``readiness_sentinel_path``). +File existence is atomic — no string-parse race, no wall-clock settle-sleep. +""" + +from __future__ import annotations + +import json +import os +import signal +import subprocess +import sys + +import pytest + +from autoskillit.core.readiness import readiness_sentinel_path +from tests._subprocess_ready import wait_for_subprocess_ready + + +@pytest.mark.integration +def test_sigterm_writes_scenario_json(tmp_path): + """Server writes scenario.json when terminated by SIGTERM. + + Invariant: must be deterministically passing. A single miss is a + structural failure — do not bump deadlines as a fix. + """ + output_dir = tmp_path / "scenario" + output_dir.mkdir() + + env = { + **os.environ, + "RECORD_SCENARIO": "1", + "RECORD_SCENARIO_DIR": str(output_dir), + "RECORD_SCENARIO_RECIPE": "test-recipe", + } + # Use sys.executable -m to ensure we run the worktree-installed version, + # not a system-wide `autoskillit` binary that may lack the lifespan fix. + proc = subprocess.Popen( + [sys.executable, "-m", "autoskillit"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=env, + ) + + # Wait for the filesystem sentinel — written inside the lifespan's try: + # block AFTER the anyio signal receiver is armed. Observing the sentinel + # guarantees SIGTERM will be caught by the event-loop-routed handler. + sentinel_path = readiness_sentinel_path(proc.pid) + wait_for_subprocess_ready(proc, sentinel_path, deadline_s=10.0) + + # SIGTERM is the exact signal Claude Code sends on /exit. Close stdin so + # the stdio transport detects EOF and the event loop can fully unwind. + proc.stdin.close() + proc.stdin = None # prevent communicate() from flushing the closed pipe + proc.send_signal(signal.SIGTERM) + try: + stdout_bytes, stderr_bytes = proc.communicate(timeout=10) + except subprocess.TimeoutExpired: + proc.kill() + stdout_bytes, stderr_bytes = proc.communicate() + + stdout = stdout_bytes.decode(errors="replace") + stderr = stderr_bytes.decode(errors="replace") + + # Clean shutdown: event-loop-routed SIGTERM → scope.cancel() → finalize() + assert proc.returncode == 0, ( + f"Expected clean exit (rc=0), got rc={proc.returncode}\n" + f"stdout: {stdout!r}\n" + f"stderr: {stderr!r}" + ) + + scenario_json = output_dir / "scenario.json" + assert scenario_json.exists(), ( + "scenario.json not written after SIGTERM — finalize() likely bypassed (issue #745)\n" + f"stdout: {stdout!r}\n" + f"stderr: {stderr!r}" + ) + data = json.loads(scenario_json.read_text()) + assert data.get("recipe") == "test-recipe" diff --git a/tests/execution/test_recording_sigterm_early_term.py b/tests/execution/test_recording_sigterm_early_term.py new file mode 100644 index 0000000000..643fbeeaa0 --- /dev/null +++ b/tests/execution/test_recording_sigterm_early_term.py @@ -0,0 +1,86 @@ +"""Edge case: SIGTERM sent to subprocess before readiness sentinel appears. + +Regression guard for the boot-window race: if SIGTERM is delivered during +server startup (before the lifespan has written the sentinel), the process +must NOT hang or dump a traceback — it must exit cleanly within the deadline. + +Acceptable outcomes: + (a) Process exits cleanly AND scenario.json is NOT created (SIGTERM arrived + before the recording session was fully started). + (b) scenario.json IS created (SIGTERM arrived exactly at the yield point — + finalize() had time to run). + +The invariant is: no hang, no zombie process, no unhandled exception traceback +in stderr that escapes anyio's cancel scope. +""" + +from __future__ import annotations + +import json +import os +import signal +import subprocess +import sys + +import pytest + + +@pytest.mark.integration +def test_sigterm_during_startup_no_hang(tmp_path): + """SIGTERM before readiness sentinel: no hang, no zombie process.""" + output_dir = tmp_path / "scenario" + output_dir.mkdir() + + env = { + **os.environ, + "RECORD_SCENARIO": "1", + "RECORD_SCENARIO_DIR": str(output_dir), + "RECORD_SCENARIO_RECIPE": "test-recipe", + } + proc = subprocess.Popen( + [sys.executable, "-m", "autoskillit"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=env, + ) + + # Send SIGTERM immediately — before ANY sentinel check. + # This exercises the boot-window path. + proc.stdin.close() + proc.stdin = None + proc.send_signal(signal.SIGTERM) + + try: + stdout_bytes, stderr_bytes = proc.communicate(timeout=5) + except subprocess.TimeoutExpired: + proc.kill() + proc.communicate() + pytest.fail( + "Subprocess hung after early SIGTERM — " + "anyio signal receiver was not armed before mcp.run_async() started, " + "or SIGTERM was not routed through the event loop." + ) + + stderr = stderr_bytes.decode(errors="replace") + + # Must not have a raw KeyboardInterrupt traceback escaping anyio's cancel scope + assert "KeyboardInterrupt" not in stderr or proc.returncode == 0, ( + f"KeyboardInterrupt traceback in stderr (rc={proc.returncode}):\n{stderr!r}" + ) + + # Either: + # (a) No scenario.json (SIGTERM arrived before lifespan entered) — acceptable + # (b) scenario.json present and valid (SIGTERM arrived at yield) — also acceptable + scenario_json = output_dir / "scenario.json" + if scenario_json.exists(): + try: + content = json.loads(scenario_json.read_text()) + except json.JSONDecodeError: + pass # Pre-init / partial write is acceptable for early SIGTERM + else: + # If it parsed, it must be a dict (even if empty) + assert isinstance(content, dict), f"Unexpected scenario.json content: {content!r}" + + # Process must have exited (not a zombie) + assert proc.poll() is not None, "Process is still running — zombie detected" diff --git a/tests/execution/test_remote_resolver.py b/tests/execution/test_remote_resolver.py index 67f98ab9d2..49ff97782f 100644 --- a/tests/execution/test_remote_resolver.py +++ b/tests/execution/test_remote_resolver.py @@ -124,3 +124,19 @@ async def test_resolve_returns_none_when_no_remotes(tmp_path: Path) -> None: repo = _make_repo_with_remotes(tmp_path) result = await resolve_remote_repo(str(repo)) assert result is None + + +def test_resolve_remote_has_timeout_in_source() -> None: + """Static check: resolve_remote_repo uses wait_for with a timeout on subprocess calls.""" + import ast + import inspect + + source = inspect.getsource(resolve_remote_repo) + tree = ast.parse(source) + has_wait_for = any( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "wait_for" + for node in ast.walk(tree) + ) + assert has_wait_for, "resolve_remote_repo should use asyncio.wait_for for timeout protection" diff --git a/tests/execution/test_session.py b/tests/execution/test_session.py index 591a79d21b..b15a60866f 100644 --- a/tests/execution/test_session.py +++ b/tests/execution/test_session.py @@ -1067,6 +1067,7 @@ def test_to_json_produces_all_required_keys(self): "cli_subtype", "is_error", "exit_code", + "kill_reason", "needs_retry", "retry_reason", "stderr", diff --git a/tests/execution/test_session_adjudication.py b/tests/execution/test_session_adjudication.py index 2a5d48b5f4..e43f61f02a 100644 --- a/tests/execution/test_session_adjudication.py +++ b/tests/execution/test_session_adjudication.py @@ -187,13 +187,18 @@ def test_natural_exit_channel_a_valid_result_true(self): class TestComputeSuccessNaturalExitNonZero: - """NATURAL_EXIT with non-zero returncode is always a failure.""" + """NATURAL_EXIT with non-zero returncode. - def test_natural_exit_nonzero_returncode_with_success_session_returns_false(self): - """NATURAL_EXIT + non-zero returncode is unrecoverable regardless of session envelope. + Default: failure (no bypass). Exception: post-completion kill bypass fires when + the session envelope is SUCCESS, result is non-empty, and the completion marker + is present — the signal is a teardown artifact, not a genuine CLI error. + """ + + def test_natural_exit_nonzero_returncode_without_marker_returns_false(self): + """NATURAL_EXIT + non-zero returncode + no completion marker → failure. - Documents that PTY-masking quirks on natural exit cannot be distinguished from - genuine CLI errors, so we fail conservatively. + Without a completion marker, we cannot distinguish a post-completion kill + from a genuine crash. Fail conservatively (PTY masking cannot be ruled out). """ session = ClaudeSessionResult( subtype="success", is_error=False, result="done", session_id="s1" @@ -221,6 +226,90 @@ def test_completed_and_natural_exit_same_outcome_when_returncode_zero(self): assert result_natural is True +class TestComputeSuccessNaturalExitPostCompletionKill: + """NATURAL_EXIT with non-zero returncode is success when completion marker is present.""" + + def test_natural_exit_sigkill_with_marker_is_success(self): + """NATURAL_EXIT + returncode -9 + SUCCESS subtype + completion marker → success. + + Documents the post-completion kill bypass: a process killed by an external + watchdog AFTER completing its work produces -9 on NATURAL_EXIT. The completion + marker in the result confirms the session finished before the kill. + """ + marker = "%%ORDER_UP%%" + session = ClaudeSessionResult( + subtype="success", + is_error=False, + result=f"fixes_applied = 2\n{marker}", + session_id="s1", + ) + assert ( + _compute_success( + session, + returncode=-9, + termination=TerminationReason.NATURAL_EXIT, + completion_marker=marker, + ) + is True + ) + + def test_natural_exit_sigkill_without_marker_remains_failure(self): + """No bypass when no completion_marker is configured — conservative path unchanged.""" + session = ClaudeSessionResult( + subtype="success", + is_error=False, + result="fixes_applied = 2", + session_id="s1", + ) + assert ( + _compute_success( + session, + returncode=-9, + termination=TerminationReason.NATURAL_EXIT, + completion_marker="", # no marker configured + ) + is False + ) + + def test_natural_exit_sigkill_marker_absent_from_result_remains_failure(self): + """Bypass does not fire when marker is configured but missing from result.""" + marker = "%%ORDER_UP%%" + session = ClaudeSessionResult( + subtype="success", + is_error=False, + result="partial output without marker", + session_id="s1", + ) + assert ( + _compute_success( + session, + returncode=-9, + termination=TerminationReason.NATURAL_EXIT, + completion_marker=marker, + ) + is False + ) + + def test_natural_exit_nonzero_non_success_subtype_remains_failure(self): + """Bypass does not fire for non-success subtypes even with marker present.""" + marker = "%%ORDER_UP%%" + session = ClaudeSessionResult( + subtype="unparseable", + is_error=False, + result=f"some output {marker}", + session_id="s1", + ) + assert ( + _compute_success( + session, + returncode=-9, + termination=TerminationReason.NATURAL_EXIT, + completion_marker=marker, + ) + is False + ) + + class TestComputeRetry: """_compute_retry cross-validates all signals for retry eligibility.""" @@ -1648,3 +1737,81 @@ def test_parse_session_result_non_write_tools_no_file_path(make_ndjson): session = parse_session_result(ndjson) assert session.tool_uses == [{"name": "Bash", "id": "tu3"}] assert "file_path" not in session.tool_uses[0] + + +class TestMinus9ReturncodeCoverage: + """Specification tests: returncode=-9 under COMPLETED is a valid success (1c). + + Before the fix, channel_won unconditionally sent SIGKILL (-9) to every + COMPLETED session. These tests document that the adjudicator correctly + classifies -9 under COMPLETED as successful — the bug was in the kill logic, + not the adjudicator. + """ + + def test_compute_success_completed_returncode_minus_9_is_success(self) -> None: + """COMPLETED + CHANNEL_A + returncode=-9 + content → success=True.""" + session = _make_success_session("ok") + result = _compute_success( + session, + returncode=-9, + termination=TerminationReason.COMPLETED, + channel_confirmation=ChannelConfirmation.CHANNEL_A, + ) + assert result is True + + def test_compute_success_completed_minus_9_channel_b_is_success(self) -> None: + """COMPLETED + CHANNEL_B + returncode=-9 → success=True (bypass).""" + session = ClaudeSessionResult( + subtype="success", + result="", + is_error=False, + session_id="b9", + ) + result = _compute_success( + session, + returncode=-9, + termination=TerminationReason.COMPLETED, + channel_confirmation=ChannelConfirmation.CHANNEL_B, + ) + assert result is True + + @pytest.mark.parametrize("returncode", [0, -15, -9]) + @pytest.mark.parametrize("termination", list(TerminationReason)) + def test_compute_retry_handles_minus_9_for_all_termination_reasons( + self, + termination: TerminationReason, + returncode: int, + ) -> None: + """_compute_retry must not raise for any (TerminationReason, returncode) pair.""" + session = ClaudeSessionResult( + subtype="success", + result="done. %%ORDER_UP%%", + is_error=False, + session_id="rc9", + errors=[], + ) + result = _compute_retry(session, returncode=returncode, termination=termination) + assert isinstance(result, tuple) and len(result) == 2 + + @pytest.mark.parametrize("returncode", [0, -15, -9]) + @pytest.mark.parametrize("termination", list(TerminationReason)) + def test_compute_success_handles_minus_9_for_all_termination_reasons( + self, + termination: TerminationReason, + returncode: int, + ) -> None: + """_compute_success must not raise for any (TerminationReason, returncode) pair.""" + session = ClaudeSessionResult( + subtype="success", + result="done. %%ORDER_UP%%", + is_error=False, + session_id="rc9", + errors=[], + ) + result = _compute_success( + session, + returncode=returncode, + termination=termination, + completion_marker="%%ORDER_UP%%", + ) + assert isinstance(result, bool) diff --git a/tests/execution/test_session_log.py b/tests/execution/test_session_log.py index e1b047a3a6..88f53a15ee 100644 --- a/tests/execution/test_session_log.py +++ b/tests/execution/test_session_log.py @@ -3,11 +3,15 @@ from __future__ import annotations import json +import os +import sys +import time from datetime import UTC, datetime from pathlib import Path import pytest +from autoskillit.execution.linux_tracing import read_boot_id, read_starttime_ticks from autoskillit.execution.session_log import ( flush_session_log, read_telemetry_clear_marker, @@ -387,15 +391,36 @@ def test_recover_crashed_sessions_skips_recent_files(tmp_path): def _write_old_trace(tmpfs: Path, filename: str, content: str) -> Path: - """Write a trace file and backdate its mtime to 60 seconds ago.""" - import time + """Write a trace file (backdated 60s) and its enrollment sidecar. + The enrollment sidecar uses the current boot_id so Gate 2 passes. + The PID embedded in the filename is expected to be dead (so Gate 3 passes). + """ trace = tmpfs / filename trace.write_text(content) old_mtime = time.time() - 60 - import os - os.utime(trace, (old_mtime, old_mtime)) + + # Write companion enrollment sidecar so Gate 1 passes + try: + pid = int(Path(filename).stem.split("_")[-1]) + except (ValueError, IndexError): + pid = 0 + enrollment = tmpfs / f"autoskillit_enrollment_{pid}.json" + enrollment.write_text( + json.dumps( + { + "schema_version": 1, + "pid": pid, + "boot_id": read_boot_id() or "", + "starttime_ticks": None, + "session_id": "", + "enrolled_at": "2026-01-01T00:00:00+00:00", + "kitchen_id": "", + "order_id": "", + } + ) + ) return trace @@ -567,6 +592,122 @@ def test_flush_writes_step_timing_json(tmp_path): assert (session_dir / "step_timing.json").is_file() +# --------------------------------------------------------------------------- +# Test 1.10 — proc_trace.jsonl rows self-identify with comm field +# --------------------------------------------------------------------------- + + +def test_proc_trace_jsonl_rows_include_comm(tmp_path): + """proc_trace.jsonl rows must include a 'comm' field for post-hoc drift detection. + + Test 1.10: after flush_session_log, every row in proc_trace.jsonl must carry + the process identity (comm). This makes any drift visible to anyone triaging + a session log — any row lacking comm is a drift indicator. + """ + snaps = [ + {**_snap(), "comm": "claude"}, + {**_snap(), "comm": "claude"}, + {**_snap(), "comm": "claude"}, + ] + _flush(tmp_path, proc_snapshots=snaps, session_id="comm-test-001") + + trace_path = tmp_path / "sessions" / "comm-test-001" / "proc_trace.jsonl" + assert trace_path.exists() + rows = [json.loads(line) for line in trace_path.read_text().splitlines()] + for i, row in enumerate(rows): + assert "comm" in row, ( + f"Row {i} in proc_trace.jsonl is missing 'comm' field. " + "Every snapshot row must self-identify the traced process." + ) + assert row["comm"] == "claude", f"Expected comm='claude' in row {i}, got {row['comm']!r}" + + +# --------------------------------------------------------------------------- +# Test 1.11 — recovery path reads comm and excludes alien files +# --------------------------------------------------------------------------- + + +def _write_old_trace_with_comm(tmpfs: Path, pid: int, comm: str, *, n_snaps: int = 2) -> Path: + """Write a backdated trace file with snapshots that have a specific comm.""" + filename = f"autoskillit_trace_{pid}.jsonl" + trace = tmpfs / filename + snaps = [] + for _ in range(n_snaps): + snap_dict = {**_snap(), "comm": comm} + snaps.append(json.dumps(snap_dict)) + trace.write_text("\n".join(snaps) + "\n") + + # Backdate so Gate 1 (age > 30s) passes + old_mtime = time.time() - 60 + os.utime(trace, (old_mtime, old_mtime)) + + # Write enrollment sidecar so Gate 1 (sidecar present) passes. + # Use schema_version=2 with comm='claude' — autoskillit always enrolls its own + # binary as 'claude'. Snapshots whose first comm != enrollment.comm are alien. + enrollment = tmpfs / f"autoskillit_enrollment_{pid}.json" + enrollment.write_text( + json.dumps( + { + "schema_version": 2, + "pid": pid, + "boot_id": read_boot_id() or "", + "starttime_ticks": None, + "session_id": "", + "enrolled_at": "2026-01-01T00:00:00+00:00", + "kitchen_id": "", + "order_id": "", + "comm": "claude", + } + ) + ) + return trace + + +def test_recover_crashed_sessions_excludes_non_claude_trace_files(tmp_path): + """recover_crashed_sessions tags alien trace files (non-claude comm) and excludes them. + + Test 1.11: place two trace files — one with comm='claude' and one with + comm='sleep'. The 'sleep' file is an alien artifact (test pollution or a + non-autoskillit process). After the fix, recovery recognises it via comm + and either skips it or marks it with alien=true in the recovered record. + """ + tmpfs = tmp_path / "shm" + tmpfs.mkdir() + log_dir = tmp_path / "logs" + + # One legitimate claude trace + _write_old_trace_with_comm(tmpfs, pid=20001, comm="claude") + # One alien trace (e.g., leftover from a test or wrong process) + _write_old_trace_with_comm(tmpfs, pid=20002, comm="sleep") + + recover_crashed_sessions(tmpfs_path=str(tmpfs), log_dir=str(log_dir)) + + sessions_dir = log_dir / "sessions" + recovered = list(sessions_dir.iterdir()) if sessions_dir.exists() else [] + session_summaries = [] + for s in recovered: + summary_file = s / "summary.json" + if summary_file.exists(): + session_summaries.append(json.loads(summary_file.read_text())) + + claude_sessions = [s for s in session_summaries if "20001" in s.get("session_id", "")] + + # The claude trace must be recovered (not excluded) + assert claude_sessions, "The claude trace file must be recovered by recover_crashed_sessions" + + # The alien trace should not produce a normal session — it should be excluded + # or marked as alien so it doesn't pollute capacity planning / anomaly analytics + alien_included_normally = [ + s + for s in session_summaries + if "20002" in s.get("session_id", "") and not s.get("alien") and not s.get("pre_fix_data") + ] + assert not alien_included_normally, ( + "Alien trace (comm='sleep') must not be recovered as a normal session. " + "It should be skipped or marked alien=true to prevent #771-style mis-attribution." + ) + + def test_flush_writes_audit_log_json(tmp_path): """audit_log.json written to session dir when step_name and audit_record dict provided.""" record = { @@ -811,3 +952,105 @@ def test_flush_session_log_order_id_defaults_to_empty(tmp_path): entry = json.loads((tmp_path / "sessions.jsonl").read_text().strip()) assert "order_id" in entry assert entry["order_id"] == "" + + +@pytest.mark.skipif(sys.platform != "linux", reason="Linux-only: uses /proc and boot_id") +def test_recover_crashed_sessions_skips_live_pid(tmp_path): + """A trace file whose enrolled PID is still alive must not be recovered.""" + tmpfs = tmp_path / "shm" + tmpfs.mkdir() + pid = os.getpid() + trace = tmpfs / f"autoskillit_trace_{pid}.jsonl" + enrollment = tmpfs / f"autoskillit_enrollment_{pid}.json" + trace.write_text("") + enrollment.write_text( + json.dumps( + { + "schema_version": 1, + "pid": pid, + "boot_id": read_boot_id() or "", + "starttime_ticks": read_starttime_ticks(pid), + "session_id": "", + "enrolled_at": datetime.now(UTC).isoformat(), + "kitchen_id": "", + "order_id": "", + } + ) + ) + os.utime(trace, (time.time() - 60,) * 2) + + count = recover_crashed_sessions(tmpfs_path=str(tmpfs), log_dir=str(tmp_path)) + + assert count == 0 + assert trace.exists(), "Trace file for alive PID must not be deleted" + assert enrollment.exists(), "Enrollment sidecar for alive PID must not be deleted" + + +def test_recover_crashed_sessions_skips_file_without_enrollment(tmp_path): + """A trace file with no enrollment sidecar must be skipped — it is not + an autoskillit-owned trace (e.g. a test artifact or alien file).""" + tmpfs = tmp_path / "shm" + tmpfs.mkdir() + trace = tmpfs / "autoskillit_trace_99997.jsonl" + trace.write_text("") + os.utime(trace, (time.time() - 60,) * 2) + + count = recover_crashed_sessions(tmpfs_path=str(tmpfs), log_dir=str(tmp_path)) + + assert count == 0 + assert trace.exists(), "Alien trace file must not be deleted" + + +def test_recover_crashed_sessions_skips_wrong_boot_id(tmp_path, monkeypatch): + """An enrollment sidecar with a different boot_id must be rejected.""" + monkeypatch.setattr( + "autoskillit.execution.session_log.read_boot_id", + lambda: "current-boot-id", + ) + tmpfs = tmp_path / "shm" + tmpfs.mkdir() + pid = 99996 + trace = tmpfs / f"autoskillit_trace_{pid}.jsonl" + enrollment = tmpfs / f"autoskillit_enrollment_{pid}.json" + trace.write_text("") + enrollment.write_text( + json.dumps( + { + "schema_version": 1, + "pid": pid, + "boot_id": "stale-boot-id", + "starttime_ticks": 1234, + "session_id": "", + "enrolled_at": "2026-01-01T00:00:00+00:00", + "kitchen_id": "", + "order_id": "", + } + ) + ) + os.utime(trace, (time.time() - 60,) * 2) + + count = recover_crashed_sessions(tmpfs_path=str(tmpfs), log_dir=str(tmp_path)) + + assert count == 0 + + +def test_flush_writes_crash_exception_file(tmp_path): + """When exception_text is provided, flush_session_log writes crash_exception.txt.""" + flush_session_log( + log_dir=str(tmp_path), + cwd="/tmp", + session_id="test-session", + pid=1234, + skill_command="/test", + success=False, + subtype="crashed", + exit_code=-1, + start_ts=datetime.now(UTC).isoformat(), + proc_snapshots=None, + termination_reason="CRASHED", + exception_text="RuntimeError: boom\n at headless.py:1023", + ) + session_dir = tmp_path / "sessions" / "test-session" + crash_file = session_dir / "crash_exception.txt" + assert crash_file.exists() + assert "RuntimeError: boom" in crash_file.read_text() diff --git a/tests/execution/test_session_log_integration.py b/tests/execution/test_session_log_integration.py index 6b2d432dc9..c9311aec2c 100644 --- a/tests/execution/test_session_log_integration.py +++ b/tests/execution/test_session_log_integration.py @@ -11,6 +11,8 @@ import anyio import pytest +from tests.execution.conftest import _ALLOCATE_60MB_SCRIPT + pytestmark = pytest.mark.skipif(sys.platform != "linux", reason="Linux only") @@ -18,14 +20,14 @@ async def test_full_tracing_pipeline_writes_distinct_timestamps(tmp_path): """End-to-end: snapshot accumulation + flush produces unique ts per record.""" from autoskillit.config import LinuxTracingConfig - from autoskillit.execution.linux_tracing import start_linux_tracing + from autoskillit.execution.linux_tracing import start_linux_tracing, trace_target_from_pid from autoskillit.execution.session_log import flush_session_log - config = LinuxTracingConfig(proc_interval=0.05) + config = LinuxTracingConfig(proc_interval=0.05, tmpfs_path=str(tmp_path)) start_ts = datetime.now(UTC).isoformat() start_mono = time.monotonic() async with anyio.create_task_group() as tg: - handle = start_linux_tracing(os.getpid(), config, tg) + handle = start_linux_tracing(trace_target_from_pid(os.getpid()), config, tg) await anyio.sleep(0.3) snaps = handle.stop() tg.cancel_scope.cancel() @@ -70,3 +72,128 @@ async def test_full_tracing_pipeline_writes_distinct_timestamps(tmp_path): "duration_seconds in summary.json must reflect monotonic elapsed, " "not wall-clock subtraction" ) + + +# --------------------------------------------------------------------------- +# REQ-DIAG-001 — new anomaly kinds surface in anomalies.jsonl +# --------------------------------------------------------------------------- + +_BASE_SNAP: dict[str, object] = { + "captured_at": "2026-01-01T00:00:00+00:00", + "vm_rss_kb": 100000, + "threads": 4, + "fd_count": 10, + "fd_soft_limit": 1024, + "ctx_switches_voluntary": 500, + "ctx_switches_involuntary": 20, + "sig_pnd": "0000000000000000", + "sig_blk": "0000000000000000", + "sig_cgt": "0000000000000000", + "oom_score": 50, + "cpu_percent": 0.0, +} + + +def _flush_with_snaps(tmp_path, session_id: str, snaps: list[dict]) -> None: + from autoskillit.execution.session_log import flush_session_log + + flush_session_log( + log_dir=str(tmp_path), + cwd="/tmp", + session_id=session_id, + pid=12345, + skill_command="/test", + success=True, + subtype="completed", + exit_code=0, + start_ts="2026-01-01T00:00:00+00:00", + proc_snapshots=snaps, + ) + + +def test_flush_session_log_surfaces_d_state_sustained(tmp_path): + """flush_session_log writes d_state_sustained to anomalies.jsonl (REQ-DIAG-001).""" + snaps = [ + {**_BASE_SNAP, "state": "disk-sleep", "wchan": "ext4_file_write_iter"}, + {**_BASE_SNAP, "state": "disk-sleep", "wchan": "ext4_file_write_iter"}, + ] + _flush_with_snaps(tmp_path, "diag-d-state-001", snaps) + + anomalies_path = tmp_path / "sessions" / "diag-d-state-001" / "anomalies.jsonl" + assert anomalies_path.exists(), "anomalies.jsonl must be created when anomalies are detected" + kinds = [json.loads(line)["kind"] for line in anomalies_path.read_text().splitlines()] + assert "d_state_sustained" in kinds + + +def test_flush_session_log_surfaces_high_cpu_sustained(tmp_path): + """flush_session_log writes high_cpu_sustained to anomalies.jsonl (REQ-DIAG-001).""" + snaps = [ + {**_BASE_SNAP, "state": "sleeping", "wchan": "", "cpu_percent": 95.0}, + {**_BASE_SNAP, "state": "sleeping", "wchan": "", "cpu_percent": 95.0}, + ] + _flush_with_snaps(tmp_path, "diag-high-cpu-001", snaps) + + anomalies_path = tmp_path / "sessions" / "diag-high-cpu-001" / "anomalies.jsonl" + assert anomalies_path.exists(), "anomalies.jsonl must be created when anomalies are detected" + kinds = [json.loads(line)["kind"] for line in anomalies_path.read_text().splitlines()] + assert "high_cpu_sustained" in kinds + + +# --------------------------------------------------------------------------- +# Test 1.6 — Sanity lower bound on peak RSS for a real workload +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +@pytest.mark.skipif( + __import__("shutil").which("script") is None, + reason="script(1) not available", +) +async def test_peak_rss_kb_above_sanity_floor(tmp_path): + """End-to-end: PTY-wrapped tracing produces peak_rss_kb > 30_000 in summary.json. + + Test 1.6: a deliberate lower bound that script(1) (~2 MB) cannot satisfy. + If this ever fails, the test name points directly at the PTY wrapper tracer bug class. + """ + from autoskillit.config import LinuxTracingConfig + from autoskillit.execution.process import run_managed_async + from autoskillit.execution.session_log import flush_session_log + + cfg = LinuxTracingConfig(proc_interval=0.1, tmpfs_path=str(tmp_path / "shm")) + (tmp_path / "shm").mkdir(parents=True) + + helper = tmp_path / "alloc.py" + helper.write_text(_ALLOCATE_60MB_SCRIPT) + + result = await run_managed_async( + ["python3", str(helper)], + cwd=tmp_path, + timeout=30.0, + pty_mode=True, + linux_tracing_config=cfg, + ) + + assert result.proc_snapshots is not None, "Snapshots must be present" + + flush_session_log( + log_dir=str(tmp_path / "logs"), + cwd=str(tmp_path), + session_id="sanity-floor-001", + pid=result.pid, + skill_command="/test", + success=True, + subtype="completed", + exit_code=0, + start_ts=result.start_ts or "2026-01-01T00:00:00+00:00", + proc_snapshots=result.proc_snapshots, + ) + + summary_path = tmp_path / "logs" / "sessions" / "sanity-floor-001" / "summary.json" + assert summary_path.exists() + summary = json.loads(summary_path.read_text()) + + assert summary["peak_rss_kb"] > 30_000, ( + f"peak_rss_kb is {summary['peak_rss_kb']} KB — too low for a 60 MB allocation. " + "script(1) only uses ~2 MB RSS. If this fails, the PTY wrapper tracer bug (#806) " + "has returned." + ) diff --git a/tests/execution/test_termination_action.py b/tests/execution/test_termination_action.py new file mode 100644 index 0000000000..30b1a54bf6 --- /dev/null +++ b/tests/execution/test_termination_action.py @@ -0,0 +1,91 @@ +"""Unit tests for decide_termination_action — pure decision function (1a). + +Tests the decision table that replaces the if/elif/else dispatch in process.py. +All tests here must FAIL before Phase 2 implementation introduces +decide_termination_action, TerminationAction, and KillReason. +""" + +from __future__ import annotations + +import pytest + +from autoskillit.core.types import TerminationAction, TerminationReason +from autoskillit.execution.process import decide_termination_action + + +@pytest.mark.parametrize( + "termination,timeout_fired,process_exited,expected", + [ + # (COMPLETED, timeout=False, exited=True) → NO_KILL + (TerminationReason.COMPLETED, False, True, TerminationAction.NO_KILL), + # (COMPLETED, timeout=False, exited=False) → DRAIN_THEN_KILL_IF_ALIVE ← the -9 bug row + (TerminationReason.COMPLETED, False, False, TerminationAction.DRAIN_THEN_KILL_IF_ALIVE), + # (NATURAL_EXIT, timeout=False, exited=True) → NO_KILL + (TerminationReason.NATURAL_EXIT, False, True, TerminationAction.NO_KILL), + # (NATURAL_EXIT, timeout=False, exited=False) → NO_KILL + (TerminationReason.NATURAL_EXIT, False, False, TerminationAction.NO_KILL), + # (TIMED_OUT, timeout=True, exited=True) → IMMEDIATE_KILL + (TerminationReason.TIMED_OUT, True, True, TerminationAction.IMMEDIATE_KILL), + # (TIMED_OUT, timeout=True, exited=False) → IMMEDIATE_KILL + (TerminationReason.TIMED_OUT, True, False, TerminationAction.IMMEDIATE_KILL), + # (IDLE_STALL, timeout=False, exited=False) → IMMEDIATE_KILL + (TerminationReason.IDLE_STALL, False, False, TerminationAction.IMMEDIATE_KILL), + # (STALE, timeout=False, exited=False) → IMMEDIATE_KILL + (TerminationReason.STALE, False, False, TerminationAction.IMMEDIATE_KILL), + # timeout_fired beats process_exited + (TerminationReason.COMPLETED, True, True, TerminationAction.IMMEDIATE_KILL), + # IDLE_STALL with process_exited=True, no timeout → NO_KILL (process exit wins) + (TerminationReason.IDLE_STALL, False, True, TerminationAction.NO_KILL), + # STALE with process already exited → NO_KILL (process exit wins) + (TerminationReason.STALE, False, True, TerminationAction.NO_KILL), + ], + ids=[ + "completed_exited_no_kill", + "completed_alive_drain_kill", + "natural_exit_exited_no_kill", + "natural_exit_alive_no_kill", + "timed_out_exited_immediate_kill", + "timed_out_alive_immediate_kill", + "idle_stall_alive_immediate_kill", + "stale_alive_immediate_kill", + "timeout_beats_exited", + "idle_stall_exited_no_kill", + "stale_exited_no_kill", + ], +) +def test_decide_termination_action_matrix( + termination: TerminationReason, + timeout_fired: bool, + process_exited: bool, + expected: TerminationAction, +) -> None: + """Decision table covers all meaningful (termination, timeout_fired, process_exited) combos.""" + result = decide_termination_action( + termination, timeout_fired=timeout_fired, process_exited=process_exited + ) + assert result == expected + + +@pytest.mark.parametrize("termination", list(TerminationReason)) +def test_decide_termination_action_exhaustive_no_raise(termination: TerminationReason) -> None: + """Exhaustiveness guard: must return a valid TerminationAction for every TerminationReason.""" + result = decide_termination_action(termination, timeout_fired=False, process_exited=False) + assert isinstance(result, TerminationAction) + + +@pytest.mark.parametrize("termination", list(TerminationReason)) +def test_decide_termination_action_timeout_always_immediate_kill( + termination: TerminationReason, +) -> None: + """timeout_fired=True always yields IMMEDIATE_KILL regardless of termination reason.""" + result = decide_termination_action(termination, timeout_fired=True, process_exited=False) + assert result == TerminationAction.IMMEDIATE_KILL + + +@pytest.mark.parametrize("termination", list(TerminationReason)) +def test_decide_termination_action_process_exited_yields_no_kill_when_no_timeout( + termination: TerminationReason, +) -> None: + """process_exited=True with no timeout yields NO_KILL for any termination reason.""" + result = decide_termination_action(termination, timeout_fired=False, process_exited=True) + assert result == TerminationAction.NO_KILL diff --git a/tests/execution/test_termination_executor.py b/tests/execution/test_termination_executor.py new file mode 100644 index 0000000000..8df59755c2 --- /dev/null +++ b/tests/execution/test_termination_executor.py @@ -0,0 +1,197 @@ +"""Integration tests for execute_termination_action (1b). + +Uses real subprocesses to verify drain-window behavior. All tests here must +FAIL before Phase 2 implements execute_termination_action and the KillReason enum. +""" + +from __future__ import annotations + +import sys +import textwrap +import time +from unittest.mock import patch + +import anyio +import pytest + +from autoskillit.core.types import KillReason, TerminationAction +from autoskillit.execution.process import execute_termination_action + +# --------------------------------------------------------------------------- +# Helper scripts +# --------------------------------------------------------------------------- + +# Script that exits after sleeping N seconds (float arg) +_EXIT_AFTER_SLEEP = textwrap.dedent("""\ + import sys, time + delay = float(sys.argv[1]) if len(sys.argv) > 1 else 0.0 + time.sleep(delay) + sys.exit(0) +""") + + +async def _spawn_script(script_text: str, args: list[str], tmp_path) -> anyio.abc.Process: + """Spawn a Python subprocess running script_text with args.""" + script = tmp_path / "helper.py" + script.write_text(script_text) + return await anyio.open_process( + [sys.executable, str(script), *args], + start_new_session=True, + ) + + +class TestDrainWindowPermitsNaturalExit: + """DRAIN_THEN_KILL_IF_ALIVE: process exits inside window → natural_exit.""" + + @pytest.mark.anyio + async def test_drain_window_permits_natural_exit_when_process_exits_inside_window( + self, tmp_path + ) -> None: + """Process exits at 0.5s; grace=3.0s → kill_reason=NATURAL_EXIT, no kill called.""" + proc = await _spawn_script(_EXIT_AFTER_SLEEP, ["0.5"], tmp_path) + proc_exited_event = anyio.Event() + + # Start a task that waits for the process and sets the event + async def _watch() -> None: + await proc.wait() + proc_exited_event.set() + + kill_calls: list[int] = [] + + async def _mock_kill(pid: int, timeout: float = 2.0) -> None: + kill_calls.append(pid) + + with patch( + "autoskillit.execution.process.async_kill_process_tree", + side_effect=_mock_kill, + ): + import structlog + + proc_log = structlog.get_logger().bind(pid=proc.pid) + + async with anyio.create_task_group() as tg: + tg.start_soon(_watch) + kill_reason = await execute_termination_action( + TerminationAction.DRAIN_THEN_KILL_IF_ALIVE, + proc=proc, + process_exited_event=proc_exited_event, + grace_seconds=3.0, + proc_log=proc_log, + ) + tg.cancel_scope.cancel() + + assert kill_reason == KillReason.NATURAL_EXIT + assert kill_calls == [], ( + f"async_kill_process_tree should not have been called, got calls to pids={kill_calls}" + ) + + +class TestDrainWindowEscalatesToKill: + """DRAIN_THEN_KILL_IF_ALIVE: process survives grace window → KILL_AFTER_COMPLETION.""" + + @pytest.mark.anyio + async def test_drain_window_escalates_to_kill_when_process_survives(self, tmp_path) -> None: + """Process sleeps 10s; grace=0.3s → kill_reason=KILL_AFTER_COMPLETION, kill called once.""" + proc = await _spawn_script(_EXIT_AFTER_SLEEP, ["10.0"], tmp_path) + proc_exited_event = anyio.Event() + + kill_calls: list[int] = [] + + async def _mock_kill(pid: int, timeout: float = 2.0) -> None: + kill_calls.append(pid) + await proc.aclose() + + import structlog + + proc_log = structlog.get_logger().bind(pid=proc.pid) + + with patch( + "autoskillit.execution.process.async_kill_process_tree", + side_effect=_mock_kill, + ): + kill_reason = await execute_termination_action( + TerminationAction.DRAIN_THEN_KILL_IF_ALIVE, + proc=proc, + process_exited_event=proc_exited_event, + grace_seconds=0.3, + proc_log=proc_log, + ) + + assert kill_reason == KillReason.KILL_AFTER_COMPLETION + assert len(kill_calls) == 1, f"Expected exactly one kill call, got {kill_calls}" + + +class TestImmediateKillSkipsDrain: + """IMMEDIATE_KILL: no drain delay, kill called within milliseconds.""" + + @pytest.mark.anyio + async def test_immediate_kill_skips_drain(self, tmp_path) -> None: + """IMMEDIATE_KILL must call kill without waiting for drain window.""" + proc = await _spawn_script(_EXIT_AFTER_SLEEP, ["10.0"], tmp_path) + proc_exited_event = anyio.Event() + + kill_calls: list[int] = [] + call_time: list[float] = [] + + async def _mock_kill(pid: int, timeout: float = 2.0) -> None: + call_time.append(time.monotonic()) + kill_calls.append(pid) + await proc.aclose() + + import structlog + + proc_log = structlog.get_logger().bind(pid=proc.pid) + start = time.monotonic() + + with patch( + "autoskillit.execution.process.async_kill_process_tree", + side_effect=_mock_kill, + ): + kill_reason = await execute_termination_action( + TerminationAction.IMMEDIATE_KILL, + proc=proc, + process_exited_event=proc_exited_event, + grace_seconds=3.0, # large grace, should be ignored + proc_log=proc_log, + ) + + elapsed = (call_time[0] - start) if call_time else 999.0 + assert kill_reason == KillReason.INFRA_KILL + assert len(kill_calls) == 1 + assert elapsed < 0.5, f"IMMEDIATE_KILL took {elapsed:.3f}s — should be near-instant" + + +class TestNoKillNeverTouchesKillHelper: + """NO_KILL: async_kill_process_tree must never be called.""" + + @pytest.mark.anyio + async def test_no_kill_action_never_touches_kill_helper(self, tmp_path) -> None: + """NO_KILL returns NATURAL_EXIT without calling async_kill_process_tree.""" + proc = await _spawn_script(_EXIT_AFTER_SLEEP, ["0.1"], tmp_path) + await proc.wait() # let it exit first + proc_exited_event = anyio.Event() + proc_exited_event.set() + + kill_calls: list[int] = [] + + async def _mock_kill(pid: int, timeout: float = 2.0) -> None: + kill_calls.append(pid) + + import structlog + + proc_log = structlog.get_logger().bind(pid=proc.pid) + + with patch( + "autoskillit.execution.process.async_kill_process_tree", + side_effect=_mock_kill, + ): + kill_reason = await execute_termination_action( + TerminationAction.NO_KILL, + proc=proc, + process_exited_event=proc_exited_event, + grace_seconds=3.0, + proc_log=proc_log, + ) + + assert kill_reason == KillReason.NATURAL_EXIT + assert kill_calls == [], f"NO_KILL must not call async_kill_process_tree, got {kill_calls}" diff --git a/tests/execution/test_trace_target_resolver.py b/tests/execution/test_trace_target_resolver.py new file mode 100644 index 0000000000..9cff1f98b7 --- /dev/null +++ b/tests/execution/test_trace_target_resolver.py @@ -0,0 +1,79 @@ +"""Tests for resolve_trace_target — descendant-walk and basename-match contract. + +These tests verify the new TraceTarget resolver introduced to fix issue #806: +anyio.open_process returns the PID of script(1), not claude. The resolver walks +process descendants to find the actual workload. +""" + +from __future__ import annotations + +import shutil +import subprocess +import sys + +import pytest + +pytestmark = pytest.mark.skipif( + sys.platform != "linux", + reason="Linux only — tests /proc descendant walking", +) + + +@pytest.mark.skipif(shutil.which("script") is None, reason="script(1) not available") +def test_resolve_trace_target_walks_from_wrapper_to_workload(): + """resolve_trace_target resolves from script(1) wrapper to the workload process. + + Test 1.3: lock in the descendant-walk + basename-match contract. + """ + from autoskillit.execution.linux_tracing import resolve_trace_target + + proc = subprocess.Popen( + ["script", "-qefc", "python3 -c 'import time; time.sleep(5)'", "/dev/null"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + try: + target = resolve_trace_target(root_pid=proc.pid, expected_basename="python3", timeout=2.0) + assert target.pid != proc.pid, ( + "Resolved PID must not be the wrapper (script) PID — " + "resolver must walk children to find the workload" + ) + assert target.comm == "python3", f"Expected comm='python3', got {target.comm!r}" + assert any(p.endswith("python3") for p in target.cmdline), ( + f"Expected python3 in cmdline, got {target.cmdline!r}" + ) + assert isinstance(target.starttime_ticks, int) and target.starttime_ticks > 0 + finally: + proc.kill() + proc.wait() + + +def test_resolve_trace_target_raises_on_miss(): + """resolve_trace_target raises TraceTargetResolutionError when workload never appears. + + Test 1.4: failure must be loud, not a silent fall-back to wrapper PID. + """ + from autoskillit.execution.linux_tracing import ( + TraceTargetResolutionError, + resolve_trace_target, + ) + + proc = subprocess.Popen(["sleep", "5"]) + try: + with pytest.raises(TraceTargetResolutionError) as exc_info: + resolve_trace_target( + root_pid=proc.pid, + expected_basename="definitely_not_there", + timeout=0.5, + ) + error_msg = str(exc_info.value) + # Error must mention the root pid and/or expected basename so the caller + # can diagnose what resolution was attempted + assert str(proc.pid) in error_msg or "definitely_not_there" in error_msg, ( + f"Error message must mention root_pid or expected_basename. Got: {error_msg!r}" + ) + assert exc_info.value.root_pid == proc.pid + assert exc_info.value.expected_basename == "definitely_not_there" + finally: + proc.kill() + proc.wait() diff --git a/tests/execution/test_zero_write_detection.py b/tests/execution/test_zero_write_detection.py index cc36eff13e..4f6120ae69 100644 --- a/tests/execution/test_zero_write_detection.py +++ b/tests/execution/test_zero_write_detection.py @@ -138,6 +138,416 @@ def test_zero_writes_with_no_tool_uses_on_always_write_fails(self) -> None: assert sr.subtype == "zero_writes" assert sr.retry_reason == RetryReason.ZERO_WRITES + def test_conditional_already_green_worktree_not_demoted(self) -> None: + """resolve-failures conditional + 'verdict = already_green' → success preserved. + + This is the Issue #603 false-positive scenario: worktree is already green, + skill emits 'fixes_applied = 0' AND 'verdict = already_green', and the gate + must NOT demote to zero_writes. + + With the new write_expected_when pattern (verdict = real_fix), the gate only + triggers when the skill declares it actually applied a real fix. + """ + result_record = { + "type": "result", + "subtype": "success", + "is_error": False, + "result": ( + "Tests are green. fixes_applied = 0\nverdict = already_green\n" + "no changes needed\n%%ORDER_UP%%" + ), + "session_id": "test-sess", + } + stdout = json.dumps(result_record) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:resolve-failures /tmp/wt /tmp/plan.md main", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"verdict\s*=\s*real_fix",), + ), + ) + assert sr.success is True, ( + "Already-green worktree (verdict = already_green) must NOT be demoted. " + "The pattern 'verdict = real_fix' must not match 'verdict = already_green'." + ) + assert sr.subtype != "zero_writes" + + def test_conditional_no_verdict_not_demoted_but_write_not_expected(self) -> None: + """resolve-failures with no verdict token: write gate does not fire, result passes. + + With the new write_expected_when (verdict = real_fix), a result emitting only + fixes_applied = 0 (no verdict token) does NOT trigger write expectation. + The verdict is now the load-bearing routing signal: fixes_applied alone is + insufficient to declare a real fix. + """ + result_record = { + "type": "result", + "subtype": "success", + "is_error": False, + "result": "fixes_applied = 0\n%%ORDER_UP%%", + "session_id": "test-sess", + } + stdout = json.dumps(result_record) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:resolve-failures /tmp/wt /tmp/plan.md main", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"verdict\s*=\s*real_fix",), + ), + ) + # Write not expected (no verdict = real_fix) → success, NOT demoted + assert sr.success is True, ( + "fixes_applied = 0 without verdict token must NOT be demoted — " + "the new gate only fires on 'verdict = real_fix'" + ) + assert sr.subtype != "zero_writes" + + def test_conditional_real_fix_verdict_without_writes_demoted(self) -> None: + """resolve-failures emitting verdict=real_fix but 0 writes → demoted to zero_writes. + + When the skill declares 'verdict = real_fix', writes are expected. + If no Edit/Write calls were made, the write gate must fire and demote the result. + """ + result_record = { + "type": "result", + "subtype": "success", + "is_error": False, + "result": "verdict = real_fix\nfixes_applied = 1\n%%ORDER_UP%%", + "session_id": "test-sess", + } + stdout = json.dumps(result_record) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:resolve-failures /tmp/wt /tmp/plan.md main", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"verdict\s*=\s*real_fix",), + ), + ) + assert sr.success is False, ( + "verdict = real_fix with 0 writes must be demoted to zero_writes" + ) + assert sr.subtype == "zero_writes" + assert sr.retry_reason == RetryReason.ZERO_WRITES + + def test_conditional_fix_applied_but_no_writes_demoted(self) -> None: + """Conditional + 'fixes_applied = 1' + 0 writes → zero_writes (Bash-only fix, no artifact). + + If the skill claims it applied fixes but produced no Edit/Write calls, + the gate must fire. This catches the Bash-only fix scenario where the + skill forgot to write the fix_log artifact. + """ + result_record = { + "type": "result", + "subtype": "success", + "is_error": False, + "result": "fixes_applied = 1\nfixed: uv.lock stale pin\n%%ORDER_UP%%", + "session_id": "test-sess", + } + stdout = json.dumps(result_record) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:resolve-failures /tmp/wt /tmp/plan.md main", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"fixes_applied\s*=\s*[1-9][0-9]*",), + ), + ) + assert sr.success is False + assert sr.subtype == "zero_writes" + assert sr.retry_reason == RetryReason.ZERO_WRITES + + def test_conditional_all_phases_done_not_demoted(self) -> None: + """retry-worktree with 'phases_implemented = 0' output → success preserved. + + When called on a worktree where all phases are already complete, + retry-worktree emits 'phases_implemented = 0' and the gate must NOT fire. + """ + result_record = { + "type": "result", + "subtype": "success", + "is_error": False, + "result": ( + "worktree_path = /tmp/wt\nbranch_name = feature/123\n" + "phases_implemented = 0\nAll phases already complete.\n%%ORDER_UP%%" + ), + "session_id": "test-sess", + } + stdout = json.dumps(result_record) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:retry-worktree /tmp/plan.md /tmp/wt", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"phases_implemented\s*=\s*[1-9][0-9]*",), + ), + ) + assert sr.success is True, ( + "All-phases-done worktree (phases_implemented = 0) must NOT be demoted to zero_writes." + ) + assert sr.subtype != "zero_writes" + + def test_conditional_no_pr_found_not_demoted(self) -> None: + """resolve-review graceful degradation (no PR found) → success preserved. + + When no PR is found, resolve-review exits 0 with no writes and no + fixes_applied token. The conditional gate must not fire (no match → write not expected). + """ + result_record = { + "type": "result", + "subtype": "success", + "is_error": False, + "result": "No PR found or gh unavailable — skipping review resolution\n%%ORDER_UP%%", + "session_id": "test-sess", + } + stdout = json.dumps(result_record) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:resolve-review feature-branch main", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"fixes_applied\s*=\s*[1-9][0-9]*",), + ), + ) + assert sr.success is True, ( + "No-PR graceful degradation (no fixes_applied token) must NOT be demoted." + ) + assert sr.subtype != "zero_writes" + + def test_resolve_claims_review_no_fixes_applied_not_demoted(self) -> None: + """resolve-claims-review: 'Fixes applied: 0' → gate inactive → success preserved. + + The pattern [1-9][0-9]* excludes zero, so zero-fix runs are not demoted. + """ + result_record = { + "type": "result", + "subtype": "success", + "is_error": False, + "result": "Fixes applied: 0\nneeds_rerun = false\n%%ORDER_UP%%", + "session_id": "test-sess", + } + stdout = json.dumps(result_record) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:resolve-claims-review /tmp/wt main", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"Fixes applied:\s*[1-9][0-9]*",), + ), + ) + assert sr.success is True, ( + "'Fixes applied: 0' must NOT be demoted — pattern [1-9][0-9]* excludes zero." + ) + assert sr.subtype != "zero_writes" + + def test_resolve_claims_review_all_escalations_not_demoted(self) -> None: + """resolve-claims-review: all-escalations path → success preserved. + + When all accepted findings are rerun_required/design_flaw, no code is written + and 'Fixes applied: 0' is emitted. The gate must not fire. + """ + result_record = { + "type": "result", + "subtype": "success", + "is_error": False, + "result": "Fixes applied: 0\nneeds_rerun = true\n%%ORDER_UP%%", + "session_id": "test-sess", + } + stdout = json.dumps(result_record) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:resolve-claims-review /tmp/wt main", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"Fixes applied:\s*[1-9][0-9]*",), + ), + ) + assert sr.success is True, ( + "All-escalations path (Fixes applied: 0, needs_rerun=true) must NOT be demoted." + ) + assert sr.subtype != "zero_writes" + + def test_resolve_claims_review_graceful_degradation_not_demoted(self) -> None: + """resolve-claims-review: no-PR graceful degradation → success preserved. + + When no PR is found, the skill exits without a 'Fixes applied' line. + No pattern match → gate inactive → success preserved. + """ + result_record = { + "type": "result", + "subtype": "success", + "is_error": False, + "result": "No PR found or gh unavailable — skipping\n%%ORDER_UP%%", + "session_id": "test-sess", + } + stdout = json.dumps(result_record) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:resolve-claims-review /tmp/wt main", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"Fixes applied:\s*[1-9][0-9]*",), + ), + ) + assert sr.success is True, ( + "Graceful degradation (no 'Fixes applied' line) must NOT be demoted." + ) + assert sr.subtype != "zero_writes" + + def test_resolve_claims_review_fixes_applied_zero_writes_demoted(self) -> None: + """resolve-claims-review: 'Fixes applied: 3' + 0 writes → demoted to zero_writes. + + When the skill claims fixes were applied but produced no Edit/Write calls, + this indicates silent degradation. The gate must fire. + """ + result_record = { + "type": "result", + "subtype": "success", + "is_error": False, + "result": "Fixes applied: 3\nneeds_rerun = false\n%%ORDER_UP%%", + "session_id": "test-sess", + } + stdout = json.dumps(result_record) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:resolve-claims-review /tmp/wt main", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"Fixes applied:\s*[1-9][0-9]*",), + ), + ) + assert sr.success is False, ( + "'Fixes applied: 3' with 0 writes must be demoted — silent degradation detected." + ) + assert sr.subtype == "zero_writes" + assert sr.retry_reason == RetryReason.ZERO_WRITES + + def test_resolve_claims_review_fixes_applied_with_writes_passes(self) -> None: + """resolve-claims-review: 'Fixes applied: 3' + 3 writes → success preserved. + + The gate short-circuits at write_call_count > 0 before evaluating result text. + """ + stdout = _ndjson_with_tool_uses(["Edit", "Edit", "Edit"]) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:resolve-claims-review /tmp/wt main", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"Fixes applied:\s*[1-9][0-9]*",), + ), + ) + assert sr.success is True, "Fixes applied with actual writes must NOT be demoted." + assert sr.subtype != "zero_writes" + + def test_resolve_research_review_no_fixes_applied_not_demoted(self) -> None: + """resolve-research-review: 'Fixes applied: 0' → gate inactive → success preserved.""" + result_record = { + "type": "result", + "subtype": "success", + "is_error": False, + "result": "Fixes applied: 0\nneeds_rerun = false\n%%ORDER_UP%%", + "session_id": "test-sess", + } + stdout = json.dumps(result_record) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:resolve-research-review /tmp/wt main", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"Fixes applied:\s*[1-9][0-9]*",), + ), + ) + assert sr.success is True, ( + "'Fixes applied: 0' must NOT be demoted — pattern [1-9][0-9]* excludes zero." + ) + assert sr.subtype != "zero_writes" + + def test_resolve_research_review_all_escalations_not_demoted(self) -> None: + """resolve-research-review: all-escalations path → success preserved.""" + result_record = { + "type": "result", + "subtype": "success", + "is_error": False, + "result": "Fixes applied: 0\nneeds_rerun = true\n%%ORDER_UP%%", + "session_id": "test-sess", + } + stdout = json.dumps(result_record) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:resolve-research-review /tmp/wt main", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"Fixes applied:\s*[1-9][0-9]*",), + ), + ) + assert sr.success is True, ( + "All-escalations path (Fixes applied: 0, needs_rerun=true) must NOT be demoted." + ) + assert sr.subtype != "zero_writes" + + def test_resolve_research_review_graceful_degradation_not_demoted(self) -> None: + """resolve-research-review: no-PR graceful degradation → success preserved.""" + result_record = { + "type": "result", + "subtype": "success", + "is_error": False, + "result": "No PR found or gh unavailable — skipping\n%%ORDER_UP%%", + "session_id": "test-sess", + } + stdout = json.dumps(result_record) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:resolve-research-review /tmp/wt main", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"Fixes applied:\s*[1-9][0-9]*",), + ), + ) + assert sr.success is True, ( + "Graceful degradation (no 'Fixes applied' line) must NOT be demoted." + ) + assert sr.subtype != "zero_writes" + + def test_resolve_research_review_fixes_applied_zero_writes_demoted(self) -> None: + """resolve-research-review: 'Fixes applied: 3' + 0 writes → demoted to zero_writes.""" + result_record = { + "type": "result", + "subtype": "success", + "is_error": False, + "result": "Fixes applied: 3\nneeds_rerun = false\n%%ORDER_UP%%", + "session_id": "test-sess", + } + stdout = json.dumps(result_record) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:resolve-research-review /tmp/wt main", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"Fixes applied:\s*[1-9][0-9]*",), + ), + ) + assert sr.success is False, ( + "'Fixes applied: 3' with 0 writes must be demoted — silent degradation detected." + ) + assert sr.subtype == "zero_writes" + assert sr.retry_reason == RetryReason.ZERO_WRITES + + def test_resolve_research_review_fixes_applied_with_writes_passes(self) -> None: + """resolve-research-review: 'Fixes applied: 3' + 3 writes → success preserved.""" + stdout = _ndjson_with_tool_uses(["Edit", "Edit", "Edit"]) + sr = _build_skill_result( + _make_result(returncode=0, stdout=stdout), + skill_command="/autoskillit:resolve-research-review /tmp/wt main", + write_behavior=WriteBehaviorSpec( + mode="conditional", + expected_when=(r"Fixes applied:\s*[1-9][0-9]*",), + ), + ) + assert sr.success is True, "Fixes applied with actual writes must NOT be demoted." + assert sr.subtype != "zero_writes" + class TestWriteCallCountPropagation: """write_call_count must be accurately computed and propagated.""" diff --git a/tests/hooks/__init__.py b/tests/hooks/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/hooks/test_fmt_status.py b/tests/hooks/test_fmt_status.py new file mode 100644 index 0000000000..d1b6e459f5 --- /dev/null +++ b/tests/hooks/test_fmt_status.py @@ -0,0 +1,40 @@ +"""Tests for autoskillit.hooks._fmt_status.""" + +from __future__ import annotations + + +class TestFmtCloneRepo: + """Test 6: _fmt_clone_repo renders new discriminator keys.""" + + def test_fmt_clone_repo_renders_source_type_key(self) -> None: + """New clone_source_type key is rendered in the flat-KV output.""" + from autoskillit.hooks._fmt_status import _fmt_clone_repo + + result = _fmt_clone_repo( + { + "clone_path": "/x", + "source_dir": "/y", + "remote_url": "u", + "clone_source_type": "remote", + "clone_source_reason": "ok", + }, + False, + ) + assert "clone_source_type: remote" in result + + def test_fmt_clone_repo_renders_local_source_type(self) -> None: + """clone_source_type=local is rendered correctly.""" + from autoskillit.hooks._fmt_status import _fmt_clone_repo + + result = _fmt_clone_repo( + { + "clone_path": "/x", + "source_dir": "/y", + "remote_url": "", + "clone_source_type": "local", + "clone_source_reason": "strategy_clone_local", + }, + False, + ) + assert "clone_source_type: local" in result + assert "clone_source_reason: strategy_clone_local" in result diff --git a/tests/infra/test_ask_user_question_guard.py b/tests/infra/test_ask_user_question_guard.py new file mode 100644 index 0000000000..72c28142ca --- /dev/null +++ b/tests/infra/test_ask_user_question_guard.py @@ -0,0 +1,204 @@ +"""Tests for the ask_user_question_guard PreToolUse hook.""" + +from __future__ import annotations + +import json +import os +import subprocess +import sys +from dataclasses import dataclass +from datetime import UTC, datetime, timedelta +from pathlib import Path + + +@dataclass +class RunResult: + exit_code: int + stdout: str + stderr: str + + +def run_guard( + hook_input: dict, env_extra: dict | None = None, *, headless: bool = False +) -> RunResult: + hook_path = ( + Path(__file__).resolve().parents[2] / "src/autoskillit/hooks/ask_user_question_guard.py" + ) + extra = dict(env_extra or {}) + if headless: + extra["AUTOSKILLIT_HEADLESS"] = "1" + else: + extra.pop("AUTOSKILLIT_HEADLESS", None) + # Start from a clean env without AUTOSKILLIT_HEADLESS to avoid test-env leakage + env = {k: v for k, v in os.environ.items() if k != "AUTOSKILLIT_HEADLESS"} + env.update(extra) + result = subprocess.run( + [sys.executable, str(hook_path)], + input=json.dumps(hook_input), + capture_output=True, + text=True, + env=env, + ) + return RunResult(exit_code=result.returncode, stdout=result.stdout, stderr=result.stderr) + + +# Existing tests (updated to use headless=True where the headless path matters) + + +def test_guard_denies_when_no_marker(tmp_path: Path) -> None: + hook_input = { + "tool_name": "AskUserQuestion", + "tool_input": {}, + "session_id": "session-xyz", + "hook_event_name": "PreToolUse", + } + result = run_guard( + hook_input, + env_extra={"AUTOSKILLIT_STATE_DIR": str(tmp_path)}, + headless=True, + ) + assert result.exit_code == 0 + payload = json.loads(result.stdout) + hook_out = payload["hookSpecificOutput"] + assert hook_out["hookEventName"] == "PreToolUse" + assert hook_out["permissionDecision"] == "deny" + reason = hook_out["permissionDecisionReason"] + assert "headless sessions" in reason + assert "open_kitchen first" in reason + + +def test_guard_permits_when_marker_present(tmp_path: Path, monkeypatch) -> None: + monkeypatch.setenv("AUTOSKILLIT_STATE_DIR", str(tmp_path)) + marker_dir = tmp_path / "kitchen_state" + marker_dir.mkdir(parents=True) + (marker_dir / "session-xyz.json").write_text( + json.dumps( + { + "session_id": "session-xyz", + "opened_at": datetime.now(UTC).isoformat(), + "recipe_name": "my_recipe", + "marker_version": 1, + } + ) + ) + result = run_guard( + { + "tool_name": "AskUserQuestion", + "session_id": "session-xyz", + "hook_event_name": "PreToolUse", + }, + env_extra={"AUTOSKILLIT_STATE_DIR": str(tmp_path)}, + headless=True, + ) + assert result.exit_code == 0 + assert result.stdout.strip() == "" # permit path exits silently + + +def test_guard_permits_unrelated_tool(tmp_path: Path) -> None: + result = run_guard( + {"tool_name": "Read", "session_id": "x"}, + env_extra={"AUTOSKILLIT_STATE_DIR": str(tmp_path)}, + ) + assert result.exit_code == 0 + assert result.stdout.strip() == "" # non-AskUserQuestion exits silently + + +# New tests: session-type axis + + +def test_guard_permits_interactive_session(tmp_path: Path) -> None: + """Interactive sessions must always permit AskUserQuestion — user is present.""" + hook_input = { + "tool_name": "AskUserQuestion", + "tool_input": {}, + "session_id": "session-interactive", + "hook_event_name": "PreToolUse", + } + # No kitchen marker, no AUTOSKILLIT_HEADLESS — the exact bug scenario + result = run_guard( + hook_input, + env_extra={"AUTOSKILLIT_STATE_DIR": str(tmp_path)}, + headless=False, + ) + assert result.exit_code == 0 + assert result.stdout.strip() == "" # must permit silently + + +def test_guard_denies_headless_without_marker(tmp_path: Path) -> None: + """Headless sessions without a kitchen marker must be denied.""" + hook_input = { + "tool_name": "AskUserQuestion", + "tool_input": {}, + "session_id": "session-headless-no-marker", + "hook_event_name": "PreToolUse", + } + result = run_guard( + hook_input, + env_extra={"AUTOSKILLIT_STATE_DIR": str(tmp_path)}, + headless=True, + ) + assert result.exit_code == 0 + payload = json.loads(result.stdout) + hook_out = payload["hookSpecificOutput"] + assert hook_out["permissionDecision"] == "deny" + + +def test_guard_permits_headless_with_marker(tmp_path: Path) -> None: + """Headless sessions with a fresh kitchen marker must be permitted.""" + marker_dir = tmp_path / "kitchen_state" + marker_dir.mkdir(parents=True) + (marker_dir / "session-headless-ok.json").write_text( + json.dumps( + { + "session_id": "session-headless-ok", + "opened_at": datetime.now(UTC).isoformat(), + "recipe_name": "test_recipe", + "marker_version": 1, + } + ) + ) + hook_input = { + "tool_name": "AskUserQuestion", + "tool_input": {}, + "session_id": "session-headless-ok", + "hook_event_name": "PreToolUse", + } + result = run_guard( + hook_input, + env_extra={"AUTOSKILLIT_STATE_DIR": str(tmp_path)}, + headless=True, + ) + assert result.exit_code == 0 + assert result.stdout.strip() == "" # permit path exits silently + + +def test_guard_denies_stale_marker(tmp_path: Path) -> None: + """Headless sessions with a stale marker (>24h) must be denied.""" + marker_dir = tmp_path / "kitchen_state" + marker_dir.mkdir(parents=True) + stale_time = datetime.now(UTC) - timedelta(hours=25) + (marker_dir / "session-stale.json").write_text( + json.dumps( + { + "session_id": "session-stale", + "opened_at": stale_time.isoformat(), + "recipe_name": "old_recipe", + "marker_version": 1, + } + ) + ) + hook_input = { + "tool_name": "AskUserQuestion", + "tool_input": {}, + "session_id": "session-stale", + "hook_event_name": "PreToolUse", + } + result = run_guard( + hook_input, + env_extra={"AUTOSKILLIT_STATE_DIR": str(tmp_path)}, + headless=True, + ) + assert result.exit_code == 0 + payload = json.loads(result.stdout) + hook_out = payload["hookSpecificOutput"] + assert hook_out["permissionDecision"] == "deny" diff --git a/tests/infra/test_ci_dev_config.py b/tests/infra/test_ci_dev_config.py index 2420fda7d5..03c9b42a51 100644 --- a/tests/infra/test_ci_dev_config.py +++ b/tests/infra/test_ci_dev_config.py @@ -250,23 +250,26 @@ def test_ci_push_trigger_includes_stable(self) -> None: class TestRecipeWorkflowField: - def test_ci_watch_steps_carry_workflow_field(self): - """All wait_for_ci steps in bundled top-level recipes must specify a workflow. - - Without a workflow field, wait_for_ci queries all workflows on the branch, - causing false failures when unrelated workflows (version bumps, labelers) - complete with failure before the test workflow runs. - """ + def test_ci_watch_event_value_is_captured_or_absent(self): + """Every wait_for_ci step's event value must either be: + (a) a template reference to an upstream-captured variable + (e.g. ${{ context.ci_event }}), OR + (b) absent (matches any event — the ci.py default when scope.event is None). + Hardcoded literals ('push', 'pull_request', 'merge_group') are forbidden because + they create capture inversions when the repo's actual trigger differs.""" recipes_dir = REPO_ROOT / "src" / "autoskillit" / "recipes" for recipe_path in recipes_dir.glob("*.yaml"): recipe = yaml.safe_load(recipe_path.read_text()) for step_name, step in recipe.get("steps", {}).items(): - if step.get("tool") == "wait_for_ci": - assert "workflow" in step.get("with", {}), ( - f"{recipe_path.name}:{step_name} missing workflow in with: — " - "add 'workflow: \"tests.yml\"' to scope CI polling to the correct" - " workflow" - ) + if step.get("tool") != "wait_for_ci": + continue + event = step.get("with", {}).get("event") + if event is None: + continue # absent is fine — matches any event + assert event.startswith("${{") and "context." in event, ( + f"{recipe_path.name}:{step_name} — event must be a captured context " + f"reference or absent, not {event!r}" + ) class TestPtyTestGuard: diff --git a/tests/infra/test_ci_workflow.py b/tests/infra/test_ci_workflow.py new file mode 100644 index 0000000000..ac2e138b24 --- /dev/null +++ b/tests/infra/test_ci_workflow.py @@ -0,0 +1,26 @@ +"""CI workflow structural tests.""" + +from __future__ import annotations + +from pathlib import Path + + +def _repo_root() -> Path: + return Path(__file__).resolve().parents[2] + + +def test_ci_workflow_does_not_pre_regenerate_hooks_json() -> None: + """The CI workflow must not have a 'Generate hooks.json (if absent)' step. + + That step was tautological: hooks.json is gitignored, CI generates it fresh, + then the test compared on-disk vs generate_hooks_json() — always passing. + The new test uses registry.sha256 (committed) which cannot be silenced by pre-regen. + """ + import yaml + + workflow = yaml.safe_load((_repo_root() / ".github" / "workflows" / "tests.yml").read_text()) + step_names = [s.get("name") for job in workflow["jobs"].values() for s in job.get("steps", [])] + assert not any("Generate hooks.json" in (n or "") for n in step_names), ( + "CI must not pre-regenerate hooks.json — this defeats drift detection. " + "Remove the 'Generate hooks.json (if absent)' step." + ) diff --git a/tests/infra/test_claude_md_critical_rules.py b/tests/infra/test_claude_md_critical_rules.py index c24a5dc1ab..3ecdbe01ea 100644 --- a/tests/infra/test_claude_md_critical_rules.py +++ b/tests/infra/test_claude_md_critical_rules.py @@ -1,7 +1,7 @@ """Tests that CLAUDE.md contains required critical rules and documentation. Encodes behavioral contracts derived from friction analysis (issue #250): -- FRICT-1B-3: set_project_path initialization rule in §3.5 +- FRICT-1B-3: set_project_path initialization rule in §3.3 - FRICT-3A-1: pre-commit critical rule in §3.1 - FRICT-5-2: session diagnostics hyphen path convention documented - FRICT-7-1: session diagnostics under a dedicated heading, not trailing paragraph @@ -13,7 +13,7 @@ import pytest -REPO_ROOT = Path(__file__).parent.parent.parent +REPO_ROOT = Path(__file__).resolve().parent.parent.parent @pytest.fixture() @@ -22,21 +22,21 @@ def claude_md() -> str: def test_claude_md_code_index_requires_set_project_path(claude_md: str) -> None: - """§3.5 must instruct agents to call set_project_path before using code-index tools. + """§3.3 must instruct agents to call set_project_path before using code-index tools. Without this call every code-index tool fails with 'Project path not set', cascading into parallel call cancellations (FRICT-1B-3). """ - # Find the §3.5 section using the full heading to avoid false matches - assert "### **3.5" in claude_md, "§3.5 section not found in CLAUDE.md" - section_start = claude_md.index("### **3.5") + # Find the §3.3 section using the full heading to avoid false matches + assert "### **3.3" in claude_md, "§3.3 section not found in CLAUDE.md" + section_start = claude_md.index("### **3.3") # Find the next top-level section heading (### 3.) to bound the search next_section = claude_md.find("### **3.", section_start + 1) section_text = ( claude_md[section_start:next_section] if next_section != -1 else claude_md[section_start:] ) assert "set_project_path" in section_text, ( - "CLAUDE.md §3.5 (Code Index MCP Usage) must instruct agents to call " + "CLAUDE.md §3.3 (Code Index MCP Usage) must instruct agents to call " "set_project_path before using any code-index tool in a new session (FRICT-1B-3)." ) diff --git a/tests/infra/test_dependency_pins.py b/tests/infra/test_dependency_pins.py new file mode 100644 index 0000000000..8c5028a5f7 --- /dev/null +++ b/tests/infra/test_dependency_pins.py @@ -0,0 +1,51 @@ +"""Dependency pin guards (REQ-DEP-001, REQ-DEP-002). + +Verifies third-party dependency pins satisfy the audit-derived constraints: + - pytest is at the latest patched 9.x release + - igraph has both an explicit lower bound AND an explicit upper bound +""" + +from __future__ import annotations + +import tomllib +from pathlib import Path +from typing import Any + +_PROJECT_ROOT = Path(__file__).resolve().parents[2] + + +def _load_lock() -> dict[str, Any]: + return tomllib.loads((_PROJECT_ROOT / "uv.lock").read_text()) + + +def _load_pyproject() -> dict[str, Any]: + return tomllib.loads((_PROJECT_ROOT / "pyproject.toml").read_text()) + + +def test_pytest_pin_at_or_above_minor() -> None: + """REQ-DEP-001: pytest must be at the latest patched 9.x release.""" + lock = _load_lock() + pytest_pkg = next(p for p in lock["package"] if p["name"] == "pytest") + parts = pytest_pkg["version"].split(".", maxsplit=2) + major, minor = int(parts[0]), int(parts[1]) + patch_raw = parts[2] if len(parts) > 2 else "0" + patch = int("".join(c for c in patch_raw.split(".")[0] if c.isdigit()) or "0") + assert (major, minor) == (9, 0) + assert patch >= 3, f"pytest must be ≥9.0.3 (got {pytest_pkg['version']})" + + +def test_igraph_pin_has_explicit_bounds() -> None: + """REQ-DEP-002: igraph must have an explicit lower bound AND an explicit + upper bound in pyproject.toml. The unbounded ``>=1.0`` constraint silently + accepts breaking major bumps.""" + pyproject = _load_pyproject() + deps = pyproject["project"]["dependencies"] + igraph_spec = next( + d + for d in deps + if d.split(">")[0].split("<")[0].split("=")[0].strip().lower() + in {"igraph", "python-igraph"} + ) + assert ">=" in igraph_spec and "<" in igraph_spec, ( + f"igraph constraint must have explicit upper bound: {igraph_spec!r}" + ) diff --git a/tests/infra/test_docstring_labels.py b/tests/infra/test_docstring_labels.py index ce92aee654..4b622c00b7 100644 --- a/tests/infra/test_docstring_labels.py +++ b/tests/infra/test_docstring_labels.py @@ -4,22 +4,24 @@ from pathlib import Path +_REPO_ROOT = Path(__file__).resolve().parent.parent.parent + def test_session_py_docstring_says_l2(): """session.py docstring must carry an L2 label.""" - src = Path("src/autoskillit/execution/session.py").read_text() + src = (_REPO_ROOT / "src/autoskillit/execution/session.py").read_text() assert "L2" in src.split('"""')[1], "session.py docstring must say L2" def test_headless_py_docstring_says_l1(): """headless.py docstring must carry an L1 label.""" - src = Path("src/autoskillit/execution/headless.py").read_text() + src = (_REPO_ROOT / "src/autoskillit/execution/headless.py").read_text() assert "L1" in src.split('"""')[1], "headless.py docstring must say L1" def test_smoke_utils_documents_limitation(): """smoke_utils.py documents its file-path coupling limitation.""" - src = Path("src/autoskillit/smoke_utils.py").read_text() + src = (_REPO_ROOT / "src/autoskillit/smoke_utils.py").read_text() assert "limitation" in src.lower() or "known" in src.lower(), ( "smoke_utils.py must document its path-coupling limitation" ) @@ -27,7 +29,7 @@ def test_smoke_utils_documents_limitation(): def test_claude_md_no_stale_l3_headless_label(): """CLAUDE.md must not contain stale 'L3 service' label for headless.""" - src = Path("CLAUDE.md").read_text() + src = (_REPO_ROOT / "CLAUDE.md").read_text() assert "L3 service module" not in src, ( "CLAUDE.md still contains stale 'L3 service module' label for headless" ) diff --git a/tests/infra/test_generated_file_write_guard.py b/tests/infra/test_generated_file_write_guard.py new file mode 100644 index 0000000000..b0acb87257 --- /dev/null +++ b/tests/infra/test_generated_file_write_guard.py @@ -0,0 +1,69 @@ +"""Tests for generated_file_write_guard.py PreToolUse hook.""" + +import json +import subprocess +import sys + +from autoskillit.core.paths import pkg_root + + +def _run_guard(event: dict) -> dict | None: + script = pkg_root() / "hooks" / "generated_file_write_guard.py" + result = subprocess.run( + [sys.executable, str(script)], + input=json.dumps(event), + capture_output=True, + text=True, + timeout=5, + ) + assert result.returncode == 0 + if result.stdout.strip(): + return json.loads(result.stdout.strip()) + return None + + +def test_write_guard_denies_hooks_json_write(): + event = {"tool_name": "Write", "tool_input": {"file_path": "/any/path/hooks/hooks.json"}} + output = _run_guard(event) + assert output is not None + assert output["hookSpecificOutput"]["permissionDecision"] == "deny" + + +def test_write_guard_denies_settings_json_write(): + event = {"tool_name": "Write", "tool_input": {"file_path": "/repo/.claude/settings.json"}} + output = _run_guard(event) + assert output is not None + assert output["hookSpecificOutput"]["permissionDecision"] == "deny" + + +def test_write_guard_denies_edit_targeting_hooks_json(): + event = {"tool_name": "Edit", "tool_input": {"file_path": "/any/path/hooks/hooks.json"}} + output = _run_guard(event) + assert output is not None + assert output["hookSpecificOutput"]["permissionDecision"] == "deny" + + +def test_write_guard_allows_unrelated_hooks_json(): + """Ensure files like 'my-hooks.json' are not false-positive denied.""" + event = {"tool_name": "Write", "tool_input": {"file_path": "/repo/my-hooks.json"}} + output = _run_guard(event) + assert output is None, "Unrelated *hooks.json file must not be denied" + + +def test_write_guard_allows_other_files(): + event = {"tool_name": "Write", "tool_input": {"file_path": "/repo/src/foo.py"}} + output = _run_guard(event) + assert output is None, "Non-generated-file Write must pass through (no stdout)" + + +def test_write_guard_fail_open_on_invalid_json(): + script = pkg_root() / "hooks" / "generated_file_write_guard.py" + result = subprocess.run( + [sys.executable, str(script)], + input="not json", + capture_output=True, + text=True, + timeout=5, + ) + assert result.returncode == 0 + assert result.stdout.strip() == "", "Fail-open: invalid stdin must produce no output" diff --git a/tests/infra/test_gitattributes.py b/tests/infra/test_gitattributes.py new file mode 100644 index 0000000000..e57aaab637 --- /dev/null +++ b/tests/infra/test_gitattributes.py @@ -0,0 +1,26 @@ +"""REQ-R741-A03 — .gitattributes must exist and mark vendored JS as binary.""" + +from __future__ import annotations + +from pathlib import Path + +_REPO_ROOT = Path(__file__).resolve().parents[2] + + +def test_gitattributes_exists() -> None: + """.gitattributes must be present at the repository root.""" + attrs = _REPO_ROOT / ".gitattributes" + assert attrs.exists(), ".gitattributes missing from repository root" + + +def test_gitattributes_marks_mermaid_binary() -> None: + """.gitattributes must contain a binary rule covering mermaid.min.js.""" + content = (_REPO_ROOT / ".gitattributes").read_text() + # The rule may use a glob (assets/**/*.js) or the explicit path — + # either form is valid as long as 'mermaid' and 'binary' both appear. + assert "mermaid" in content or "assets" in content, ( + ".gitattributes must reference 'mermaid' or 'assets' for the binary rule" + ) + assert "binary" in content, ( + ".gitattributes must contain the 'binary' attribute to suppress git diff" + ) diff --git a/tests/infra/test_hook_executability.py b/tests/infra/test_hook_executability.py index d57bc09331..97a8d87190 100644 --- a/tests/infra/test_hook_executability.py +++ b/tests/infra/test_hook_executability.py @@ -11,6 +11,7 @@ import shlex import subprocess import sys +from pathlib import Path import pytest @@ -70,29 +71,23 @@ def test_hook_registry_matches_generated_hooks_json() -> None: assert registry_pairs == generated_pairs -def test_hooks_json_on_disk_exists_and_matches() -> None: - """hooks.json on disk must exist and match generate_hooks_json() exactly. +def test_committed_registry_hash_matches_live_registry() -> None: + """registry.sha256 (committed) must match the live HOOK_REGISTRY_HASH. - This test fails when the generation step has not been run. It guards - against drift between HOOK_REGISTRY and the on-disk plugin manifest. + Fails when HOOK_REGISTRY is edited without running `task sync-hooks-hash`. + Unlike the old byte-equality test, this cannot be silenced by CI pre-regen + because the anchor is committed. """ - hooks_json_path = pkg_root() / "hooks" / "hooks.json" - assert hooks_json_path.exists(), ( - "src/autoskillit/hooks/hooks.json is missing. " - 'Run: uv run python -c "' - "from autoskillit.hooks import generate_hooks_json; " - "from autoskillit.core.io import atomic_write; " - "from autoskillit.core.paths import pkg_root; " - "import json; " - "atomic_write(pkg_root() / 'hooks' / 'hooks.json', " - "json.dumps(generate_hooks_json(), indent=2) + chr(10))" - '"' + from autoskillit.hook_registry import HOOK_REGISTRY_HASH, HOOKS_DIR + + sha_file = HOOKS_DIR / "registry.sha256" + assert sha_file.exists(), ( + "src/autoskillit/hooks/registry.sha256 is missing. " + "Run `task sync-hooks-hash` and commit the result." ) - on_disk = json.loads(hooks_json_path.read_text()) - expected = generate_hooks_json() - assert on_disk == expected, ( - "hooks.json on disk does not match generate_hooks_json(). " - "Re-run the generation command to regenerate." + committed = sha_file.read_text().strip() + assert committed == HOOK_REGISTRY_HASH, ( + "registry.sha256 is stale. Run `task sync-hooks-hash` and commit the result." ) @@ -117,3 +112,65 @@ def test_generate_hooks_json_session_start_no_matcher() -> None: assert session_start_entries, "hooks.json must include SessionStart" for entry in session_start_entries: assert "matcher" not in entry, "SessionStart entries must not have a matcher key" + + +# T-CROSS-2 +def test_generate_hooks_json_and_sync_produce_equivalent_entries(tmp_path) -> None: + """Both generation paths must produce structurally identical hook entries + for every event type. Verifies that _build_hook_entry() is shared, + preventing path A/B divergence. + """ + from autoskillit.cli._hooks import _evict_stale_autoskillit_hooks, sync_hooks_to_settings + + settings = tmp_path / ".claude" / "settings.json" + settings.parent.mkdir() + settings.write_text('{"hooks": {}}') + _evict_stale_autoskillit_hooks(settings) + sync_hooks_to_settings(settings) + deployed = json.loads(settings.read_text()) + + canonical = generate_hooks_json() + + for event_type in ("PreToolUse", "PostToolUse", "SessionStart"): + canonical_entries = canonical.get("hooks", {}).get(event_type, []) + deployed_entries = deployed.get("hooks", {}).get(event_type, []) + assert len(canonical_entries) == len(deployed_entries), ( + f"{event_type}: canonical has {len(canonical_entries)} entries, " + f"deployed has {len(deployed_entries)}" + ) + for i, (c_entry, d_entry) in enumerate(zip(canonical_entries, deployed_entries)): + assert set(c_entry.keys()) == set(d_entry.keys()), ( + f"{event_type}[{i}]: key mismatch. " + f"canonical keys={set(c_entry.keys())}, " + f"deployed keys={set(d_entry.keys())}" + ) + if "matcher" in c_entry: + assert c_entry["matcher"] == d_entry["matcher"], ( + f"{event_type}[{i}]: matcher mismatch" + ) + + +def test_generated_hooks_json_includes_ask_user_question_gate() -> None: + from autoskillit.hook_registry import generate_hooks_json + + h = generate_hooks_json() + pretool = h["hooks"].get("PreToolUse", []) + matchers = [entry["matcher"] for entry in pretool] + assert "AskUserQuestion" in matchers + + +def test_generated_hooks_json_embeds_registry_hash() -> None: + from autoskillit.hook_registry import HOOK_REGISTRY_HASH, generate_hooks_json + + h = generate_hooks_json() + assert h.get("_autoskillit_registry_hash") == HOOK_REGISTRY_HASH + + +def test_synced_settings_json_embeds_registry_hash(tmp_path: Path) -> None: + from autoskillit.cli._hooks import sync_hooks_to_settings + from autoskillit.hook_registry import HOOK_REGISTRY_HASH + + settings_path = tmp_path / "settings.json" + sync_hooks_to_settings(settings_path) + data = json.loads(settings_path.read_text()) + assert data.get("_autoskillit_registry_hash") == HOOK_REGISTRY_HASH diff --git a/tests/infra/test_hook_registration_coverage.py b/tests/infra/test_hook_registration_coverage.py index 374033f189..0d9d0b131c 100644 --- a/tests/infra/test_hook_registration_coverage.py +++ b/tests/infra/test_hook_registration_coverage.py @@ -8,7 +8,13 @@ def test_all_pretooluse_hook_scripts_are_registered() -> None: - """Every hook .py (excl. PostToolUse, SessionStart, __init__) is PreToolUse-registered.""" + """Every hook .py (excl. PostToolUse, SessionStart, __init__, private helpers) + is PreToolUse-registered. + + Underscore-prefixed modules (e.g. ``_fmt_primitives.py``) are private helper + modules imported by hook scripts, not standalone hook scripts themselves, and + are excluded from registration coverage. + """ post_or_session_registered = { script for hd in HOOK_REGISTRY @@ -18,7 +24,9 @@ def test_all_pretooluse_hook_scripts_are_registered() -> None: hook_files = { f.name for f in HOOKS_DIR.glob("*.py") - if f.name != "__init__.py" and f.name not in post_or_session_registered + if f.name != "__init__.py" + and not f.name.startswith("_") + and f.name not in post_or_session_registered } registered_scripts: set[str] = set() for hook_def in HOOK_REGISTRY: @@ -39,7 +47,11 @@ def test_all_posttooluse_hook_scripts_are_registered() -> None: registered_post = { script for hd in HOOK_REGISTRY if hd.event_type == "PostToolUse" for script in hd.scripts } - all_scripts = {p.name for p in HOOKS_DIR.glob("*.py") if p.name != "__init__.py"} + all_scripts = { + p.name + for p in HOOKS_DIR.glob("*.py") + if p.name != "__init__.py" and not p.name.startswith("_") + } pre_registered = { script for hd in HOOK_REGISTRY if hd.event_type == "PreToolUse" for script in hd.scripts } @@ -55,3 +67,102 @@ def test_all_session_start_hook_scripts_are_registered() -> None: } for script in session_scripts: assert (HOOKS_DIR / script).exists(), f"SessionStart script not found: {script}" + + +# T-GUARD-2 +def test_generated_file_write_guard_registered() -> None: + """generated_file_write_guard.py must be registered in HOOK_REGISTRY.""" + all_scripts = {s for h in HOOK_REGISTRY for s in h.scripts} + assert "generated_file_write_guard.py" in all_scripts, ( + "generated_file_write_guard.py must be registered in HOOK_REGISTRY" + ) + + +def test_registry_has_ask_user_question_pre_kitchen_gate(): + from autoskillit.hook_registry import HOOK_REGISTRY + + ask_matchers = [ + h for h in HOOK_REGISTRY if h.event_type == "PreToolUse" and h.matcher == "AskUserQuestion" + ] + assert len(ask_matchers) == 1 + assert ask_matchers[0].scripts == ["ask_user_question_guard.py"] + + +def test_retired_script_basenames_exists_and_complete() -> None: + from autoskillit.hook_registry import RETIRED_SCRIPT_BASENAMES + + required = { + "quota_check.py", + "skill_cmd_check.py", + "quota_post_check.py", + "pretty_output.py", + "token_summary_appender.py", + "session_start_reminder.py", + } + missing = required - set(RETIRED_SCRIPT_BASENAMES) + assert not missing, f"RETIRED_SCRIPT_BASENAMES is missing: {missing}" + + +def test_no_retired_name_has_a_live_file() -> None: + from autoskillit.hook_registry import HOOKS_DIR, RETIRED_SCRIPT_BASENAMES + + for name in RETIRED_SCRIPT_BASENAMES: + assert not (HOOKS_DIR / name).exists(), ( + f"Retired script name '{name}' has a live file at {HOOKS_DIR / name}. " + "Remove the file or remove it from RETIRED_SCRIPT_BASENAMES." + ) + + +def test_is_own_hook_recognizes_retired_basename_orphan() -> None: + from autoskillit.hook_registry import _is_own_hook + + orphan = "python3 /opt/some/cache/pretty_output.py" + assert _is_own_hook(orphan), ( + "_is_own_hook must recognize retired script basenames as autoskillit-owned" + ) + + +def test_hook_registry_hash_is_deterministic() -> None: + from autoskillit.hook_registry import HOOK_REGISTRY_HASH + + assert isinstance(HOOK_REGISTRY_HASH, str) + assert len(HOOK_REGISTRY_HASH) == 64 + + +def test_compute_registry_hash_is_stable_across_invocations() -> None: + from autoskillit.hook_registry import ( + HOOK_REGISTRY, + RETIRED_SCRIPT_BASENAMES, + compute_registry_hash, + ) + + a = compute_registry_hash(HOOK_REGISTRY, RETIRED_SCRIPT_BASENAMES) + b = compute_registry_hash(list(HOOK_REGISTRY), frozenset(RETIRED_SCRIPT_BASENAMES)) + assert a == b + + +def test_hook_registry_hash_changes_on_registry_mutation() -> None: + from autoskillit.hook_registry import ( + HOOK_REGISTRY, + HOOK_REGISTRY_HASH, + RETIRED_SCRIPT_BASENAMES, + HookDef, + compute_registry_hash, + ) + + mutated = list(HOOK_REGISTRY) + [ + HookDef(event_type="PreToolUse", matcher="X", scripts=["x.py"]) + ] + assert compute_registry_hash(mutated, RETIRED_SCRIPT_BASENAMES) != HOOK_REGISTRY_HASH + + +def test_hook_registry_hash_changes_on_retired_mutation() -> None: + from autoskillit.hook_registry import ( + HOOK_REGISTRY, + HOOK_REGISTRY_HASH, + RETIRED_SCRIPT_BASENAMES, + compute_registry_hash, + ) + + mutated_retired = frozenset(RETIRED_SCRIPT_BASENAMES | {"extra_retired.py"}) + assert compute_registry_hash(HOOK_REGISTRY, mutated_retired) != HOOK_REGISTRY_HASH diff --git a/tests/infra/test_hook_settings.py b/tests/infra/test_hook_settings.py new file mode 100644 index 0000000000..3904ac78e7 --- /dev/null +++ b/tests/infra/test_hook_settings.py @@ -0,0 +1,202 @@ +"""Tests for the shared stdlib-only quota hook settings resolver. + +``autoskillit.hooks._hook_settings.resolve_quota_settings()`` resolves cache path, +cache max age, and buffer seconds from a layered hierarchy: + + 1. ``cache_path_override`` parameter (tests / DI) + 2. ``AUTOSKILLIT_QUOTA_GUARD__`` env var + 3. ``.autoskillit/temp/.hook_config.json`` snapshot + 4. Module defaults (matching ``config/defaults.yaml``) + +These tests use ``tmp_path`` and ``monkeypatch`` for isolation — no global state. +""" + +from __future__ import annotations + +import json + +_ENV_VARS = ( + "AUTOSKILLIT_QUOTA_GUARD__CACHE_PATH", + "AUTOSKILLIT_QUOTA_GUARD__CACHE_MAX_AGE", + "AUTOSKILLIT_QUOTA_GUARD__BUFFER_SECONDS", +) + + +def _clear_env(monkeypatch): + for name in _ENV_VARS: + monkeypatch.delenv(name, raising=False) + + +def _write_hook_config(tmp_path, quota_guard: dict) -> None: + hook_cfg = tmp_path / ".autoskillit" / "temp" / ".hook_config.json" + hook_cfg.parent.mkdir(parents=True, exist_ok=True) + hook_cfg.write_text(json.dumps({"quota_guard": quota_guard})) + + +# T-HS-1 +def test_resolve_defaults_without_env_or_hook_config(tmp_path, monkeypatch): + """With no env var and no hook config, resolver returns module defaults.""" + from autoskillit.hooks._hook_settings import ( + DEFAULT_BUFFER_SECONDS, + DEFAULT_CACHE_MAX_AGE, + DEFAULT_CACHE_PATH, + resolve_quota_settings, + ) + + monkeypatch.chdir(tmp_path) + _clear_env(monkeypatch) + + settings = resolve_quota_settings() + + assert settings.cache_path == DEFAULT_CACHE_PATH + assert settings.cache_max_age == DEFAULT_CACHE_MAX_AGE + assert settings.buffer_seconds == DEFAULT_BUFFER_SECONDS + + +# T-HS-2 +def test_env_var_overrides_cache_max_age(tmp_path, monkeypatch): + """AUTOSKILLIT_QUOTA_GUARD__CACHE_MAX_AGE env var sets cache_max_age.""" + from autoskillit.hooks._hook_settings import resolve_quota_settings + + monkeypatch.chdir(tmp_path) + _clear_env(monkeypatch) + monkeypatch.setenv("AUTOSKILLIT_QUOTA_GUARD__CACHE_MAX_AGE", "600") + + settings = resolve_quota_settings() + + assert settings.cache_max_age == 600 + + +# T-HS-3 +def test_env_var_overrides_cache_path(tmp_path, monkeypatch): + """AUTOSKILLIT_QUOTA_GUARD__CACHE_PATH env var sets cache_path.""" + from autoskillit.hooks._hook_settings import resolve_quota_settings + + monkeypatch.chdir(tmp_path) + _clear_env(monkeypatch) + monkeypatch.setenv("AUTOSKILLIT_QUOTA_GUARD__CACHE_PATH", "/custom/path.json") + + settings = resolve_quota_settings() + + assert settings.cache_path == "/custom/path.json" + + +# T-HS-4 +def test_env_var_overrides_buffer_seconds(tmp_path, monkeypatch): + """AUTOSKILLIT_QUOTA_GUARD__BUFFER_SECONDS env var sets buffer_seconds.""" + from autoskillit.hooks._hook_settings import resolve_quota_settings + + monkeypatch.chdir(tmp_path) + _clear_env(monkeypatch) + monkeypatch.setenv("AUTOSKILLIT_QUOTA_GUARD__BUFFER_SECONDS", "120") + + settings = resolve_quota_settings() + + assert settings.buffer_seconds == 120 + + +# T-HS-5 +def test_hook_config_overrides_defaults(tmp_path, monkeypatch): + """Hook config snapshot overrides module defaults when env vars are unset.""" + from autoskillit.hooks._hook_settings import resolve_quota_settings + + monkeypatch.chdir(tmp_path) + _clear_env(monkeypatch) + _write_hook_config( + tmp_path, + { + "cache_max_age": 600, + "cache_path": "/bridge/cache.json", + "buffer_seconds": 90, + }, + ) + + settings = resolve_quota_settings() + + assert settings.cache_max_age == 600 + assert settings.cache_path == "/bridge/cache.json" + assert settings.buffer_seconds == 90 + + +# T-HS-6 +def test_env_var_beats_hook_config(tmp_path, monkeypatch): + """Env var takes precedence over hook config snapshot.""" + from autoskillit.hooks._hook_settings import resolve_quota_settings + + monkeypatch.chdir(tmp_path) + _clear_env(monkeypatch) + _write_hook_config( + tmp_path, + { + "cache_max_age": 600, + "cache_path": "/bridge/cache.json", + "buffer_seconds": 90, + }, + ) + monkeypatch.setenv("AUTOSKILLIT_QUOTA_GUARD__CACHE_MAX_AGE", "900") + monkeypatch.setenv("AUTOSKILLIT_QUOTA_GUARD__CACHE_PATH", "/env/cache.json") + monkeypatch.setenv("AUTOSKILLIT_QUOTA_GUARD__BUFFER_SECONDS", "300") + + settings = resolve_quota_settings() + + assert settings.cache_max_age == 900 + assert settings.cache_path == "/env/cache.json" + assert settings.buffer_seconds == 300 + + +# T-HS-7 +def test_cache_path_override_parameter_beats_all(tmp_path, monkeypatch): + """``cache_path_override`` parameter wins over env var and hook config.""" + from autoskillit.hooks._hook_settings import resolve_quota_settings + + monkeypatch.chdir(tmp_path) + _clear_env(monkeypatch) + _write_hook_config(tmp_path, {"cache_path": "/bridge/cache.json"}) + monkeypatch.setenv("AUTOSKILLIT_QUOTA_GUARD__CACHE_PATH", "/env/cache.json") + + settings = resolve_quota_settings(cache_path_override="/test.json") + + assert settings.cache_path == "/test.json" + + +# T-HS-8 +def test_invalid_env_var_falls_through(tmp_path, monkeypatch): + """Non-numeric env var values fall through to hook config / default.""" + from autoskillit.hooks._hook_settings import ( + DEFAULT_BUFFER_SECONDS, + resolve_quota_settings, + ) + + monkeypatch.chdir(tmp_path) + _clear_env(monkeypatch) + monkeypatch.setenv("AUTOSKILLIT_QUOTA_GUARD__CACHE_MAX_AGE", "not-a-number") + _write_hook_config(tmp_path, {"cache_max_age": 450}) + + settings = resolve_quota_settings() + + # Invalid env var → falls through to hook config (450) + assert settings.cache_max_age == 450 + # buffer_seconds has neither env var nor hook config → default + assert settings.buffer_seconds == DEFAULT_BUFFER_SECONDS + + +# T-HS-9 +def test_defaults_match_defaults_yaml(): + """Module default constants must match ``config/defaults.yaml`` exactly. + + Structural guard against drift between the stdlib-only hook module and the + canonical dynaconf-loaded settings layer. + """ + from autoskillit.core import load_yaml, pkg_root + from autoskillit.hooks._hook_settings import ( + DEFAULT_BUFFER_SECONDS, + DEFAULT_CACHE_MAX_AGE, + DEFAULT_CACHE_PATH, + ) + + defaults = load_yaml(pkg_root() / "config" / "defaults.yaml") + assert isinstance(defaults, dict) + quota_guard = defaults["quota_guard"] + assert DEFAULT_CACHE_PATH == quota_guard["cache_path"] + assert DEFAULT_CACHE_MAX_AGE == quota_guard["cache_max_age"] + assert DEFAULT_BUFFER_SECONDS == quota_guard["buffer_seconds"] diff --git a/tests/infra/test_hook_sync.py b/tests/infra/test_hook_sync.py index 4e4917219d..1c5b867f65 100644 --- a/tests/infra/test_hook_sync.py +++ b/tests/infra/test_hook_sync.py @@ -12,7 +12,7 @@ def test_hook_config_path_components_in_sync(): Both scripts must address the same config file. This test guards against independent evolution of the two constant sets. """ - from autoskillit.hooks.pretty_output import _HOOK_CONFIG_PATH_COMPONENTS + from autoskillit.hooks.pretty_output_hook import _HOOK_CONFIG_PATH_COMPONENTS from autoskillit.server.helpers import _HOOK_CONFIG_FILENAME, _HOOK_DIR_COMPONENTS path_from_pretty = Path(*_HOOK_CONFIG_PATH_COMPONENTS) @@ -24,3 +24,19 @@ def test_hook_config_path_components_in_sync(): f" server/helpers: {path_from_helpers}\n" "Update the constants to point to the same file." ) + + +def test_hook_config_path_single_source_of_truth(): + """_hook_settings must define path constants that match _fmt_primitives. + + After consolidation, quota_guard and quota_post_hook both delegate to + _hook_settings for config path resolution. This test verifies that + _hook_settings.HOOK_DIR_COMPONENTS + HOOK_CONFIG_FILENAME reconstructs + _fmt_primitives._HOOK_CONFIG_PATH_COMPONENTS exactly. + """ + from autoskillit.hooks._fmt_primitives import _HOOK_CONFIG_PATH_COMPONENTS + from autoskillit.hooks._hook_settings import HOOK_CONFIG_FILENAME, HOOK_DIR_COMPONENTS + + assert (*HOOK_DIR_COMPONENTS, HOOK_CONFIG_FILENAME) == _HOOK_CONFIG_PATH_COMPONENTS, ( + "_hook_settings path constants must match _fmt_primitives._HOOK_CONFIG_PATH_COMPONENTS" + ) diff --git a/tests/infra/test_open_kitchen_guard.py b/tests/infra/test_open_kitchen_guard.py index 1b8c573a38..19ca2a6a9c 100644 --- a/tests/infra/test_open_kitchen_guard.py +++ b/tests/infra/test_open_kitchen_guard.py @@ -6,6 +6,7 @@ import os import subprocess import sys +from pathlib import Path from autoskillit.core.paths import pkg_root @@ -47,3 +48,60 @@ def test_open_kitchen_guard_allows_human_session() -> None: assert not result.stdout.strip(), ( f"Hook must emit no output for non-headless sessions, got: {result.stdout!r}" ) + + +def test_open_kitchen_guard_writes_marker_on_permit(tmp_path: Path, monkeypatch) -> None: + monkeypatch.setenv("AUTOSKILLIT_STATE_DIR", str(tmp_path)) + monkeypatch.delenv("AUTOSKILLIT_HEADLESS", raising=False) + hook_input = { + "tool_name": "mcp__autoskillit__open_kitchen", + "tool_input": {"name": "my_recipe"}, + "session_id": "session-abc", + "hook_event_name": "PreToolUse", + } + hook_path = pkg_root() / "hooks" / "open_kitchen_guard.py" + env = {k: v for k, v in os.environ.items() if k != "AUTOSKILLIT_HEADLESS"} + env["AUTOSKILLIT_STATE_DIR"] = str(tmp_path) + result = subprocess.run( + [sys.executable, str(hook_path)], + input=json.dumps(hook_input), + capture_output=True, + text=True, + env=env, + ) + assert result.returncode == 0 + if result.stdout.strip(): + payload = json.loads(result.stdout) + hook_out = payload.get("hookSpecificOutput", {}) + assert hook_out.get("permissionDecision") != "deny" + marker_path = tmp_path / "kitchen_state" / "session-abc.json" + assert marker_path.exists(), f"Marker not written at {marker_path}" + data = json.loads(marker_path.read_text()) + assert data["session_id"] == "session-abc" + assert data["recipe_name"] == "my_recipe" + assert data["marker_version"] == 1 + + +def test_open_kitchen_guard_no_marker_on_deny(tmp_path: Path, monkeypatch) -> None: + """When headless, the guard denies; no marker should be written.""" + monkeypatch.setenv("AUTOSKILLIT_STATE_DIR", str(tmp_path)) + hook_path = pkg_root() / "hooks" / "open_kitchen_guard.py" + env = {**os.environ, "AUTOSKILLIT_HEADLESS": "1", "AUTOSKILLIT_STATE_DIR": str(tmp_path)} + result = subprocess.run( + [sys.executable, str(hook_path)], + input=json.dumps( + { + "tool_name": "mcp__autoskillit__open_kitchen", + "tool_input": {"name": "my_recipe"}, + "session_id": "session-abc", + "hook_event_name": "PreToolUse", + } + ), + capture_output=True, + text=True, + env=env, + ) + assert result.returncode == 0 + payload = json.loads(result.stdout) + assert payload["hookSpecificOutput"]["permissionDecision"] == "deny" + assert not (tmp_path / "kitchen_state" / "session-abc.json").exists() diff --git a/tests/infra/test_pretty_output.py b/tests/infra/test_pretty_output.py index 552f696967..87373758ed 100644 --- a/tests/infra/test_pretty_output.py +++ b/tests/infra/test_pretty_output.py @@ -14,7 +14,8 @@ from autoskillit.core.types import ChannelConfirmation, TerminationReason from autoskillit.execution.headless import _build_skill_result -from autoskillit.hooks.pretty_output import _format_response +from autoskillit.hooks._fmt_primitives import _HOOK_CONFIG_PATH_COMPONENTS +from autoskillit.hooks.pretty_output_hook import _format_response from tests.conftest import _make_result # Realistic recipe YAML that mirrors actual bundled recipes. @@ -52,7 +53,7 @@ def _run_hook( Returns (stdout_output, exit_code). """ - from autoskillit.hooks.pretty_output import main + from autoskillit.hooks.pretty_output_hook import main stdin_text = raw_stdin if raw_stdin is not None else json.dumps(event or {}) @@ -64,7 +65,7 @@ def _run_hook( stack.enter_context(redirect_stdout(buf)) if cwd is not None: stack.enter_context( - patch("autoskillit.hooks.pretty_output.Path.cwd", return_value=cwd) + patch("autoskillit.hooks.pretty_output_hook.Path.cwd", return_value=cwd) ) try: main() @@ -112,7 +113,7 @@ def test_hook_script_exists(): """pretty_output.py must exist in the hooks directory.""" from autoskillit.core.paths import pkg_root - assert (pkg_root() / "hooks" / "pretty_output.py").exists() + assert (pkg_root() / "hooks" / "pretty_output_hook.py").exists() # PHK-2 @@ -248,7 +249,7 @@ def test_format_test_check_pass(): """test_check pass must show tool name, checkmark, PASS, passed: True.""" event = { "tool_name": "mcp__plugin_autoskillit_autoskillit__test_check", - "tool_response": json.dumps({"passed": True, "output": "...245 passed..."}), + "tool_response": json.dumps({"passed": True, "stdout": "...245 passed..."}), } out, _ = _run_hook(event=event) text = json.loads(out)["hookSpecificOutput"]["updatedMCPToolOutput"] @@ -272,7 +273,7 @@ def test_format_test_check_fail_shows_failure_lines(): ) event = { "tool_name": "mcp__plugin_autoskillit_autoskillit__test_check", - "tool_response": json.dumps({"passed": False, "output": pytest_output}), + "tool_response": json.dumps({"passed": False, "stdout": pytest_output}), } out, _ = _run_hook(event=event) text = json.loads(out)["hookSpecificOutput"]["updatedMCPToolOutput"] @@ -376,13 +377,14 @@ def test_format_get_token_summary_compact(): out, _ = _run_hook(event=event) text = json.loads(out)["hookSpecificOutput"]["updatedMCPToolOutput"] assert "token_summary" in text - # Assert specific compact line format: name xN [in:Xk out:Xk cached:XM t:Xs] - assert "investigate x1 [in:45.2k out:12.8k cached:1.2M t:0.0s]" in text - assert "make_plan x2 [in:30.0k out:8.0k cached:500.0k t:0.0s]" in text - assert "implement x1 [in:60.0k out:15.0k cached:2.0M t:0.0s]" in text - assert "total_in:" in text + # Assert specific compact line format: name xN [uc:Xk out:Xk cr:XM cw:XM t:Xs] + assert "investigate x1 [uc:45.2k out:12.8k cr:1.2M cw:0 t:0.0s]" in text + assert "make_plan x2 [uc:30.0k out:8.0k cr:0 cw:500.0k t:0.0s]" in text + assert "implement x1 [uc:60.0k out:15.0k cr:2.0M cw:0 t:0.0s]" in text + assert "total_uncached:" in text assert "total_out:" in text - assert "total_cached:" in text + assert "total_cache_read:" in text + assert "total_cache_write:" in text # PHK-16 @@ -414,9 +416,9 @@ def test_format_kitchen_status(): def test_pipeline_mode_compact_run_skill(tmp_path): """In pipeline mode (hook config present), run_skill output uses compact format.""" # Create the hook config file to signal pipeline mode - config_dir = tmp_path / ".autoskillit" / "temp" - config_dir.mkdir(parents=True) - (config_dir / ".autoskillit_hook_config.json").write_text('{"quota_guard": {}}') + config_path = tmp_path.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS) + config_path.parent.mkdir(parents=True, exist_ok=True) + config_path.write_text('{"quota_guard": {}}') event = _make_run_skill_event(success=False, needs_retry=True, retry_reason="budget_exhausted") @@ -591,9 +593,9 @@ def test_fmt_merge_worktree_dirty_tree_shows_files(): # PHK-26 def test_fmt_run_skill_pipeline_includes_stderr(tmp_path): """run_skill pipeline mode must include stderr.""" - config_dir = tmp_path / ".autoskillit" / "temp" - config_dir.mkdir(parents=True) - (config_dir / ".autoskillit_hook_config.json").write_text('{"quota_guard": {}}') + config_path = tmp_path.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS) + config_path.parent.mkdir(parents=True, exist_ok=True) + config_path.write_text('{"quota_guard": {}}') event = _make_run_skill_event( success=False, @@ -1055,7 +1057,7 @@ def test_formatter_coverage_contract(): formatters, and forces an explicit choice when adding new tools. """ from autoskillit.core.types import GATED_TOOLS, UNGATED_TOOLS - from autoskillit.hooks.pretty_output import _FORMATTERS, _UNFORMATTED_TOOLS + from autoskillit.hooks.pretty_output_hook import _FORMATTERS, _UNFORMATTED_TOOLS all_tools = GATED_TOOLS | UNGATED_TOOLS covered = set(_FORMATTERS.keys()) | _UNFORMATTED_TOOLS @@ -1221,7 +1223,7 @@ def test_fmt_generic_list_of_dicts_caps_at_20_items(): def test_hook_token_summary_output_equivalent_to_canonical(): """1g: Hook inline _fmt_get_token_summary produces identical output to TelemetryFormatter.format_compact_kv for the same input data.""" - from autoskillit.hooks.pretty_output import _fmt_get_token_summary + from autoskillit.hooks.pretty_output_hook import _fmt_get_token_summary from autoskillit.pipeline.telemetry_fmt import TelemetryFormatter data = { @@ -1270,6 +1272,60 @@ def test_hook_token_summary_output_equivalent_to_canonical(): ) +def test_fmt_run_skill_interactive_shows_four_token_fields(): + """_fmt_run_skill interactive mode shows all 4 token fields.""" + data = { + "success": True, + "subtype": "COMPLETED", + "exit_code": 0, + "needs_retry": False, + "result": "done", + "token_usage": { + "input_tokens": 5000, + "output_tokens": 3000, + "cache_read_input_tokens": 200000, + "cache_creation_input_tokens": 8000, + }, + } + rendered = _format_response( + "mcp__plugin_autoskillit_autoskillit__run_skill", + json.dumps({"result": json.dumps(data)}), + pipeline=False, + ) + assert rendered is not None + assert "tokens_uncached:" in rendered + assert "tokens_out:" in rendered + assert "tokens_cache_read:" in rendered + assert "tokens_cache_write:" in rendered + + +def test_fmt_run_skill_suppresses_zero_cache_fields(): + """_fmt_run_skill suppresses tokens_cache_read and tokens_cache_write when both are 0.""" + data = { + "success": True, + "subtype": "COMPLETED", + "exit_code": 0, + "needs_retry": False, + "result": "done", + "token_usage": { + "input_tokens": 5000, + "output_tokens": 3000, + "cache_read_input_tokens": 0, + "cache_creation_input_tokens": 0, + }, + } + rendered = _format_response( + "mcp__plugin_autoskillit_autoskillit__run_skill", + json.dumps({"result": json.dumps(data)}), + pipeline=False, + ) + assert rendered is not None + assert "tokens_uncached:" in rendered + assert "tokens_out:" in rendered + assert "tokens_cache_read:" not in rendered + assert "tokens_cache_write:" not in rendered + + # --------------------------------------------------------------------------- # Timing summary dedicated formatter # --------------------------------------------------------------------------- @@ -1369,7 +1425,7 @@ def test_fmt_run_skill_contradictory_subtype_never_renders_fail_success(): def test_fmt_load_recipe_field_coverage(): """Every LoadRecipeResult field must be in RENDERED or SUPPRESSED.""" - from autoskillit.hooks.pretty_output import ( + from autoskillit.hooks.pretty_output_hook import ( _FMT_LOAD_RECIPE_RENDERED, _FMT_LOAD_RECIPE_SUPPRESSED, ) @@ -1391,7 +1447,7 @@ def test_fmt_load_recipe_field_coverage(): def test_fmt_load_recipe_derivation_map_coverage(): """Every key/value in _LOAD_RECIPE_CONTENT_DERIVED_FROM must be in _FMT_LOAD_RECIPE_RENDERED. Catches when a new derived field is added without declaring its source relationship.""" - from autoskillit.hooks.pretty_output import ( + from autoskillit.hooks.pretty_output_hook import ( _FMT_LOAD_RECIPE_RENDERED, _LOAD_RECIPE_CONTENT_DERIVED_FROM, ) @@ -1463,7 +1519,7 @@ def test_fmt_load_recipe_suppresses_greeting(): def test_fmt_list_recipes_field_coverage(): """Every ListRecipesResult field must be in RENDERED or SUPPRESSED.""" - from autoskillit.hooks.pretty_output import ( + from autoskillit.hooks.pretty_output_hook import ( _FMT_LIST_RECIPES_RENDERED, _FMT_LIST_RECIPES_SUPPRESSED, ) @@ -1484,7 +1540,7 @@ def test_fmt_list_recipes_field_coverage(): def test_fmt_recipe_list_item_field_coverage(): """Every RecipeListItem field must be in RENDERED or SUPPRESSED.""" - from autoskillit.hooks.pretty_output import ( + from autoskillit.hooks.pretty_output_hook import ( _FMT_RECIPE_LIST_ITEM_RENDERED, _FMT_RECIPE_LIST_ITEM_SUPPRESSED, ) @@ -1585,7 +1641,7 @@ def test_wrap_plain_str_helper_produces_correct_shape(): def test_unformatted_tools_and_formatters_are_disjoint(): """_UNFORMATTED_TOOLS and _FORMATTERS must be mutually exclusive.""" - from autoskillit.hooks.pretty_output import _FORMATTERS, _UNFORMATTED_TOOLS + from autoskillit.hooks.pretty_output_hook import _FORMATTERS, _UNFORMATTED_TOOLS overlap = set(_FORMATTERS) & _UNFORMATTED_TOOLS assert not overlap, f"Tools in both dispatch tables: {overlap}" @@ -1615,7 +1671,7 @@ def test_fmt_recipe_body_ingredients_not_duplicated_when_table_present(): """When ingredients_table is present, ingredient names must not appear in the --- RECIPE --- section. This is the canonical test for the raw/derived field duplication bug.""" - from autoskillit.hooks.pretty_output import _fmt_recipe_body + from autoskillit.hooks.pretty_output_hook import _fmt_recipe_body data = { "content": REALISTIC_RECIPE_YAML, @@ -1647,7 +1703,7 @@ def test_fmt_recipe_body_ingredients_not_duplicated_when_table_present(): def test_strip_yaml_ingredients_block_removes_ingredients_section(): - from autoskillit.hooks.pretty_output import _strip_yaml_ingredients_block + from autoskillit.hooks.pretty_output_hook import _strip_yaml_ingredients_block yaml = "name: test\ningredients:\n task:\n description: a task\nsteps:\n do: {}\n" result = _strip_yaml_ingredients_block(yaml) @@ -1658,7 +1714,7 @@ def test_strip_yaml_ingredients_block_removes_ingredients_section(): def test_strip_yaml_ingredients_block_noop_when_no_ingredients_key(): - from autoskillit.hooks.pretty_output import _strip_yaml_ingredients_block + from autoskillit.hooks.pretty_output_hook import _strip_yaml_ingredients_block yaml = "name: test\nsteps:\n do: {}\n" result = _strip_yaml_ingredients_block(yaml) @@ -1666,7 +1722,7 @@ def test_strip_yaml_ingredients_block_noop_when_no_ingredients_key(): def test_strip_yaml_ingredients_block_at_end_of_file(): - from autoskillit.hooks.pretty_output import _strip_yaml_ingredients_block + from autoskillit.hooks.pretty_output_hook import _strip_yaml_ingredients_block yaml = "name: test\nsteps:\n do: {}\ningredients:\n foo:\n description: bar\n" result = _strip_yaml_ingredients_block(yaml) @@ -1675,7 +1731,7 @@ def test_strip_yaml_ingredients_block_at_end_of_file(): def test_strip_yaml_ingredients_block_multiline_description(): - from autoskillit.hooks.pretty_output import _strip_yaml_ingredients_block + from autoskillit.hooks.pretty_output_hook import _strip_yaml_ingredients_block yaml = ( "name: test\n" @@ -1695,7 +1751,7 @@ def test_strip_yaml_ingredients_block_multiline_description(): def test_fmt_open_kitchen_ingredients_not_duplicated_when_table_present(): """open_kitchen routes through _fmt_recipe_body — verify same deduplication applies.""" - from autoskillit.hooks.pretty_output import _fmt_open_kitchen + from autoskillit.hooks.pretty_output_hook import _fmt_open_kitchen data = { "content": REALISTIC_RECIPE_YAML, @@ -1714,3 +1770,102 @@ def test_fmt_open_kitchen_ingredients_not_duplicated_when_table_present(): recipe_section = result.split("--- INGREDIENTS TABLE")[0] assert " task:" not in recipe_section assert "review_approach:" not in recipe_section + + +def test_pretty_output_public_surface_unchanged() -> None: + """T-5 (audit finding 8.3): the hook entrypoint and the format router are + the only public surface; the four-way split must preserve them.""" + import autoskillit.hooks.pretty_output_hook as p + + assert callable(p.main) + assert callable(p._format_response) + + +# PHK-kill-reason: formatter branches on kill_reason (1e) + + +def test_fmt_run_skill_success_with_kill_after_completion_annotates_exit_code() -> None: + """kill_reason=kill_after_completion must annotate exit_code line.""" + from autoskillit.hooks._fmt_execution import _fmt_run_skill + + data = { + "success": True, + "result": "Implementation complete.", + "session_id": "abc123", + "subtype": "end_turn", + "is_error": False, + "exit_code": -9, + "kill_reason": "kill_after_completion", + "needs_retry": False, + "retry_reason": "none", + "stderr": "", + } + text = _fmt_run_skill(data, pipeline=False) + assert "exit_code: -9 (infra-terminated after completion" in text, ( + f"Expected kill_after_completion annotation in exit_code line, got: {text!r}" + ) + + +def test_fmt_run_skill_success_with_natural_exit_shows_bare_exit_code() -> None: + """kill_reason=natural_exit must render bare exit_code without annotation.""" + from autoskillit.hooks._fmt_execution import _fmt_run_skill + + data = { + "success": True, + "result": "Done.", + "session_id": "abc123", + "subtype": "end_turn", + "is_error": False, + "exit_code": 0, + "kill_reason": "natural_exit", + "needs_retry": False, + "retry_reason": "none", + "stderr": "", + } + text = _fmt_run_skill(data, pipeline=False) + assert "exit_code: 0" in text + assert "infra-terminated" not in text + assert "infra-killed" not in text + + +def test_fmt_run_skill_infra_kill_annotates_reason() -> None: + """kill_reason=infra_kill must annotate exit_code with infra-killed.""" + from autoskillit.hooks._fmt_execution import _fmt_run_skill + + data = { + "success": False, + "result": "", + "session_id": "abc123", + "subtype": "timeout", + "is_error": True, + "exit_code": -9, + "kill_reason": "infra_kill", + "needs_retry": False, + "retry_reason": "none", + "stderr": "", + } + text = _fmt_run_skill(data, pipeline=False) + assert "infra-killed" in text, ( + f"Expected 'infra-killed' annotation for infra_kill reason, got: {text!r}" + ) + + +def test_fmt_run_skill_legacy_payload_without_kill_reason_renders_bare() -> None: + """Payload without kill_reason field must render bare exit_code (backward compat).""" + from autoskillit.hooks._fmt_execution import _fmt_run_skill + + data = { + "success": True, + "result": "Done.", + "session_id": "abc123", + "subtype": "end_turn", + "is_error": False, + "exit_code": 0, + # no kill_reason key + "needs_retry": False, + "retry_reason": "none", + "stderr": "", + } + text = _fmt_run_skill(data, pipeline=False) + assert "exit_code: 0" in text + assert "infra" not in text diff --git a/tests/infra/test_pretty_output_integration.py b/tests/infra/test_pretty_output_integration.py index ee9e20abe1..215dccff15 100644 --- a/tests/infra/test_pretty_output_integration.py +++ b/tests/infra/test_pretty_output_integration.py @@ -28,7 +28,7 @@ class TestFormatterSchemaConsistency: @pytest.mark.anyio async def test_list_recipes_tool_output_through_hook(self, tool_ctx): """PHK-E1: list_recipes real output contains all recipe names through hook.""" - from autoskillit.hooks.pretty_output import _format_response + from autoskillit.hooks.pretty_output_hook import _format_response from autoskillit.server.tools_recipe import list_recipes result_json = await list_recipes() @@ -43,7 +43,7 @@ async def test_list_recipes_tool_output_through_hook(self, tool_ctx): @pytest.mark.anyio async def test_kitchen_status_tool_output_through_hook(self, tool_ctx): """PHK-E2: kitchen_status real output contains all key fields through hook.""" - from autoskillit.hooks.pretty_output import _format_response + from autoskillit.hooks.pretty_output_hook import _format_response from autoskillit.server.tools_status import kitchen_status result_json = await kitchen_status() @@ -58,7 +58,7 @@ async def test_kitchen_status_tool_output_through_hook(self, tool_ctx): @pytest.mark.anyio async def test_integration_get_token_summary_table_not_eaten(self, tool_ctx): """T-6: Real get_token_summary(format='table') response must survive _format_response.""" - from autoskillit.hooks.pretty_output import _format_response + from autoskillit.hooks.pretty_output_hook import _format_response from autoskillit.pipeline.telemetry_fmt import TelemetryFormatter # Simulate what the real tool handler returns for format="table" diff --git a/tests/infra/test_pyproject_metadata.py b/tests/infra/test_pyproject_metadata.py index 37004d7bae..ac55a09d86 100644 --- a/tests/infra/test_pyproject_metadata.py +++ b/tests/infra/test_pyproject_metadata.py @@ -36,3 +36,11 @@ def test_pyproject_has_sdist_target(): data.get("tool", {}).get("hatch", {}).get("build", {}).get("targets", {}).get("sdist", {}) ) assert "include" in sdist, "[tool.hatch.build.targets.sdist] must list included paths" + + +def test_markdown_it_py_in_dependencies() -> None: + """REQ-R741-A05 — markdown-it-py must be a declared runtime dependency.""" + deps: list[str] = _project()["project"]["dependencies"] + assert any("markdown-it-py" in d for d in deps), ( + "markdown-it-py not found in [project].dependencies in pyproject.toml" + ) diff --git a/tests/infra/test_quota_check.py b/tests/infra/test_quota_check.py index 75436d9138..cb7777a19c 100644 --- a/tests/infra/test_quota_check.py +++ b/tests/infra/test_quota_check.py @@ -1,24 +1,57 @@ """Tests for the quota_check PreToolUse hook. -The hook reads a local quota cache file and denies run_skill when utilization -exceeds the threshold. It fails open when the cache is missing/stale/corrupt. +The hook reads a local quota cache file and denies run_skill when the cached +binding marks ``should_block=True``. It fails open when the cache is +missing/stale/corrupt. """ import io import json from contextlib import redirect_stdout -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from pathlib import Path from unittest.mock import patch +from autoskillit.hooks._fmt_primitives import _HOOK_CONFIG_PATH_COMPONENTS -def _write_cache(cache_path: Path, utilization: float, resets_at: str | None = None) -> None: - """Write a fresh quota cache file.""" +_LONG_PATTERNS = ("weekly", "sonnet", "opus") + + +def _classify_threshold(window_name: str) -> float: + lowered = window_name.lower() + return 98.0 if any(p in lowered for p in _LONG_PATTERNS) else 85.0 + + +def _write_cache( + cache_path: Path, + utilization: float, + resets_at: str | None = None, + window_name: str = "five_hour", + extra_windows: dict | None = None, + should_block: bool | None = None, + effective_threshold: float | None = None, +) -> None: + """Write a fresh quota cache file in the full-snapshot format. + + When ``should_block`` is None, classifies the window via the default + long-window patterns and computes ``should_block`` from utilization. + """ + if effective_threshold is None: + effective_threshold = _classify_threshold(window_name) + if should_block is None: + should_block = utilization >= effective_threshold + windows = {window_name: {"utilization": utilization, "resets_at": resets_at}} + if extra_windows: + windows.update(extra_windows) payload = { "fetched_at": datetime.now(UTC).isoformat(), - "five_hour": { + "windows": windows, + "binding": { + "window_name": window_name, "utilization": utilization, "resets_at": resets_at, + "should_block": should_block, + "effective_threshold": effective_threshold, }, } cache_path.parent.mkdir(parents=True, exist_ok=True) @@ -35,7 +68,7 @@ def _run_hook( Returns (stdout, exit_code). stdout empty = approve, JSON string = deny. Uses cache_path_override parameter for DI — no module-level patching needed. """ - from autoskillit.hooks.quota_check import main + from autoskillit.hooks.quota_guard import main stdin_text = raw_stdin if raw_stdin is not None else json.dumps(event or {}) @@ -64,8 +97,19 @@ def test_deny_message_contains_sleep_seconds(tmp_path): out, _ = _run_hook(event={"tool_name": "run_skill"}, cache_path=cache) data = json.loads(out) reason = data["hookSpecificOutput"]["permissionDecisionReason"] - assert "Sleep" in reason - assert "seconds" in reason + assert "Sleeping" in reason + assert "time.sleep" in reason + + +def test_deny_message_contains_echo_repeat(tmp_path): + """Updated PreToolUse deny message includes echo/repeat instruction.""" + cache = tmp_path / "quota_cache.json" + _write_cache(cache, utilization=90.0) + out, _ = _run_hook(event={"tool_name": "run_skill"}, cache_path=cache) + data = json.loads(out) + reason = data["hookSpecificOutput"]["permissionDecisionReason"] + assert "Before executing, state aloud:" in reason + assert "QUOTA WAIT REQUIRED" in reason def test_approve_when_utilization_below_threshold(tmp_path): @@ -116,50 +160,58 @@ def test_approve_when_stale_cache(tmp_path): def _write_hook_config( - hook_cfg_path: Path, threshold: float, cache_max_age: int, cache_path: str + hook_cfg_path: Path, + cache_max_age: int, + cache_path: str, + extra: dict | None = None, ) -> None: """Write a hook config file to the given path.""" + quota_guard: dict = { + "cache_max_age": cache_max_age, + "cache_path": cache_path, + } + if extra: + quota_guard.update(extra) hook_cfg_path.parent.mkdir(parents=True, exist_ok=True) - hook_cfg_path.write_text( - json.dumps( - { - "quota_guard": { - "threshold": threshold, - "cache_max_age": cache_max_age, - "cache_path": cache_path, - } - } - ) - ) + hook_cfg_path.write_text(json.dumps({"quota_guard": quota_guard})) + +# T-CFG-1: hook trusts cache binding, never re-derives a verdict from hook config. +def test_hook_does_not_consult_threshold_field_in_hook_config(tmp_path, monkeypatch): + """Hook trusts ``binding.should_block`` and ignores any threshold in hook config. -# T-CFG-1 -def test_quota_check_reads_threshold_from_hook_config(tmp_path, monkeypatch): - """Hook must deny when utilization exceeds user-configured threshold from hook config.""" + Single-source-of-truth assertion: even if a stale ``short_window_threshold`` + in hook config would imply a deny, the hook must approve when the cache + binding says ``should_block=False``. + """ monkeypatch.chdir(tmp_path) cache = tmp_path / "custom_cache.json" - _write_cache(cache, utilization=60.0) + _write_cache( + cache, + utilization=70.0, + window_name="five_hour", + should_block=False, + effective_threshold=85.0, + ) _write_hook_config( - tmp_path / ".autoskillit" / "temp" / ".autoskillit_hook_config.json", - threshold=50.0, + tmp_path.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS), cache_max_age=300, cache_path=str(cache), + extra={"short_window_threshold": 50.0}, ) out, _ = _run_hook(event={"tool_name": "run_skill"}) - data = json.loads(out) - assert data["hookSpecificOutput"]["permissionDecision"] == "deny" + assert out.strip() == "" # T-CFG-2 def test_quota_check_reads_cache_path_from_hook_config(tmp_path, monkeypatch): - """Hook must read cache from hook config cache_path when AUTOSKILLIT_QUOTA_CACHE is unset.""" + """Hook must read cache from hook config cache_path when the env var is unset.""" monkeypatch.chdir(tmp_path) - monkeypatch.delenv("AUTOSKILLIT_QUOTA_CACHE", raising=False) + monkeypatch.delenv("AUTOSKILLIT_QUOTA_GUARD__CACHE_PATH", raising=False) custom_cache = tmp_path / "my_custom_cache.json" _write_cache(custom_cache, utilization=95.0) _write_hook_config( - tmp_path / ".autoskillit" / "temp" / ".autoskillit_hook_config.json", - threshold=90.0, + tmp_path.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS), cache_max_age=300, cache_path=str(custom_cache), ) @@ -170,32 +222,34 @@ def test_quota_check_reads_cache_path_from_hook_config(tmp_path, monkeypatch): # T-CFG-3 def test_quota_check_env_var_overrides_hook_config_cache_path(tmp_path, monkeypatch): - """AUTOSKILLIT_QUOTA_CACHE env var must take precedence over hook config cache_path. + """``AUTOSKILLIT_QUOTA_GUARD__CACHE_PATH`` must beat hook config ``cache_path``. - Backward-compat regression test: env var path must still win even when hook config is present. + Regression test: env var path must win even when a hook config is present at the + canonical path (.autoskillit/.hook_config.json). Writing different + utilization values to each cache confirms which source the hook actually reads. """ monkeypatch.chdir(tmp_path) + # env-var cache: high utilization → should deny if env var wins correct_cache = tmp_path / "correct_cache.json" _write_cache(correct_cache, utilization=95.0) - wrong_cache = tmp_path / "wrong_cache.json" # not written — should not be read + # hook-config cache: low utilization → would approve if hook config wins + wrong_cache = tmp_path / "wrong_cache.json" + _write_cache(wrong_cache, utilization=50.0) _write_hook_config( - tmp_path / "temp" / ".autoskillit_hook_config.json", - threshold=90.0, + tmp_path.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS), cache_max_age=300, cache_path=str(wrong_cache), ) - monkeypatch.setenv("AUTOSKILLIT_QUOTA_CACHE", str(correct_cache)) + monkeypatch.setenv("AUTOSKILLIT_QUOTA_GUARD__CACHE_PATH", str(correct_cache)) out, _ = _run_hook(event={"tool_name": "run_skill"}) data = json.loads(out) + # env var must win: deny because correct_cache has utilization=95.0 assert data["hookSpecificOutput"]["permissionDecision"] == "deny" # T-CFG-4 def test_quota_check_falls_back_to_defaults_without_hook_config(tmp_path, monkeypatch): - """Without hook config, hook falls back to hard-coded defaults (threshold=90.0). - - Regression test: no regression when kitchen was never opened or hook config was removed. - """ + """Without hook config, hook still resolves cache via override / env var.""" monkeypatch.chdir(tmp_path) cache = tmp_path / "quota_cache.json" _write_cache(cache, utilization=95.0) @@ -204,6 +258,78 @@ def test_quota_check_falls_back_to_defaults_without_hook_config(tmp_path, monkey assert data["hookSpecificOutput"]["permissionDecision"] == "deny" +# T-CFG-6 +def test_quota_check_buffer_seconds_from_hook_config(tmp_path, monkeypatch): + """Hook uses buffer_seconds from hook config when env var is unset. + + Writes a cache with ``resets_at=None`` so the hook takes the plain-buffer branch + (``n = settings.buffer_seconds``), making the assertion deterministic. + """ + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("AUTOSKILLIT_QUOTA_GUARD__BUFFER_SECONDS", raising=False) + cache = tmp_path / "quota_cache.json" + _write_cache(cache, utilization=95.0, resets_at=None) + _write_hook_config( + tmp_path.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS), + cache_max_age=300, + cache_path=str(cache), + extra={"buffer_seconds": 120}, + ) + out, _ = _run_hook(event={"tool_name": "run_skill"}) + data = json.loads(out) + reason = data["hookSpecificOutput"]["permissionDecisionReason"] + assert "time.sleep(120)" in reason + assert "Sleeping 120s" in reason + + +# T-CFG-7 +def test_quota_check_buffer_seconds_env_var_override(tmp_path, monkeypatch): + """``AUTOSKILLIT_QUOTA_GUARD__BUFFER_SECONDS`` overrides the deny-message sleep duration.""" + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("AUTOSKILLIT_QUOTA_GUARD__BUFFER_SECONDS", "180") + cache = tmp_path / "quota_cache.json" + _write_cache(cache, utilization=95.0, resets_at=None) + out, _ = _run_hook(event={"tool_name": "run_skill"}, cache_path=cache) + data = json.loads(out) + reason = data["hookSpecificOutput"]["permissionDecisionReason"] + assert "time.sleep(180)" in reason + assert "Sleeping 180s" in reason + + +# T-CFG-8 +def test_quota_check_cache_max_age_env_var_override(tmp_path, monkeypatch): + """AUTOSKILLIT_QUOTA_GUARD__CACHE_MAX_AGE env var overrides the cache freshness window. + + With ``cache_max_age=60`` and a 61-second-old cache, the hook must treat the + cache as stale and emit a cache_miss event (fail-open approve). + """ + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("AUTOSKILLIT_QUOTA_GUARD__CACHE_MAX_AGE", "60") + cache = tmp_path / "quota_cache.json" + stale_fetched_at = (datetime.now(UTC) - timedelta(seconds=61)).isoformat() + payload = { + "fetched_at": stale_fetched_at, + "windows": {"five_hour": {"utilization": 95.0, "resets_at": None}}, + "binding": { + "window_name": "five_hour", + "utilization": 95.0, + "resets_at": None, + "should_block": True, + "effective_threshold": 85.0, + }, + } + cache.write_text(json.dumps(payload)) + log_dir = tmp_path / "logs" + monkeypatch.setenv("AUTOSKILLIT_LOG_DIR", str(log_dir)) + out, exit_code = _run_hook(event={"tool_name": "run_skill"}, cache_path=cache) + assert out.strip() == "" + assert exit_code == 0 + events = [ + json.loads(line) for line in (log_dir / "quota_events.jsonl").read_text().splitlines() + ] + assert events[0]["event"] == "cache_miss" + + # T1 def test_quota_event_approved_written_to_log(tmp_path, monkeypatch): cache = tmp_path / "quota_cache.json" @@ -217,7 +343,7 @@ def test_quota_event_approved_written_to_log(tmp_path, monkeypatch): assert len(events) == 1 assert events[0]["event"] == "approved" assert events[0]["utilization"] == 50.0 - assert events[0]["threshold"] == 90.0 + assert events[0]["effective_threshold"] == 85.0 assert "ts" in events[0] @@ -235,7 +361,7 @@ def test_quota_event_blocked_written_to_log(tmp_path, monkeypatch): ev = events[0] assert ev["event"] == "blocked" assert ev["utilization"] == 95.0 - assert ev["threshold"] == 90.0 + assert ev["effective_threshold"] == 85.0 assert isinstance(ev["sleep_seconds"], int) assert ev["sleep_seconds"] > 0 assert "ts" in ev @@ -321,15 +447,138 @@ def test_defaults_yaml_cache_max_age_is_300(): assert defaults["quota_guard"]["cache_max_age"] == 300 +# T-HOOK-PWT-1: regression test for #721 — weekly at 86% must approve. +def test_hook_approves_weekly_at_86_percent_should_block_false(tmp_path): + """Weekly window at 86% utilisation must NOT be blocked. + + Regression test for issue #721: long-window quotas (weekly/sonnet/opus) + use a higher threshold (98%), so 86% is comfortable headroom — not exhaustion. + """ + cache = tmp_path / "quota_cache.json" + _write_cache( + cache, + utilization=86.0, + window_name="weekly", + should_block=False, + effective_threshold=98.0, + ) + out, _ = _run_hook(event={"tool_name": "run_skill"}, cache_path=cache) + assert out.strip() == "" + + +# T-HOOK-PWT-2: weekly above 98% must still deny. +def test_hook_blocks_weekly_above_long_threshold(tmp_path): + cache = tmp_path / "quota_cache.json" + _write_cache( + cache, + utilization=99.0, + window_name="weekly", + should_block=True, + effective_threshold=98.0, + ) + out, _ = _run_hook(event={"tool_name": "run_skill"}, cache_path=cache) + data = json.loads(out) + assert data["hookSpecificOutput"]["permissionDecision"] == "deny" + reason = data["hookSpecificOutput"]["permissionDecisionReason"] + assert "weekly" in reason + assert "98" in reason + + +# T-HOOK-PWT-3: short window above 85% must deny with short threshold in message. +def test_hook_blocks_short_window_above_threshold_message(tmp_path): + cache = tmp_path / "quota_cache.json" + _write_cache( + cache, + utilization=90.0, + window_name="five_hour", + should_block=True, + effective_threshold=85.0, + ) + out, _ = _run_hook(event={"tool_name": "run_skill"}, cache_path=cache) + data = json.loads(out) + reason = data["hookSpecificOutput"]["permissionDecisionReason"] + assert "five_hour" in reason + assert "85" in reason + + +# T-HOOK-PWT-4: missing should_block field → fail open (approve). +def test_hook_falls_back_when_should_block_field_missing(tmp_path): + """Old-format cache without should_block defaults to approve (fail-open).""" + cache = tmp_path / "quota_cache.json" + payload = { + "fetched_at": datetime.now(UTC).isoformat(), + "windows": {"five_hour": {"utilization": 95.0, "resets_at": None}}, + "binding": { + "window_name": "five_hour", + "utilization": 95.0, + "resets_at": None, + }, + } + cache.write_text(json.dumps(payload)) + out, _ = _run_hook(event={"tool_name": "run_skill"}, cache_path=cache) + assert out.strip() == "" + + +# T-HOOK-MW-1: cache with one_hour binding above threshold → deny +def test_deny_when_binding_window_is_one_hour_exhausted(tmp_path): + """Hook denies when binding window (one_hour) is above threshold.""" + cache = tmp_path / "quota_cache.json" + _write_cache( + cache, + utilization=91.0, + window_name="one_hour", + extra_windows={"five_hour": {"utilization": 35.0, "resets_at": None}}, + ) + out, _ = _run_hook(event={"tool_name": "run_skill"}, cache_path=cache) + data = json.loads(out) + assert data["hookSpecificOutput"]["permissionDecision"] == "deny" + + +# T-HOOK-MW-2: cache with binding below threshold → approve +def test_approve_when_binding_below_threshold(tmp_path): + """Hook approves when binding utilization is below threshold (even with high other window).""" + cache = tmp_path / "quota_cache.json" + _write_cache( + cache, + utilization=35.0, + window_name="five_hour", + extra_windows={"one_hour": {"utilization": 20.0, "resets_at": None}}, + ) + out, exit_code = _run_hook(event={"tool_name": "run_skill"}, cache_path=cache) + assert exit_code == 0 + assert out.strip() == "" + + +# Test 18: hook reads should_block=False from a cache produced with long_enabled=False +def test_hook_respects_should_block_false_when_class_disabled(tmp_path): + """Hook approves when cache binding has should_block=False, even if utilization is high. + + Simulates the outcome of _compute_binding called with long_enabled=False: + the binding is five_hour at 30%, should_block=False, effective_threshold=85.0. + The hook must exit 0 with no permissionDecision deny line — zero hook code changes required. + """ + cache = tmp_path / "quota_cache.json" + _write_cache( + cache, + utilization=30.0, + window_name="five_hour", + should_block=False, + effective_threshold=85.0, + ) + out, exit_code = _run_hook(event={"tool_name": "run_skill"}, cache_path=cache) + assert exit_code == 0 + assert out.strip() == "" + + def test_resolve_quota_log_dir_and_resolve_log_dir_in_sync(monkeypatch): """_resolve_quota_log_dir() must produce the same path as resolve_log_dir('') for identical env inputs. Guards against independent evolution of the two implementations. - Constraint: these functions MUST NOT be merged — quota_check.py is stdlib-only + Constraint: these functions MUST NOT be merged — quota_guard.py is stdlib-only and self-contained. This test is the canonical drift guard. """ from autoskillit.execution.session_log import resolve_log_dir - from autoskillit.hooks.quota_check import _resolve_quota_log_dir + from autoskillit.hooks.quota_guard import _resolve_quota_log_dir # Case 1: platform default (no env overrides) monkeypatch.delenv("AUTOSKILLIT_LOG_DIR", raising=False) @@ -356,3 +605,37 @@ def test_resolve_quota_log_dir_and_resolve_log_dir_in_sync(monkeypatch): f" quota_check: {quota_path_xdg}\n" f" session_log: {session_path_xdg}" ) + + +def test_hook_approves_when_disabled_flag_set_in_hook_config(tmp_path, monkeypatch): + """Hook bypasses all checks and approves when disabled=True in hook config. + + Even with a high-utilization blocking cache, the hook must exit 0 with + no output when the quota_guard.disabled flag is set. + """ + monkeypatch.chdir(tmp_path) + cache = tmp_path / "blocking_cache.json" + _write_cache(cache, utilization=99.0, should_block=True) + _write_hook_config( + tmp_path.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS), + cache_max_age=300, + cache_path=str(cache), + extra={"disabled": True}, + ) + out, _ = _run_hook(event={"tool_name": "run_skill"}) + assert out.strip() == "" + + +def test_hook_still_blocks_without_disabled_flag(tmp_path, monkeypatch): + """Regression guard: hook still blocks when disabled key is absent from hook config.""" + monkeypatch.chdir(tmp_path) + cache = tmp_path / "blocking_cache.json" + _write_cache(cache, utilization=99.0, should_block=True) + _write_hook_config( + tmp_path.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS), + cache_max_age=300, + cache_path=str(cache), + ) + out, _ = _run_hook(event={"tool_name": "run_skill"}) + data = json.loads(out) + assert data["hookSpecificOutput"]["permissionDecision"] == "deny" diff --git a/tests/infra/test_quota_post_check.py b/tests/infra/test_quota_post_check.py new file mode 100644 index 0000000000..e0aa2cc27f --- /dev/null +++ b/tests/infra/test_quota_post_check.py @@ -0,0 +1,417 @@ +"""Tests for the quota_post_check PostToolUse hook. + +The hook fires after run_skill completes and checks whether post-execution +quota utilization exceeds the threshold. When over threshold, it replaces the +tool output with a quota warning + sleep instruction via updatedMCPToolOutput. +""" + +import io +import json +from contextlib import redirect_stdout +from datetime import UTC, datetime, timedelta +from pathlib import Path +from unittest.mock import patch + +from autoskillit.hooks._fmt_primitives import _HOOK_CONFIG_PATH_COMPONENTS + +_LONG_PATTERNS = ("weekly", "sonnet", "opus") + + +def _classify_threshold(window_name: str) -> float: + lowered = window_name.lower() + return 98.0 if any(p in lowered for p in _LONG_PATTERNS) else 85.0 + + +def _write_cache( + cache_path: Path, + utilization: float, + resets_at: str | None = None, + window_name: str = "five_hour", + extra_windows: dict | None = None, + should_block: bool | None = None, + effective_threshold: float | None = None, +) -> None: + """Write a fresh quota cache file in the full-snapshot format. + + When ``should_block`` is None, classifies the window via the default + long-window patterns and computes ``should_block`` from utilization. + """ + if effective_threshold is None: + effective_threshold = _classify_threshold(window_name) + if should_block is None: + should_block = utilization >= effective_threshold + windows = {window_name: {"utilization": utilization, "resets_at": resets_at}} + if extra_windows: + windows.update(extra_windows) + payload = { + "fetched_at": datetime.now(UTC).isoformat(), + "windows": windows, + "binding": { + "window_name": window_name, + "utilization": utilization, + "resets_at": resets_at, + "should_block": should_block, + "effective_threshold": effective_threshold, + }, + } + cache_path.parent.mkdir(parents=True, exist_ok=True) + cache_path.write_text(json.dumps(payload)) + + +def _build_event( + tool_name: str = "mcp__plugin_autoskillit_autoskillit__run_skill", + success: bool = True, + result_text: str = "plan written", +) -> dict: + """Build a synthetic PostToolUse event for run_skill.""" + inner = json.dumps({"success": success, "result": result_text}) + outer = json.dumps({"result": inner}) + return { + "tool_name": tool_name, + "tool_response": outer, + } + + +def _run_hook( + event: dict | None = None, + raw_stdin: str | None = None, + cache_path: Path | None = None, +) -> tuple[str, int]: + """Run quota_post_check.main() with synthetic stdin and optional cache file. + + Returns (stdout, exit_code). stdout empty = no warning, JSON string = warning. + """ + from autoskillit.hooks.quota_post_hook import main + + stdin_text = raw_stdin if raw_stdin is not None else json.dumps(event or {}) + + buf = io.StringIO() + exit_code = 0 + with patch("sys.stdin", io.StringIO(stdin_text)): + with redirect_stdout(buf): + try: + main(cache_path_override=str(cache_path) if cache_path is not None else None) + except SystemExit as e: + exit_code = e.code if e.code is not None else 0 + return buf.getvalue(), exit_code + + +# T1: PostToolUse quota warning emitted when over threshold +def test_qpc1_emits_warning_when_over_threshold(tmp_path): + """PostToolUse hook emits updatedMCPToolOutput with quota warning.""" + cache = tmp_path / "quota_cache.json" + _write_cache(cache, utilization=90.0) + event = _build_event() + out, _ = _run_hook(event=event, cache_path=cache) + data = json.loads(out) + assert "hookSpecificOutput" in data + assert "updatedMCPToolOutput" in data["hookSpecificOutput"] + assert "QUOTA WARNING" in data["hookSpecificOutput"]["updatedMCPToolOutput"] + + +# T2: Silent exit when under threshold +def test_qpc2_silent_when_under_threshold(tmp_path): + """PostToolUse hook exits silently (no stdout) when utilization < threshold.""" + cache = tmp_path / "quota_cache.json" + _write_cache(cache, utilization=50.0) + event = _build_event() + out, _ = _run_hook(event=event, cache_path=cache) + assert out.strip() == "" + + +# T3: Fail-open on missing cache +def test_qpc3_silent_on_missing_cache(tmp_path): + """PostToolUse hook exits silently when cache file does not exist.""" + event = _build_event() + out, _ = _run_hook(event=event, cache_path=tmp_path / "nonexistent.json") + assert out.strip() == "" + + +# T4: Fail-open on corrupt cache +def test_qpc4_silent_on_corrupt_cache(tmp_path): + """PostToolUse hook exits silently when cache file contains invalid JSON.""" + cache = tmp_path / "quota_cache.json" + cache.write_text("not-json-{{{") + event = _build_event() + out, _ = _run_hook(event=event, cache_path=cache) + assert out.strip() == "" + + +# T5: Fail-open on stale cache +def test_qpc5_silent_on_stale_cache(tmp_path): + """PostToolUse hook exits silently when cache is older than max_age.""" + cache = tmp_path / "quota_cache.json" + payload = { + "fetched_at": "2020-01-01T00:00:00+00:00", + "five_hour": {"utilization": 99.0, "resets_at": None}, + } + cache.write_text(json.dumps(payload)) + event = _build_event() + out, _ = _run_hook(event=event, cache_path=cache) + assert out.strip() == "" + + +# T6: Warning output includes sleep seconds and run_cmd instruction +def test_qpc6_warning_contains_sleep_instruction(tmp_path): + """Warning output includes explicit run_cmd sleep command with correct seconds.""" + cache = tmp_path / "quota_cache.json" + resets_at = (datetime.now(UTC) + timedelta(hours=1)).isoformat() + _write_cache(cache, utilization=90.0, resets_at=resets_at) + event = _build_event() + out, _ = _run_hook(event=event, cache_path=cache) + data = json.loads(out) + output = data["hookSpecificOutput"]["updatedMCPToolOutput"] + assert "run_cmd" in output + assert "time.sleep" in output + + +# T7: Warning preserves run_skill result summary +def test_qpc7_warning_preserves_result_summary(tmp_path): + """updatedMCPToolOutput includes the run_skill result (success/fail, key fields).""" + cache = tmp_path / "quota_cache.json" + _write_cache(cache, utilization=90.0) + event = _build_event(success=True, result_text="plan written") + out, _ = _run_hook(event=event, cache_path=cache) + data = json.loads(out) + output = data["hookSpecificOutput"]["updatedMCPToolOutput"] + assert "success: True" in output + assert "plan written" in output + + +# T8: JSONL event logging for post-check warning +def test_qpc8_warning_event_written_to_log(tmp_path, monkeypatch): + """Post-check logs a 'post_check_warning' event to quota_events.jsonl.""" + cache = tmp_path / "quota_cache.json" + _write_cache(cache, utilization=90.0) + log_dir = tmp_path / "logs" + monkeypatch.setenv("AUTOSKILLIT_LOG_DIR", str(log_dir)) + event = _build_event() + _run_hook(event=event, cache_path=cache) + events = [ + json.loads(line) for line in (log_dir / "quota_events.jsonl").read_text().splitlines() + ] + assert len(events) == 1 + assert events[0]["event"] == "post_check_warning" + + +# T9: JSONL event logging for post-check pass +def test_qpc9_pass_event_written_to_log(tmp_path, monkeypatch): + """Post-check logs a 'post_check_pass' event when under threshold.""" + cache = tmp_path / "quota_cache.json" + _write_cache(cache, utilization=50.0) + log_dir = tmp_path / "logs" + monkeypatch.setenv("AUTOSKILLIT_LOG_DIR", str(log_dir)) + event = _build_event() + _run_hook(event=event, cache_path=cache) + events = [ + json.loads(line) for line in (log_dir / "quota_events.jsonl").read_text().splitlines() + ] + assert len(events) == 1 + assert events[0]["event"] == "post_check_pass" + + +# T10: Hook fires on failed run_skill results too +def test_qpc10_fires_on_failed_run_skill(tmp_path): + """PostToolUse hook checks quota even when run_skill returned success=False.""" + cache = tmp_path / "quota_cache.json" + _write_cache(cache, utilization=90.0) + event = _build_event(success=False) + out, _ = _run_hook(event=event, cache_path=cache) + data = json.loads(out) + assert "QUOTA WARNING" in data["hookSpecificOutput"]["updatedMCPToolOutput"] + + +# T11: Hook reads cache_path from hook config +def test_qpc11_reads_cache_path_from_hook_config(tmp_path, monkeypatch): + """PostToolUse hook reads cache_path from .autoskillit/.hook_config.json. + + The hook trusts the cache binding's ``should_block`` flag — it never re-derives + a verdict from a hook config threshold. This test only verifies that the hook + locates the cache file via the hook config cache_path setting. + """ + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("AUTOSKILLIT_QUOTA_GUARD__CACHE_PATH", raising=False) + cache = tmp_path / "custom_cache.json" + _write_cache(cache, utilization=95.0) + hook_cfg_path = tmp_path.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS) + hook_cfg_path.parent.mkdir(parents=True, exist_ok=True) + hook_cfg_path.write_text( + json.dumps( + { + "quota_guard": { + "cache_max_age": 300, + "cache_path": str(cache), + } + } + ) + ) + event = _build_event() + out, _ = _run_hook(event=event) + data = json.loads(out) + assert "QUOTA WARNING" in data["hookSpecificOutput"]["updatedMCPToolOutput"] + + +# T12: Hook registered in HOOK_REGISTRY +def test_qpc12_registered_in_hook_registry(): + """quota_post_hook.py is registered as PostToolUse in HOOK_REGISTRY.""" + from autoskillit.hook_registry import HOOK_REGISTRY + + post_tool_scripts = [ + s for h in HOOK_REGISTRY if h.event_type == "PostToolUse" for s in h.scripts + ] + assert "quota_post_hook.py" in post_tool_scripts + + +# T13: Fail-open on malformed stdin +def test_qpc13_failopen_on_malformed_stdin(tmp_path): + """PostToolUse hook exits silently when stdin is not valid JSON.""" + cache = tmp_path / "quota_cache.json" + _write_cache(cache, utilization=90.0) + out, exit_code = _run_hook(raw_stdin="not-json-garbage", cache_path=cache) + assert out.strip() == "" + assert exit_code == 0 + + +# T14: Non-run_skill tools do not trigger post-check +def test_qpc14_only_run_skill_matcher(): + """The hook_registry PostToolUse entry for quota_post_check matches only run_skill.""" + import re + + from autoskillit.hook_registry import HOOK_REGISTRY + + entry = next( + h + for h in HOOK_REGISTRY + if h.event_type == "PostToolUse" and "quota_post_hook.py" in h.scripts + ) + assert re.match(entry.matcher, "mcp__plugin_autoskillit_autoskillit__run_skill") + assert not re.match(entry.matcher, "mcp__plugin_autoskillit_autoskillit__run_cmd") + assert not re.match(entry.matcher, "mcp__plugin_autoskillit_autoskillit__kitchen_status") + + +# T-PCHK-PWT-1: regression test for #721 — post_check silent for weekly at 86%. +def test_post_hook_silent_when_weekly_below_long_threshold(tmp_path): + """Weekly window at 86% must NOT emit a warning. Regression test for #721.""" + cache = tmp_path / "quota_cache.json" + _write_cache( + cache, + utilization=86.0, + window_name="weekly", + should_block=False, + effective_threshold=98.0, + ) + event = _build_event() + out, exit_code = _run_hook(event=event, cache_path=cache) + assert out.strip() == "" + assert exit_code == 0 + + +# T-PCHK-PWT-2: weekly above 98% must still warn. +def test_post_hook_warns_when_weekly_above_long_threshold(tmp_path): + cache = tmp_path / "quota_cache.json" + _write_cache( + cache, + utilization=99.0, + window_name="weekly", + should_block=True, + effective_threshold=98.0, + ) + event = _build_event() + out, _ = _run_hook(event=event, cache_path=cache) + data = json.loads(out) + output = data["hookSpecificOutput"]["updatedMCPToolOutput"] + assert "QUOTA WARNING" in output + assert "weekly" in output + assert "98" in output + + +# T-PCHK-MW-1: post_check warns when binding window is exhausted (not five_hour) +def test_warns_when_binding_window_exhausted(tmp_path): + """PostToolUse hook emits warning when binding is one_hour (not five_hour).""" + cache = tmp_path / "quota_cache.json" + _write_cache( + cache, + utilization=91.0, + window_name="one_hour", + extra_windows={"five_hour": {"utilization": 35.0, "resets_at": None}}, + ) + event = _build_event() + out, _ = _run_hook(event=event, cache_path=cache) + data = json.loads(out) + assert "QUOTA WARNING" in data["hookSpecificOutput"]["updatedMCPToolOutput"] + + +# T-PCHK-15 +def test_qpc_buffer_seconds_from_hook_config(tmp_path, monkeypatch): + """Post-check warning sleep uses ``buffer_seconds`` from hook config. + + Writes a cache with ``resets_at=None`` so the hook takes the plain-buffer branch + (``n = settings.buffer_seconds``), making the assertion deterministic. + """ + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("AUTOSKILLIT_QUOTA_GUARD__BUFFER_SECONDS", raising=False) + cache = tmp_path / "quota_cache.json" + _write_cache(cache, utilization=95.0, resets_at=None) + hook_cfg_path = tmp_path.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS) + hook_cfg_path.parent.mkdir(parents=True, exist_ok=True) + hook_cfg_path.write_text( + json.dumps( + { + "quota_guard": { + "cache_max_age": 300, + "cache_path": str(cache), + "buffer_seconds": 120, + } + } + ) + ) + event = _build_event() + out, _ = _run_hook(event=event) + data = json.loads(out) + output = data["hookSpecificOutput"]["updatedMCPToolOutput"] + assert "time.sleep(120)" in output + assert "Sleeping 120s" in output + + +# T-PCHK-16 +def test_qpc_buffer_seconds_env_var_override(tmp_path, monkeypatch): + """AUTOSKILLIT_QUOTA_GUARD__BUFFER_SECONDS env var overrides the warning sleep duration.""" + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("AUTOSKILLIT_QUOTA_GUARD__BUFFER_SECONDS", "180") + cache = tmp_path / "quota_cache.json" + _write_cache(cache, utilization=95.0, resets_at=None) + event = _build_event() + out, _ = _run_hook(event=event, cache_path=cache) + data = json.loads(out) + output = data["hookSpecificOutput"]["updatedMCPToolOutput"] + assert "time.sleep(180)" in output + assert "Sleeping 180s" in output + + +# T-PCHK-17 +def test_qpc_cache_max_age_env_var_override(tmp_path, monkeypatch): + """AUTOSKILLIT_QUOTA_GUARD__CACHE_MAX_AGE env var overrides the cache freshness window. + + With ``cache_max_age=60`` and a 61-second-old cache, the hook treats the cache + as stale and exits silently (fail-open, no warning output). + """ + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("AUTOSKILLIT_QUOTA_GUARD__CACHE_MAX_AGE", "60") + cache = tmp_path / "quota_cache.json" + stale_fetched_at = (datetime.now(UTC) - timedelta(seconds=61)).isoformat() + payload = { + "fetched_at": stale_fetched_at, + "windows": {"five_hour": {"utilization": 95.0, "resets_at": None}}, + "binding": { + "window_name": "five_hour", + "utilization": 95.0, + "resets_at": None, + "should_block": True, + "effective_threshold": 85.0, + }, + } + cache.write_text(json.dumps(payload)) + event = _build_event() + out, exit_code = _run_hook(event=event, cache_path=cache) + assert out.strip() == "" + assert exit_code == 0 diff --git a/tests/infra/test_release_sanity.py b/tests/infra/test_release_sanity.py index 9981ea6d40..b521db1ed4 100644 --- a/tests/infra/test_release_sanity.py +++ b/tests/infra/test_release_sanity.py @@ -23,3 +23,38 @@ def test_sync_manifest_in_gitignore(): """.autoskillit/sync_manifest.json must be gitignored.""" gitignore = (REPO_ROOT / ".gitignore").read_text() assert ".autoskillit/sync_manifest.json" in gitignore + + +def test_autoskillit_root_files_are_all_registered(): + """.autoskillit/ root must only contain files registered in _COMMITTED_BY_DESIGN + or _AUTOSKILLIT_GITIGNORE_ENTRIES (or .gitignore itself). + + Catches any session-scoped file mistakenly placed outside temp/ at CI time. + If .hook_config.json (or any future runtime artifact) is present in the root + rather than temp/, this test fails immediately. + """ + from autoskillit.core.io import _AUTOSKILLIT_GITIGNORE_ENTRIES, _COMMITTED_BY_DESIGN + + autoskillit_dir = REPO_ROOT / ".autoskillit" + if not autoskillit_dir.is_dir(): + return # project not initialized — skip + + registered_names = ( + _COMMITTED_BY_DESIGN + | {e.rstrip("/") for e in _AUTOSKILLIT_GITIGNORE_ENTRIES} + | {".gitignore"} # the directory's own gitignore is always valid + ) + + unregistered = [ + p.name + for p in autoskillit_dir.iterdir() + if not p.is_dir() and p.name not in registered_names + ] + + assert not unregistered, ( + f"Unregistered files found in .autoskillit/: {unregistered}. " + f"Session-scoped runtime files belong in .autoskillit/temp/ where they " + f"are auto-gitignored by temp/.gitignore ('*'). Persistent files that " + f"belong in .autoskillit/ root need an entry added to " + f"_AUTOSKILLIT_GITIGNORE_ENTRIES in src/autoskillit/core/io.py." + ) diff --git a/tests/infra/test_schema_version_convention.py b/tests/infra/test_schema_version_convention.py new file mode 100644 index 0000000000..0053786840 --- /dev/null +++ b/tests/infra/test_schema_version_convention.py @@ -0,0 +1,239 @@ +"""Allowlist ratchet: enforce that new JSON dict write sites use write_versioned_json. + +Scans src/autoskillit/ for atomic_write calls whose second argument wraps json.dumps +of a dict payload. Sites in the _LEGACY_JSON_WRITES allowlist are grandfathered; +any new site must use write_versioned_json instead. +""" + +from __future__ import annotations + +import ast +from pathlib import Path + +import pytest + + +def _scan_atomic_write_json_dict_sites() -> set[tuple[str, int]]: + """AST-scan src/autoskillit/ for atomic_write(path, json.dumps({...})) calls. + + Returns set of (relative_path, line_number) for sites where the second + positional argument to atomic_write is (or wraps) json.dumps of a dict payload. + """ + src_root = Path(__file__).resolve().parents[2] / "src" / "autoskillit" + sites: set[tuple[str, int]] = set() + + for py_file in src_root.rglob("*.py"): + try: + tree = ast.parse(py_file.read_text(), filename=str(py_file)) + except SyntaxError: + continue + + for node in ast.walk(tree): + if not isinstance(node, ast.Call): + continue + # Match atomic_write(path, json.dumps(...)) + func = node.func + is_atomic_write = (isinstance(func, ast.Name) and func.id == "atomic_write") or ( + isinstance(func, ast.Attribute) and func.attr == "atomic_write" + ) + if not is_atomic_write: + continue + if len(node.args) < 2: + continue + + second_arg = node.args[1] + json_dumps_call = _extract_json_dumps(second_arg) + if json_dumps_call is None: + continue + + # Check if the json.dumps argument is a dict (or could be a dict) + if not _is_dict_payload(json_dumps_call): + continue + + # Skip if it's a dump_yaml_str call + if _is_yaml_dump(second_arg): + continue + + rel = str(py_file.relative_to(src_root.parent.parent)) + sites.add((rel, node.lineno)) + + return sites + + +def _extract_json_dumps(node: ast.expr) -> ast.Call | None: + """If node is json.dumps(...) or wraps it (e.g. json.dumps(...) + '\\n'), extract the call.""" + if isinstance(node, ast.Call): + func = node.func + if isinstance(func, ast.Attribute) and func.attr == "dumps": + if isinstance(func.value, ast.Name) and func.value.id == "json": + return node + if isinstance(func.value, ast.Name) and func.value.id == "_json": + return node + # Handle json.dumps(...) + "\n" + if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add): + return _extract_json_dumps(node.left) or _extract_json_dumps(node.right) + return None + + +def _is_dict_payload(json_dumps_call: ast.Call) -> bool: + """Return True if the first arg to json.dumps is likely a dict (not list/str).""" + if not json_dumps_call.args: + return False + arg = json_dumps_call.args[0] + # Explicit list/listcomp/set → not a dict + if isinstance(arg, (ast.List, ast.ListComp, ast.SetComp)): + return False + # Explicit string → not a dict + if isinstance(arg, ast.Constant) and isinstance(arg.value, str): + return False + # Explicit dict → definitely a dict + if isinstance(arg, ast.Dict): + return True + # Name/Attribute/Call → assume dict (conservative) + return True + + +def _is_yaml_dump(node: ast.expr) -> bool: + """Return True if the node involves dump_yaml_str.""" + if isinstance(node, ast.Call): + func = node.func + if isinstance(func, ast.Name) and func.id == "dump_yaml_str": + return True + if isinstance(func, ast.Attribute) and func.attr == "dump_yaml_str": + return True + return False + + +# Hard-curated allowlist of existing atomic_write + json.dumps sites detected by AST scan. +# Quota cache is NOT here because it's migrated to write_versioned_json in Phase 4. +# Any new site that writes a dict payload SHOULD use write_versioned_json. +_LEGACY_JSON_WRITES: set[tuple[str, int]] = { + # core/io.py — write_versioned_json itself (the blessed helper) uses atomic_write+json.dumps + ("src/autoskillit/core/io.py", 118), + # session_log.py — summary dict, token_usage list, audit_log list + ("src/autoskillit/execution/session_log.py", 244), + ("src/autoskillit/execution/session_log.py", 260), + ("src/autoskillit/execution/session_log.py", 263), + # migration/store.py — failure store dicts + ("src/autoskillit/migration/store.py", 54), + ("src/autoskillit/migration/store.py", 64), + # clone_registry.py — clones dict (CloneRegistry.__exit__ atomic write-back) + ("src/autoskillit/workspace/clone_registry.py", 82), + # staleness_cache.py — cache dict + ("src/autoskillit/recipe/staleness_cache.py", 67), + # background.py — payload dict + ("src/autoskillit/pipeline/background.py", 132), + # _lifespan.py — hooks.json self-heal on startup drift (co-owned with Claude plugin system) + ("src/autoskillit/server/_lifespan.py", 55), + # tools_kitchen.py — hook config dict + ("src/autoskillit/server/tools_kitchen.py", 142), + ("src/autoskillit/server/tools_kitchen.py", 471), + # tools_status.py — mcp_data dict + ("src/autoskillit/server/tools_status.py", 385), + # tools_github.py — bug report dict + ("src/autoskillit/server/tools_github.py", 268), + # _hooks.py — settings.json dict (co-owned with Claude CLI) + ("src/autoskillit/cli/_hooks.py", 23), + # _init_helpers.py — ~/.claude.json (co-owned) + ("src/autoskillit/cli/_init_helpers.py", 376), + # _init_helpers.py — evict_direct_mcp_entry write-back to ~/.claude.json (co-owned) + ("src/autoskillit/cli/_init_helpers.py", 395), + # _installed_plugins.py — installed_plugins.json (co-owned with Claude plugin system) + ("src/autoskillit/cli/_installed_plugins.py", 65), + # _marketplace.py — marketplace.json (co-owned) + ("src/autoskillit/cli/_marketplace.py", 85), + # _marketplace.py — hooks.json (co-owned) + ("src/autoskillit/cli/_marketplace.py", 161), + # _update_checks.py — dismissal state file + ("src/autoskillit/cli/_update_checks.py", 102), + # _update_checks.py — fetch cache + ("src/autoskillit/cli/_update_checks.py", 129), + # smoke_utils.py — domain partitions dict, hunk ranges list, merge queue list + ("src/autoskillit/smoke_utils.py", 53), + ("src/autoskillit/smoke_utils.py", 83), + ("src/autoskillit/smoke_utils.py", 138), +} + + +class TestSchemaVersionConvention: + def test_current_json_write_sites_match_allowlist(self): + """All atomic_write+json.dumps(dict) sites must be in _LEGACY_JSON_WRITES.""" + current = _scan_atomic_write_json_dict_sites() + added = current - _LEGACY_JSON_WRITES + removed = _LEGACY_JSON_WRITES - current + + msg_parts = [] + if added: + msg_parts.append( + "New json.dumps dict write sites found (use write_versioned_json instead):\n" + + "\n".join(f" + {f}:{ln}" for f, ln in sorted(added)) + ) + if removed: + msg_parts.append( + "Allowlisted sites no longer found (remove from _LEGACY_JSON_WRITES):\n" + + "\n".join(f" - {f}:{ln}" for f, ln in sorted(removed)) + ) + assert current == _LEGACY_JSON_WRITES, "\n\n".join(msg_parts) + + def test_new_json_write_site_without_helper_fails(self, monkeypatch): + """Meta-test: a fake extra site should cause the ratchet to fail.""" + original_scan = _scan_atomic_write_json_dict_sites + + def patched_scan(): + sites = original_scan() + sites.add(("src/autoskillit/fake_module.py", 999)) + return sites + + monkeypatch.setattr( + "tests.infra.test_schema_version_convention._scan_atomic_write_json_dict_sites", + patched_scan, + ) + with pytest.raises(AssertionError, match="fake_module"): + self.test_current_json_write_sites_match_allowlist() + + def test_allowlist_excludes_externally_co_owned_files(self): + """Documented exclusions: settings.json, ~/.claude.json, installed_plugins.json, etc.""" + co_owned_paths = { + "_hooks.py", + "_init_helpers.py", + "_marketplace.py", + } + for path, _line in _LEGACY_JSON_WRITES: + basename = Path(path).name + if basename in co_owned_paths: + assert isinstance(path, str) and path, ( + f"Co-owned allowlist entry has invalid path: {path!r}" + ) + assert isinstance(_line, int) and _line > 0, ( + f"Co-owned allowlist entry has invalid line number: {_line!r}" + ) + + def test_allowlist_includes_list_payloads_as_documented(self): + """List-payload sites are included since the AST scanner can't distinguish return types.""" + # These sites write list payloads through function calls but are caught by the scanner + list_sites = [ + ("src/autoskillit/execution/session_log.py", 260), + ("src/autoskillit/execution/session_log.py", 263), + ("src/autoskillit/smoke_utils.py", 83), + ("src/autoskillit/smoke_utils.py", 138), + ] + for site in list_sites: + assert site in _LEGACY_JSON_WRITES, ( + f"List-payload site {site} should be in _LEGACY_JSON_WRITES (scanner limitation)" + ) + + def test_allowlist_excludes_yaml_writes(self): + """YAML write sites must not appear in the allowlist.""" + for path, _line in _LEGACY_JSON_WRITES: + assert "yaml" not in Path(path).stem.lower() or "staleness" in path, ( + f"YAML write file {path} should not be in _LEGACY_JSON_WRITES" + ) + + def test_allowlist_excludes_string_body_writes(self): + """Gitignore, marker files, pre-rendered report text must not be in allowlist.""" + string_body_keywords = ["gitignore", "marker", "report"] + for path, _line in _LEGACY_JSON_WRITES: + for kw in string_body_keywords: + assert kw not in Path(path).stem.lower(), ( + f"String-body file {path} should not be in _LEGACY_JSON_WRITES" + ) diff --git a/tests/infra/test_session_scope_enforcement.py b/tests/infra/test_session_scope_enforcement.py new file mode 100644 index 0000000000..fe84c1a0ec --- /dev/null +++ b/tests/infra/test_session_scope_enforcement.py @@ -0,0 +1,102 @@ +"""Structural enforcement tests: session-scope metadata on HookDef. + +These tests ensure that: +1. HookDef declares a session_scope field (so authors must think about scope) +2. Any hook declared with session_scope != "any" has AUTOSKILLIT_HEADLESS in its source +3. Any scoped hook has test coverage for both headless and non-headless cases + +These form a closed loop that makes the "guard designed for headless but applied +globally" bug class structurally impossible without explicit, tested, declared intent. +""" + +from __future__ import annotations + +import dataclasses +from pathlib import Path + +import pytest + +from autoskillit.hook_registry import HOOK_REGISTRY, HOOKS_DIR, HookDef + + +def test_hookdef_has_session_scope() -> None: + """HookDef must have a session_scope field.""" + fields = {f.name for f in dataclasses.fields(HookDef)} + assert "session_scope" in fields, ( + "HookDef is missing the 'session_scope' field. " + "Add: session_scope: Literal['any', 'headless_only', 'interactive_only'] = 'any'" + ) + + +def test_session_scope_default_is_any() -> None: + """The default session_scope must be 'any' so existing entries remain unchanged.""" + default_def = HookDef(matcher="test.*", scripts=["test.py"]) + assert default_def.session_scope == "any" # type: ignore[attr-defined] + + +def _scoped_hooks() -> list[tuple[HookDef, str]]: + """Return (hookdef, script_path) pairs for all non-'any' scoped hooks.""" + pairs = [] + for hookdef in HOOK_REGISTRY: + scope = getattr(hookdef, "session_scope", "any") + if scope != "any": + for script in hookdef.scripts: + pairs.append((hookdef, script)) + return pairs + + +@pytest.mark.parametrize("hookdef,script", _scoped_hooks()) +def test_scoped_guard_contains_headless_check(hookdef: HookDef, script: str) -> None: + """Every guard declared with session_scope != 'any' must check AUTOSKILLIT_HEADLESS.""" + script_path = HOOKS_DIR / script + assert script_path.exists(), f"Hook script not found: {script_path}" + source = script_path.read_text(encoding="utf-8") + assert "AUTOSKILLIT_HEADLESS" in source, ( + f"{script} is declared with session_scope={hookdef.session_scope!r} " # type: ignore[attr-defined] + f"but does not contain 'AUTOSKILLIT_HEADLESS'. " + f"Add the env-var check or change session_scope to 'any'." + ) + + +def _scoped_guard_names() -> list[str]: + """Return the base name of each unique guard script declared with non-'any' scope.""" + seen: set[str] = set() + result = [] + for hookdef in HOOK_REGISTRY: + scope = getattr(hookdef, "session_scope", "any") + if scope != "any": + for script in hookdef.scripts: + if script not in seen: + seen.add(script) + result.append(script) + return result + + +def _find_test_file(guard_script: str) -> Path | None: + """Locate the test file for a guard script in tests/infra/.""" + stem = Path(guard_script).stem # e.g. "ask_user_question_guard" + tests_infra = Path(__file__).resolve().parent + candidate = tests_infra / f"test_{stem}.py" + return candidate if candidate.exists() else None + + +@pytest.mark.parametrize("guard_script", _scoped_guard_names()) +def test_scoped_guard_has_both_session_type_test_cases(guard_script: str) -> None: + """Every scoped guard's test file must exercise both headless and non-headless paths.""" + test_file = _find_test_file(guard_script) + assert test_file is not None, ( + f"No test file found for scoped guard '{guard_script}'. " + f"Expected: tests/infra/test_{Path(guard_script).stem}.py" + ) + source = test_file.read_text(encoding="utf-8") + code_lines = "\n".join( + line for line in source.splitlines() if not line.lstrip().startswith("#") + ) + has_headless_true = "headless=True" in code_lines or "AUTOSKILLIT_HEADLESS" in code_lines + has_headless_false = "headless=False" in code_lines + assert has_headless_true, ( + f"{test_file.name} must test the headless=True path for scoped guard '{guard_script}'." + ) + assert has_headless_false, ( + f"{test_file.name} must test the headless=False path for scoped guard '{guard_script}'." + ) diff --git a/tests/infra/test_session_start_reminder.py b/tests/infra/test_session_start_reminder.py index 8cedeb7677..1d19a160e3 100644 --- a/tests/infra/test_session_start_reminder.py +++ b/tests/infra/test_session_start_reminder.py @@ -1,13 +1,14 @@ -"""Tests for the SessionStart hook — session_start_reminder.py.""" +"""Tests for the SessionStart hook — session_start_hook.py.""" from __future__ import annotations import json import subprocess import sys +from datetime import UTC from pathlib import Path -SCRIPT = Path(__file__).resolve().parents[2] / "src/autoskillit/hooks/session_start_reminder.py" +SCRIPT = Path(__file__).resolve().parents[2] / "src/autoskillit/hooks/session_start_hook.py" def _run(stdin_data: str) -> tuple[int, str]: @@ -56,3 +57,55 @@ def test_nonexistent_transcript_no_crash(tmp_path: Path) -> None: rc, out = _run(payload) assert rc == 0 assert "additionalContext" not in out + + +def test_session_start_sweeps_stale_markers(tmp_path: Path) -> None: + import json + from datetime import datetime + + marker_dir = tmp_path / "kitchen_state" + marker_dir.mkdir(parents=True) + stale = marker_dir / "old-session.json" + stale.write_text( + json.dumps( + { + "session_id": "old-session", + "opened_at": "2020-01-01T00:00:00+00:00", + "recipe_name": None, + "marker_version": 1, + } + ) + ) + fresh = marker_dir / "new-session.json" + fresh.write_text( + json.dumps( + { + "session_id": "new-session", + "opened_at": datetime.now(UTC).isoformat(), + "recipe_name": None, + "marker_version": 1, + } + ) + ) + transcript = tmp_path / "transcript.jsonl" + transcript.write_text("") + payload = json.dumps( + { + "session_id": "new-session", + "transcript_path": str(transcript), + "autoskillit_state_dir": str(tmp_path), + } + ) + import subprocess + import sys + + result = subprocess.run( + [sys.executable, str(SCRIPT)], + input=payload, + capture_output=True, + text=True, + env={**__import__("os").environ, "AUTOSKILLIT_STATE_DIR": str(tmp_path)}, + ) + assert result.returncode == 0 + assert not stale.exists(), "Stale marker should have been swept" + assert fresh.exists(), "Fresh marker must survive" diff --git a/tests/infra/test_skill_cmd_check.py b/tests/infra/test_skill_cmd_check.py index f2ef04f027..08ac6c6c04 100644 --- a/tests/infra/test_skill_cmd_check.py +++ b/tests/infra/test_skill_cmd_check.py @@ -4,7 +4,7 @@ from io import StringIO from unittest.mock import patch -from autoskillit.hooks.skill_cmd_check import _looks_like_path, main +from autoskillit.hooks.skill_cmd_guard import _looks_like_path, main def _run_hook(tool_input: dict) -> dict | None: @@ -197,3 +197,59 @@ def test_hookSpecificOutput_structure(self): assert hso["hookEventName"] == "PreToolUse" assert hso["permissionDecision"] == "deny" assert "permissionDecisionReason" in hso + + def test_deny_suggests_all_tokens_single_line(self): + """Corrected command includes path tokens first, then non-path tokens.""" + cmd = "/autoskillit:retry-worktree use this plan .autoskillit/temp/plan.md /path/worktree" + result = _run_hook({"skill_command": cmd}) + assert _decision(result) == "deny" + reason = result["hookSpecificOutput"]["permissionDecisionReason"] + # Both path tokens appear in corrected suggestion + assert ".autoskillit/temp/plan.md" in reason + assert "/path/worktree" in reason + # Non-path tokens also preserved in the suggestion + assert "use this plan" in reason + + def test_deny_suggests_paths_before_non_path_tokens(self): + """In corrected command, path tokens appear before non-path tokens.""" + cmd = ( + "/autoskillit:implement-worktree-no-merge the verified plan" + " .autoskillit/temp/rectify/plan.md" + ) + result = _run_hook({"skill_command": cmd}) + reason = result["hookSpecificOutput"]["permissionDecisionReason"] + path_pos = reason.find(".autoskillit/temp/rectify/plan.md") + nonpath_pos = reason.find("the verified plan") + # Path must appear before non-path text in the corrected suggestion + assert path_pos < nonpath_pos + + def test_deny_multiline_prose_before_path_preserves_prose_after_path(self): + """Multiline prose context is preserved and placed after path args in suggestion.""" + cmd = ( + "/autoskillit:implement-worktree-no-merge " + "implement the feature described below\n\n" + ".autoskillit/temp/plan.md" + ) + result = _run_hook({"skill_command": cmd}) + assert _decision(result) == "deny" + reason = result["hookSpecificOutput"]["permissionDecisionReason"] + # Path must appear in the corrected suggestion + assert ".autoskillit/temp/plan.md" in reason + # Prose content must also be present (not dropped) + assert "implement the feature described below" in reason + # Path precedes prose in the corrected suggestion + path_pos = reason.find(".autoskillit/temp/plan.md") + prose_pos = reason.find("implement the feature described below") + assert path_pos < prose_pos + + def test_deny_message_no_old_parenthetical(self): + """Old '(append any remaining positional args...)' phrasing must not appear.""" + result = _run_hook({"skill_command": _CANONICAL_BUG}) + reason = result["hookSpecificOutput"]["permissionDecisionReason"] + assert "append any remaining positional args" not in reason + + def test_deny_message_uses_relocate_wording(self): + """Deny message must explicitly say 'relocate' or 'Relocate'.""" + result = _run_hook({"skill_command": _CANONICAL_BUG}) + reason = result["hookSpecificOutput"]["permissionDecisionReason"] + assert "relocate" in reason.lower() diff --git a/tests/infra/test_taskfile.py b/tests/infra/test_taskfile.py index e164dd8cdb..03ff88f9b7 100644 --- a/tests/infra/test_taskfile.py +++ b/tests/infra/test_taskfile.py @@ -1,5 +1,6 @@ from __future__ import annotations +import re from pathlib import Path import yaml @@ -60,3 +61,27 @@ def test_install_dev_task_uses_integration_branch(self): cmds = " ".join(str(c) for c in task.get("cmds", [])) assert "@integration" in cmds, "install-dev must install from @integration branch" assert "autoskillit install" in cmds, "install-dev must run autoskillit install after uv" + + def test_vendor_mermaid_task_exists(self) -> None: + """REQ-R741-A02 — vendor-mermaid task must be declared in Taskfile.yml.""" + data = self._load() + assert "vendor-mermaid" in data["tasks"], "vendor-mermaid task missing from Taskfile.yml" + + def test_vendor_mermaid_task_targets_v11(self) -> None: + """REQ-R741-A02 — vendor-mermaid task must reference mermaid@11 and the asset path.""" + data = self._load() + task = data["tasks"]["vendor-mermaid"] + cmds = " ".join(str(c) for c in task.get("cmds", [])) + assert "mermaid@11" in cmds, "vendor-mermaid must curl mermaid@11" + assert "assets/mermaid/mermaid.min.js" in cmds, ( + "vendor-mermaid must write to src/autoskillit/assets/mermaid/mermaid.min.js" + ) + + +def test_taskfile_pytest_paths_exist() -> None: + """All pytest file paths in Taskfile.yml must exist.""" + raw = TASKFILE.read_text() + paths = re.findall(r"tests/[\w/]+\.py", raw) + for path_str in paths: + full = REPO_ROOT / path_str + assert full.exists(), f"Taskfile references {path_str} but it does not exist" diff --git a/tests/infra/test_token_summary_appender.py b/tests/infra/test_token_summary_appender.py index 44c8a49df0..0ae7465395 100644 --- a/tests/infra/test_token_summary_appender.py +++ b/tests/infra/test_token_summary_appender.py @@ -14,6 +14,8 @@ from pathlib import Path from unittest.mock import MagicMock, patch +from autoskillit.hooks._fmt_primitives import _HOOK_CONFIG_PATH_COMPONENTS + def _run_hook( event: dict | None = None, @@ -32,7 +34,7 @@ def _run_hook( value from that file. When absent, ``_read_kitchen_id`` reads from the real filesystem (returns '' if no file present in the test CWD). """ - from autoskillit.hooks.token_summary_appender import main + from autoskillit.hooks.token_summary_hook import main stdin_text = raw_stdin if raw_stdin is not None else json.dumps(event or {}) exit_code = 0 @@ -44,7 +46,7 @@ def _run_hook( if log_root is not None: stack.enter_context( patch( - "autoskillit.hooks.token_summary_appender._log_root", + "autoskillit.hooks.token_summary_hook._log_root", return_value=log_root, ) ) @@ -53,7 +55,7 @@ def _run_hook( kitchen_id = cfg_data.get("kitchen_id") or cfg_data.get("pipeline_id", "") stack.enter_context( patch( - "autoskillit.hooks.token_summary_appender._read_kitchen_id", + "autoskillit.hooks.token_summary_hook._read_kitchen_id", return_value=kitchen_id, ) ) @@ -99,10 +101,10 @@ def _write_sessions(log_root: Path, entries: list[dict]) -> None: def test_tsa1_token_summary_appender_script_exists() -> None: - """token_summary_appender.py must exist in hooks/ on disk.""" + """token_summary_hook.py must exist in hooks/ on disk.""" from autoskillit.core.paths import pkg_root - assert (pkg_root() / "hooks" / "token_summary_appender.py").exists() + assert (pkg_root() / "hooks" / "token_summary_hook.py").exists() def test_tsa_rest_api_no_gh_pr_commands() -> None: @@ -112,7 +114,7 @@ def test_tsa_rest_api_no_gh_pr_commands() -> None: """ from autoskillit.core.paths import pkg_root - source = (pkg_root() / "hooks" / "token_summary_appender.py").read_text(encoding="utf-8") + source = (pkg_root() / "hooks" / "token_summary_hook.py").read_text(encoding="utf-8") assert "gh pr edit" not in source, ( "gh pr edit found in hook — must be replaced with " "gh api repos/.../pulls/{N} --method PATCH --field body=..." @@ -131,7 +133,7 @@ def test_tsa2_no_pr_url_exits_zero() -> None: """No GitHub PR URL in tool result → exits 0, no gh subprocess.""" from autoskillit.core.paths import pkg_root - hook_path = pkg_root() / "hooks" / "token_summary_appender.py" + hook_path = pkg_root() / "hooks" / "token_summary_hook.py" event = _make_run_skill_event("done.\n%%ORDER_UP%%") stdin_text = json.dumps(event) @@ -271,6 +273,10 @@ def subprocess_side_effect(args: list[str], **kwargs: object) -> MagicMock: assert "open-pr" in body_content # Total row assert "**Total**" in body_content + # 4-column token headers + assert "uncached" in body_content + assert "cache_read" in body_content + assert "cache_write" in body_content # --------------------------------------------------------------------------- @@ -332,7 +338,7 @@ def subprocess_side_effect(args: list[str], **kwargs: object) -> MagicMock: def test_tsa7_canonical_step_name() -> None: """_canonical strips trailing -N suffix; non-digit suffixes are preserved.""" - from autoskillit.hooks.token_summary_appender import _canonical + from autoskillit.hooks.token_summary_hook import _canonical assert _canonical("plan-30") == "plan" assert _canonical("open-pr-2") == "open-pr" @@ -348,7 +354,7 @@ def test_tsa7_canonical_step_name() -> None: def test_tsa8_gh_pr_edit_failure_exits_nonzero(tmp_path: Path) -> None: - """gh pr edit returning non-zero → hook exits non-zero (error surfaced).""" + """gh pr edit returning non-zero → hook exits 0 (fail-open, error logged to stderr).""" log_root = tmp_path / "logs" log_root.mkdir() pipeline_id = "test-pipeline-tsa8" @@ -390,7 +396,7 @@ def subprocess_side_effect(args: list[str], **kwargs: object) -> MagicMock: with patch("subprocess.run", side_effect=subprocess_side_effect): _, exit_code = _run_hook(event, log_root=log_root, hook_config_path=hook_config) - assert exit_code != 0 + assert exit_code == 0 # --------------------------------------------------------------------------- @@ -528,7 +534,7 @@ def run_side(args, **kwargs): mock_stderr.write = lambda s: stderr_output.append(s) _, exit_code = _run_hook(event, log_root=log_root, hook_config_path=hook_config) - assert exit_code == 1 + assert exit_code == 0 combined = "".join(stderr_output) assert "authentication required" in combined, ( "stderr from CalledProcessError must appear in diagnostic output — " @@ -587,7 +593,7 @@ def test_tsa_humanize_preserves_decimal() -> None: Fails before P6-2 fix (str(int(45.7)) → '45'), passes after (str(45.7) → '45.7'). Token counts are always integers in practice, so this is a semantic correctness fix. """ - from autoskillit.hooks.token_summary_appender import _humanize + from autoskillit.hooks.token_summary_hook import _humanize assert _humanize(999) == "999" assert _humanize(0) == "0" @@ -802,12 +808,75 @@ def test_e3_backward_compat_sessions_without_order_id_field(tmp_path: Path) -> N assert len(patch_calls) == 0, "Old sessions without order_id should be skipped" +# --------------------------------------------------------------------------- +# T4 — token_summary_appender is fail-open (exit 0 on errors) +# --------------------------------------------------------------------------- + + +def test_token_summary_hook_patch_failure_exits_zero(tmp_path: Path) -> None: + """CalledProcessError on PATCH must exit 0, not 1 (fail-open hook).""" + event = { + "tool_name": "mcp__autoskillit_server__run_skill", + "tool_response": json.dumps({"result": json.dumps({"success": True})}), + } + # Use a valid-enough PR URL to trigger the gh api PATCH path + pr_event = { + **event, + "tool_response": json.dumps( + { + "result": json.dumps( + { + "success": True, + "pr_url": "https://github.com/owner/repo/pull/1", + } + ) + } + ), + } + + original_run = subprocess.run + + def failing_run(cmd, **kwargs): + if "PATCH" in (cmd if isinstance(cmd, str) else " ".join(str(c) for c in cmd)): + raise subprocess.CalledProcessError(1, cmd, stderr="API error") + return original_run(cmd, **kwargs) + + with patch("autoskillit.hooks.token_summary_hook.subprocess.run", failing_run): + _, exit_code = _run_hook( + event=pr_event, + log_root=tmp_path, + ) + # hook must exit 0 even when gh api PATCH raises CalledProcessError + assert exit_code == 0 + + +def test_token_summary_hook_unexpected_error_exits_zero(monkeypatch: object) -> None: + """Unhandled exception in outer except must exit 0 (fail-open).""" + + # Patch json.loads to raise to trigger the outer except path + + original_loads = json.loads + + call_count = [0] + + def bomb_loads(s: str) -> object: + call_count[0] += 1 + if call_count[0] == 1: + raise RuntimeError("injected failure") + return original_loads(s) + + with patch("autoskillit.hooks.token_summary_hook.json.loads", bomb_loads): + _, exit_code = _run_hook(event={"tool_name": "any", "tool_response": "{}"}) + + assert exit_code == 0 + + def test_e4_kitchen_id_renamed_in_hook_config(tmp_path: Path) -> None: """E-4: _read_kitchen_id reads 'kitchen_id' key; falls back to 'pipeline_id' for old.""" - from autoskillit.hooks.token_summary_appender import _read_kitchen_id + from autoskillit.hooks.token_summary_hook import _read_kitchen_id # New format - cfg_path = tmp_path / ".autoskillit" / "temp" / ".autoskillit_hook_config.json" + cfg_path = tmp_path.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS) cfg_path.parent.mkdir(parents=True) cfg_path.write_text(json.dumps({"kitchen_id": "new-kitchen-uuid"})) @@ -818,3 +887,21 @@ def test_e4_kitchen_id_renamed_in_hook_config(tmp_path: Path) -> None: cfg_path.write_text(json.dumps({"pipeline_id": "legacy-pipeline-uuid"})) result = _read_kitchen_id(base=tmp_path) assert result == "legacy-pipeline-uuid" + + +def test_hook_subprocess_calls_have_timeout() -> None: + """All subprocess.run() calls in token_summary_hook.py must have timeout=.""" + import ast + + src = Path("src/autoskillit/hooks/token_summary_hook.py").read_text() + tree = ast.parse(src) + for node in ast.walk(tree): + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "run" + ): + kw_names = {kw.arg for kw in node.keywords} + assert "timeout" in kw_names, ( + f"subprocess.run() at line {node.lineno} in token_summary_hook.py missing timeout=" + ) diff --git a/tests/migration/test_engine.py b/tests/migration/test_engine.py index 758f55735a..d4df822a5d 100644 --- a/tests/migration/test_engine.py +++ b/tests/migration/test_engine.py @@ -24,6 +24,8 @@ ) from autoskillit.migration.loader import MigrationChange, MigrationNote +PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent + # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- @@ -292,8 +294,9 @@ async def test_contract_adapter_migrate_regenerates_card_on_disk(self, tmp_path: contracts_dir = recipes_dir / "contracts" contracts_dir.mkdir(parents=True) - # Copy a real bundled recipe so generate_recipe_card has valid input - src_recipe = pkg_root() / "recipes" / "smoke-test.yaml" + # Copy the project-local smoke-test recipe so generate_recipe_card has valid input + src_recipe = PROJECT_ROOT / ".autoskillit" / "recipes" / "smoke-test.yaml" + assert src_recipe.exists(), f"smoke-test source missing: {src_recipe}" shutil.copy2(src_recipe, recipes_dir / "smoke-test.yaml") contract_path = contracts_dir / "smoke-test.yaml" diff --git a/tests/pipeline/test_context.py b/tests/pipeline/test_context.py index e28396f606..f34a5e94d2 100644 --- a/tests/pipeline/test_context.py +++ b/tests/pipeline/test_context.py @@ -5,6 +5,8 @@ from pathlib import Path from typing import get_args, get_type_hints +import pytest + from autoskillit.config import AutomationConfig from autoskillit.core import GitHubFetcher from autoskillit.pipeline.audit import DefaultAuditLog, FailureRecord @@ -156,6 +158,20 @@ def test_headless_executor_protocol_accepts_timeout() -> None: assert params["stale_threshold"].default is None +def test_headless_executor_protocol_accepts_idle_output_timeout() -> None: + """HeadlessExecutor.run() signature must include optional idle_output_timeout.""" + import inspect + + from autoskillit.core import HeadlessExecutor + + sig = inspect.signature(HeadlessExecutor.run) + params = sig.parameters + assert "idle_output_timeout" in params, ( + "HeadlessExecutor.run missing idle_output_timeout param" + ) + assert params["idle_output_timeout"].default is None + + def test_recipe_repository_protocol_has_rich_methods() -> None: """RecipeRepository protocol must expose load_and_validate, validate_from_path, list_all.""" from autoskillit.core import RecipeRepository @@ -185,7 +201,7 @@ def test_toolcontext_github_client_annotated_with_protocol(): def test_toolcontext_response_log_annotated_with_mcp_response_store_protocol() -> None: - """ToolContext.response_log must be annotated with the McpResponseStore protocol. + """ToolContext.response_log must be annotated with the McpResponseLog protocol. response_log uses default_factory (Null Object pattern) not field(default=None), so it is excluded from test_toolcontext_optional_fields_all_have_protocol_annotations. @@ -193,28 +209,28 @@ def test_toolcontext_response_log_annotated_with_mcp_response_store_protocol() - """ from typing import get_type_hints - from autoskillit.core import McpResponseStore + from autoskillit.core import McpResponseLog hints = get_type_hints(ToolContext) assert "response_log" in hints, "ToolContext must have a response_log field" - assert hints["response_log"] is McpResponseStore, ( - f"ToolContext.response_log must be annotated with McpResponseStore protocol, " + assert hints["response_log"] is McpResponseLog, ( + f"ToolContext.response_log must be annotated with McpResponseLog protocol, " f"got: {hints['response_log']!r}" ) def test_tool_context_has_timing_log_field(tmp_path): - """ToolContext.timing_log is a non-None TimingStore instance.""" - from autoskillit.core import TimingStore + """ToolContext.timing_log is a non-None TimingLog instance.""" + from autoskillit.core import TimingLog ctx = _make_ctx(tmp_path) assert ctx.timing_log is not None - assert isinstance(ctx.timing_log, TimingStore) + assert isinstance(ctx.timing_log, TimingLog) -def test_toolcontext_default_background_wired_with_audit(tmp_path): - """ToolContext without explicit background= must produce a supervisor - whose audit is the same instance as ctx.audit.""" +@pytest.mark.anyio +async def test_toolcontext_default_background_wired_with_audit(tmp_path): + """ToolContext background supervisor records failures to ctx.audit.""" from autoskillit.pipeline.background import DefaultBackgroundSupervisor audit = DefaultAuditLog() @@ -228,4 +244,38 @@ def test_toolcontext_default_background_wired_with_audit(tmp_path): runner=None, ) assert isinstance(ctx.background, DefaultBackgroundSupervisor) - assert ctx.background._audit is audit + + async def _fail() -> None: + raise RuntimeError("deliberate test failure") + + ctx.background.submit(_fail(), label="test-task") + await ctx.background.drain() + + records = audit.get_report() + assert any(r.subtype == "background_exception" for r in records) + + +# --------------------------------------------------------------------------- +# token_factory field +# --------------------------------------------------------------------------- + + +def test_tool_context_has_token_factory_field(): + """ToolContext dataclass exposes token_factory as an optional callable Protocol field.""" + import dataclasses + import typing + + from autoskillit.core import TokenFactory + from autoskillit.pipeline.context import ToolContext + + fields = {f.name: f for f in dataclasses.fields(ToolContext)} + assert "token_factory" in fields + assert fields["token_factory"].default is None + + hints = typing.get_type_hints(ToolContext) + assert "token_factory" in hints + # Annotation must be a union that includes the TokenFactory Protocol (callable) + args = typing.get_args(hints["token_factory"]) + assert TokenFactory in args, ( + f"token_factory type hint {hints['token_factory']} does not include TokenFactory Protocol" + ) diff --git a/tests/pipeline/test_fidelity.py b/tests/pipeline/test_fidelity.py deleted file mode 100644 index b21a8a6da9..0000000000 --- a/tests/pipeline/test_fidelity.py +++ /dev/null @@ -1,175 +0,0 @@ -"""Tests for review-pr fidelity dimension: linked issue extraction and findings. - -These tests verify the Python helpers in -autoskillit.execution.pr_analysis, which support the fidelity subagent described -in the review-pr SKILL.md Steps 2.8 and 3. -""" - -from __future__ import annotations - -from autoskillit.execution.pr_analysis import ( - extract_linked_issues, - is_valid_fidelity_finding, -) - -# --------------------------------------------------------------------------- -# extract_linked_issues — PR body and commit messages -# --------------------------------------------------------------------------- - - -def test_linked_issue_extraction_closes(): - """'Closes #123' in PR body yields ['123'].""" - result = extract_linked_issues("Closes #123\n\nSome description.") - assert result == ["123"] - - -def test_linked_issue_extraction_fixes_commit(): - """'Fixes #456' in commit headline is extracted.""" - result = extract_linked_issues("Fixes #456: update auth handler") - assert result == ["456"] - - -def test_linked_issue_extraction_resolves(): - """'Resolves #789' is extracted.""" - result = extract_linked_issues("Resolves #789") - assert result == ["789"] - - -def test_linked_issue_extraction_multiple(): - """'Closes #1, Resolves #2' yields both numbers deduplicated.""" - body = "Closes #1\nResolves #2\nSome description." - result = extract_linked_issues(body) - assert sorted(result, key=int) == ["1", "2"] - # Check deduplication: each issue appears once - assert len(result) == len(set(result)) - - -def test_linked_issue_extraction_deduplication(): - """Same issue referenced twice yields one entry.""" - text = "Closes #42\nFixes #42" - result = extract_linked_issues(text) - assert result == ["42"] - - -def test_linked_issue_extraction_none(): - """PR body with no Closes/Fixes/Resolves refs yields empty list.""" - result = extract_linked_issues("Just a generic PR description.") - assert result == [] - - -def test_linked_issue_extraction_case_insensitive(): - """Extraction is case-insensitive: CLOSES, fixes, Resolves all match.""" - result = extract_linked_issues("CLOSES #10\nfixes #20\nResolves #30") - assert sorted(result, key=int) == ["10", "20", "30"] - - -def test_linked_issue_extraction_commit_concatenation(): - """PR body and commit messages concatenated together yield combined results.""" - pr_body = "Closes #100" - commits = "Fixes #200" - combined = f"{pr_body}\n{commits}" - result = extract_linked_issues(combined) - assert sorted(result, key=int) == ["100", "200"] - - -def test_linked_issue_extraction_empty_string(): - """Empty string yields empty list.""" - assert extract_linked_issues("") == [] - - -# --------------------------------------------------------------------------- -# is_valid_fidelity_finding — format validation -# --------------------------------------------------------------------------- - - -def test_fidelity_finding_format(): - """Fidelity subagent output JSON has dimension='fidelity' and valid severity.""" - finding = { - "file": "src/auth.py", - "line": 42, - "dimension": "fidelity", - "severity": "critical", - "message": "Missing requirement: OAuth token refresh not implemented.", - "requires_decision": False, - } - assert is_valid_fidelity_finding(finding) is True - - -def test_fidelity_gap_is_actionable(): - """Gap finding has severity='critical' and requires_decision=false.""" - gap = { - "file": "src/auth.py", - "line": 10, - "dimension": "fidelity", - "severity": "critical", - "message": "Gap: token refresh flow not addressed.", - "requires_decision": False, - } - assert is_valid_fidelity_finding(gap) is True - assert gap["severity"] == "critical" - assert gap["requires_decision"] is False - - -def test_fidelity_drift_is_warning(): - """Drift finding has severity='warning'.""" - drift = { - "file": "src/logging.py", - "line": 7, - "dimension": "fidelity", - "severity": "warning", - "message": "Drift: logging config changed with no corresponding issue requirement.", - "requires_decision": False, - } - assert is_valid_fidelity_finding(drift) is True - assert drift["severity"] == "warning" - - -def test_fidelity_gap_with_no_file_is_valid(): - """Gap finding with file='' and line=0 is valid (unpostable — summary only).""" - gap = { - "file": "", - "line": 0, - "dimension": "fidelity", - "severity": "critical", - "message": "Gap: entire feature section 'notifications' not implemented.", - "requires_decision": False, - } - assert is_valid_fidelity_finding(gap) is True - - -def test_fidelity_finding_wrong_dimension_invalid(): - """Finding with dimension='arch' is not a valid fidelity finding.""" - finding = { - "file": "src/auth.py", - "line": 1, - "dimension": "arch", - "severity": "critical", - "message": "some issue", - "requires_decision": False, - } - assert is_valid_fidelity_finding(finding) is False - - -def test_fidelity_finding_unknown_severity_invalid(): - """Finding with severity='high' (not critical/warning) is invalid.""" - finding = { - "file": "src/auth.py", - "line": 1, - "dimension": "fidelity", - "severity": "high", - "message": "some issue", - "requires_decision": False, - } - assert is_valid_fidelity_finding(finding) is False - - -def test_fidelity_skipped_when_no_linked_issues(): - """extract_linked_issues returns [] for PRs with no Closes/Fixes/Resolves refs. - - The fidelity skip condition is len(linked_issues) == 0. This test confirms - that a PR body without issue references produces an empty list, which is the - signal the review-pr skill uses to skip fidelity subagent launch. - """ - pr_body = "This PR adds a minor cleanup, no issue references." - linked = extract_linked_issues(pr_body) - assert linked == [] diff --git a/tests/pipeline/test_gate.py b/tests/pipeline/test_gate.py index 23dae638f0..6a18a4af13 100644 --- a/tests/pipeline/test_gate.py +++ b/tests/pipeline/test_gate.py @@ -1,25 +1,6 @@ # test_gate.py — unit tests for _gate.py constants and functions -def test_gated_tools_is_frozenset(): - from autoskillit.pipeline.gate import GATED_TOOLS - - assert isinstance(GATED_TOOLS, frozenset) - - -def test_ungated_tools_is_frozenset(): - from autoskillit.pipeline.gate import UNGATED_TOOLS - - assert isinstance(UNGATED_TOOLS, frozenset) - - -def test_tool_sets_total_count(): - from autoskillit.pipeline.gate import GATED_TOOLS, UNGATED_TOOLS - - assert len(GATED_TOOLS) == 39 - assert len(UNGATED_TOOLS) == 2 - - def test_gated_tools_contains_expected_names(): from autoskillit.pipeline.gate import GATED_TOOLS @@ -49,6 +30,7 @@ def test_gated_tools_contains_expected_names(): "check_pr_mergeable", "set_commit_status", "wait_for_merge_queue", + "check_repo_merge_state", "toggle_auto_merge", # formerly ungated — now kitchen-gated: "fetch_github_issue", @@ -80,7 +62,7 @@ def test_check_quota_not_in_ungated_tools(): def test_ungated_tools_contains_expected_names(): from autoskillit.pipeline.gate import UNGATED_TOOLS - expected = {"open_kitchen", "close_kitchen"} + expected = {"open_kitchen", "close_kitchen", "disable_quota_guard"} assert UNGATED_TOOLS == expected @@ -187,28 +169,16 @@ def test_gated_tools_does_not_contain_run_recipe(): assert "run_recipe" not in GATED_TOOLS -def test_headless_tools_is_frozenset(): - from autoskillit.core.types import HEADLESS_TOOLS - - assert isinstance(HEADLESS_TOOLS, frozenset) - - def test_headless_tools_contains_expected_names(): from autoskillit.core.types import HEADLESS_TOOLS assert HEADLESS_TOOLS == {"test_check"} -def test_free_range_tools_is_frozenset(): - from autoskillit.core.types import FREE_RANGE_TOOLS - - assert isinstance(FREE_RANGE_TOOLS, frozenset) - - def test_free_range_tools_contains_expected_names(): from autoskillit.core.types import FREE_RANGE_TOOLS - assert FREE_RANGE_TOOLS == {"open_kitchen", "close_kitchen"} + assert FREE_RANGE_TOOLS == {"open_kitchen", "close_kitchen", "disable_quota_guard"} def test_ungated_tools_equals_free_range_tools(): @@ -224,7 +194,6 @@ def test_all_tool_sets_disjoint_and_complete(): assert GATED_TOOLS.isdisjoint(UNGATED_TOOLS) assert GATED_TOOLS.isdisjoint(HEADLESS_TOOLS) assert UNGATED_TOOLS.isdisjoint(HEADLESS_TOOLS) - assert len(GATED_TOOLS | UNGATED_TOOLS | HEADLESS_TOOLS) == 42 def test_worker_tools_removed_from_core(): diff --git a/tests/pipeline/test_pr_domain_partitioner.py b/tests/pipeline/test_pr_domain_partitioner.py deleted file mode 100644 index 9d3133565b..0000000000 --- a/tests/pipeline/test_pr_domain_partitioner.py +++ /dev/null @@ -1,100 +0,0 @@ -from __future__ import annotations - -from autoskillit.execution.pr_analysis import DOMAIN_PATHS, partition_files_by_domain - - -def test_server_files_assigned_to_server_domain(): - result = partition_files_by_domain(["src/autoskillit/server/tools_execution.py"]) - assert "Server/MCP Tools" in result - assert "src/autoskillit/server/tools_execution.py" in result["Server/MCP Tools"] - - -def test_execution_file_assigned_to_pipeline_execution_domain(): - result = partition_files_by_domain(["src/autoskillit/execution/headless.py"]) - assert "Pipeline/Execution" in result - assert "src/autoskillit/execution/headless.py" in result["Pipeline/Execution"] - - -def test_pipeline_file_assigned_to_pipeline_execution_domain(): - result = partition_files_by_domain(["src/autoskillit/pipeline/pr_gates.py"]) - assert "Pipeline/Execution" in result - assert "src/autoskillit/pipeline/pr_gates.py" in result["Pipeline/Execution"] - - -def test_recipe_file_assigned_to_recipe_domain(): - result = partition_files_by_domain(["src/autoskillit/recipe/schema.py"]) - assert "Recipe/Validation" in result - - -def test_cli_file_assigned_to_cli_workspace_domain(): - result = partition_files_by_domain(["src/autoskillit/cli/app.py"]) - assert "CLI/Workspace" in result - - -def test_workspace_file_assigned_to_cli_workspace_domain(): - result = partition_files_by_domain(["src/autoskillit/workspace/skills.py"]) - assert "CLI/Workspace" in result - - -def test_skills_file_assigned_to_skills_domain(): - result = partition_files_by_domain(["src/autoskillit/skills_extended/open-pr/SKILL.md"]) - assert "Skills" in result - - -def test_test_file_assigned_to_tests_domain(): - result = partition_files_by_domain(["tests/test_something.py"]) - assert "Tests" in result - - -def test_core_file_assigned_to_core_config_infra(): - result = partition_files_by_domain(["src/autoskillit/core/types.py"]) - assert "Core/Config/Infra" in result - - -def test_config_file_assigned_to_core_config_infra(): - result = partition_files_by_domain(["src/autoskillit/config/settings.py"]) - assert "Core/Config/Infra" in result - - -def test_hooks_file_assigned_to_core_config_infra(): - result = partition_files_by_domain(["src/autoskillit/hooks/quota_check.py"]) - assert "Core/Config/Infra" in result - - -def test_unknown_file_goes_to_other(): - result = partition_files_by_domain(["pyproject.toml"]) - assert "Other" in result - assert "pyproject.toml" in result["Other"] - - -def test_empty_list_returns_empty_dict(): - result = partition_files_by_domain([]) - assert result == {} - - -def test_result_only_includes_non_empty_domains(): - result = partition_files_by_domain(["src/autoskillit/server/tools_execution.py"]) - assert "Tests" not in result - assert "Skills" not in result - - -def test_domain_paths_defines_at_least_seven_domains(): - assert len(DOMAIN_PATHS) >= 7 - - -def test_mixed_files_across_multiple_domains(): - files = [ - "src/autoskillit/server/tools_execution.py", - "src/autoskillit/execution/headless.py", - "tests/test_something.py", - ] - result = partition_files_by_domain(files) - assert "Server/MCP Tools" in result - assert "Pipeline/Execution" in result - assert "Tests" in result - - -def test_custom_domain_paths_override(): - custom = {"MyDomain": ["custom/path/"]} - result = partition_files_by_domain(["custom/path/foo.py"], domain_paths=custom) - assert "MyDomain" in result diff --git a/tests/pipeline/test_telemetry_formatter.py b/tests/pipeline/test_telemetry_formatter.py index 9e8e5a279a..23b14e8973 100644 --- a/tests/pipeline/test_telemetry_formatter.py +++ b/tests/pipeline/test_telemetry_formatter.py @@ -57,6 +57,9 @@ def test_produces_markdown_table(self) -> None: result = TelemetryFormatter.format_token_table(_STEPS, _TOTAL) assert "| Step |" in result assert "|---" in result + assert "| uncached |" in result + assert "| cache_read |" in result + assert "| cache_write |" in result assert "- input_tokens:" not in result assert "# Token Summary" not in result @@ -121,10 +124,10 @@ def test_snapshot(self) -> None: [ "## Token Usage Summary", "", - "| Step | input | output | cached | count | time |", - "|------|-------|--------|--------|-------|------|", - "| plan | 1.0k | 500 | 300 | 1 | 46s |", - "| **Total** | 1.0k | 500 | 300 | | 46s |", + "| Step | uncached | output | cache_read | cache_write | count | time |", + "|------|----------|--------|------------|-------------|-------|------|", + "| plan | 1.0k | 500 | 200 | 100 | 1 | 46s |", + "| **Total** | 1.0k | 500 | 200 | 100 | | 46s |", ] ) assert result == expected @@ -224,6 +227,29 @@ def test_format_timing_table_terminal_output_has_leading_indent() -> None: # --------------------------------------------------------------------------- +def test_terminal_table_has_four_token_columns() -> None: + """Terminal table must show UNCACHED, CACHE_RD, CACHE_WR column headers.""" + result = TelemetryFormatter.format_token_table_terminal(_STEPS, _TOTAL) + assert "UNCACHED" in result + assert "CACHE_RD" in result + assert "CACHE_WR" in result + + +def test_compact_kv_four_token_prefixes() -> None: + """Compact KV format must use uc:, cr:, cw: prefixes and split totals.""" + result = TelemetryFormatter.format_compact_kv(_STEPS, _TOTAL) + assert "uc:" in result + assert "cr:" in result + assert "cw:" in result + assert "total_uncached:" in result + assert "total_cache_read:" in result + assert "total_cache_write:" in result + assert "in:" not in result + assert " cached:" not in result + assert "total_in:" not in result + assert "total_cached:" not in result + + class TestFormatCompactKv: def test_produces_compact_lines(self) -> None: result = TelemetryFormatter.format_compact_kv(_STEPS, _TOTAL) @@ -233,14 +259,15 @@ def test_produces_compact_lines(self) -> None: def test_includes_humanized_tokens(self) -> None: result = TelemetryFormatter.format_compact_kv(_STEPS, _TOTAL) - assert "in:7.0k" in result + assert "uc:7.0k" in result assert "out:5.9k" in result def test_includes_total_lines(self) -> None: result = TelemetryFormatter.format_compact_kv(_STEPS, _TOTAL) - assert "total_in:" in result + assert "total_uncached:" in result assert "total_out:" in result - assert "total_cached:" in result + assert "total_cache_read:" in result + assert "total_cache_write:" in result def test_prefers_wall_clock_seconds(self) -> None: result = TelemetryFormatter.format_compact_kv(_STEPS, _TOTAL) diff --git a/tests/pipeline/test_timings.py b/tests/pipeline/test_timings.py index 9a953c7b16..49a47a2e40 100644 --- a/tests/pipeline/test_timings.py +++ b/tests/pipeline/test_timings.py @@ -210,6 +210,17 @@ def test_returns_count(self, tmp_path): n = log.load_from_log_dir(tmp_path) assert n == 2 + def test_load_null_total_seconds(self, tmp_path): + """TimingLog must handle total_seconds: null without TypeError.""" + from autoskillit.pipeline.timings import DefaultTimingLog + + _write_timing_session(tmp_path, "s001", {"step_name": "implement", "total_seconds": None}) + log = DefaultTimingLog() + n = log.load_from_log_dir(tmp_path) + assert n == 1 + report = log.get_report() + assert report[0]["total_seconds"] == 0.0 + class TestLoadFromLogDirCwdFilterTiming: """ diff --git a/tests/pipeline/test_tokens.py b/tests/pipeline/test_tokens.py index c0f160329e..d0577ec5b5 100644 --- a/tests/pipeline/test_tokens.py +++ b/tests/pipeline/test_tokens.py @@ -247,7 +247,7 @@ def test_record_backward_clock_elapsed_is_non_negative(self): end_ts="2026-01-01T12:00:00+00:00", # earlier ) entries = log.get_report() - assert entries[0]["elapsed_seconds"] >= 0 + assert entries[0]["elapsed_seconds"] == pytest.approx(0.0) def test_record_uses_elapsed_seconds_param_over_iso_subtraction(self): """When elapsed_seconds kwarg is provided, it is used directly, not ISO subtraction.""" @@ -395,6 +395,26 @@ def test_empty_log_root_returns_zero(self, tmp_path): n = log.load_from_log_dir(tmp_path) assert n == 0 + def test_load_null_timing_seconds(self, tmp_path): + """TokenLog must handle timing_seconds: null without TypeError.""" + _write_session( + tmp_path, + "s001", + { + "step_name": "implement", + "input_tokens": 100, + "output_tokens": 50, + "cache_creation_input_tokens": 0, + "cache_read_input_tokens": 0, + "timing_seconds": None, + }, + ) + log = DefaultTokenLog() + n = log.load_from_log_dir(tmp_path) + assert n == 1 + report = log.get_report() + assert report[0]["elapsed_seconds"] == 0.0 + class TestLoadFromLogDirDesignDocumentation: """P9-F1: tokens.py must document design decisions inline.""" diff --git a/tests/recipe/fixtures/clone_local_with_remote_url_capture_invalid.yaml b/tests/recipe/fixtures/clone_local_with_remote_url_capture_invalid.yaml new file mode 100644 index 0000000000..9d7276ef46 --- /dev/null +++ b/tests/recipe/fixtures/clone_local_with_remote_url_capture_invalid.yaml @@ -0,0 +1,23 @@ +name: clone-local-with-remote-url-capture-invalid +description: > + Negative fixture: clone_repo with strategy=clone_local captures remote_url. + This is the dangerous combination rejected by the + clone-local-strategy-with-remote-url-capture rule. +kitchen_rules: Use run_skill. + +steps: + clone: + tool: run_python + python: autoskillit.workspace.clone.clone_repo + with: + strategy: clone_local + run_name: test-run + capture: + remote_url: "${{ result.remote_url }}" + clone_path: "${{ result.clone_path }}" + + push_final: + tool: push_to_remote + with: + remote_url: "${{ context.remote_url }}" + clone_path: "${{ context.clone_path }}" diff --git a/tests/recipe/fixtures/clone_local_without_remote_url_capture_valid.yaml b/tests/recipe/fixtures/clone_local_without_remote_url_capture_valid.yaml new file mode 100644 index 0000000000..062e4a5c99 --- /dev/null +++ b/tests/recipe/fixtures/clone_local_without_remote_url_capture_valid.yaml @@ -0,0 +1,16 @@ +name: clone-local-without-remote-url-capture-valid +description: > + Positive fixture: clone_repo with strategy=clone_local captures only clone_path, + not remote_url. This is the legitimate local-clone usage that must pass the + clone-local-strategy-with-remote-url-capture rule. +kitchen_rules: Use run_skill. + +steps: + clone: + tool: run_python + python: autoskillit.workspace.clone.clone_repo + with: + strategy: clone_local + run_name: test-run + capture: + clone_path: "${{ result.clone_path }}" diff --git a/tests/recipe/test__api.py b/tests/recipe/test__api.py index 14614cd88d..b08b41791b 100644 --- a/tests/recipe/test__api.py +++ b/tests/recipe/test__api.py @@ -29,3 +29,18 @@ def test_drop_sub_recipe_step_preserves_future_fields() -> None: assert result.kitchen_rules == ["rule1"] assert "placeholder" not in result.steps assert "other" in result.steps + + +# --------------------------------------------------------------------------- +# T2 — _path_mtime_ns replaces the two old helpers +# (migrated from recipe/test_io.py — this test introspects recipe._api) +# --------------------------------------------------------------------------- + + +def test_path_mtime_ns_exists_and_old_helpers_removed() -> None: + """recipe/_api.py must expose _path_mtime_ns; _file_mtime_ns/_dir_mtime_ns removed.""" + import autoskillit.recipe._api as api + + assert hasattr(api, "_path_mtime_ns"), "_path_mtime_ns must exist" + assert not hasattr(api, "_file_mtime_ns"), "_file_mtime_ns must be removed" + assert not hasattr(api, "_dir_mtime_ns"), "_dir_mtime_ns must be removed" diff --git a/tests/recipe/test_anti_pattern_guards.py b/tests/recipe/test_anti_pattern_guards.py index 3dcb74d5b0..6dc2fbc7a2 100644 --- a/tests/recipe/test_anti_pattern_guards.py +++ b/tests/recipe/test_anti_pattern_guards.py @@ -6,6 +6,13 @@ import yaml from autoskillit.recipe.io import builtin_recipes_dir, load_recipe +from autoskillit.recipe.rules_blocks import _block_budgets # re-use the cached loader + + +def _budget_for(block_name: str) -> dict: # type: ignore[type-arg] + """Return the budget dict for a named block, falling back to the DEFAULT entry.""" + budgets = _block_budgets() + return budgets.get(block_name, budgets.get("DEFAULT", {})) def _all_bundled_recipes(): @@ -107,3 +114,19 @@ def test_merge_prs_has_no_loop_push_kitchen_rule(): assert not unexpected, ( f"push_to_remote found in unexpected steps (loop pushes are prohibited): {unexpected}" ) + + +@pytest.mark.parametrize("recipe_path", _all_bundled_recipes(), ids=lambda p: p.stem) +def test_no_block_exceeds_run_cmd_budget(recipe_path): + """For every RecipeBlock in every bundled recipe, assert run_cmd count ≤ budget. + + Generalises the pre-queue block rule to all future declared blocks. + Will FAIL until rules_blocks.py and Recipe.blocks are implemented. + """ + recipe = load_recipe(recipe_path) + for block in recipe.blocks: + budget = _budget_for(block.name).get("run_cmd", 1) + assert block.tool_counts.get("run_cmd", 0) <= budget, ( + f"{recipe_path.stem}: block {block.name!r} has " + f"{block.tool_counts.get('run_cmd', 0)} run_cmd steps (budget {budget})" + ) diff --git a/tests/recipe/test_api.py b/tests/recipe/test_api.py index 913c3c3bd7..38fd37e336 100644 --- a/tests/recipe/test_api.py +++ b/tests/recipe/test_api.py @@ -47,6 +47,19 @@ def _setup_project_recipe(tmp_path: Path, name: str, content: str) -> Path: return recipe_path +def _make_recipe_with_ingredient(name: str, ingredient: object) -> object: + """Build a minimal Recipe with a single named ingredient for unit testing.""" + from autoskillit.recipe.schema import Recipe, RecipeStep + + return Recipe( + name="test", + description="test recipe", + ingredients={name: ingredient}, + steps={"done": RecipeStep(action="stop", message="done")}, + kitchen_rules=[], + ) + + # T4a def test_load_and_validate_includes_kitchen_rules(tmp_path): """Response has top-level 'kitchen_rules' key with rule strings.""" @@ -72,6 +85,40 @@ def test_load_and_validate_omits_kitchen_rules_when_empty(tmp_path): assert "kitchen_rules" not in result, "kitchen_rules should be absent when recipe has none" +# Minimal recipe YAML with requires_packs +_RECIPE_WITH_PACKS = """\ +name: test-recipe-with-packs +description: A test recipe with pack requirements +autoskillit_version: "0.3.0" +requires_packs: [research, github] +steps: + stop: + action: stop + message: "done" +""" + + +# T4c +def test_load_and_validate_includes_requires_packs(tmp_path): + """Response has top-level 'requires_packs' key with pack names when recipe specifies them.""" + from autoskillit.recipe._api import load_and_validate + + _setup_project_recipe(tmp_path, "test-recipe-with-packs", _RECIPE_WITH_PACKS) + result = load_and_validate("test-recipe-with-packs", project_dir=tmp_path) + + assert "requires_packs" in result, "requires_packs should be present" + assert result["requires_packs"] == ["research", "github"] + + +# T4d +def test_load_recipe_result_requires_packs_absent_for_standard_recipe(): + """Standard recipes without requires_packs omit the key (matches kitchen_rules pattern).""" + from autoskillit.recipe._api import load_and_validate + + result = load_and_validate(name="implementation", project_dir=None) + assert "requires_packs" not in result + + # --------------------------------------------------------------------------- # Minimal recipe fixture for cache tests # --------------------------------------------------------------------------- @@ -280,6 +327,8 @@ def capturing_fn( recipe_info=None, resolved_defaults=None, ingredient_overrides=None, + temp_dir=None, + temp_dir_relpath=None, ): captured["recipe_info"] = recipe_info return real_fn( @@ -289,6 +338,8 @@ def capturing_fn( recipe_info=recipe_info, resolved_defaults=resolved_defaults, ingredient_overrides=ingredient_overrides, + temp_dir=temp_dir, + temp_dir_relpath=temp_dir_relpath, ) monkeypatch.setattr(api_mod, "load_and_validate", capturing_fn) @@ -508,6 +559,84 @@ def test_gfm_description_cap_with_real_implementation_recipe(self): ) +def test_build_ingredient_rows_resolved_overrides_literal_default(): + """T1: config-resolved value wins over a non-empty YAML literal default.""" + from autoskillit.recipe._api import build_ingredient_rows + from autoskillit.recipe.schema import RecipeIngredient + + recipe = _make_recipe_with_ingredient( + "base_branch", + RecipeIngredient(description="Base branch", default="main"), + ) + rows = build_ingredient_rows(recipe, resolved_defaults={"base_branch": "integration"}) + assert ("base_branch", "Base branch", "integration") in rows + + +def test_build_ingredient_rows_literal_default_preserved_when_no_resolved(): + """T2: YAML literal default is used when resolved_defaults has no entry.""" + from autoskillit.recipe._api import build_ingredient_rows + from autoskillit.recipe.schema import RecipeIngredient + + recipe = _make_recipe_with_ingredient( + "base_branch", + RecipeIngredient(description="Base branch", default="main"), + ) + rows = build_ingredient_rows(recipe, resolved_defaults={}) + assert ("base_branch", "Base branch", "main") in rows + + +def test_build_ingredient_rows_resolved_overrides_empty_sentinel(): + """T3: resolved value also wins over the empty-string sentinel (regression guard).""" + from autoskillit.recipe._api import build_ingredient_rows + from autoskillit.recipe.schema import RecipeIngredient + + recipe = _make_recipe_with_ingredient( + "base_branch", + RecipeIngredient(description="Base branch", default=""), + ) + rows = build_ingredient_rows(recipe, resolved_defaults={"base_branch": "integration"}) + assert ("base_branch", "Base branch", "integration") in rows + + +def test_build_ingredient_rows_empty_sentinel_falls_back_to_auto_detect(): + """T4: empty-string sentinel displays 'auto-detect' when no resolved value exists.""" + from autoskillit.recipe._api import build_ingredient_rows + from autoskillit.recipe.schema import RecipeIngredient + + recipe = _make_recipe_with_ingredient( + "base_branch", + RecipeIngredient(description="Base branch", default=""), + ) + rows = build_ingredient_rows(recipe, resolved_defaults={}) + assert ("base_branch", "Base branch", "auto-detect") in rows + + +def test_build_ingredient_rows_resolved_does_not_override_required_marker(): + """T5: required-without-default always shows '(required)'; resolved override must not apply.""" + from autoskillit.recipe._api import build_ingredient_rows + from autoskillit.recipe.schema import RecipeIngredient + + recipe = _make_recipe_with_ingredient( + "x", + RecipeIngredient(description="Required thing", required=True), + ) + rows = build_ingredient_rows(recipe, resolved_defaults={"x": "something"}) + assert any(r[0] == "x *" and r[2] == "(required)" for r in rows) + + +def test_build_ingredient_rows_resolved_overrides_boolean_literal(): + """T6: resolved value wins over a boolean-literal default ('true'/'false' → 'on'/'off').""" + from autoskillit.recipe._api import build_ingredient_rows + from autoskillit.recipe.schema import RecipeIngredient + + recipe = _make_recipe_with_ingredient( + "flag", + RecipeIngredient(description="A flag", default="true"), + ) + rows = build_ingredient_rows(recipe, resolved_defaults={"flag": "off"}) + assert ("flag", "A flag", "off") in rows + + def test_build_ingredient_rows_returns_tuples(): """build_ingredient_rows must return a list of (name, description, default) tuples with full (uncapped) description strings — the terminal renderer, not this function, diff --git a/tests/recipe/test_bundled_recipe_hidden_policy.py b/tests/recipe/test_bundled_recipe_hidden_policy.py index 9a663c885e..9bca70c632 100644 --- a/tests/recipe/test_bundled_recipe_hidden_policy.py +++ b/tests/recipe/test_bundled_recipe_hidden_policy.py @@ -11,7 +11,6 @@ "remediation", "implementation-groups", "merge-prs", - "smoke-test", ] diff --git a/tests/recipe/test_bundled_recipes.py b/tests/recipe/test_bundled_recipes.py index 23d51fe26a..566f649504 100644 --- a/tests/recipe/test_bundled_recipes.py +++ b/tests/recipe/test_bundled_recipes.py @@ -2,14 +2,37 @@ from __future__ import annotations +from pathlib import Path + import pytest -import yaml +import structlog.testing from autoskillit.core import SKILL_TOOLS +from autoskillit.recipe._analysis import build_recipe_graph from autoskillit.recipe.contracts import load_bundled_manifest from autoskillit.recipe.io import builtin_recipes_dir, load_recipe +from autoskillit.recipe.rules_merge import _is_commit_guard from autoskillit.recipe.validator import analyze_dataflow, run_semantic_rules +PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent +SMOKE_RECIPE = PROJECT_ROOT / ".autoskillit" / "recipes" / "smoke-test.yaml" + + +def _resolve_recipe_path(name: str) -> Path: + """Resolve recipe name to path, handling project-local smoke-test.""" + if name == "smoke-test": + return SMOKE_RECIPE + return builtin_recipes_dir() / f"{name}.yaml" + + +_ALL_CLONE_RECIPE_PATHS: list[Path] = [] +for _dir in (builtin_recipes_dir(), PROJECT_ROOT / ".autoskillit" / "recipes"): + if _dir.is_dir(): + for _p in sorted(_dir.glob("*.yaml")): + _wf = load_recipe(_p) + if any(s.tool == "clone_repo" for s in _wf.steps.values()): + _ALL_CLONE_RECIPE_PATHS.append(_p) + def _assert_ci_conflict_fix_on_context_limit(recipe) -> None: """Shared assertion: ci_conflict_fix must abort via release_issue_failure on context limit.""" @@ -20,6 +43,44 @@ def _assert_ci_conflict_fix_on_context_limit(recipe) -> None: ) +def _assert_ci_steps(recipe) -> None: + """Assert shared CI step structure across all pipeline recipe variants. + + Covers T_CI1–T_CI6: ci_watch, resolve_ci, and re_push steps. + Called from each recipe test class to eliminate triplication. + """ + # ci_watch step (T_CI1, T_CI2, T_CI3) + assert "ci_watch" in recipe.steps + ci = recipe.steps["ci_watch"] + assert ci.tool == "wait_for_ci" + assert ci.skip_when_false == "inputs.open_pr" + assert ci.with_args.get("timeout_seconds") == 300 + assert ci.on_success == "check_repo_merge_state" + assert ci.on_failure == "detect_ci_conflict" + assert "release_issue_success" in recipe.steps + assert "context.merge_target" in ci.with_args["branch"] + assert "cmd" not in ci.with_args + assert "ci_conclusion" in ci.capture + assert "ci_failed_jobs" in ci.capture + + # resolve_ci step (T_CI4, T_CI5) + assert "resolve_ci" in recipe.steps + resolve_ci = recipe.steps["resolve_ci"] + assert resolve_ci.tool == "run_skill" + skill_cmd = resolve_ci.with_args.get("skill_command", "") + assert "resolve-failures" in skill_cmd + assert resolve_ci.retries == 2 + assert resolve_ci.on_exhausted == "release_issue_failure" + assert "context.work_dir" in skill_cmd + + # re_push step (T_CI6) + assert "re_push" in recipe.steps + re_push = recipe.steps["re_push"] + assert re_push.tool == "push_to_remote" + assert re_push.on_success == "ci_watch" + assert re_push.on_failure == "release_issue_failure" + + # --------------------------------------------------------------------------- # TestImplementationPipelineStructure # --------------------------------------------------------------------------- @@ -129,17 +190,23 @@ def test_ip_audit_impl_uses_base_sha_as_ref(self, recipe) -> None: "audit_impl must NOT use context.branch_name (deleted by merge_worktree)" ) - def test_ip_c1_fix_step_routes_on_success_to_test(self, recipe) -> None: - """T_IP_C1: fix step must route on_success back to test (not next_or_done). + def test_ip_c1_fix_step_routes_via_on_result_to_test(self, recipe) -> None: + """T_IP_C1: fix step must route via verdict-gated on_result back to test. - assess-and-merge used to merge internally, so fix routed to next_or_done - after the internal merge. resolve-failures does not merge, so the orchestrator - must route fix → test to re-validate before entering merge_worktree. + After Part B, fix uses on_result: verdict dispatch instead of unconditional + on_success: test. real_fix and already_green verdicts route to test for + re-validation before entering merge_worktree. """ step = recipe.steps["fix"] - assert step.on_success == "test", ( - "fix step must route back to test — resolve-failures only fixes failures, " - "it does not merge. The orchestrator must re-validate before merge_worktree." + assert step.on_success is None, ( + "fix step must use on_result: verdict dispatch, not unconditional on_success" + ) + assert step.on_result is not None, "fix step must have on_result: verdict dispatch" + test_routes = [ + c.route for c in step.on_result.conditions if c.when and "real_fix" in c.when + ] + assert any(r == "test" for r in test_routes), ( + "fix step on_result must route verdict=real_fix to test for re-validation" ) def test_ip_base_sha_captured_before_implement(self, recipe) -> None: @@ -233,17 +300,17 @@ def test_ip_push_after_audit_warning_fires(self, recipe) -> None: ) assert all(v.severity == Severity.WARNING for v in violations) - def test_ip_open_pr_step_routes_to_review_pr(self, recipe) -> None: - """open_pr_step.on_success routes to extract_pr_number before review_pr.""" - open_pr_step = recipe.steps["open_pr_step"] - assert open_pr_step.on_success == "extract_pr_number", ( - "open_pr_step must route to extract_pr_number" + def test_ip_compose_pr_routes_to_extract_pr_number(self, recipe) -> None: + """compose_pr.on_success routes to extract_pr_number before review_pr.""" + compose_pr = recipe.steps["compose_pr"] + assert compose_pr.on_success == "extract_pr_number", ( + "compose_pr must route to extract_pr_number" ) - def test_ip_open_pr_step_has_skip_when_false(self, recipe) -> None: - """open_pr_step must declare skip_when_false: inputs.open_pr.""" - open_pr_step = recipe.steps["open_pr_step"] - assert open_pr_step.skip_when_false == "inputs.open_pr" + def test_ip_compose_pr_has_skip_when_false(self, recipe) -> None: + """compose_pr must declare skip_when_false: inputs.open_pr.""" + compose_pr = recipe.steps["compose_pr"] + assert compose_pr.skip_when_false == "inputs.open_pr" def test_ip_audit_impl_has_skip_when_false(self, recipe) -> None: """audit_impl must declare skip_when_false: inputs.audit.""" @@ -274,14 +341,14 @@ def test_create_branch_uses_run_name_as_prefix(self, recipe) -> None: cmd = recipe.steps["compute_branch"].with_args["cmd"] assert "inputs.run_name" in cmd - def test_ip_main_push_step_not_reachable_after_open_pr(self, recipe) -> None: - """The main `push` step must not be reachable after open_pr_step — + def test_ip_main_push_step_not_reachable_after_compose_pr(self, recipe) -> None: + """The main `push` step must not be reachable after compose_pr — that would be a double-push. The new `re_push` step IS reachable and is correct.""" from autoskillit.recipe.validator import _build_step_graph graph = _build_step_graph(recipe) visited: set[str] = set() - queue = [recipe.steps["open_pr_step"].on_success] + queue = [recipe.steps["compose_pr"].on_success] while queue: current = queue.pop(0) if current in visited or current not in recipe.steps: @@ -289,13 +356,13 @@ def test_ip_main_push_step_not_reachable_after_open_pr(self, recipe) -> None: visited.add(current) queue.extend(graph.get(current, [])) assert "push" not in visited, ( - "'push' step is reachable after open_pr_step — double-push risk. " + "'push' step is reachable after compose_pr — double-push risk. " "(re_push is allowed; push is not)" ) def test_ip_open_pr_false_path_reaches_push_then_cleanup(self, recipe) -> None: - """When open_pr_step is bypassed (open_pr=false), execution must go: - audit_impl (GO) → push → [open_pr_step bypassed] → cleanup_success → done. + """When compose_pr is bypassed (open_pr=false), execution must go: + audit_impl (GO) → push → [compose_pr bypassed] → cleanup_success → done. After the fix, audit_impl's GO route points directly to push, so push is always reachable from audit_impl's successors.""" from autoskillit.recipe.validator import _build_step_graph @@ -318,9 +385,9 @@ def test_ip_plan_step_captures_all_plan_paths(self, recipe) -> None: assert "all_plan_paths" in recipe.steps["plan"].capture assert "result.plan_path" in recipe.steps["plan"].capture["all_plan_paths"] - def test_ip_open_pr_step_references_all_plan_paths(self, recipe) -> None: - """open_pr_step must pass all accumulated plan paths, not just the last.""" - cmd = recipe.steps["open_pr_step"].with_args.get("skill_command", "") + def test_ip_prepare_pr_references_all_plan_paths(self, recipe) -> None: + """prepare_pr must pass all accumulated plan paths, not just the last.""" + cmd = recipe.steps["prepare_pr"].with_args.get("skill_command", "") assert "context.all_plan_paths" in cmd assert "context.plan_path" not in cmd @@ -355,53 +422,9 @@ def test_ip_next_or_done_no_more_groups_route(self, recipe) -> None: conds = step.on_result.conditions assert not any("more_groups" in (c.when or "") for c in conds) - def test_ip_ci_watch_exists_and_is_gated(self, recipe) -> None: - """T_CI1: ci_watch step exists, uses wait_for_ci, has skip_when_false: inputs.open_pr, - and specifies timeout_seconds: 300.""" - assert "ci_watch" in recipe.steps - step = recipe.steps["ci_watch"] - assert step.tool == "wait_for_ci" - assert step.skip_when_false == "inputs.open_pr" - assert step.with_args.get("timeout_seconds") == 300 - - def test_ip_ci_watch_routing(self, recipe) -> None: - """T_CI2: ci_watch on_success -> check_merge_queue; on_failure -> detect_ci_conflict.""" - step = recipe.steps["ci_watch"] - assert step.on_success == "check_merge_queue" - assert step.on_failure == "detect_ci_conflict" - assert "release_issue_success" in recipe.steps - - def test_ip_ci_watch_uses_merge_target(self, recipe) -> None: - """T_CI3: ci_watch uses branch param with context.merge_target, no inline shell.""" - step = recipe.steps["ci_watch"] - assert "context.merge_target" in step.with_args["branch"] - assert "cmd" not in step.with_args - assert "ci_conclusion" in step.capture - assert "ci_failed_jobs" in step.capture - - def test_ip_resolve_ci_structure(self, recipe) -> None: - """T_CI4: resolve_ci step exists, uses resolve-failures, has retries: 2 - and on_exhausted: release_issue_failure.""" - assert "resolve_ci" in recipe.steps - step = recipe.steps["resolve_ci"] - assert step.tool == "run_skill" - skill_cmd = step.with_args.get("skill_command", "") - assert "resolve-failures" in skill_cmd - assert step.retries == 2 - assert step.on_exhausted == "release_issue_failure" - - def test_ip_resolve_ci_uses_work_dir(self, recipe) -> None: - """T_CI5: resolve_ci uses context.work_dir as the worktree path.""" - cmd = recipe.steps["resolve_ci"].with_args.get("skill_command", "") - assert "context.work_dir" in cmd - - def test_ip_re_push_loops_back_to_ci_watch(self, recipe) -> None: - """T_CI6: re_push step exists, is push_to_remote, routes on_success back to ci_watch.""" - assert "re_push" in recipe.steps - step = recipe.steps["re_push"] - assert step.tool == "push_to_remote" - assert step.on_success == "ci_watch" - assert step.on_failure == "release_issue_failure" + def test_ci_step_structure(self, recipe) -> None: + """T_CI1–T_CI6: shared ci_watch, resolve_ci, and re_push structure.""" + _assert_ci_steps(recipe) def test_ip_re_push_has_explicit_remote_url(self, recipe) -> None: """T_CI7: re_push uses explicit remote_url (satisfies push-missing-explicit-remote-url).""" @@ -409,17 +432,10 @@ def test_ip_re_push_has_explicit_remote_url(self, recipe) -> None: assert "remote_url" in with_args assert "context.remote_url" in with_args["remote_url"] - def test_ip_open_pr_step_routes_to_review_pr_ci(self, recipe) -> None: - """T_CI8: open_pr_step.on_success routes to extract_pr_number before review_pr.""" - step = recipe.steps["open_pr_step"] - assert step.on_success == "extract_pr_number", ( - "open_pr_step must route to extract_pr_number" - ) - - def test_ip_ci_watch_routes_failure_to_conflict_gate(self, recipe) -> None: - """ci_watch.on_failure must route to detect_ci_conflict, not directly to diagnose_ci.""" - step = recipe.steps["ci_watch"] - assert step.on_failure == "detect_ci_conflict" + def test_ip_compose_pr_routes_to_extract_pr_number_ci(self, recipe) -> None: + """T_CI8: compose_pr.on_success routes to extract_pr_number before review_pr.""" + step = recipe.steps["compose_pr"] + assert step.on_success == "extract_pr_number", "compose_pr must route to extract_pr_number" def test_ip_detect_ci_conflict_exists(self, recipe) -> None: assert "detect_ci_conflict" in recipe.steps @@ -490,10 +506,10 @@ def test_ip_audit_impl_has_on_context_limit(self, recipe) -> None: "a valid verdict — aborting via escalate_stop is correct" ) - def test_ip_open_pr_step_has_on_context_limit(self, recipe) -> None: - step = recipe.steps["open_pr_step"] + def test_ip_compose_pr_has_on_context_limit(self, recipe) -> None: + step = recipe.steps["compose_pr"] assert step.on_context_limit == "release_issue_failure", ( - "open_pr_step is advisory (skip_when_false); on context limit the pipeline " + "compose_pr is advisory (skip_when_false); on context limit the pipeline " "cannot determine PR state — release the issue via release_issue_failure" ) @@ -576,9 +592,17 @@ def test_ig_audit_impl_uses_base_sha_as_ref(self, recipe) -> None: assert "context.base_sha" in skill_cmd assert "context.branch_name" not in skill_cmd - def test_ig_fix_step_routes_on_success_to_test(self, recipe) -> None: - """fix step must route on_success to test (resolve-failures does not merge).""" - assert recipe.steps["fix"].on_success == "test" + def test_ig_fix_step_routes_via_on_result_to_test(self, recipe) -> None: + """fix step must route via verdict-gated on_result to test.""" + step = recipe.steps["fix"] + assert step.on_success is None, "fix step must use on_result: verdict dispatch" + assert step.on_result is not None, "fix step must have on_result: verdict dispatch" + test_routes = [ + c.route for c in step.on_result.conditions if c.when and "real_fix" in c.when + ] + assert any(r == "test" for r in test_routes), ( + "fix step on_result must route verdict=real_fix to test" + ) def test_ig_push_after_audit_warning_fires(self, recipe) -> None: """push-before-audit semantic rule fires as WARNING (audit has skip_when_false).""" @@ -590,53 +614,9 @@ def test_ig_push_after_audit_warning_fires(self, recipe) -> None: assert len(violations) >= 1 assert all(v.severity == Severity.WARNING for v in violations) - def test_ig_ci_watch_exists_and_is_gated(self, recipe) -> None: - """T_CI1: ci_watch step exists, uses wait_for_ci, has skip_when_false: inputs.open_pr, - and specifies timeout_seconds: 300.""" - assert "ci_watch" in recipe.steps - step = recipe.steps["ci_watch"] - assert step.tool == "wait_for_ci" - assert step.skip_when_false == "inputs.open_pr" - assert step.with_args.get("timeout_seconds") == 300 - - def test_ig_ci_watch_routing(self, recipe) -> None: - """T_CI2: ci_watch on_success -> check_merge_queue; on_failure -> detect_ci_conflict.""" # noqa: E501 - step = recipe.steps["ci_watch"] - assert step.on_success == "check_merge_queue" - assert step.on_failure == "detect_ci_conflict" - assert "release_issue_success" in recipe.steps - - def test_ig_ci_watch_uses_merge_target(self, recipe) -> None: - """T_CI3: ci_watch uses branch param with context.merge_target, no inline shell.""" - step = recipe.steps["ci_watch"] - assert "context.merge_target" in step.with_args["branch"] - assert "cmd" not in step.with_args - assert "ci_conclusion" in step.capture - assert "ci_failed_jobs" in step.capture - - def test_ig_resolve_ci_structure(self, recipe) -> None: - """T_CI4: resolve_ci step exists, uses resolve-failures, has retries: 2 - and on_exhausted: release_issue_failure.""" - assert "resolve_ci" in recipe.steps - step = recipe.steps["resolve_ci"] - assert step.tool == "run_skill" - skill_cmd = step.with_args.get("skill_command", "") - assert "resolve-failures" in skill_cmd - assert step.retries == 2 - assert step.on_exhausted == "release_issue_failure" - - def test_ig_resolve_ci_uses_work_dir(self, recipe) -> None: - """T_CI5: resolve_ci uses context.work_dir as the worktree path.""" - cmd = recipe.steps["resolve_ci"].with_args.get("skill_command", "") - assert "context.work_dir" in cmd - - def test_ig_re_push_loops_back_to_ci_watch(self, recipe) -> None: - """T_CI6: re_push step exists, is push_to_remote, routes on_success back to ci_watch.""" - assert "re_push" in recipe.steps - step = recipe.steps["re_push"] - assert step.tool == "push_to_remote" - assert step.on_success == "ci_watch" - assert step.on_failure == "release_issue_failure" + def test_ci_step_structure(self, recipe) -> None: + """T_CI1–T_CI6: shared ci_watch, resolve_ci, and re_push structure.""" + _assert_ci_steps(recipe) def test_ig_re_push_has_explicit_remote_url(self, recipe) -> None: """T_CI7: re_push uses explicit remote_url.""" @@ -644,11 +624,6 @@ def test_ig_re_push_has_explicit_remote_url(self, recipe) -> None: assert "remote_url" in with_args assert "context.remote_url" in with_args["remote_url"] - def test_ig_ci_watch_routes_failure_to_conflict_gate(self, recipe) -> None: - """ci_watch.on_failure must route to detect_ci_conflict, not directly to diagnose_ci.""" - step = recipe.steps["ci_watch"] - assert step.on_failure == "detect_ci_conflict" - def test_ig_detect_ci_conflict_exists(self, recipe) -> None: assert "detect_ci_conflict" in recipe.steps step = recipe.steps["detect_ci_conflict"] @@ -705,29 +680,30 @@ def test_ig_extract_pr_number_step_exists(self, recipe) -> None: step = recipe.steps["extract_pr_number"] assert step.tool == "run_cmd" assert "pr_number" in step.capture - assert step.on_success == "review_pr" + assert step.on_success == "annotate_pr_diff" - def test_ig_open_pr_step_routes_to_extract_pr_number(self, recipe) -> None: - """REQ-C7-01: open_pr_step must route to extract_pr_number (not review_pr directly).""" - step = recipe.steps["open_pr_step"] + def test_ig_compose_pr_routes_to_extract_pr_number(self, recipe) -> None: + """REQ-C7-01: compose_pr must route to extract_pr_number (not review_pr directly).""" + step = recipe.steps["compose_pr"] assert step.on_success == "extract_pr_number", ( - "open_pr_step must route to extract_pr_number so pr_number is available " + "compose_pr must route to extract_pr_number so pr_number is available " "for enable_auto_merge and wait_for_queue" ) - def test_ig_ci_watch_routes_to_check_merge_queue(self, recipe) -> None: - """REQ-C7-01: ci_watch.on_success must route to check_merge_queue (not release_issue_success).""" # noqa: E501 + def test_ig_ci_watch_routes_to_check_repo_merge_state(self, recipe) -> None: + """REQ-C7-01: ci_watch.on_success must route to check_repo_merge_state (not release_issue_success).""" # noqa: E501 step = recipe.steps["ci_watch"] - assert step.on_success == "check_merge_queue", ( - "ci_watch must route to check_merge_queue so the PR can enter the merge queue. " + assert step.on_success == "check_repo_merge_state", ( + "ci_watch must route to check_repo_merge_state so the PR can enter the merge queue. " "Routing directly to release_issue_success skips the queue lifecycle entirely." ) - def test_ig_check_merge_queue_step_exists(self, recipe) -> None: - """REQ-C7-01: check_merge_queue step must exist.""" - assert "check_merge_queue" in recipe.steps - step = recipe.steps["check_merge_queue"] - assert step.tool == "run_cmd" + def test_ig_check_repo_merge_state_step_exists(self, recipe) -> None: + """REQ-C7-01: check_repo_merge_state step must exist.""" + assert "check_repo_merge_state" in recipe.steps + step = recipe.steps["check_repo_merge_state"] + assert step.tool == "check_repo_merge_state" + assert step.block == "pre_queue_gate" assert "queue_available" in step.capture def test_ig_wait_for_queue_step_exists(self, recipe) -> None: @@ -776,10 +752,10 @@ def test_ig_audit_impl_has_on_context_limit(self, recipe) -> None: "a valid verdict — aborting via escalate_stop is correct" ) - def test_ig_open_pr_step_has_on_context_limit(self, recipe) -> None: - step = recipe.steps["open_pr_step"] + def test_ig_compose_pr_has_on_context_limit(self, recipe) -> None: + step = recipe.steps["compose_pr"] assert step.on_context_limit == "release_issue_failure", ( - "open_pr_step is advisory (skip_when_false); on context limit the pipeline " + "compose_pr is advisory (skip_when_false); on context limit the pipeline " "cannot determine PR state — release the issue via release_issue_failure" ) @@ -922,53 +898,9 @@ def test_remediation_rectify_uses_context_investigation_path(self, recipe) -> No "to pass the explicit path from the capture block" ) - def test_if_ci_watch_exists_and_is_gated(self, recipe) -> None: - """T_CI1: ci_watch step exists, uses wait_for_ci, has skip_when_false: inputs.open_pr, - and specifies timeout_seconds: 300.""" - assert "ci_watch" in recipe.steps - step = recipe.steps["ci_watch"] - assert step.tool == "wait_for_ci" - assert step.skip_when_false == "inputs.open_pr" - assert step.with_args.get("timeout_seconds") == 300 - - def test_if_ci_watch_routing(self, recipe) -> None: - """T_CI2: ci_watch on_success -> check_merge_queue; on_failure -> detect_ci_conflict.""" - step = recipe.steps["ci_watch"] - assert step.on_success == "check_merge_queue" - assert step.on_failure == "detect_ci_conflict" - assert "release_issue_success" in recipe.steps - - def test_if_ci_watch_uses_merge_target(self, recipe) -> None: - """T_CI3: ci_watch uses branch param with context.merge_target, no inline shell.""" - step = recipe.steps["ci_watch"] - assert "context.merge_target" in step.with_args["branch"] - assert "cmd" not in step.with_args - assert "ci_conclusion" in step.capture - assert "ci_failed_jobs" in step.capture - - def test_if_resolve_ci_structure(self, recipe) -> None: - """T_CI4: resolve_ci step exists, uses resolve-failures, has retries: 2 - and on_exhausted: release_issue_failure.""" - assert "resolve_ci" in recipe.steps - step = recipe.steps["resolve_ci"] - assert step.tool == "run_skill" - skill_cmd = step.with_args.get("skill_command", "") - assert "resolve-failures" in skill_cmd - assert step.retries == 2 - assert step.on_exhausted == "release_issue_failure" - - def test_if_resolve_ci_uses_work_dir(self, recipe) -> None: - """T_CI5: resolve_ci uses context.work_dir as the worktree path.""" - cmd = recipe.steps["resolve_ci"].with_args.get("skill_command", "") - assert "context.work_dir" in cmd - - def test_if_re_push_loops_back_to_ci_watch(self, recipe) -> None: - """T_CI6: re_push step exists, is push_to_remote, routes on_success back to ci_watch.""" - assert "re_push" in recipe.steps - step = recipe.steps["re_push"] - assert step.tool == "push_to_remote" - assert step.on_success == "ci_watch" - assert step.on_failure == "release_issue_failure" + def test_ci_step_structure(self, recipe) -> None: + """T_CI1–T_CI6: shared ci_watch, resolve_ci, and re_push structure.""" + _assert_ci_steps(recipe) def test_if_re_push_has_explicit_remote_url(self, recipe) -> None: """T_CI7: re_push uses explicit remote_url.""" @@ -976,12 +908,10 @@ def test_if_re_push_has_explicit_remote_url(self, recipe) -> None: assert "remote_url" in with_args assert "context.remote_url" in with_args["remote_url"] - def test_if_open_pr_step_routes_to_review_pr(self, recipe) -> None: - """T_CI8: open_pr_step.on_success routes to extract_pr_number before review_pr.""" - step = recipe.steps["open_pr_step"] - assert step.on_success == "extract_pr_number", ( - "open_pr_step must route to extract_pr_number" - ) + def test_if_compose_pr_routes_to_extract_pr_number(self, recipe) -> None: + """T_CI8: compose_pr.on_success routes to extract_pr_number before review_pr.""" + step = recipe.steps["compose_pr"] + assert step.on_success == "extract_pr_number", "compose_pr must route to extract_pr_number" def test_if_resolve_review_uses_resolve_review_skill(self, recipe) -> None: """T_IF_RR1: resolve_review step must invoke resolve-review, not resolve-failures. @@ -1035,11 +965,6 @@ def test_remediation_assess_step_has_on_context_limit(self, recipe) -> None: f"got: {assess.on_context_limit!r}" ) - def test_if_ci_watch_routes_failure_to_conflict_gate(self, recipe) -> None: - """ci_watch.on_failure must route to detect_ci_conflict, not directly to diagnose_ci.""" - step = recipe.steps["ci_watch"] - assert step.on_failure == "detect_ci_conflict" - def test_if_detect_ci_conflict_exists(self, recipe) -> None: assert "detect_ci_conflict" in recipe.steps step = recipe.steps["detect_ci_conflict"] @@ -1111,10 +1036,10 @@ def test_if_audit_impl_has_on_context_limit(self, recipe) -> None: "a valid verdict — aborting via escalate_stop is correct" ) - def test_if_open_pr_step_has_on_context_limit(self, recipe) -> None: - step = recipe.steps["open_pr_step"] + def test_if_compose_pr_has_on_context_limit(self, recipe) -> None: + step = recipe.steps["compose_pr"] assert step.on_context_limit == "release_issue_failure", ( - "open_pr_step is advisory (skip_when_false); on context limit the pipeline " + "compose_pr is advisory (skip_when_false); on context limit the pipeline " "cannot determine PR state — release the issue via release_issue_failure" ) @@ -1122,88 +1047,6 @@ def test_if_ci_conflict_fix_has_on_context_limit(self, recipe) -> None: _assert_ci_conflict_fix_on_context_limit(recipe) -# --------------------------------------------------------------------------- -# TestSmokeTestStructure -# --------------------------------------------------------------------------- - - -class TestSmokeTestStructure: - """Structural assertions for the smoke-test.yaml recipe steps.""" - - @pytest.fixture() - def smoke_yaml(self) -> dict: - recipe_path = builtin_recipes_dir() / "smoke-test.yaml" - return yaml.safe_load(recipe_path.read_text()) - - # T_ST1 - def test_create_branch_is_run_cmd(self, smoke_yaml: dict) -> None: - """create_branch step has tool == "run_cmd" (not action == "route").""" - assert smoke_yaml["steps"]["create_branch"]["tool"] == "run_cmd" - - # T_ST2 - def test_create_branch_captures_feature_branch(self, smoke_yaml: dict) -> None: - """create_branch step has capture containing key feature_branch.""" - assert "feature_branch" in smoke_yaml["steps"]["create_branch"]["capture"] - - # T_ST3 - def test_check_summary_is_run_python(self, smoke_yaml: dict) -> None: - """check_summary step has python discriminator (not action == "route").""" - assert ( - smoke_yaml["steps"]["check_summary"]["python"] - == "autoskillit.smoke_utils.check_bug_report_non_empty" - ) - - # T_ST4 - def test_check_summary_on_result_routes(self, smoke_yaml: dict) -> None: - """check_summary step has on_result with predicate conditions for non_empty. - - v0.3.0 predicate format: on_result is a list of {when, route} dicts. - """ - on_result = smoke_yaml["steps"]["check_summary"]["on_result"] - assert isinstance(on_result, list), "on_result must be a predicate conditions list" - routes = {c.get("route") for c in on_result} - whens = [c.get("when", "") or "" for c in on_result] - assert any("non_empty" in w for w in whens), ( - "check_summary on_result must check result.non_empty" - ) - assert "create_summary" in routes, "check_summary must route to create_summary" - assert "done" in routes, "check_summary must have a fallthrough route to done" - - # T_ST5 - def test_merge_references_context_feature_branch(self, smoke_yaml: dict) -> None: - """merge step with_args references context.feature_branch.""" - base_branch = smoke_yaml["steps"]["merge"]["with"]["base_branch"] - assert "context.feature_branch" in base_branch - - # A6 - def test_smoke_feature_branch_unconditionally_set(self, smoke_yaml: dict) -> None: - """A6: feature_branch must be set by a non-optional step before merge.""" - steps = smoke_yaml["steps"] - step_names = list(steps.keys()) - merge_idx = next( - ( - i - for i, name in enumerate(step_names) - if steps[name].get("tool") == "merge_worktree" - ), - None, - ) - assert merge_idx is not None, "merge step not found" - unconditional = next( - ( - name - for name in step_names[:merge_idx] - if "feature_branch" in steps[name].get("capture", {}) - and not steps[name].get("optional", False) - ), - None, - ) - assert unconditional is not None, ( - "feature_branch is only captured by optional create_branch. " - "When collect_on_branch=false, merge step receives undefined context.feature_branch." - ) - - # --------------------------------------------------------------------------- # Contract tests — plan_parts output (D4–D5) # --------------------------------------------------------------------------- @@ -1247,8 +1090,13 @@ def test_bundled_recipes_diagrams_dir_exists() -> None: def test_all_predicate_steps_have_on_failure() -> None: """Every tool/python step with on_result.conditions must declare on_failure.""" - for recipe_name in ["implementation", "remediation", "smoke-test"]: - recipe = load_recipe(builtin_recipes_dir() / f"{recipe_name}.yaml") + paths = { + "implementation": builtin_recipes_dir() / "implementation.yaml", + "remediation": builtin_recipes_dir() / "remediation.yaml", + "smoke-test": SMOKE_RECIPE, + } + for recipe_name, recipe_path in paths.items(): + recipe = load_recipe(recipe_path) for step_name, step in recipe.steps.items(): is_tool = step.tool is not None or step.python is not None if is_tool and step.on_result and step.on_result.conditions: @@ -1265,18 +1113,22 @@ def test_audit_impl_on_failure_routes_to_escalation() -> None: assert rem.steps["audit_impl"].on_failure == "escalate_stop" -def test_smoke_check_summary_has_error_escalation() -> None: - """check_summary must have a result.error condition routing to a non-done step.""" - recipe = load_recipe(builtin_recipes_dir() / "smoke-test.yaml") - step = recipe.steps["check_summary"] - error_routes = [ - c.route - for c in step.on_result.conditions - if c.when is not None and "result.error" in c.when - ] - assert error_routes, "check_summary must have a result.error condition" - assert all(r != "done" for r in error_routes), ( - f"check_summary result.error must not route to done; got {error_routes}" +@pytest.mark.parametrize( + "recipe_name,yaml_name", + [ + ("implementation", "implementation.yaml"), + ("remediation", "remediation.yaml"), + ("merge-prs", "merge-prs.yaml"), + ("implementation-groups", "implementation-groups.yaml"), + ], +) +def test_audit_ingredient_defaults_to_false(recipe_name: str, yaml_name: str) -> None: + """audit must default to 'false' (OFF) in all recipes — opt-in, not opt-out.""" + recipe = load_recipe(builtin_recipes_dir() / yaml_name) + audit_ing = recipe.ingredients.get("audit") + assert audit_ing is not None, f"{recipe_name}: 'audit' ingredient not found" + assert audit_ing.default == "false", ( + f"{recipe_name}: audit.default must be 'false' (OFF by default), got {audit_ing.default!r}" ) @@ -1349,23 +1201,17 @@ class TestReviewPrRecipeIntegration: def recipe(self, request: pytest.FixtureRequest) -> object: return load_recipe(builtin_recipes_dir() / request.param) - def test_open_pr_step_routes_to_review_pr(self, recipe: object) -> None: - """T_RP1: open_pr_step.on_success routes per-recipe to the correct next step. + def test_compose_pr_routes_to_extract_pr_number(self, recipe: object) -> None: + """T_RP1: compose_pr.on_success routes per-recipe to extract_pr_number. All queue-aware recipes (implementation, remediation, implementation-groups) insert - extract_pr_number between open_pr_step and review_pr to capture the PR number for + extract_pr_number between compose_pr and review_pr to capture the PR number for merge queue support. """ - _expected: dict[str, str] = { - "implementation": "extract_pr_number", - "remediation": "extract_pr_number", - "implementation-groups": "extract_pr_number", - } recipe_name = recipe.name # type: ignore[attr-defined] - expected = _expected[recipe_name] - on_success = recipe.steps["open_pr_step"].on_success # type: ignore[attr-defined] - assert on_success == expected, ( - f"{recipe_name}: open_pr_step.on_success must be {expected!r}, got {on_success!r}" + on_success = recipe.steps["compose_pr"].on_success # type: ignore[attr-defined] + assert on_success == "extract_pr_number", ( + f"{recipe_name}: compose_pr.on_success must be 'extract_pr_number', got {on_success!r}" ) def test_review_pr_step_exists_and_is_run_skill(self, recipe: object) -> None: @@ -1411,8 +1257,20 @@ def test_resolve_review_has_retries(self, recipe: object) -> None: assert recipe.steps["resolve_review"].retries == 2 # type: ignore[attr-defined] def test_resolve_review_routes_to_re_push_review(self, recipe: object) -> None: - """T_RP7: resolve_review.on_success routes to re_push_review.""" - assert recipe.steps["resolve_review"].on_success == "re_push_review" # type: ignore[attr-defined] + """T_RP7: resolve_review uses on_result: verdict dispatch routing to re_push_review.""" + step = recipe.steps["resolve_review"] # type: ignore[attr-defined] + assert step.on_success is None, ( + "resolve_review must use on_result: verdict dispatch, not unconditional on_success" + ) + assert step.on_result is not None, ( + "resolve_review must have on_result: block for verdict-gated routing" + ) + real_fix_routes = [ + c.route for c in step.on_result.conditions if c.when and "real_fix" in c.when + ] + assert any("re_push_review" in r for r in real_fix_routes), ( + "resolve_review on_result must route verdict=real_fix to re_push_review" + ) def test_re_push_review_routes_to_ci_watch(self, recipe: object) -> None: """T_RP8: re_push_review routes to ci_watch (one-shot review gate).""" @@ -1483,99 +1341,6 @@ def test_implementation_groups_has_ci_watch() -> None: assert "re_push" in recipe.steps -# --------------------------------------------------------------------------- -# Confirm-cleanup gate tests -# --------------------------------------------------------------------------- - - -def _build_reverse_on_success(recipe) -> dict[str, list[str]]: - """Build a reverse mapping: step_name → list of steps whose on_success points to it.""" - reverse: dict[str, list[str]] = {name: [] for name in recipe.steps} - for name, step in recipe.steps.items(): - if step.on_success and step.on_success in recipe.steps: - reverse[step.on_success].append(name) - return reverse - - -@pytest.mark.parametrize( - "recipe_name", - [ - "implementation", - "remediation", - "implementation-groups", - "merge-prs", - ], -) -def test_bundled_recipe_cleanup_uses_confirm(recipe_name: str) -> None: - """Every bundled recipe that clones must use action:confirm before deleting clone. - - Verifies that at least one confirm step's on_success points directly to a remove_clone step. - """ - recipe = load_recipe(builtin_recipes_dir() / f"{recipe_name}.yaml") - confirm_steps = [name for name, step in recipe.steps.items() if step.action == "confirm"] - assert confirm_steps, f"{recipe_name} has no confirm step — cleanup is unguarded" - - # At least one confirm step must route directly to a remove_clone step on success - for conf_name in confirm_steps: - conf_step = recipe.steps[conf_name] - if conf_step.on_success and conf_step.on_success in recipe.steps: - target = recipe.steps[conf_step.on_success] - if target.tool == "remove_clone": - return # Found a properly connected confirm → remove_clone pair - - raise AssertionError( - f"{recipe_name}: confirm step(s) exist but none has on_success pointing to remove_clone" - ) - - -def test_no_bundled_recipe_auto_deletes_on_success() -> None: - """No bundled recipe should call remove_clone(keep=false) directly from success path. - - Uses transitive predecessor checking: walks the on_success graph backwards from each - remove_clone(keep=false) step to verify that every reachable ancestor (via on_success - edges, not crossing confirm steps) is itself a confirm step. - """ - for recipe_name in [ - "implementation", - "remediation", - "implementation-groups", - "merge-prs", - ]: - recipe = load_recipe(builtin_recipes_dir() / f"{recipe_name}.yaml") - reverse_on_success = _build_reverse_on_success(recipe) - - for name, step in recipe.steps.items(): - if step.tool == "remove_clone": - keep = (step.with_args or {}).get("keep", "false") - if keep == "false": - # Walk backwards via on_success edges, stopping at confirm steps. - # Any non-confirm step found is unguarded — a violation. - violations: list[str] = [] - visited: set[str] = set() - queue = [name] - - while queue: - current = queue.pop(0) - for pred in reverse_on_success.get(current, []): - if pred in visited: - continue - visited.add(pred) - pred_step = recipe.steps[pred] - if pred_step.action == "confirm": - # Guarded — stop tracing further back through this branch - pass - else: - violations.append(pred) - queue.append( - pred - ) # Continue tracing to find all unguarded ancestors - - assert not violations, ( - f"{recipe_name}: {name} (keep=false) is reachable via on_success " - f"from unguarded (non-confirm) steps: {violations}" - ) - - # --------------------------------------------------------------------------- # TestBaseBranchDefaults # --------------------------------------------------------------------------- @@ -1598,12 +1363,12 @@ def test_recipe_base_branch_auto_detects(self, recipe_name: str) -> None: f"{recipe_name}.yaml: base_branch must use auto-detect (default: '')" ) - def test_smoke_test_base_branch_remains_main(self) -> None: - """smoke-test.yaml must keep base_branch default 'main' — isolated scratch repo context.""" - recipe = load_recipe(builtin_recipes_dir() / "smoke-test.yaml") - assert recipe.ingredients["base_branch"].default == "main", ( - "smoke-test.yaml creates a fresh git repo initialized with 'main' — " - "its base_branch default must stay 'main'" + def test_smoke_test_base_branch_uses_auto_detect(self) -> None: + """smoke-test.yaml must use auto-detect for base_branch so config-resolved value wins.""" + recipe = load_recipe(SMOKE_RECIPE) + assert recipe.ingredients["base_branch"].default == "", ( + "smoke-test.yaml base_branch must use auto-detect (default: '') so that " + "branching.default_base_branch from config is honoured at runtime (#703)" ) @@ -1619,10 +1384,10 @@ class TestImplementationRecipeMergeQueueRule: def recipe(self): return load_recipe(builtin_recipes_dir() / "implementation.yaml") - def test_kitchen_rules_mention_check_merge_queue(self, recipe) -> None: + def test_kitchen_rules_mention_check_repo_merge_state(self, recipe) -> None: all_rules = " ".join(recipe.kitchen_rules) - assert "check_merge_queue" in all_rules, ( - "implementation.yaml kitchen_rules must reference check_merge_queue" + assert "check_repo_merge_state" in all_rules, ( + "implementation.yaml kitchen_rules must reference check_repo_merge_state" ) assert "MERGE ROUTING" in all_rules, ( "implementation.yaml kitchen_rules must contain a MERGE ROUTING rule" @@ -1649,10 +1414,6 @@ def test_kitchen_rules_prohibit_direct_gh_pr_merge(self, recipe) -> None: # WF7: build_recipe_graph emits zero warnings for all bundled recipes # --------------------------------------------------------------------------- -import structlog.testing # noqa: E402 - -from autoskillit.recipe._analysis import build_recipe_graph # noqa: E402 - _BUNDLED_RECIPE_PATHS = sorted(builtin_recipes_dir().glob("*.yaml")) @@ -1689,6 +1450,69 @@ def test_all_advisory_run_skill_steps_have_on_context_limit(recipe_path): ) +# --------------------------------------------------------------------------- +# Cross-recipe review-pr pre-computation tests +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize( + "recipe_name", + ["implementation", "remediation", "implementation-groups", "merge-prs"], +) +def test_review_pr_step_passes_annotated_diff_inputs(recipe_name: str) -> None: + """Every review-pr invocation must pass annotated_diff_path= and hunk_ranges_path= + in skill_command, or have a reachable annotate_pr_diff predecessor step.""" + recipe = load_recipe(builtin_recipes_dir() / f"{recipe_name}.yaml") + # Find review-pr steps + review_steps = [ + (name, step) + for name, step in recipe.steps.items() + if step.tool in SKILL_TOOLS and "review-pr" in step.with_args.get("skill_command", "") + ] + assert review_steps, f"No review-pr step found in {recipe_name}.yaml" + for step_name, step in review_steps: + cmd = step.with_args.get("skill_command", "") + has_inline = "annotated_diff_path=" in cmd and "hunk_ranges_path=" in cmd + has_predecessor = any( + s.with_args.get("callable", "") == "autoskillit.smoke_utils.annotate_pr_diff" + for s in recipe.steps.values() + if s.tool == "run_python" + ) + assert has_inline or has_predecessor, ( + f"{recipe_name}.yaml: step '{step_name}' invokes review-pr but neither " + f"passes annotated_diff_path=/hunk_ranges_path= inline nor has an " + f"annotate_pr_diff predecessor step" + ) + + +@pytest.mark.parametrize( + "recipe_name", + ["implementation", "remediation", "implementation-groups", "merge-prs"], +) +def test_annotate_pr_diff_captures_both_paths(recipe_name: str) -> None: + """The annotate_pr_diff step must capture annotated_diff_path and hunk_ranges_path.""" + recipe = load_recipe(builtin_recipes_dir() / f"{recipe_name}.yaml") + annotate_steps = [ + (name, step) + for name, step in recipe.steps.items() + if step.tool == "run_python" + and step.with_args.get("callable", "") == "autoskillit.smoke_utils.annotate_pr_diff" + ] + assert annotate_steps, f"No annotate_pr_diff step found in {recipe_name}.yaml" + for step_name, step in annotate_steps: + assert step.capture is not None, ( + f"{recipe_name}.yaml: annotate_pr_diff step '{step_name}' has no capture block" + ) + assert "annotated_diff_path" in step.capture, ( + f"{recipe_name}.yaml: annotate_pr_diff step '{step_name}' must capture " + f"annotated_diff_path" + ) + assert "hunk_ranges_path" in step.capture, ( + f"{recipe_name}.yaml: annotate_pr_diff step '{step_name}' must capture " + f"hunk_ranges_path" + ) + + # --------------------------------------------------------------------------- # TestRunModeIngredient # --------------------------------------------------------------------------- @@ -1775,85 +1599,60 @@ def test_no_bare_temp_paths_in_bundled_recipe_notes() -> None: # --------------------------------------------------------------------------- -def test_implementation_groups_has_defer_cleanup_ingredient() -> None: - """implementation-groups.yaml declares 'defer_cleanup' ingredient with default 'false'.""" - recipe = load_recipe(builtin_recipes_dir() / "implementation-groups.yaml") - assert "defer_cleanup" in recipe.ingredients, ( - "implementation-groups.yaml must declare a 'defer_cleanup' ingredient" - ) - assert recipe.ingredients["defer_cleanup"].default == "false", ( - "defer_cleanup default must be 'false'" - ) - - -def test_implementation_has_defer_cleanup_ingredient() -> None: - """implementation.yaml declares 'defer_cleanup' ingredient.""" - recipe = load_recipe(builtin_recipes_dir() / "implementation.yaml") - assert "defer_cleanup" in recipe.ingredients, ( - "implementation.yaml must declare a 'defer_cleanup' ingredient" - ) - assert recipe.ingredients["defer_cleanup"].default == "false", ( - "defer_cleanup default must be 'false'" +@pytest.mark.parametrize( + "recipe_name", + ["implementation", "remediation", "implementation-groups", "merge-prs", "smoke-test"], +) +def test_recipe_has_no_defer_cleanup_ingredient(recipe_name: str) -> None: + """Recipes must not declare 'defer_cleanup' — that design is removed.""" + recipe = load_recipe(_resolve_recipe_path(recipe_name)) + assert "defer_cleanup" not in recipe.ingredients, ( + f"{recipe_name}.yaml must not declare 'defer_cleanup'" ) -def test_remediation_has_defer_cleanup_ingredient() -> None: - """remediation.yaml declares 'defer_cleanup' ingredient.""" - recipe = load_recipe(builtin_recipes_dir() / "remediation.yaml") - assert "defer_cleanup" in recipe.ingredients, ( - "remediation.yaml must declare a 'defer_cleanup' ingredient" - ) - assert recipe.ingredients["defer_cleanup"].default == "false", ( - "defer_cleanup default must be 'false'" +@pytest.mark.parametrize( + "recipe_name", + ["implementation", "remediation", "implementation-groups", "merge-prs", "smoke-test"], +) +def test_recipe_has_no_registry_path_ingredient(recipe_name: str) -> None: + """Recipes must not declare 'registry_path' — replaced by a well-known default.""" + recipe = load_recipe(_resolve_recipe_path(recipe_name)) + assert "registry_path" not in recipe.ingredients, ( + f"{recipe_name}.yaml must not declare 'registry_path'" ) -def test_check_defer_cleanup_step_routes_to_register_or_confirm() -> None: - """check_defer_cleanup routes to register_success_deferred or confirm_cleanup.""" - recipe = load_recipe(builtin_recipes_dir() / "implementation.yaml") - assert "check_defer_cleanup" in recipe.steps, ( - "implementation.yaml must have a 'check_defer_cleanup' step" - ) - step = recipe.steps["check_defer_cleanup"] - assert step.on_result is not None, "check_defer_cleanup must declare on_result" - conds = step.on_result.conditions - routes = {c.route for c in conds} - assert "register_success_deferred" in routes, ( - "check_defer_cleanup on_result must route to 'register_success_deferred'" - ) - fallthrough_routes = [c.route for c in conds if c.when is None] - assert fallthrough_routes == ["confirm_cleanup"], ( - "check_defer_cleanup fallthrough (when=None) must route to 'confirm_cleanup'" - ) - assert step.on_failure == "confirm_cleanup", ( - "check_defer_cleanup on_failure must route to 'confirm_cleanup'" +@pytest.mark.parametrize( + "recipe_name", + ["implementation", "remediation", "implementation-groups", "merge-prs", "smoke-test"], +) +def test_recipe_has_no_interactive_cleanup_steps(recipe_name: str) -> None: + """Recipes must not have confirm_cleanup or delete_clone — these blocked unattended runs.""" + recipe = load_recipe(_resolve_recipe_path(recipe_name)) + assert "confirm_cleanup" not in recipe.steps, ( + f"{recipe_name}.yaml must not have 'confirm_cleanup' step" ) - - -def test_register_success_deferred_routes_to_done() -> None: - """register_success_deferred routes on_success and on_failure to done.""" - recipe = load_recipe(builtin_recipes_dir() / "implementation.yaml") - assert "register_success_deferred" in recipe.steps, ( - "implementation.yaml must have a 'register_success_deferred' step" + assert "delete_clone" not in recipe.steps, ( + f"{recipe_name}.yaml must not have 'delete_clone' step" ) - step = recipe.steps["register_success_deferred"] - assert step.on_success == "done", "register_success_deferred.on_success must route to 'done'" - assert step.on_failure == "done", "register_success_deferred.on_failure must route to 'done'" -def test_register_error_deferred_routes_to_escalate_stop() -> None: - """register_error_deferred routes on_success and on_failure to escalate_stop.""" - recipe = load_recipe(builtin_recipes_dir() / "implementation.yaml") - assert "register_error_deferred" in recipe.steps, ( - "implementation.yaml must have a 'register_error_deferred' step" - ) - step = recipe.steps["register_error_deferred"] - assert step.on_success == "escalate_stop", ( - "register_error_deferred.on_success must route to 'escalate_stop'" - ) - assert step.on_failure == "escalate_stop", ( - "register_error_deferred.on_failure must route to 'escalate_stop'" - ) +@pytest.mark.parametrize( + "recipe_name", ["implementation", "remediation", "implementation-groups", "merge-prs"] +) +def test_recipe_has_unconditional_register_steps(recipe_name: str) -> None: + """register_clone_success routes to done; register_clone_failure routes to escalate_stop.""" + recipe = load_recipe(builtin_recipes_dir() / f"{recipe_name}.yaml") + assert "register_clone_success" in recipe.steps + assert "register_clone_failure" in recipe.steps + s = recipe.steps["register_clone_success"] + f = recipe.steps["register_clone_failure"] + assert s.on_success == "done" + assert f.on_success == "escalate_stop" + assert f.on_failure == "escalate_stop" + assert "check_defer_cleanup" not in recipe.steps + assert "check_defer_on_failure" not in recipe.steps @pytest.mark.parametrize( @@ -1879,3 +1678,565 @@ def test_re_push_steps_have_force_true(recipe_name: str) -> None: f"{step_name} in {recipe_name} must include force='true' — " "post-rebase push requires --force-with-lease" ) + + +class TestResearchRecipeStructure: + @pytest.fixture + def recipe(self): + return load_recipe(builtin_recipes_dir() / "research.yaml") + + def test_research_has_review_pr_ingredient(self, recipe) -> None: + """research.yaml must declare a review_pr ingredient with default 'false'.""" + assert "review_pr" in recipe.ingredients, ( + "research.yaml must declare a 'review_pr' ingredient to gate the optional " + "review-research-pr step" + ) + assert recipe.ingredients["review_pr"].default == "false" + + def test_research_has_review_research_pr_step(self, recipe) -> None: + """research.yaml must include a review_research_pr step.""" + assert "review_research_pr" in recipe.steps + + def test_research_review_step_skip_when_false(self, recipe) -> None: + """review_research_pr step must use skip_when_false: inputs.review_pr.""" + step = recipe.steps["review_research_pr"] + assert step.skip_when_false == "inputs.review_pr" + + def test_research_no_issue_number_ingredient(self, recipe) -> None: + """Removed: issue_number is the phase-2 gate.""" + assert "issue_number" not in recipe.ingredients + + def test_research_no_setup_phases_ingredient(self, recipe) -> None: + """Removed: setup_phases toggle replaced by always-decompose.""" + assert "setup_phases" not in recipe.ingredients + + def test_research_no_check_phase_step(self, recipe) -> None: + assert "check_phase" not in recipe.steps + + def test_research_no_phase1_done_step(self, recipe) -> None: + assert "phase1_done" not in recipe.steps + + def test_research_no_open_plan_issue_step(self, recipe) -> None: + assert "open_plan_issue" not in recipe.steps + + def test_research_no_save_experiment_plan_step(self, recipe) -> None: + assert "save_experiment_plan" not in recipe.steps + + def test_research_no_check_setup_needed_step(self, recipe) -> None: + assert "check_setup_needed" not in recipe.steps + + def test_research_no_implement_experiment_step(self, recipe) -> None: + assert "implement_experiment" not in recipe.steps + + def test_research_has_issue_url_ingredient(self, recipe) -> None: + assert "issue_url" in recipe.ingredients + assert not recipe.ingredients["issue_url"].required + + def test_research_has_review_design_ingredient(self, recipe) -> None: + assert "review_design" in recipe.ingredients + assert recipe.ingredients["review_design"].default == "true" + + def test_research_has_review_design_step(self, recipe) -> None: + assert "review_design" in recipe.steps + + def test_review_design_step_skip_when_false(self, recipe) -> None: + step = recipe.steps["review_design"] + assert step.skip_when_false == "inputs.review_design" + + def test_review_design_step_retries_and_exhausted(self, recipe) -> None: + step = recipe.steps["review_design"] + assert step.retries == 2 + assert step.on_exhausted == "create_worktree" + + def test_plan_experiment_routes_to_review_design(self, recipe) -> None: + step = recipe.steps["plan_experiment"] + assert step.on_success == "review_design" + + def test_review_design_on_result_routing(self, recipe) -> None: + """review_design STOP verdict routes to resolve_design_review (not design_rejected).""" + step = recipe.steps["review_design"] + assert step.on_result is not None + routes = {c.when: c.route for c in step.on_result.conditions if c.when} + assert any("GO" in (w or "") for w in routes), "Missing GO route" + go_route = next(c.route for c in step.on_result.conditions if c.when and "GO" in c.when) + assert go_route == "plan_visualization" + revise_route = next( + c.route for c in step.on_result.conditions if c.when and "REVISE" in c.when + ) + assert revise_route == "revise_design" + stop_route = next( + c.route for c in step.on_result.conditions if c.when and "STOP" in c.when + ) + assert stop_route == "resolve_design_review" + + def test_has_revise_design_step(self, recipe) -> None: + assert "revise_design" in recipe.steps + + def test_has_design_rejected_step(self, recipe) -> None: + assert "design_rejected" in recipe.steps + + def test_design_rejected_step_is_action_stop(self, recipe) -> None: + """design_rejected must halt the pipeline (action=stop) with an explanatory message. + + Regression guard: changing action to 'route' would silently break + the hard-halt guarantee for fundamentally flawed designs. + """ + step = recipe.steps["design_rejected"] + assert step.action == "stop" + assert step.message, "design_rejected must have a non-empty message" + assert "STOP" in step.message, ( + "design_rejected message must reference the STOP verdict for clarity." + ) + + def test_kitchen_rule_6_acknowledges_stop_verdict_exception(self, recipe) -> None: + """Kitchen rule #6 must scope 'do not stop' to exhaustion/failure, not STOP verdict. + + The current blanket 'do not stop' language contradicts the design_rejected + hard halt. The rule must explicitly note that verdict=STOP is the sole exception. + """ + rule6 = recipe.kitchen_rules[5] # 0-indexed; rule #6 is index 5 + rule6_lower = rule6.lower() + assert "stop" in rule6_lower, ( + "Kitchen rule #6 must reference 'stop' in the verdict exception context." + ) + assert "verdict" in rule6_lower or "exception" in rule6_lower, ( + "Kitchen rule #6 must acknowledge that verdict=STOP is an exception to " + "'do not stop on exhaustion/failure'. Current language is overbroad and " + "contradicts the design_rejected routing." + ) + + def test_has_resolve_design_review_step(self, recipe) -> None: + """resolve_design_review step must be present in research.yaml.""" + assert "resolve_design_review" in recipe.steps + + def test_resolve_design_review_routes_revised_to_revise_design(self, recipe) -> None: + """resolve_design_review routes resolution=revised back to revise_design.""" + step = recipe.steps["resolve_design_review"] + assert step.on_result is not None + revised_route = next( + c.route for c in step.on_result.conditions if c.when and "revised" in c.when + ) + assert revised_route == "revise_design" + + def test_resolve_design_review_routes_failed_to_design_rejected(self, recipe) -> None: + """resolve_design_review routes resolution=failed to design_rejected.""" + step = recipe.steps["resolve_design_review"] + assert step.on_result is not None + failed_route = next( + c.route for c in step.on_result.conditions if c.when and "failed" in c.when + ) + assert failed_route == "design_rejected" + + def test_resolve_design_review_fallbacks_to_design_rejected(self, recipe) -> None: + """resolve_design_review routes on_failure and on_context_limit to design_rejected.""" + step = recipe.steps["resolve_design_review"] + assert step.on_failure == "design_rejected" + assert step.on_context_limit == "design_rejected" + + def test_resolve_design_review_captures_revision_guidance(self, recipe) -> None: + """resolve_design_review must capture revision_guidance for the revise_design loop.""" + step = recipe.steps["resolve_design_review"] + assert "revision_guidance" in step.capture, ( + "resolve_design_review must capture revision_guidance so revise_design → " + "plan_experiment picks up the triage-generated guidance" + ) + + def test_has_resolve_research_review_step(self, recipe) -> None: + step = recipe.steps["resolve_research_review"] + assert step.retries == 2 + assert step.on_exhausted == "route_claims_resolve" + assert step.on_success == "route_claims_resolve" + assert step.on_failure == "route_claims_resolve" + + def test_has_re_push_research_step(self, recipe) -> None: + assert "re_push_research" in recipe.steps + + def test_research_validates_cleanly(self, recipe) -> None: + """validate_recipe returns no errors on the simplified recipe.""" + from autoskillit.recipe.validator import validate_recipe + + errors = validate_recipe(recipe) + assert errors == [], f"Validation errors: {errors}" + + def test_requires_packs_includes_exp_lens(self, recipe) -> None: + assert "exp-lens" in recipe.requires_packs + assert "research" in recipe.requires_packs + + def test_re_run_experiment_step(self, recipe) -> None: + assert "re_run_experiment" in recipe.steps + step = recipe.steps["re_run_experiment"] + assert step.tool == "run_skill" + assert "--adjust" in step.with_args.get("skill_command", "") + assert step.on_success == "re_generate_report" + + def test_re_generate_report_step(self, recipe) -> None: + assert "re_generate_report" in recipe.steps + step = recipe.steps["re_generate_report"] + assert step.tool == "run_skill" + assert step.on_success == "re_stage_bundle" + + def test_re_test_step(self, recipe) -> None: + assert "re_test" in recipe.steps + step = recipe.steps["re_test"] + assert step.tool == "test_check" + assert step.on_success == "re_push_research" + + def test_revalidation_loop_all_paths_reach_begin_archival(self, recipe) -> None: + """Every path from merge_escalations reaches begin_archival.""" + for step_name in ("re_run_experiment", "re_generate_report", "re_test"): + step = recipe.steps[step_name] + assert step.on_failure in ("begin_archival", "re_push_research") + assert recipe.steps["re_push_research"].on_success == "finalize_bundle" + + def test_audit_claims_ingredient_default_false(self, recipe) -> None: + assert "audit_claims" in recipe.ingredients + assert recipe.ingredients["audit_claims"].required is False + assert recipe.ingredients["audit_claims"].default == "false" + + def test_review_research_pr_captures_review_verdict(self, recipe) -> None: + step = recipe.steps["review_research_pr"] + assert "review_verdict" in step.capture + assert "verdict" not in step.capture # old key must be gone + + def test_audit_claims_step_routes_to_route_review_resolve(self, recipe) -> None: + step = recipe.steps["audit_claims"] + assert step.tool == "run_skill" + assert "audit_claims" in step.skip_when_false + # all on_result routes point to route_review_resolve + routes = {c.route for c in step.on_result.conditions} + assert routes == {"route_review_resolve"} + + def test_new_routing_steps_exist(self, recipe) -> None: + assert "route_review_resolve" in recipe.steps + assert "route_claims_resolve" in recipe.steps + assert "merge_escalations" in recipe.steps + assert "check_escalations" not in recipe.steps # replaced + + def test_route_review_resolve_routing_logic(self, recipe) -> None: + step = recipe.steps["route_review_resolve"] + assert step.action == "route" + conditions = step.on_result.conditions + # changes_requested → resolve_research_review; else → route_claims_resolve + guarded = [c for c in conditions if c.when is not None] + default = [c for c in conditions if c.when is None] + assert len(guarded) == 1 + assert "changes_requested" in guarded[0].when + assert guarded[0].route == "resolve_research_review" + assert len(default) == 1 + assert default[0].route == "route_claims_resolve" + + def test_route_claims_resolve_routing_logic(self, recipe) -> None: + step = recipe.steps["route_claims_resolve"] + assert step.action == "route" + conditions = step.on_result.conditions + # changes_requested → resolve_claims_review; else → merge_escalations + guarded = [c for c in conditions if c.when is not None] + default = [c for c in conditions if c.when is None] + assert len(guarded) == 1 + assert "changes_requested" in guarded[0].when + assert guarded[0].route == "resolve_claims_review" + assert len(default) == 1 + assert default[0].route == "merge_escalations" + + def test_merge_escalations_routing_logic(self, recipe) -> None: + step = recipe.steps["merge_escalations"] + assert step.action == "route" + conditions = step.on_result.conditions + # review_needs_rerun == true → re_run_experiment + # claims_needs_rerun == true → re_run_experiment + # else → re_push_research + guarded = [c for c in conditions if c.when is not None] + default = [c for c in conditions if c.when is None] + assert len(guarded) == 2 + rerun_routes = {c.route for c in guarded} + assert rerun_routes == {"re_run_experiment"} + assert any("review_needs_rerun" in c.when for c in guarded) + assert any("claims_needs_rerun" in c.when for c in guarded) + assert len(default) == 1 + assert default[0].route == "re_push_research" + + def test_resolve_claims_review_step_exists(self, recipe) -> None: + step = recipe.steps["resolve_claims_review"] + assert "claims_needs_rerun" in step.capture + + def test_resolve_research_review_captures_review_needs_rerun(self, recipe) -> None: + step = recipe.steps["resolve_research_review"] + assert "review_needs_rerun" in step.capture + assert "needs_rerun" not in step.capture # old key must be gone + + def test_research_recipe_validates_cleanly_with_new_steps(self, recipe) -> None: + from autoskillit.recipe.validator import validate_recipe + + errors = validate_recipe(recipe) + assert errors == [], f"Validation errors: {errors}" + + # --- Archival phase tests --- + + def test_archival_begin_archival_step_exists(self, recipe) -> None: + """begin_archival must be a route step gating archival on pr_url.""" + assert "begin_archival" in recipe.steps + step = recipe.steps["begin_archival"] + assert step.action == "route" + + def test_archival_begin_archival_routes_to_capture(self, recipe) -> None: + """begin_archival routes to capture_experiment_branch when pr_url is truthy.""" + step = recipe.steps["begin_archival"] + assert step.on_result is not None + conditions = step.on_result.conditions + truthy_route = next((c for c in conditions if c.when and "pr_url" in c.when), None) + assert truthy_route is not None + assert truthy_route.route == "capture_experiment_branch" + + def test_archival_begin_archival_default_to_complete(self, recipe) -> None: + """begin_archival default route goes to research_complete.""" + step = recipe.steps["begin_archival"] + conditions = step.on_result.conditions + default = next((c for c in conditions if not c.when), None) + assert default is not None + assert default.route == "research_complete" + + def test_archival_capture_experiment_branch_step(self, recipe) -> None: + """capture_experiment_branch captures experiment_branch from git rev-parse.""" + assert "capture_experiment_branch" in recipe.steps + step = recipe.steps["capture_experiment_branch"] + assert step.tool == "run_cmd" + assert "experiment_branch" in step.capture + assert step.on_success == "create_artifact_branch" + assert step.on_failure == "research_complete" + + def test_archival_create_artifact_branch_step(self, recipe) -> None: + """create_artifact_branch creates temp worktree and captures artifact_branch.""" + assert "create_artifact_branch" in recipe.steps + step = recipe.steps["create_artifact_branch"] + assert step.tool == "run_cmd" + assert "artifact_branch" in step.capture + assert step.on_success == "open_artifact_pr" + assert step.on_failure == "research_complete" + + def test_archival_create_artifact_branch_uses_research_checkout(self, recipe) -> None: + """create_artifact_branch must use git checkout -- research/ pattern.""" + step = recipe.steps["create_artifact_branch"] + cmd = step.with_args["cmd"] + assert "research/" in cmd, "Must checkout research/ directory from experiment branch" + assert "worktree add" in cmd, "Must create a temporary worktree" + + def test_archival_open_artifact_pr_step(self, recipe) -> None: + """open_artifact_pr creates the artifact-only PR and captures artifact_pr_url.""" + assert "open_artifact_pr" in recipe.steps + step = recipe.steps["open_artifact_pr"] + assert step.tool == "run_cmd" + assert "artifact_pr_url" in step.capture + assert step.on_success == "tag_experiment_branch" + assert step.on_failure == "research_complete" + + def test_archival_tag_experiment_branch_step(self, recipe) -> None: + """tag_experiment_branch creates annotated archive tag and captures archive_tag.""" + assert "tag_experiment_branch" in recipe.steps + step = recipe.steps["tag_experiment_branch"] + assert step.tool == "run_cmd" + assert "archive_tag" in step.capture + assert step.on_success == "close_experiment_pr" + assert step.on_failure == "research_complete" + + def test_archival_tag_uses_archive_prefix(self, recipe) -> None: + """Tag name must use archive/research/ prefix convention.""" + step = recipe.steps["tag_experiment_branch"] + cmd = step.with_args["cmd"] + assert "archive/research/" in cmd + + def test_archival_close_experiment_pr_step(self, recipe) -> None: + """close_experiment_pr closes the original PR and routes to research_complete.""" + assert "close_experiment_pr" in recipe.steps + step = recipe.steps["close_experiment_pr"] + assert step.tool == "run_cmd" + assert step.on_success == "research_complete" + assert step.on_failure == "research_complete" + + def test_archival_close_pr_references_artifact_and_tag(self, recipe) -> None: + """close_experiment_pr comment must reference both artifact PR and archive tag.""" + step = recipe.steps["close_experiment_pr"] + cmd = step.with_args["cmd"] + assert "artifact_pr_url" in cmd, "Must reference artifact PR URL" + assert "archive_tag" in cmd, "Must reference archive tag" + + def test_archival_graceful_degradation(self, recipe) -> None: + """Every archival step must route on_failure to research_complete.""" + archival_steps = [ + "capture_experiment_branch", + "create_artifact_branch", + "open_artifact_pr", + "tag_experiment_branch", + "close_experiment_pr", + ] + for name in archival_steps: + step = recipe.steps[name] + assert step.on_failure == "research_complete", ( + f"{name}.on_failure must be research_complete for graceful degradation" + ) + + def test_re_push_research_routes_to_finalize_bundle(self, recipe) -> None: + """re_push_research routes to finalize_bundle on success, begin_archival on failure.""" + step = recipe.steps["re_push_research"] + assert step.on_success == "finalize_bundle" + assert step.on_failure == "begin_archival" + + def test_finalize_bundle_routes_to_finalize_bundle_render(self, recipe) -> None: + """finalize_bundle on_success routes to finalize_bundle_render (not begin_archival).""" + step = recipe.steps["finalize_bundle"] + assert step.on_success == "finalize_bundle_render" + assert step.on_failure == "begin_archival" + + def test_finalize_bundle_render_step_exists_and_routes(self, recipe) -> None: + """finalize_bundle_render routes to route_archive_or_export on both outcomes.""" + assert "finalize_bundle_render" in recipe.steps + step = recipe.steps["finalize_bundle_render"] + assert step.on_success == "route_archive_or_export" + assert step.on_failure == "route_archive_or_export" + + def test_create_worktree_copies_review_cycle_artifacts(self, recipe) -> None: + """create_worktree must copy review-design dashboards and revision guidance.""" + step = recipe.steps["create_worktree"] + cmd = step.with_args["cmd"] + assert "review-cycles" in cmd, ( + "create_worktree must create artifacts/review-cycles/ subdirectory" + ) + assert "evaluation_dashboard" in cmd and "review-cycles" in cmd, ( + "create_worktree must copy evaluation dashboards to review-cycles/" + ) + assert "revision_guidance" in cmd and "review-cycles" in cmd, ( + "create_worktree must copy revision guidance to review-cycles/" + ) + + def test_create_worktree_copies_plan_version_artifacts(self, recipe) -> None: + """create_worktree must copy intermediate plan versions.""" + step = recipe.steps["create_worktree"] + cmd = step.with_args["cmd"] + assert "plan-versions" in cmd, ( + "create_worktree must create artifacts/plan-versions/ subdirectory" + ) + assert "experiment_plan" in cmd and "plan-versions" in cmd, ( + "create_worktree must copy plan versions to plan-versions/" + ) + + def test_stage_bundle_step_exists(self, recipe) -> None: + """A stage_bundle step must exist to organize phase artifacts.""" + assert "stage_bundle" in recipe.steps, ( + "research.yaml must have a stage_bundle step for phase artifact staging" + ) + step = recipe.steps["stage_bundle"] + cmd = step.with_args["cmd"] + assert "phase-groups" in cmd, "Must copy make-groups output" + assert "phase-plans" in cmd, "Must copy make-plan output" + + def test_test_routes_to_push_branch(self, recipe) -> None: + """test step must route to push_branch now that commit_research_artifacts is removed.""" + step = recipe.steps["test"] + assert step.on_success == "push_branch", ( + "test.on_success must be push_branch after commit_research_artifacts is removed" + ) + + def test_retest_routes_to_push_branch(self, recipe) -> None: + """retest step must route to push_branch now that commit_research_artifacts is removed.""" + step = recipe.steps["retest"] + assert step.on_success == "push_branch", ( + "retest.on_success must be push_branch after commit_research_artifacts is removed" + ) + + def test_stage_bundle_routes_to_route_pr_or_local(self, recipe) -> None: + """stage_bundle must route to route_pr_or_local on success and failure.""" + step = recipe.steps["stage_bundle"] + assert step.on_success == "route_pr_or_local" + assert step.on_failure == "route_pr_or_local" + + +# --------------------------------------------------------------------------- +# Cross-recipe CI parameterization guard +# --------------------------------------------------------------------------- + + +def test_bundled_recipes_have_no_ci_hardcoded_workflow() -> None: + """No bundled recipe should hardcode workflow in wait_for_ci steps.""" + for yaml_path in sorted(builtin_recipes_dir().glob("*.yaml")): + recipe = load_recipe(yaml_path) + findings = run_semantic_rules(recipe) + wf_findings = [f for f in findings if f.rule == "ci-hardcoded-workflow"] + assert wf_findings == [], f"{recipe.name} has hardcoded workflow: {wf_findings}" + + +# --------------------------------------------------------------------------- +# Commit guard and context-limit completeness guards +# --------------------------------------------------------------------------- + + +def test_merge_worktree_has_commit_guard_predecessor() -> None: + """Every merge_worktree step in bundled recipes must have a commit_guard predecessor. + + A commit_guard step auto-commits any dirty files before the merge_worktree + dirty-tree gate runs, providing structural immunity to context-exhausted skills + that leave edits on disk without committing them. + """ + from autoskillit.recipe.validator import make_validation_context + + for yaml_path in sorted(builtin_recipes_dir().glob("*.yaml")): + recipe = load_recipe(yaml_path) + merge_steps = [n for n, s in recipe.steps.items() if s.tool == "merge_worktree"] + if not merge_steps: + continue + ctx = make_validation_context(recipe) + for step_name in merge_steps: + preds = ctx.predecessors.get(step_name, set()) + has_guard = any(_is_commit_guard(p, ctx) for p in preds) + assert has_guard, ( + f"{yaml_path.name}: merge_worktree step '{step_name}' has no commit_guard " + f"predecessor. Add a commit_guard run_cmd step immediately before merge. " + f"Predecessors: {sorted(preds)}" + ) + + +def test_resolve_failures_steps_have_on_context_limit() -> None: + """Every step invoking resolve-failures must declare on_context_limit. + + Without on_context_limit, context exhaustion mid-fix falls through to + on_failure, discarding all uncommitted edits and losing partial progress. + """ + from autoskillit.recipe.contracts import resolve_skill_name + + for yaml_path in sorted(builtin_recipes_dir().glob("*.yaml")): + recipe = load_recipe(yaml_path) + for step_name, step in recipe.steps.items(): + if step.tool not in SKILL_TOOLS: + continue + skill_cmd = step.with_args.get("skill_command", "") + skill = resolve_skill_name(skill_cmd) + if skill != "resolve-failures": + continue + assert step.on_context_limit is not None, ( + f"{yaml_path.name}: step '{step_name}' invokes resolve-failures " + f"but has no on_context_limit. Context exhaustion will strand uncommitted " + f"edits on disk and fall through to on_failure, losing progress." + ) + + +# --------------------------------------------------------------------------- +# Cross-recipe cwd-after-clone guard +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("recipe_path", _ALL_CLONE_RECIPE_PATHS, ids=lambda p: p.stem) +def test_all_clone_recipes_use_context_cwd_after_clone(recipe_path: Path) -> None: + """After clone_repo, no step should use inputs.* as cwd.""" + import re + + input_re = re.compile(r"\$\{\{\s*inputs\.\w+\s*\}\}") + recipe = load_recipe(recipe_path) + + seen_clone = False + for name, step in recipe.steps.items(): + if step.tool == "clone_repo": + seen_clone = True + continue + if seen_clone and step.with_args: + cwd = step.with_args.get("cwd", "") + assert not input_re.search(cwd), ( + f"{recipe_path.stem}: step '{name}' uses inputs.* as cwd after clone: {cwd}" + ) diff --git a/tests/recipe/test_bundled_recipes_no_inversions.py b/tests/recipe/test_bundled_recipes_no_inversions.py new file mode 100644 index 0000000000..25f68393f3 --- /dev/null +++ b/tests/recipe/test_bundled_recipes_no_inversions.py @@ -0,0 +1,42 @@ +"""Bundled-recipe regression guard: no capture inversions or hardcoded event literals.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +import yaml + +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe +from autoskillit.recipe.registry import run_semantic_rules + +_BUNDLED_RECIPE_PATHS: list[Path] = sorted(builtin_recipes_dir().glob("*.yaml")) + + +@pytest.mark.parametrize("recipe_path", _BUNDLED_RECIPE_PATHS, ids=lambda p: p.stem) +def test_bundled_recipe_has_no_capture_inversions(recipe_path): + """After Part B: all bundled recipes produce zero inversion findings. Before + Part B: the four recipes with wait_for_ci event='push' fail this test.""" + recipe = load_recipe(recipe_path) + findings = run_semantic_rules(recipe) + inversions = [f for f in findings if "inversion" in f.rule] + assert inversions == [], f"{recipe_path.stem} has inversions: " + "\n".join( + f" {f.rule}: {f.message}" for f in inversions + ) + + +@pytest.mark.parametrize("recipe_path", _BUNDLED_RECIPE_PATHS, ids=lambda p: p.stem) +def test_diagnose_ci_skill_command_uses_captured_ci_event(recipe_path): + """No skill_command step may pass a hardcoded trigger event as a positional. + All /autoskillit:diagnose-ci invocations must thread ${{ context.ci_event }}.""" + recipe = yaml.safe_load(recipe_path.read_text()) + for step_name, step in recipe.get("steps", {}).items(): + cmd = step.get("skill_command") or step.get("with", {}).get("skill_command", "") + if "diagnose-ci" in cmd: + hardcoded_events = {"push", "merge_group"} + assert "${{ context.ci_event }}" in cmd or not any( + ev in cmd.split() for ev in hardcoded_events + ), ( + f"{recipe_path.stem}:{step_name} — diagnose-ci call hardcodes a trigger " + f"event literal instead of threading ${{{{ context.ci_event }}}}" + ) diff --git a/tests/recipe/test_check_repo_merge_state_routing.py b/tests/recipe/test_check_repo_merge_state_routing.py new file mode 100644 index 0000000000..2560f008aa --- /dev/null +++ b/tests/recipe/test_check_repo_merge_state_routing.py @@ -0,0 +1,26 @@ +"""Regression guard: check_repo_merge_state on_failure must route to immediate_merge. + +Prior to this fix, on_failure pointed to release_issue_success (a terminal success path), +which would mislabel the issue as "staged" while leaving the PR unmerged on API failure. +""" + +from __future__ import annotations + +import pytest + +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe + + +@pytest.mark.parametrize("recipe_name", ["implementation", "remediation", "implementation-groups"]) +def test_check_repo_merge_state_on_failure_routes_to_immediate_merge_not_success(recipe_name): + """check_repo_merge_state on_failure must not point to a terminal success step. + + Ensures that a network/auth failure in check_repo_merge_state falls through + to immediate_merge (direct squash merge path) rather than release_issue_success + (which would mislabel the issue as staged while the PR remains unmerged). + """ + recipe = load_recipe(builtin_recipes_dir() / f"{recipe_name}.yaml") + step = recipe.steps["check_repo_merge_state"] + assert step.on_failure == "immediate_merge", ( + f"{recipe_name}: on_failure={step.on_failure!r}, expected 'immediate_merge'" + ) diff --git a/tests/recipe/test_contract_verdict_output_required.py b/tests/recipe/test_contract_verdict_output_required.py new file mode 100644 index 0000000000..3b0a32ca31 --- /dev/null +++ b/tests/recipe/test_contract_verdict_output_required.py @@ -0,0 +1,158 @@ +"""Contract guard: conditional-write auto-fix skills must declare a typed verdict output. + +Every skill in the auto-fix family (resolve-failures, resolve-review, +resolve-claims-review, resolve-research-review) must declare a 'verdict' +output with allowed_values covering at least the four canonical values: + real_fix, already_green, flake_suspected, ci_only_failure + +diagnose-ci must declare 'failure_subtype' with at least the seven canonical values: + flaky, timing_race, deterministic, fixture, import, env, unknown +""" + +from __future__ import annotations + +import pytest + +from autoskillit.recipe.contracts import load_bundled_manifest + +_AUTO_FIX_SKILLS = [ + "resolve-failures", + "resolve-review", + "resolve-claims-review", + "resolve-research-review", +] + +_REQUIRED_VERDICT_VALUES = {"real_fix", "already_green", "flake_suspected", "ci_only_failure"} +_REQUIRED_SUBTYPE_VALUES = { + "flaky", + "timing_race", + "deterministic", + "fixture", + "import", + "env", + "unknown", +} + + +@pytest.mark.parametrize("skill_name", _AUTO_FIX_SKILLS) +def test_auto_fix_skill_write_behavior_is_conditional(skill_name: str) -> None: + """Each auto-fix skill must declare write_behavior: conditional.""" + manifest = load_bundled_manifest() + skill = manifest.get("skills", {}).get(skill_name) + assert skill is not None, f"Skill '{skill_name}' not found in bundled manifest" + assert skill.get("write_behavior") == "conditional", ( + f"Skill '{skill_name}' must have write_behavior: conditional, " + f"got {skill.get('write_behavior')!r}" + ) + + +@pytest.mark.parametrize("skill_name", _AUTO_FIX_SKILLS) +def test_auto_fix_skill_declares_verdict_output(skill_name: str) -> None: + """Each auto-fix skill must declare a 'verdict' output with allowed_values.""" + manifest = load_bundled_manifest() + skill = manifest.get("skills", {}).get(skill_name) + assert skill is not None, f"Skill '{skill_name}' not found in bundled manifest" + outputs = skill.get("outputs", []) + verdict_outputs = [o for o in outputs if o.get("name") == "verdict"] + assert len(verdict_outputs) >= 1, ( + f"Skill '{skill_name}' must declare a 'verdict' output, " + f"but outputs are: {[o.get('name') for o in outputs]}" + ) + + +@pytest.mark.parametrize("skill_name", _AUTO_FIX_SKILLS) +def test_auto_fix_skill_verdict_has_required_allowed_values(skill_name: str) -> None: + """The 'verdict' output must include all four canonical allowed values.""" + manifest = load_bundled_manifest() + skill = manifest.get("skills", {}).get(skill_name) + assert skill is not None, f"Skill '{skill_name}' not found in bundled manifest" + outputs = skill.get("outputs", []) + verdict_outputs = [o for o in outputs if o.get("name") == "verdict"] + assert len(verdict_outputs) >= 1, f"Skill '{skill_name}' has no 'verdict' output" + allowed = set(verdict_outputs[0].get("allowed_values", [])) + missing = _REQUIRED_VERDICT_VALUES - allowed + assert not missing, ( + f"Skill '{skill_name}' verdict output is missing required values: {missing}. " + f"Current allowed_values: {allowed}" + ) + + +@pytest.mark.parametrize("skill_name", _AUTO_FIX_SKILLS) +def test_auto_fix_skill_verdict_type_is_string(skill_name: str) -> None: + """The 'verdict' output must have type: string.""" + manifest = load_bundled_manifest() + skill = manifest.get("skills", {}).get(skill_name) + assert skill is not None, f"Skill '{skill_name}' not found in bundled manifest" + outputs = skill.get("outputs", []) + verdict_outputs = [o for o in outputs if o.get("name") == "verdict"] + assert len(verdict_outputs) >= 1, f"Skill '{skill_name}' has no 'verdict' output" + assert verdict_outputs[0].get("type") == "string", ( + f"Skill '{skill_name}' verdict output must have type: string, " + f"got {verdict_outputs[0].get('type')!r}" + ) + + +@pytest.mark.parametrize("skill_name", _AUTO_FIX_SKILLS) +def test_auto_fix_skill_write_expected_when_uses_verdict(skill_name: str) -> None: + """write_expected_when must reference verdict=real_fix (not fixes_applied).""" + manifest = load_bundled_manifest() + skill = manifest.get("skills", {}).get(skill_name) + assert skill is not None, f"Skill '{skill_name}' not found in bundled manifest" + patterns = skill.get("write_expected_when", []) + assert any("verdict" in p for p in patterns), ( + f"Skill '{skill_name}' write_expected_when must reference 'verdict', got {patterns!r}" + ) + + +def test_diagnose_ci_declares_failure_subtype_output() -> None: + """diagnose-ci must declare a 'failure_subtype' output.""" + manifest = load_bundled_manifest() + skill = manifest.get("skills", {}).get("diagnose-ci") + assert skill is not None, "Skill 'diagnose-ci' not found in bundled manifest" + outputs = skill.get("outputs", []) + subtype_outputs = [o for o in outputs if o.get("name") == "failure_subtype"] + assert len(subtype_outputs) >= 1, ( + f"diagnose-ci must declare a 'failure_subtype' output; " + f"current outputs: {[o.get('name') for o in outputs]}" + ) + + +def test_diagnose_ci_failure_subtype_has_required_values() -> None: + """diagnose-ci failure_subtype must include all seven canonical allowed values.""" + manifest = load_bundled_manifest() + skill = manifest.get("skills", {}).get("diagnose-ci") + assert skill is not None, "Skill 'diagnose-ci' not found in bundled manifest" + outputs = skill.get("outputs", []) + subtype_outputs = [o for o in outputs if o.get("name") == "failure_subtype"] + assert len(subtype_outputs) >= 1, "diagnose-ci has no 'failure_subtype' output" + allowed = set(subtype_outputs[0].get("allowed_values", [])) + missing = _REQUIRED_SUBTYPE_VALUES - allowed + assert not missing, ( + f"diagnose-ci failure_subtype is missing required values: {missing}. " + f"Current allowed_values: {allowed}" + ) + + +def test_conditional_write_skills_have_verdict_or_fixes_applied_declared() -> None: + """Generic future-proofing: every in-scope conditional-write skill must declare verdict. + + Excludes resolve-merge-conflicts (different oracle: pre-commit + manifest, out of scope) + and retry-worktree (phases_implemented oracle, deferred to a separate Part). + """ + _EXCLUDED = {"resolve-merge-conflicts", "retry-worktree"} + manifest = load_bundled_manifest() + violations: list[str] = [] + for skill_name, skill in manifest.get("skills", {}).items(): + if skill_name in _EXCLUDED: + continue + if skill.get("write_behavior") != "conditional": + continue + outputs = skill.get("outputs", []) + output_names = {o.get("name") for o in outputs} + if "verdict" not in output_names: + violations.append(skill_name) + assert not violations, ( + "The following conditional-write skills do not declare a 'verdict' output: " + f"{violations}. Every conditional-write skill must declare verdict to enable " + "recipe-level verdict-gated routing (prevents unconditional re-push loops)." + ) diff --git a/tests/recipe/test_contracts.py b/tests/recipe/test_contracts.py index d80a265489..57e4012f1c 100644 --- a/tests/recipe/test_contracts.py +++ b/tests/recipe/test_contracts.py @@ -81,6 +81,15 @@ def test_resolve_skill_name_dynamic() -> None: assert resolve_skill_name("/audit-${{ inputs.audit_type }}") is None +def test_resolve_skill_name_bash_placeholder_truncation() -> None: + """Skill names truncated by a bash {placeholder} suffix must be treated as dynamic.""" + from autoskillit.recipe.contracts import resolve_skill_name + + # "/autoskillit:exp-lens-{slug}" — regex extracts "exp-lens-" (stops at {) + # but the true name is dynamic; must return None to skip contract validation. + assert resolve_skill_name("/autoskillit:exp-lens-{slug} {ctx} ${{ context.plan }}") is None + + # --------------------------------------------------------------------------- # Shared YAML fixtures # --------------------------------------------------------------------------- @@ -440,10 +449,17 @@ def test_sc1_audit_impl_has_real_inputs_and_outputs() -> None: assert remediation_out["type"] == "file_path" -def test_sc2_resolve_failures_has_empty_outputs() -> None: - """T_SC2: resolve-failures has outputs: [].""" +def test_sc2_resolve_failures_declares_verdict_output() -> None: + """T_SC2: resolve-failures declares a verdict output with allowed_values.""" manifest = load_bundled_manifest() - assert manifest["skills"]["resolve-failures"]["outputs"] == [] + outputs = manifest["skills"]["resolve-failures"]["outputs"] + output_names = {o["name"] for o in outputs} + assert "verdict" in output_names, ( + "resolve-failures must declare a 'verdict' output after Part B implementation" + ) + verdict_out = next(o for o in outputs if o["name"] == "verdict") + assert "allowed_values" in verdict_out, "verdict output must have allowed_values" + assert "real_fix" in verdict_out["allowed_values"] def test_sc3_dry_walkthrough_has_empty_outputs() -> None: @@ -512,7 +528,8 @@ def test_pipeline_summary_contract_declared() -> None: "triage-issues", "analyze-prs", "merge-pr", - "open-pr", + "prepare-pr", + "compose-pr", "open-integration-pr", "implement-worktree", "implement-worktree-no-merge", @@ -552,9 +569,9 @@ def test_file_producing_skill_has_output_patterns(skill_name: str) -> None: def test_generate_recipe_card_includes_output_patterns(tmp_path: Path) -> None: """Recipe card serialization must preserve expected_output_patterns.""" manifest = load_bundled_manifest() - contract = get_skill_contract("open-pr", manifest) + contract = get_skill_contract("compose-pr", manifest) assert contract is not None - assert contract.expected_output_patterns, "Precondition: open-pr must have patterns" + assert contract.expected_output_patterns, "Precondition: compose-pr must have patterns" from autoskillit.core.paths import pkg_root @@ -566,14 +583,13 @@ def test_generate_recipe_card_includes_output_patterns(tmp_path: Path) -> None: recipes_dir.mkdir() card = generate_recipe_card(recipe_path, recipes_dir) card_skills = card.get("skills", {}) - open_pr_card = card_skills.get("open-pr") - if open_pr_card is None: - pytest.skip("open-pr not used in implementation recipe") + compose_pr_card = card_skills.get("compose-pr") + assert compose_pr_card is not None, "compose-pr must be used in implementation recipe" - assert "expected_output_patterns" in open_pr_card, ( + assert "expected_output_patterns" in compose_pr_card, ( "generate_recipe_card() must include expected_output_patterns" ) - assert open_pr_card["expected_output_patterns"], ( + assert compose_pr_card["expected_output_patterns"], ( "expected_output_patterns must be non-empty in the card" ) @@ -614,9 +630,6 @@ def test_write_behavior_defaults_to_none() -> None: "dry-walkthrough", "implement-worktree", "implement-worktree-no-merge", - "resolve-failures", - "resolve-review", - "retry-worktree", "rectify", "make-plan", "report-bug", @@ -637,6 +650,44 @@ def test_every_always_write_skill_has_contract(skill_name: str) -> None: ) +# Skills that write conditionally — write expected only when the completion +# token indicates actual work was performed. +CONDITIONAL_WRITE_SKILLS: dict[str, str] = { + # skill_name → substring that must appear in write_expected_when patterns + "resolve-failures": "verdict", + "resolve-merge-conflicts": "conflict_report_path", + "resolve-review": "verdict", + "retry-worktree": "phases_implemented", + "resolve-claims-review": "verdict", + "resolve-research-review": "verdict", +} + + +@pytest.mark.parametrize("skill_name,pattern_substring", sorted(CONDITIONAL_WRITE_SKILLS.items())) +def test_every_conditional_write_skill_has_correct_contract( + skill_name: str, pattern_substring: str +) -> None: + """Skills with legitimate no-write exits must declare write_behavior='conditional'. + + Each conditional skill must have at least one write_expected_when pattern + containing the expected token substring. This prevents regression to 'always'. + """ + manifest = load_bundled_manifest() + contract = get_skill_contract(skill_name, manifest) + assert contract is not None, f"Skill '{skill_name}' missing from skill_contracts.yaml" + assert contract.write_behavior == "conditional", ( + f"Skill '{skill_name}' must use write_behavior='conditional'. " + f"It has a legitimate no-write success path. Got: '{contract.write_behavior}'" + ) + assert len(contract.write_expected_when) > 0, ( + f"Skill '{skill_name}': conditional mode requires non-empty write_expected_when" + ) + assert any(pattern_substring in p for p in contract.write_expected_when), ( + f"Skill '{skill_name}': write_expected_when must contain a pattern with " + f"'{pattern_substring}' (the structured completion token)" + ) + + # --------------------------------------------------------------------------- # REQ-C4-02: DataFlowEntry rename # --------------------------------------------------------------------------- diff --git a/tests/recipe/test_contracts_block_fingerprint.py b/tests/recipe/test_contracts_block_fingerprint.py new file mode 100644 index 0000000000..002b37860e --- /dev/null +++ b/tests/recipe/test_contracts_block_fingerprint.py @@ -0,0 +1,102 @@ +"""Block fingerprint drift detection tests.""" + +from __future__ import annotations + +from autoskillit.recipe.contracts import ( + check_contract_staleness, + generate_recipe_card, +) +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe +from autoskillit.recipe.schema import Recipe, RecipeStep + + +def test_recipe_card_contains_block_fingerprint_for_every_declared_block(): + """generate_recipe_card(recipe) must produce a RecipeCard with block_fingerprints + covering every block declared in the recipe's steps.""" + recipe = load_recipe(builtin_recipes_dir() / "implementation.yaml") + card = generate_recipe_card(recipe) + block_names_in_recipe = {b.name for b in recipe.blocks} + block_names_in_card = {fp.name for fp in card.block_fingerprints} + assert block_names_in_card == block_names_in_recipe + + +def test_block_fingerprint_drift_triggers_staleness(): + """Given a stored card with block_fingerprints, mutate the recipe to add a run_cmd + step in the same block, and check_contract_staleness must return a StaleItem naming + the block with reason='block_composition_drift'.""" + original_recipe = load_recipe(builtin_recipes_dir() / "implementation.yaml") + original_card = generate_recipe_card(original_recipe) + mutated_recipe = _add_synthetic_run_cmd_to_block(original_recipe, "pre_queue_gate") + stale = check_contract_staleness(mutated_recipe, stored_card=original_card) + drift_items = [s for s in stale if s.reason == "block_composition_drift"] + assert len(drift_items) >= 1 + assert any("pre_queue_gate" in s.skill for s in drift_items) + + +def test_block_fingerprint_unchanged_when_unrelated_step_added(): + """Adding a step OUTSIDE the declared block must not trigger block drift.""" + original_recipe = load_recipe(builtin_recipes_dir() / "implementation.yaml") + original_card = generate_recipe_card(original_recipe) + mutated_recipe = _add_synthetic_step_outside_any_block(original_recipe) + stale = check_contract_staleness(mutated_recipe, stored_card=original_card) + drift_items = [s for s in stale if s.reason == "block_composition_drift"] + assert drift_items == [] + + +# --------------------------------------------------------------------------- +# Test helpers +# --------------------------------------------------------------------------- + + +def _add_synthetic_run_cmd_to_block(recipe: Recipe, block_name: str) -> Recipe: + """Return a copy of recipe with an extra run_cmd step in the named block. + + The new step has no routing connections (it's a dead-end) to minimise + impact on other validation rules. + """ + new_step_name = f"_synthetic_run_cmd_{block_name}" + new_step = RecipeStep( + name=new_step_name, + tool="run_cmd", + with_args={"cmd": "echo synthetic", "step_name": new_step_name}, + block=block_name, + ) + new_steps = dict(recipe.steps) + new_steps[new_step_name] = new_step + return Recipe( + name=recipe.name, + description=recipe.description, + summary=recipe.summary, + ingredients=recipe.ingredients, + steps=new_steps, + kitchen_rules=recipe.kitchen_rules, + version=recipe.version, + experimental=recipe.experimental, + requires_packs=recipe.requires_packs, + ) + + +def _add_synthetic_step_outside_any_block(recipe: Recipe) -> Recipe: + """Return a copy of recipe with an extra step that has NO block annotation. + + Adding an unblocked step must not affect any block fingerprints. + """ + new_step_name = "_synthetic_unblocked_step" + new_step = RecipeStep( + name=new_step_name, + action="stop", + message="synthetic step outside any block", + ) + new_steps = dict(recipe.steps) + new_steps[new_step_name] = new_step + return Recipe( + name=recipe.name, + description=recipe.description, + summary=recipe.summary, + ingredients=recipe.ingredients, + steps=new_steps, + kitchen_rules=recipe.kitchen_rules, + version=recipe.version, + experimental=recipe.experimental, + requires_packs=recipe.requires_packs, + ) diff --git a/tests/recipe/test_diagnose_ci_subtype_output.py b/tests/recipe/test_diagnose_ci_subtype_output.py new file mode 100644 index 0000000000..12c9dc90b9 --- /dev/null +++ b/tests/recipe/test_diagnose_ci_subtype_output.py @@ -0,0 +1,71 @@ +"""Contract guard: diagnose-ci SKILL.md must emit failure_subtype output token. + +Verifies that diagnose-ci/SKILL.md: +1. Declares failure_subtype in its Output Tokens section +2. Includes a subtype classification decision tree +3. Is consistent with the contract in skill_contracts.yaml +""" + +from __future__ import annotations + +import re + +from autoskillit.core import pkg_root +from autoskillit.recipe.contracts import load_bundled_manifest + +_SKILL_MD = pkg_root() / "skills_extended" / "diagnose-ci" / "SKILL.md" + + +def _skill_text() -> str: + assert _SKILL_MD.exists(), f"diagnose-ci SKILL.md not found at {_SKILL_MD}" + return _SKILL_MD.read_text(encoding="utf-8") + + +def test_diagnose_ci_skill_md_emits_failure_subtype_token() -> None: + """SKILL.md Output Tokens section must include 'failure_subtype = {value}'.""" + text = _skill_text() + assert re.search(r"failure_subtype\s*=\s*\{", text), ( + "diagnose-ci SKILL.md must emit 'failure_subtype = {value}' in the " + "Output Tokens block so the token is matchable by pipeline on_result: conditions" + ) + + +def test_diagnose_ci_skill_md_contains_subtype_classification() -> None: + """SKILL.md must contain a subtype classification section or decision tree.""" + text = _skill_text() + assert "failure_subtype" in text, ( + "diagnose-ci SKILL.md must reference 'failure_subtype' in its workflow" + ) + assert any( + subtype in text + for subtype in ("flaky", "timing_race", "deterministic", "fixture", "import", "env") + ), ( + "diagnose-ci SKILL.md must reference at least one of the canonical subtype " + "values (flaky, timing_race, deterministic, fixture, import, env) in its " + "classification logic" + ) + + +def test_diagnose_ci_skill_md_covers_all_subtype_values() -> None: + """All seven canonical subtype values must appear in the SKILL.md.""" + text = _skill_text() + required = {"flaky", "timing_race", "deterministic", "fixture", "import", "env", "unknown"} + missing = {v for v in required if v not in text} + assert not missing, f"diagnose-ci SKILL.md is missing these failure_subtype values: {missing}" + + +def test_diagnose_ci_skill_md_consistent_with_contract() -> None: + """SKILL.md must be consistent with the skill_contracts.yaml declaration.""" + manifest = load_bundled_manifest() + skill = manifest.get("skills", {}).get("diagnose-ci", {}) + outputs = skill.get("outputs", []) + declared_names = {o.get("name") for o in outputs} + text = _skill_text() + # Both: contract must declare it AND SKILL.md must emit it as a structured token + assert "failure_subtype" in declared_names, ( + "diagnose-ci must declare failure_subtype in skill_contracts.yaml" + ) + assert re.search(r"failure_subtype\s*=", text), ( + "diagnose-ci contract declares 'failure_subtype' output but SKILL.md " + "does not emit it as a structured token" + ) diff --git a/tests/recipe/test_experiment_type_registry.py b/tests/recipe/test_experiment_type_registry.py new file mode 100644 index 0000000000..192828acc8 --- /dev/null +++ b/tests/recipe/test_experiment_type_registry.py @@ -0,0 +1,225 @@ +"""Tests for experiment type registry loader.""" + +from __future__ import annotations + +from pathlib import Path + +import yaml + +from autoskillit.recipe.experiment_type_registry import ( + ExperimentTypeSpec, + load_all_experiment_types, +) + +EXPECTED_TYPES = { + "benchmark", + "configuration_study", + "causal_inference", + "robustness_audit", + "exploratory", +} + +VALID_WEIGHT_VALUES = {"H", "M", "L", "S"} + +EXPECTED_DIMENSIONS = { + "causal_structure", + "variance_protocol", + "statistical_corrections", + "ecological_validity", + "measurement_alignment", + "resource_proportionality", + "data_acquisition", + "agent_implementability", +} + + +def test_all_bundled_types_present() -> None: + """All 5 bundled types load without error.""" + types = load_all_experiment_types() + assert set(types.keys()) == EXPECTED_TYPES + + +def test_each_type_has_required_fields() -> None: + """Each type spec has all required fields with correct structure.""" + types = load_all_experiment_types() + for name, spec in types.items(): + assert spec.name == name, f"{name}: spec.name mismatch" + assert isinstance(spec.classification_triggers, list), f"{name}: triggers not list" + assert len(spec.classification_triggers) >= 1, f"{name}: no triggers" + assert isinstance(spec.dimension_weights, dict), f"{name}: weights not dict" + assert isinstance(spec.applicable_lenses, dict), f"{name}: lenses not dict" + assert isinstance(spec.red_team_focus, dict), f"{name}: red_team_focus not dict" + assert isinstance(spec.l1_severity, dict), f"{name}: l1_severity not dict" + + +def test_all_weight_values_are_valid() -> None: + """All dimension_weights values are one of H, M, L, S.""" + types = load_all_experiment_types() + for name, spec in types.items(): + for dim, weight in spec.dimension_weights.items(): + assert weight in VALID_WEIGHT_VALUES, ( + f"{name}.dimension_weights[{dim!r}] = {weight!r} — not in {VALID_WEIGHT_VALUES}" + ) + + +def test_all_eight_dimensions_present() -> None: + """All 8 dimensions from the SKILL.md matrix are present in each bundled type.""" + types = load_all_experiment_types() + for name, spec in types.items(): + missing = EXPECTED_DIMENSIONS - set(spec.dimension_weights.keys()) + assert not missing, f"{name} missing dimensions: {missing}" + + +def test_dimension_weights_match_skill_matrix() -> None: + """Spot-check dimension weights against the values in SKILL.md.""" + types = load_all_experiment_types() + bench = types["benchmark"] + assert bench.dimension_weights["causal_structure"] == "S" + assert bench.dimension_weights["variance_protocol"] == "H" + assert bench.dimension_weights["agent_implementability"] == "H" + assert bench.dimension_weights["statistical_corrections"] == "M" + + causal = types["causal_inference"] + assert causal.dimension_weights["causal_structure"] == "H" + assert causal.dimension_weights["statistical_corrections"] == "H" + assert causal.dimension_weights["variance_protocol"] == "L" + + config = types["configuration_study"] + assert config.dimension_weights["causal_structure"] == "S" + assert config.dimension_weights["statistical_corrections"] == "H" + + robust = types["robustness_audit"] + assert robust.dimension_weights["ecological_validity"] == "H" + assert robust.dimension_weights["data_acquisition"] == "H" + + exploratory = types["exploratory"] + assert exploratory.dimension_weights["statistical_corrections"] == "S" + assert exploratory.dimension_weights["agent_implementability"] == "L" + + +def test_red_team_severity_caps_match_skill() -> None: + """Red-team severity caps match values in SKILL.md Step 7 RT_MAX_SEVERITY.""" + types = load_all_experiment_types() + assert types["causal_inference"].red_team_focus["severity_cap"] == "critical" + assert types["benchmark"].red_team_focus["severity_cap"] == "warning" + assert types["configuration_study"].red_team_focus["severity_cap"] == "warning" + assert types["robustness_audit"].red_team_focus["severity_cap"] == "warning" + assert types["exploratory"].red_team_focus["severity_cap"] == "info" + + +def test_red_team_type_specific_focus_present() -> None: + """Each type has a type-specific red_team_focus.specific value.""" + types = load_all_experiment_types() + assert "asymmetric effort" in types["benchmark"].red_team_focus["specific"] + assert "overfitting" in types["configuration_study"].red_team_focus["specific"] + assert "backdoor" in types["causal_inference"].red_team_focus["specific"] + assert "threat distribution" in types["robustness_audit"].red_team_focus["specific"] + assert "HARKing" in types["exploratory"].red_team_focus["specific"] + + +def test_l1_severity_values() -> None: + """l1_severity values are one of: critical, warning, info.""" + valid_severities = {"critical", "warning", "info"} + types = load_all_experiment_types() + for name, spec in types.items(): + for dim, sev in spec.l1_severity.items(): + assert sev in valid_severities, f"{name}.l1_severity[{dim!r}] = {sev!r}" + + +def test_l1_severity_causal_inference_is_critical() -> None: + """causal_inference has critical l1_severity for both L1 dimensions.""" + types = load_all_experiment_types() + causal = types["causal_inference"] + assert causal.l1_severity["estimand_clarity"] == "critical" + assert causal.l1_severity["hypothesis_falsifiability"] == "critical" + + +def test_l1_severity_exploratory_is_info() -> None: + """exploratory has info l1_severity for both L1 dimensions.""" + types = load_all_experiment_types() + exp = types["exploratory"] + assert exp.l1_severity["estimand_clarity"] == "info" + assert exp.l1_severity["hypothesis_falsifiability"] == "info" + + +def test_no_project_dir_returns_bundled_only() -> None: + """With project_dir=None, only bundled types are returned.""" + types = load_all_experiment_types(project_dir=None) + assert set(types.keys()) == EXPECTED_TYPES + + +def test_user_override_replaces_bundled_type(tmp_path: Path) -> None: + """User-defined type with same name fully replaces bundled type (no field merging).""" + user_dir = tmp_path / ".autoskillit" / "experiment-types" + user_dir.mkdir(parents=True) + (user_dir / "benchmark.yaml").write_text( + yaml.dump( + { + "name": "benchmark", + "classification_triggers": ["custom trigger only"], + "dimension_weights": {"causal_structure": "H"}, + "applicable_lenses": {"primary": "custom-lens", "secondary": None}, + "red_team_focus": {"specific": "custom focus", "severity_cap": "critical"}, + "l1_severity": { + "estimand_clarity": "critical", + "hypothesis_falsifiability": "critical", + }, + } + ) + ) + types = load_all_experiment_types(project_dir=tmp_path) + bench = types["benchmark"] + # Custom values take effect + assert bench.classification_triggers == ["custom trigger only"] + assert bench.dimension_weights == {"causal_structure": "H"} + # Bundled fields (variance_protocol, etc.) are NOT present — full replacement + assert "variance_protocol" not in bench.dimension_weights + # Other bundled types remain intact + assert "causal_inference" in types + assert len(types) == 5 + + +def test_user_new_type_is_added(tmp_path: Path) -> None: + """User-defined type with a new name is added alongside bundled types.""" + user_dir = tmp_path / ".autoskillit" / "experiment-types" + user_dir.mkdir(parents=True) + (user_dir / "network_analysis.yaml").write_text( + yaml.dump( + { + "name": "network_analysis", + "classification_triggers": ["IVs are graph topology parameters"], + "dimension_weights": { + "causal_structure": "M", + "variance_protocol": "M", + "statistical_corrections": "M", + "ecological_validity": "M", + "measurement_alignment": "H", + "resource_proportionality": "L", + "data_acquisition": "H", + "agent_implementability": "M", + }, + "applicable_lenses": {"primary": "exp-lens-estimand-clarity", "secondary": None}, + "red_team_focus": {"specific": "connectivity bias", "severity_cap": "warning"}, + "l1_severity": { + "estimand_clarity": "warning", + "hypothesis_falsifiability": "warning", + }, + } + ) + ) + types = load_all_experiment_types(project_dir=tmp_path) + assert "network_analysis" in types + assert len(types) == 6 # 5 bundled + 1 user + + +def test_missing_user_override_dir_is_silent(tmp_path: Path) -> None: + """A project_dir with no .autoskillit/experiment-types/ is fine — bundled only returned.""" + types = load_all_experiment_types(project_dir=tmp_path) + assert set(types.keys()) == EXPECTED_TYPES + + +def test_returns_dict_of_experiment_type_spec() -> None: + """load_all_experiment_types returns dict[str, ExperimentTypeSpec].""" + types = load_all_experiment_types() + for _name, spec in types.items(): + assert isinstance(spec, ExperimentTypeSpec) diff --git a/tests/recipe/test_full_audit_recipe.py b/tests/recipe/test_full_audit_recipe.py new file mode 100644 index 0000000000..363de5eadd --- /dev/null +++ b/tests/recipe/test_full_audit_recipe.py @@ -0,0 +1,118 @@ +from pathlib import Path + +RECIPE_PATH = Path(__file__).resolve().parents[2] / ".autoskillit" / "recipes" / "full-audit.yaml" + + +def test_full_audit_recipe_file_exists() -> None: + """The recipe YAML exists at the project-scoped location.""" + assert RECIPE_PATH.exists(), f"Expected recipe at {RECIPE_PATH}" + + +def test_full_audit_recipe_validates() -> None: + """full-audit.yaml loads without errors and passes validate_recipe.""" + from autoskillit.recipe.io import load_recipe + from autoskillit.recipe.validator import validate_recipe + + recipe = load_recipe(RECIPE_PATH) + errors = validate_recipe(recipe) + assert errors == [], f"Validation errors: {errors}" + + +def test_full_audit_recipe_name() -> None: + from autoskillit.recipe.io import load_recipe + + recipe = load_recipe(RECIPE_PATH) + assert recipe.name == "full-audit" + + +def test_full_audit_required_ingredients() -> None: + from autoskillit.recipe.io import load_recipe + + recipe = load_recipe(RECIPE_PATH) + assert "workspace" in recipe.ingredients + assert recipe.ingredients["workspace"].required is True + assert "branch" in recipe.ingredients + assert recipe.ingredients["branch"].required is True + + +def test_full_audit_recipe_step_names() -> None: + from autoskillit.recipe.io import load_recipe + + recipe = load_recipe(RECIPE_PATH) + expected = { + "checkout", + "run_audits", + "validate_audits", + "create_issues", + "done", + "escalate_stop", + } + assert set(recipe.steps.keys()) == expected + + +def test_full_audit_routing_chain() -> None: + """checkout → run_audits → validate_audits → create_issues → done.""" + from autoskillit.recipe.io import load_recipe + + recipe = load_recipe(RECIPE_PATH) + assert recipe.steps["checkout"].on_success == "run_audits" + assert recipe.steps["run_audits"].on_success == "validate_audits" + assert recipe.steps["validate_audits"].on_success == "create_issues" + assert recipe.steps["create_issues"].on_success == "done" + + +def test_full_audit_failure_routes() -> None: + from autoskillit.recipe.io import load_recipe + + recipe = load_recipe(RECIPE_PATH) + for name in ("checkout", "run_audits", "validate_audits", "create_issues"): + step = recipe.steps[name] + assert step.on_failure == "escalate_stop", f"{name}.on_failure != escalate_stop" + + +def test_full_audit_kitchen_rules() -> None: + from autoskillit.recipe.io import load_recipe + + recipe = load_recipe(RECIPE_PATH) + assert len(recipe.kitchen_rules) == 3 + + +def test_full_audit_discovered_as_project_recipe(tmp_path: Path) -> None: + """list_recipes discovers the recipe as RecipeSource.PROJECT.""" + import shutil + + from autoskillit.core.types import RecipeSource + from autoskillit.recipe.io import list_recipes + + project_dir = tmp_path / "project" + recipe_dir = project_dir / ".autoskillit" / "recipes" + recipe_dir.mkdir(parents=True) + shutil.copy2(RECIPE_PATH, recipe_dir / "full-audit.yaml") + + result = list_recipes(project_dir) + match = [r for r in result.items if r.name == "full-audit"] + assert len(match) == 1 + assert match[0].source == RecipeSource.PROJECT + + +def test_full_audit_semantic_rules_no_errors() -> None: + from autoskillit.core.types import Severity + from autoskillit.recipe._analysis import make_validation_context + from autoskillit.recipe.io import load_recipe + from autoskillit.recipe.registry import run_semantic_rules + + recipe = load_recipe(RECIPE_PATH) + + known_skills = frozenset( + { + "audit-tests", + "audit-cohesion", + "audit-arch", + "validate-audit", + "prepare-issue", + } + ) + ctx = make_validation_context(recipe, available_skills=known_skills) + findings = run_semantic_rules(ctx) + errors = [f for f in findings if f.severity == Severity.ERROR] + assert not errors, f"Semantic rule errors: {[f.rule + ': ' + f.message for f in errors]}" diff --git a/tests/recipe/test_implementation_pr_decomposition.py b/tests/recipe/test_implementation_pr_decomposition.py new file mode 100644 index 0000000000..d6e9720c23 --- /dev/null +++ b/tests/recipe/test_implementation_pr_decomposition.py @@ -0,0 +1,67 @@ +"""Verify implementation.yaml has the three-step PR decomposition.""" + +import pytest + +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe +from autoskillit.recipe.validator import validate_recipe + +RECIPE_PATH = builtin_recipes_dir() / "implementation.yaml" + + +@pytest.fixture(scope="module") +def recipe(): + return load_recipe(RECIPE_PATH) + + +def test_implementation_recipe_has_three_pr_steps(recipe): + """open_pr_step is replaced by three decomposed steps.""" + step_names = list(recipe.steps.keys()) + assert "open_pr_step" not in step_names + assert "prepare_pr" in step_names + assert "run_arch_lenses" in step_names + assert "compose_pr" in step_names + + +def test_prepare_pr_routes_to_run_arch_lenses(recipe): + step = recipe.steps["prepare_pr"] + assert step.on_success == "run_arch_lenses" + + +def test_run_arch_lenses_routes_to_compose_on_success(recipe): + step = recipe.steps["run_arch_lenses"] + assert step.on_success == "compose_pr" + + +def test_run_arch_lenses_routes_to_compose_on_failure(recipe): + """Partial lens failure still routes to compose_pr.""" + step = recipe.steps["run_arch_lenses"] + assert step.on_failure == "compose_pr" + + +def test_compose_pr_routes_to_extract_pr_number(recipe): + step = recipe.steps["compose_pr"] + assert step.on_success == "extract_pr_number" + + +def test_prepare_pr_captures_three_context_vars(recipe): + step = recipe.steps["prepare_pr"] + capture = step.capture or {} + assert "prep_path" in capture + assert "selected_lenses" in capture + assert "lens_context_paths" in capture + + +def test_run_arch_lenses_uses_capture_list(recipe): + step = recipe.steps["run_arch_lenses"] + assert step.capture_list is not None + assert "all_diagram_paths" in (step.capture_list or {}) + + +def test_compose_pr_captures_pr_url(recipe): + step = recipe.steps["compose_pr"] + assert "pr_url" in (step.capture or {}) + + +def test_implementation_recipe_validates_after_decomposition(recipe): + errors = validate_recipe(recipe) + assert not errors, f"Validation errors: {errors}" diff --git a/tests/recipe/test_io.py b/tests/recipe/test_io.py index 09550319fe..7b852f5b48 100644 --- a/tests/recipe/test_io.py +++ b/tests/recipe/test_io.py @@ -184,25 +184,6 @@ def test_step_on_context_limit_parsed(self, tmp_path: Path) -> None: wf = load_recipe(f) assert wf.steps["impl"].on_context_limit == "retry_worktree" - def test_no_retry_block_in_yaml(self, tmp_path: Path) -> None: - """Old retry: block must raise — unrecognised field.""" - data = { - "name": "old-retry", - "description": "test", - "kitchen_rules": ["test"], - "steps": { - "impl": { - "tool": "run_skill", - "retry": {"max_attempts": 3, "on": "needs_retry"}, - "on_success": "done", - }, - "done": {"action": "stop", "message": "Done."}, - }, - } - f = _write_yaml(tmp_path / "recipe.yaml", data) - with pytest.raises(Exception): - load_recipe(f) - def test_load_recipe_rejects_non_dict(self, tmp_path: Path) -> None: """YAML that parses to a non-dict must raise ValueError.""" path = tmp_path / "list.yaml" @@ -452,6 +433,31 @@ def test_parse_step_model_absent(self) -> None: step = _parse_step({"tool": "run_skill"}) assert step.model is None + def test_parse_step_reads_stale_threshold(self) -> None: + data = {"tool": "run_skill", "stale_threshold": 2400, "on_success": "done"} + step = _parse_step(data) + assert step.stale_threshold == 2400 + + def test_parse_step_stale_threshold_defaults_to_none(self) -> None: + data = {"tool": "run_skill", "on_success": "done"} + step = _parse_step(data) + assert step.stale_threshold is None + + def test_parse_step_reads_idle_output_timeout(self) -> None: + data = {"tool": "run_skill", "idle_output_timeout": 120, "on_success": "done"} + step = _parse_step(data) + assert step.idle_output_timeout == 120 + + def test_parse_step_idle_output_timeout_defaults_to_none(self) -> None: + data = {"tool": "run_skill", "on_success": "done"} + step = _parse_step(data) + assert step.idle_output_timeout is None + + def test_parse_step_idle_output_timeout_zero_means_disabled(self) -> None: + data = {"tool": "run_skill", "idle_output_timeout": 0, "on_success": "done"} + step = _parse_step(data) + assert step.idle_output_timeout == 0 + # MOD4 def test_bundled_resolve_failures_steps_use_config_default(self) -> None: bd = builtin_recipes_dir() @@ -862,20 +868,6 @@ def test_parse_step_handles_all_recipe_step_fields() -> None: ) -# --------------------------------------------------------------------------- -# T2 — _path_mtime_ns replaces the two old helpers -# --------------------------------------------------------------------------- - - -def test_path_mtime_ns_exists_and_old_helpers_removed() -> None: - """recipe/_api.py must expose _path_mtime_ns; _file_mtime_ns/_dir_mtime_ns removed.""" - import autoskillit.recipe._api as api - - assert hasattr(api, "_path_mtime_ns"), "_path_mtime_ns must exist" - assert not hasattr(api, "_file_mtime_ns"), "_file_mtime_ns must be removed" - assert not hasattr(api, "_dir_mtime_ns"), "_dir_mtime_ns must be removed" - - # --------------------------------------------------------------------------- # REQ-ORD-003: Stable positions when project recipe added # --------------------------------------------------------------------------- @@ -900,3 +892,40 @@ def test_list_recipes_stable_with_project_recipe_added(tmp_path: Path) -> None: assert bundled_after == bundled_before, ( "Adding a project recipe must not shift bundled recipe positions" ) + + +def test_parse_recipe_reads_requires_packs(): + from autoskillit.recipe.io import _parse_recipe + + data = { + "name": "test", + "description": "d", + "requires_packs": ["research", "github"], + } + recipe = _parse_recipe(data) + assert recipe.requires_packs == ["research", "github"] + + +def test_parse_recipe_requires_packs_defaults_to_empty(): + from autoskillit.recipe.io import _parse_recipe + + recipe = _parse_recipe({"name": "test", "description": "d"}) + assert recipe.requires_packs == [] + + +def test_research_recipe_loads_without_error(): + from autoskillit.core.paths import pkg_root + from autoskillit.recipe.io import load_recipe + + path = pkg_root() / "recipes" / "research.yaml" + recipe = load_recipe(path) + assert recipe.name == "research" + + +def test_research_recipe_declares_requires_packs(): + from autoskillit.core.paths import pkg_root + from autoskillit.recipe.io import load_recipe + + path = pkg_root() / "recipes" / "research.yaml" + recipe = load_recipe(path) + assert recipe.requires_packs == ["research", "exp-lens", "vis-lens"] diff --git a/tests/recipe/test_issue_url_pipeline.py b/tests/recipe/test_issue_url_pipeline.py index f2d12d92c9..bbbc333589 100644 --- a/tests/recipe/test_issue_url_pipeline.py +++ b/tests/recipe/test_issue_url_pipeline.py @@ -72,11 +72,11 @@ def test_issue_url_referenced_in_downstream_skill_step(self): assert any("issue_url" in str(v) for v in skill_step_with.values()) assert not any("issue_content" in str(v) for v in skill_step_with.values()) - def test_issue_number_referenced_in_open_pr_step(self): - """open_pr_step must reference context.issue_number in with: for dataflow tracking.""" + def test_issue_number_referenced_in_prepare_pr_step(self): + """prepare_pr must reference context.issue_number in with: for dataflow tracking.""" data = yaml.safe_load(_recipe_path("implementation").read_text()) - openpr_with = data["steps"]["open_pr_step"].get("with", {}) - assert any("issue_number" in str(v) for v in openpr_with.values()) + prepare_pr_with = data["steps"]["prepare_pr"].get("with", {}) + assert any("issue_number" in str(v) for v in prepare_pr_with.values()) def test_no_dead_output_for_issue_number(self): """issue_number captured by get_issue_title must not be a dead output.""" @@ -162,10 +162,10 @@ def test_issue_url_referenced_in_downstream_skill_step(self): assert any("issue_url" in str(v) for v in skill_step_with.values()) assert not any("issue_content" in str(v) for v in skill_step_with.values()) - def test_issue_number_referenced_in_open_pr_step(self): + def test_issue_number_referenced_in_prepare_pr_step(self): data = yaml.safe_load(_recipe_path("remediation").read_text()) - openpr_with = data["steps"]["open_pr_step"].get("with", {}) - assert any("issue_number" in str(v) for v in openpr_with.values()) + prepare_pr_with = data["steps"]["prepare_pr"].get("with", {}) + assert any("issue_number" in str(v) for v in prepare_pr_with.values()) def test_no_dead_output_for_issue_number(self): """issue_number captured by get_issue_title must not be a dead output.""" @@ -241,9 +241,9 @@ def test_no_issue_content_capture(self): } assert "issue_content" not in all_captures - def test_open_pr_step_still_references_issue_number(self): + def test_prepare_pr_step_still_references_issue_number(self): data = yaml.safe_load(_recipe_path("implementation-groups").read_text()) - step = data["steps"]["open_pr_step"] + step = data["steps"]["prepare_pr"] assert "context.issue_number" in str(step) @@ -253,7 +253,7 @@ class TestClaimReleaseGates: RECIPES = ["implementation", "implementation-groups", "remediation"] # Recipes where ci_watch routes directly to release_issue_success RECIPES_WITH_RELEASE_SUCCESS: list[str] = [] - # Recipes where ci_watch routes to check_merge_queue (merge-queue path) + # Recipes where ci_watch routes to check_repo_merge_state (merge-queue path) RECIPES_WITHOUT_RELEASE_SUCCESS = [ "implementation", "implementation-groups", @@ -315,25 +315,28 @@ def test_release_issue_steps_present(self): f"{name}: release_issue_success must be absent — label stays on success" ) - def test_release_issue_success_routes_to_confirm_cleanup(self): + def test_release_issue_success_routes_to_register_clone_success(self): for name in self.RECIPES_WITH_RELEASE_SUCCESS_STEP: data = yaml.safe_load(_recipe_path(name).read_text()) step = data["steps"]["release_issue_success"] - assert step["on_success"] == "check_defer_cleanup", ( - f"{name}: release_issue_success.on_success should be check_defer_cleanup" + assert step["on_success"] == "register_clone_success", ( + f"{name}: release_issue_success.on_success should be register_clone_success" ) - def test_release_issue_failure_routes_to_cleanup_failure(self): + def test_release_issue_failure_routes_to_register_clone_failure(self): for name in self.RECIPES: data = yaml.safe_load(_recipe_path(name).read_text()) step = data["steps"]["release_issue_failure"] - assert step["on_success"] == "check_defer_on_failure", ( - f"{name}: release_issue_failure.on_success should be check_defer_on_failure" + assert step["on_success"] == "register_clone_failure", ( + f"{name}: release_issue_failure.on_success should be register_clone_failure" + ) + assert step["on_failure"] == "register_clone_failure", ( + f"{name}: release_issue_failure.on_failure should be register_clone_failure" ) def test_ci_watch_on_success_routing(self): expected = { - **{name: "check_merge_queue" for name in self.RECIPES_WITHOUT_RELEASE_SUCCESS}, + **{name: "check_repo_merge_state" for name in self.RECIPES_WITHOUT_RELEASE_SUCCESS}, **{name: "release_issue_success" for name in self.RECIPES_WITH_RELEASE_SUCCESS}, } assert set(expected) == set(self.RECIPES), ( diff --git a/tests/recipe/test_merge_prs.py b/tests/recipe/test_merge_prs.py index b4cb677ad3..8e21a02901 100644 --- a/tests/recipe/test_merge_prs.py +++ b/tests/recipe/test_merge_prs.py @@ -199,8 +199,21 @@ def test_pmp_no_upstream_branch_ingredient(recipe) -> None: def test_pmp_setup_remote_routes_to_check_integration_exists(recipe) -> None: - """setup_remote.on_success must route to check_integration_exists, not analyze_prs.""" - assert recipe.steps["setup_remote"].on_success == "check_integration_exists" + """setup_remote.on_success must route toward check_integration_exists. + + With check_repo_ci_event inserted as a non-blocking pre-step that captures + ci_event, the chain is: setup_remote → check_repo_ci_event → + check_integration_exists. Both hops are required. + """ + setup_successor = recipe.steps["setup_remote"].on_success + assert setup_successor == "check_repo_ci_event", ( + f"setup_remote.on_success must be 'check_repo_ci_event', got {setup_successor!r}" + ) + ci_event_successor = recipe.steps["check_repo_ci_event"].on_success + assert ci_event_successor == "check_integration_exists", ( + f"check_repo_ci_event.on_success must be 'check_integration_exists'," + f" got {ci_event_successor!r}" + ) def test_pmp_has_check_integration_exists_step(recipe) -> None: @@ -346,9 +359,9 @@ def test_ci_watch_pr_uses_integration_branch(recipe) -> None: def test_ci_watch_pr_routing(recipe) -> None: - """ci_watch_pr on_success -> check_defer_cleanup; on_failure -> diagnose_ci.""" + """ci_watch_pr on_success -> register_clone_success; on_failure -> diagnose_ci.""" step = recipe.steps["ci_watch_pr"] - assert step.on_success == "check_defer_cleanup" + assert step.on_success == "register_clone_success" assert step.on_failure == "diagnose_ci" @@ -532,9 +545,16 @@ def test_pmp_resolve_review_integration_has_retries(recipe) -> None: def test_pmp_resolve_review_integration_routes_to_re_push(recipe) -> None: - """B19: resolve_review_integration.on_success must route to re_push_review_integration.""" + """B19: resolve_review_integration routes real_fix to re_push.""" step = recipe.steps["resolve_review_integration"] - assert step.on_success == "re_push_review_integration" + assert step.on_success is None, ( + "resolve_review_integration must use on_result: verdict dispatch" + ) + assert step.on_result is not None, "resolve_review_integration must have on_result: block" + push_routes = [c.route for c in step.on_result.conditions if c.when and "real_fix" in c.when] + assert any("re_push_review_integration" in r for r in push_routes), ( + "resolve_review_integration must route verdict=real_fix to re_push_review_integration" + ) def test_pmp_has_re_push_review_integration_step(recipe) -> None: diff --git a/tests/recipe/test_merge_prs_queue.py b/tests/recipe/test_merge_prs_queue.py index cc2d5e32ff..f19fe11ea7 100644 --- a/tests/recipe/test_merge_prs_queue.py +++ b/tests/recipe/test_merge_prs_queue.py @@ -8,6 +8,7 @@ import pytest +from autoskillit.core import PRState from autoskillit.recipe.io import builtin_recipes_dir, load_recipe from autoskillit.recipe.validator import validate_recipe @@ -144,15 +145,23 @@ def test_implementation_recipe_is_valid(impl_recipe) -> None: # --------------------------------------------------------------------------- -def test_implementation_check_merge_queue_exists(impl_recipe) -> None: - """check_merge_queue step must exist in implementation recipe.""" - assert "check_merge_queue" in impl_recipe.steps +def test_implementation_has_check_repo_merge_state(impl_recipe) -> None: + """check_repo_merge_state step must exist with correct structure.""" + assert "check_repo_merge_state" in impl_recipe.steps + step = impl_recipe.steps["check_repo_merge_state"] + assert step.tool == "check_repo_merge_state" + assert step.block == "pre_queue_gate" + assert set(step.capture or {}) >= { + "queue_available", + "merge_group_trigger", + "auto_merge_available", + } -def test_implementation_check_merge_queue_has_skip_when_false(impl_recipe) -> None: - """check_merge_queue must have skip_when_false: inputs.open_pr.""" - step = impl_recipe.steps["check_merge_queue"] - assert step.skip_when_false == "inputs.open_pr" +def test_implementation_pre_queue_gate_routes_to_route_queue_mode(impl_recipe) -> None: + """check_repo_merge_state.on_success must route to route_queue_mode.""" + step = impl_recipe.steps["check_repo_merge_state"] + assert step.on_success == "route_queue_mode" def test_implementation_route_queue_mode_is_route_action(impl_recipe) -> None: @@ -181,14 +190,66 @@ def test_implementation_queue_ejected_fix_exists(impl_recipe) -> None: assert "queue_ejected_fix" in impl_recipe.steps +def test_queue_ejected_fix_tool_is_run_cmd(impl_recipe) -> None: + step = impl_recipe.steps["queue_ejected_fix"] + assert step.tool == "run_cmd", ( + "queue_ejected_fix must be a run_cmd cheap-rebase step, not a run_skill" + ) + + +def test_queue_ejected_fix_clean_routes_to_re_push(impl_recipe) -> None: + step = impl_recipe.steps["queue_ejected_fix"] + clean_route = next( + (c.route for c in step.on_result.conditions if c.when and "clean" in c.when), + None, + ) + assert clean_route == "re_push_queue_fix" + + +def test_queue_ejected_fix_conflicts_routes_to_resolve_skill(impl_recipe) -> None: + step = impl_recipe.steps["queue_ejected_fix"] + # The catch-all (no 'when') must route to the renamed skill step + fallback_route = next( + (c.route for c in step.on_result.conditions if not c.when), + None, + ) + assert fallback_route == "resolve_queue_merge_conflicts" + + +def test_queue_ejected_fix_on_failure_routes_to_resolve_skill(impl_recipe) -> None: + step = impl_recipe.steps["queue_ejected_fix"] + assert step.on_failure == "resolve_queue_merge_conflicts" + + +def test_resolve_queue_merge_conflicts_exists_with_run_skill(impl_recipe) -> None: + assert "resolve_queue_merge_conflicts" in impl_recipe.steps + step = impl_recipe.steps["resolve_queue_merge_conflicts"] + assert step.tool == "run_skill" + + +def test_resolve_queue_merge_conflicts_captures_escalation(impl_recipe) -> None: + step = impl_recipe.steps["resolve_queue_merge_conflicts"] + assert "conflict_escalation_required" in step.capture + + +def test_resolve_queue_merge_conflicts_routes_to_re_push(impl_recipe) -> None: + step = impl_recipe.steps["resolve_queue_merge_conflicts"] + fallback_route = next( + (c.route for c in step.on_result.conditions if not c.when), + None, + ) + assert fallback_route == "re_push_queue_fix" + + def test_implementation_queue_finale_steps_all_have_skip_when_false(impl_recipe) -> None: - """All six new queue finale steps must have skip_when_false: inputs.open_pr.""" + """All queue finale steps must have skip_when_false: inputs.open_pr.""" finale_steps = [ - "check_merge_queue", + "check_repo_merge_state", "route_queue_mode", "enable_auto_merge", "wait_for_queue", "queue_ejected_fix", + "resolve_queue_merge_conflicts", "re_push_queue_fix", "reenter_merge_queue", ] @@ -201,10 +262,12 @@ def test_implementation_queue_finale_steps_all_have_skip_when_false(impl_recipe) ) -def test_implementation_ci_watch_routes_to_check_merge_queue_on_success(impl_recipe) -> None: - """ci_watch.on_success must route to check_merge_queue.""" +def test_implementation_ci_watch_routes_to_check_repo_merge_state_on_success( + impl_recipe, +) -> None: + """ci_watch.on_success must route to check_repo_merge_state.""" step = impl_recipe.steps["ci_watch"] - assert step.on_success == "check_merge_queue" + assert step.on_success == "check_repo_merge_state" def test_implementation_extract_pr_number_exists(impl_recipe) -> None: @@ -214,49 +277,12 @@ def test_implementation_extract_pr_number_exists(impl_recipe) -> None: assert step.tool == "run_cmd" -def test_implementation_open_pr_step_routes_to_extract_pr_number(impl_recipe) -> None: - """open_pr_step.on_success must route to extract_pr_number.""" - step = impl_recipe.steps["open_pr_step"] +def test_implementation_compose_pr_routes_to_extract_pr_number(impl_recipe) -> None: + """compose_pr.on_success must route to extract_pr_number.""" + step = impl_recipe.steps["compose_pr"] assert step.on_success == "extract_pr_number" -# --------------------------------------------------------------------------- -# implementation.yaml — check_merge_group_trigger -# --------------------------------------------------------------------------- - - -def test_implementation_check_merge_group_trigger_exists(impl_recipe) -> None: - """check_merge_group_trigger step must exist in implementation recipe.""" - assert "check_merge_group_trigger" in impl_recipe.steps - - -def test_implementation_check_merge_group_trigger_skip_when_false_is_open_pr(impl_recipe) -> None: - """check_merge_group_trigger must use skip_when_false: inputs.open_pr.""" - step = impl_recipe.steps["check_merge_group_trigger"] - assert step.skip_when_false == "inputs.open_pr" - - -def test_implementation_check_merge_group_trigger_captures_merge_group_trigger( - impl_recipe, -) -> None: - """check_merge_group_trigger must capture merge_group_trigger.""" - step = impl_recipe.steps["check_merge_group_trigger"] - assert "merge_group_trigger" in step.capture - - -def test_implementation_check_merge_group_trigger_routes_to_check_auto_merge(impl_recipe) -> None: - """check_merge_group_trigger.on_success and on_failure must both route to check_auto_merge.""" - step = impl_recipe.steps["check_merge_group_trigger"] - assert step.on_success == "check_auto_merge" - assert step.on_failure == "check_auto_merge" - - -def test_implementation_check_merge_queue_routes_to_check_merge_group_trigger(impl_recipe) -> None: - """check_merge_queue.on_success must route to check_merge_group_trigger.""" - step = impl_recipe.steps["check_merge_queue"] - assert step.on_success == "check_merge_group_trigger" - - def test_implementation_route_queue_mode_requires_merge_group_trigger(impl_recipe) -> None: """route_queue_mode must NOT route to enable_auto_merge without checking merge_group_trigger. @@ -292,15 +318,17 @@ def test_remediation_recipe_is_valid(remed_recipe) -> None: # --------------------------------------------------------------------------- -def test_remediation_check_merge_queue_exists(remed_recipe) -> None: - """check_merge_queue step must exist in remediation recipe.""" - assert "check_merge_queue" in remed_recipe.steps - - -def test_remediation_check_merge_queue_has_skip_when_false(remed_recipe) -> None: - """check_merge_queue must have skip_when_false: inputs.open_pr.""" - step = remed_recipe.steps["check_merge_queue"] - assert step.skip_when_false == "inputs.open_pr" +def test_remediation_has_check_repo_merge_state(remed_recipe) -> None: + """check_repo_merge_state step must exist with correct structure in remediation.""" + assert "check_repo_merge_state" in remed_recipe.steps + step = remed_recipe.steps["check_repo_merge_state"] + assert step.tool == "check_repo_merge_state" + assert step.block == "pre_queue_gate" + assert set(step.capture or {}) >= { + "queue_available", + "merge_group_trigger", + "auto_merge_available", + } def test_remediation_route_queue_mode_is_route_action(remed_recipe) -> None: @@ -330,13 +358,14 @@ def test_remediation_queue_ejected_fix_exists(remed_recipe) -> None: def test_remediation_queue_finale_steps_all_have_skip_when_false(remed_recipe) -> None: - """All new queue finale steps must have skip_when_false: inputs.open_pr.""" + """All queue finale steps must have skip_when_false: inputs.open_pr.""" finale_steps = [ - "check_merge_queue", + "check_repo_merge_state", "route_queue_mode", "enable_auto_merge", "wait_for_queue", "queue_ejected_fix", + "resolve_queue_merge_conflicts", "re_push_queue_fix", "reenter_merge_queue", ] @@ -349,10 +378,12 @@ def test_remediation_queue_finale_steps_all_have_skip_when_false(remed_recipe) - ) -def test_remediation_ci_watch_routes_to_check_merge_queue_on_success(remed_recipe) -> None: - """ci_watch.on_success must route to check_merge_queue.""" +def test_remediation_ci_watch_routes_to_check_repo_merge_state_on_success( + remed_recipe, +) -> None: + """ci_watch.on_success must route to check_repo_merge_state.""" step = remed_recipe.steps["ci_watch"] - assert step.on_success == "check_merge_queue" + assert step.on_success == "check_repo_merge_state" def test_remediation_extract_pr_number_exists(remed_recipe) -> None: @@ -362,47 +393,12 @@ def test_remediation_extract_pr_number_exists(remed_recipe) -> None: assert step.tool == "run_cmd" -def test_remediation_open_pr_step_routes_to_extract_pr_number(remed_recipe) -> None: - """open_pr_step.on_success must route to extract_pr_number.""" - step = remed_recipe.steps["open_pr_step"] +def test_remediation_compose_pr_routes_to_extract_pr_number(remed_recipe) -> None: + """compose_pr.on_success must route to extract_pr_number.""" + step = remed_recipe.steps["compose_pr"] assert step.on_success == "extract_pr_number" -# --------------------------------------------------------------------------- -# remediation.yaml — check_merge_group_trigger -# --------------------------------------------------------------------------- - - -def test_remediation_check_merge_group_trigger_exists(remed_recipe) -> None: - """check_merge_group_trigger step must exist in remediation recipe.""" - assert "check_merge_group_trigger" in remed_recipe.steps - - -def test_remediation_check_merge_group_trigger_skip_when_false_is_open_pr(remed_recipe) -> None: - """check_merge_group_trigger must use skip_when_false: inputs.open_pr.""" - step = remed_recipe.steps["check_merge_group_trigger"] - assert step.skip_when_false == "inputs.open_pr" - - -def test_remediation_check_merge_group_trigger_captures_merge_group_trigger(remed_recipe) -> None: - """check_merge_group_trigger must capture merge_group_trigger.""" - step = remed_recipe.steps["check_merge_group_trigger"] - assert "merge_group_trigger" in step.capture - - -def test_remediation_check_merge_group_trigger_routes_to_check_auto_merge(remed_recipe) -> None: - """check_merge_group_trigger.on_success and on_failure must both route to check_auto_merge.""" - step = remed_recipe.steps["check_merge_group_trigger"] - assert step.on_success == "check_auto_merge" - assert step.on_failure == "check_auto_merge" - - -def test_remediation_check_merge_queue_routes_to_check_merge_group_trigger(remed_recipe) -> None: - """check_merge_queue.on_success must route to check_merge_group_trigger.""" - step = remed_recipe.steps["check_merge_queue"] - assert step.on_success == "check_merge_group_trigger" - - def test_remediation_route_queue_mode_requires_merge_group_trigger(remed_recipe) -> None: """route_queue_mode must NOT route to enable_auto_merge without checking merge_group_trigger. @@ -417,22 +413,11 @@ def test_remediation_route_queue_mode_requires_merge_group_trigger(remed_recipe) assert "merge_group_trigger" in cond_when -# --------------------------------------------------------------------------- -# implementation-groups.yaml — check_merge_group_trigger -# --------------------------------------------------------------------------- - - -def test_impl_groups_check_merge_group_trigger_exists(impl_groups_recipe) -> None: - """check_merge_group_trigger step must exist in implementation-groups recipe.""" - assert "check_merge_group_trigger" in impl_groups_recipe.steps - - -def test_impl_groups_check_merge_queue_routes_to_check_merge_group_trigger( - impl_groups_recipe, -) -> None: - """check_merge_queue.on_success must route to check_merge_group_trigger.""" - step = impl_groups_recipe.steps["check_merge_queue"] - assert step.on_success == "check_merge_group_trigger" +def test_impl_groups_has_check_repo_merge_state(impl_groups_recipe) -> None: + """check_repo_merge_state step must exist in implementation-groups recipe.""" + assert "check_repo_merge_state" in impl_groups_recipe.steps + step = impl_groups_recipe.steps["check_repo_merge_state"] + assert step.block == "pre_queue_gate" def test_impl_groups_route_queue_mode_requires_merge_group_trigger(impl_groups_recipe) -> None: @@ -473,13 +458,13 @@ def test_route_queue_mode_auto_merge_condition_first(any_recipe) -> None: assert auto_merge_idx < queue_available_idx -def test_auto_merge_false_routes_to_confirm_cleanup(any_recipe) -> None: +def test_auto_merge_false_routes_to_register_clone_success(any_recipe) -> None: step = any_recipe.steps["route_queue_mode"] auto_merge_cond = next( c for c in step.on_result.conditions if c.when and "auto_merge" in c.when ) assert auto_merge_cond.when == "${{ inputs.auto_merge }} != 'true'" - assert auto_merge_cond.route == "confirm_cleanup" + assert auto_merge_cond.route == "register_clone_success" # --------------------------------------------------------------------------- @@ -506,9 +491,9 @@ def test_direct_merge_routes_to_wait_for_direct_merge(any_recipe) -> None: assert step.on_success == "wait_for_direct_merge" -def test_direct_merge_failure_routes_to_confirm_cleanup(any_recipe) -> None: +def test_direct_merge_failure_routes_to_register_clone_success(any_recipe) -> None: step = any_recipe.steps["direct_merge"] - assert step.on_failure == "confirm_cleanup" + assert step.on_failure == "register_clone_success" def test_wait_for_direct_merge_step_exists(any_recipe) -> None: @@ -538,7 +523,21 @@ def test_wait_for_direct_merge_closed_routes_to_conflict_fix(any_recipe) -> None def test_direct_merge_conflict_fix_exists(any_recipe) -> None: assert "direct_merge_conflict_fix" in any_recipe.steps step = any_recipe.steps["direct_merge_conflict_fix"] - assert step.tool == "run_skill" + assert step.tool == "run_cmd" + + +def test_direct_merge_conflict_fix_clean_routes_to_re_push(any_recipe) -> None: + step = any_recipe.steps["direct_merge_conflict_fix"] + clean_route = next( + (c.route for c in step.on_result.conditions if c.when and "clean" in c.when), + None, + ) + assert clean_route == "re_push_direct_fix" + + +def test_resolve_direct_merge_conflicts_exists_with_run_skill(any_recipe) -> None: + assert "resolve_direct_merge_conflicts" in any_recipe.steps + assert any_recipe.steps["resolve_direct_merge_conflicts"].tool == "run_skill" def test_re_push_direct_fix_exists(any_recipe) -> None: @@ -560,6 +559,7 @@ def test_direct_merge_steps_have_skip_when_false(any_recipe) -> None: "direct_merge", "wait_for_direct_merge", "direct_merge_conflict_fix", + "resolve_direct_merge_conflicts", "re_push_direct_fix", "redirect_merge", ] @@ -572,45 +572,37 @@ def test_direct_merge_steps_have_skip_when_false(any_recipe) -> None: # --------------------------------------------------------------------------- -# check_auto_merge detection step +# check_repo_merge_state — consolidated pre-queue gate step (any_recipe) # --------------------------------------------------------------------------- -def test_check_auto_merge_step_exists(any_recipe) -> None: - """check_auto_merge step must exist in all three recipes.""" - assert "check_auto_merge" in any_recipe.steps - - -def test_check_auto_merge_is_run_cmd(any_recipe) -> None: - step = any_recipe.steps["check_auto_merge"] - assert step.tool == "run_cmd" +def test_check_repo_merge_state_step_exists(any_recipe) -> None: + """check_repo_merge_state step must exist in all three queue-capable recipes.""" + assert "check_repo_merge_state" in any_recipe.steps -def test_check_auto_merge_captures_auto_merge_available(any_recipe) -> None: - step = any_recipe.steps["check_auto_merge"] - assert "auto_merge_available" in (step.capture or {}) +def test_check_repo_merge_state_captures_all_three_fields(any_recipe) -> None: + step = any_recipe.steps["check_repo_merge_state"] + assert set(step.capture or {}) >= { + "queue_available", + "merge_group_trigger", + "auto_merge_available", + } -def test_check_auto_merge_routes_to_route_queue_mode_on_success(any_recipe) -> None: - step = any_recipe.steps["check_auto_merge"] +def test_check_repo_merge_state_routes_to_route_queue_mode_on_success(any_recipe) -> None: + step = any_recipe.steps["check_repo_merge_state"] assert step.on_success == "route_queue_mode" -def test_check_auto_merge_routes_to_route_queue_mode_on_failure(any_recipe) -> None: - """On failure, auto_merge_available is unset; route_queue_mode defaults to immediate_merge.""" - step = any_recipe.steps["check_auto_merge"] - assert step.on_failure == "route_queue_mode" - - -def test_check_auto_merge_has_skip_when_false(any_recipe) -> None: - step = any_recipe.steps["check_auto_merge"] +def test_check_repo_merge_state_has_skip_when_false(any_recipe) -> None: + step = any_recipe.steps["check_repo_merge_state"] assert step.skip_when_false == "inputs.open_pr" -def test_check_merge_queue_routes_to_check_merge_group_trigger_on_success(any_recipe) -> None: - """check_merge_queue.on_success must route to check_merge_group_trigger.""" - step = any_recipe.steps["check_merge_queue"] - assert step.on_success == "check_merge_group_trigger" +def test_check_repo_merge_state_is_in_pre_queue_gate_block(any_recipe) -> None: + step = any_recipe.steps["check_repo_merge_state"] + assert step.block == "pre_queue_gate" def test_route_queue_mode_has_auto_merge_available_condition(any_recipe) -> None: @@ -623,7 +615,9 @@ def test_route_queue_mode_has_auto_merge_available_condition(any_recipe) -> None def test_route_queue_mode_auto_merge_available_routes_to_direct_merge(any_recipe) -> None: step = any_recipe.steps["route_queue_mode"] cond = next( - c for c in step.on_result.conditions if c.when and "auto_merge_available" in c.when + c + for c in step.on_result.conditions + if c.when and "auto_merge_available" in c.when and "queue_available" not in c.when ) assert cond.when == "${{ context.auto_merge_available }} == true" assert cond.route == "direct_merge" @@ -653,9 +647,9 @@ def test_immediate_merge_routes_to_wait_for_immediate_merge(any_recipe) -> None: assert step.on_success == "wait_for_immediate_merge" -def test_immediate_merge_failure_routes_to_confirm_cleanup(any_recipe) -> None: +def test_immediate_merge_failure_routes_to_register_clone_success(any_recipe) -> None: step = any_recipe.steps["immediate_merge"] - assert step.on_failure == "confirm_cleanup" + assert step.on_failure == "register_clone_success" def test_wait_for_immediate_merge_step_exists(any_recipe) -> None: @@ -695,7 +689,21 @@ def test_wait_for_immediate_merge_closed_routes_to_conflict_fix(any_recipe) -> N def test_immediate_merge_conflict_fix_exists(any_recipe) -> None: assert "immediate_merge_conflict_fix" in any_recipe.steps step = any_recipe.steps["immediate_merge_conflict_fix"] - assert step.tool == "run_skill" + assert step.tool == "run_cmd" + + +def test_immediate_merge_conflict_fix_clean_routes_to_re_push(any_recipe) -> None: + step = any_recipe.steps["immediate_merge_conflict_fix"] + clean_route = next( + (c.route for c in step.on_result.conditions if c.when and "clean" in c.when), + None, + ) + assert clean_route == "re_push_immediate_fix" + + +def test_resolve_immediate_merge_conflicts_exists_with_run_skill(any_recipe) -> None: + assert "resolve_immediate_merge_conflicts" in any_recipe.steps + assert any_recipe.steps["resolve_immediate_merge_conflicts"].tool == "run_skill" def test_re_push_immediate_fix_exists(any_recipe) -> None: @@ -722,10 +730,10 @@ def test_remerge_immediate_uses_squash_without_auto(any_recipe) -> None: def test_all_immediate_merge_steps_have_skip_when_false(any_recipe) -> None: immediate_steps = [ - "check_auto_merge", "immediate_merge", "wait_for_immediate_merge", "immediate_merge_conflict_fix", + "resolve_immediate_merge_conflicts", "re_push_immediate_fix", "remerge_immediate", ] @@ -757,3 +765,356 @@ def test_remediation_recipe_still_valid(remed_recipe) -> None: def test_impl_groups_recipe_still_valid(impl_groups_recipe) -> None: errors = validate_recipe(impl_groups_recipe) assert errors == [], f"validate_recipe errors: {errors}" + + +# --------------------------------------------------------------------------- +# Gap 1 + Gap 6: ci_watch_post_queue_fix step + ejected_ci_failure routing +# (applies to all three recipes) +# --------------------------------------------------------------------------- + +QUEUE_RECIPES = ["impl_recipe", "remed_recipe", "impl_groups_recipe"] + + +@pytest.mark.parametrize("recipe_fixture", QUEUE_RECIPES) +def test_ci_watch_post_queue_fix_exists(recipe_fixture, request): + """ci_watch_post_queue_fix step must exist in all three queue-capable recipes.""" + recipe = request.getfixturevalue(recipe_fixture) + assert "ci_watch_post_queue_fix" in recipe.steps, ( + f"ci_watch_post_queue_fix must be a step in {recipe_fixture}" + ) + + +@pytest.mark.parametrize("recipe_fixture", QUEUE_RECIPES) +def test_re_push_queue_fix_routes_to_ci_watch_post_queue_fix(recipe_fixture, request): + """re_push_queue_fix.on_success must route to ci_watch_post_queue_fix.""" + recipe = request.getfixturevalue(recipe_fixture) + step = recipe.steps["re_push_queue_fix"] + assert step.on_success == "ci_watch_post_queue_fix", ( + f"re_push_queue_fix.on_success must be 'ci_watch_post_queue_fix' in {recipe_fixture}" + ) + + +@pytest.mark.parametrize("recipe_fixture", QUEUE_RECIPES) +def test_ci_watch_post_queue_fix_routes_reenter_on_success(recipe_fixture, request): + """ci_watch_post_queue_fix.on_success must route to reenter_merge_queue.""" + recipe = request.getfixturevalue(recipe_fixture) + assert "ci_watch_post_queue_fix" in recipe.steps, ( + f"ci_watch_post_queue_fix must be a step in {recipe_fixture}" + ) + step = recipe.steps["ci_watch_post_queue_fix"] + assert step.on_success == "reenter_merge_queue", ( + f"ci_watch_post_queue_fix.on_success must be 'reenter_merge_queue' in {recipe_fixture}" + ) + + +@pytest.mark.parametrize("recipe_fixture", QUEUE_RECIPES) +def test_ci_watch_post_queue_fix_routes_detect_ci_conflict_on_failure(recipe_fixture, request): + """ci_watch_post_queue_fix.on_failure must route to detect_ci_conflict.""" + recipe = request.getfixturevalue(recipe_fixture) + assert "ci_watch_post_queue_fix" in recipe.steps, ( + f"ci_watch_post_queue_fix must be a step in {recipe_fixture}" + ) + step = recipe.steps["ci_watch_post_queue_fix"] + assert step.on_failure == "detect_ci_conflict", ( + f"ci_watch_post_queue_fix.on_failure must be 'detect_ci_conflict' in {recipe_fixture}" + ) + + +@pytest.mark.parametrize("recipe_fixture", QUEUE_RECIPES) +def test_ci_watch_post_queue_fix_uses_wait_for_ci_tool(recipe_fixture, request): + """ci_watch_post_queue_fix must use the wait_for_ci tool.""" + recipe = request.getfixturevalue(recipe_fixture) + assert "ci_watch_post_queue_fix" in recipe.steps, ( + f"ci_watch_post_queue_fix must be a step in {recipe_fixture}" + ) + step = recipe.steps["ci_watch_post_queue_fix"] + assert step.tool == "wait_for_ci" + + +@pytest.mark.parametrize("recipe_fixture", QUEUE_RECIPES) +def test_ci_watch_post_queue_fix_has_skip_when_false(recipe_fixture, request): + """ci_watch_post_queue_fix must have skip_when_false: inputs.open_pr.""" + recipe = request.getfixturevalue(recipe_fixture) + assert "ci_watch_post_queue_fix" in recipe.steps, ( + f"ci_watch_post_queue_fix must be a step in {recipe_fixture}" + ) + step = recipe.steps["ci_watch_post_queue_fix"] + assert step.skip_when_false == "inputs.open_pr" + + +@pytest.mark.parametrize("recipe_fixture", QUEUE_RECIPES) +def test_wait_for_queue_routes_ejected_ci_failure_to_diagnose_ci(recipe_fixture, request): + """wait_for_queue.on_result must route ejected_ci_failure to diagnose_ci.""" + recipe = request.getfixturevalue(recipe_fixture) + step = recipe.steps["wait_for_queue"] + assert step.on_result is not None, "wait_for_queue must have on_result" + conditions = step.on_result.conditions + ci_failure_routes = [ + c + for c in conditions + if c.when is not None and "ejected_ci_failure" in c.when and c.route == "diagnose_ci" + ] + assert ci_failure_routes, ( + f"wait_for_queue.on_result must route ejected_ci_failure to diagnose_ci" + f" in {recipe_fixture}" + ) + + +@pytest.mark.parametrize("recipe_fixture", QUEUE_RECIPES) +def test_wait_for_queue_ejected_ci_failure_precedes_ejected(recipe_fixture, request): + """ejected_ci_failure route must precede generic ejected in wait_for_queue.on_result.""" + recipe = request.getfixturevalue(recipe_fixture) + step = recipe.steps["wait_for_queue"] + assert step.on_result is not None, "wait_for_queue must have on_result" + conditions = step.on_result.conditions + whens = [c.when or "" for c in conditions] + ci_fail_idx = next((i for i, w in enumerate(whens) if "ejected_ci_failure" in w), None) + ejected_idx = next( + (i for i, w in enumerate(whens) if w.strip() == "${{ result.pr_state }} == ejected"), None + ) + assert ci_fail_idx is not None, "ejected_ci_failure route must exist" + assert ejected_idx is not None, "ejected route must still exist" + assert ci_fail_idx < ejected_idx, ( + "ejected_ci_failure route must appear before generic ejected route " + "to prevent CI failure ejections from being handled as conflict ejections" + ) + + +# --------------------------------------------------------------------------- +# Routing matrix exhaustiveness — queue_available × auto_merge_available +# --------------------------------------------------------------------------- + + +def test_route_queue_mode_queue_with_auto_routes_to_enable_auto_merge(any_recipe) -> None: + """queue+auto cell must route to enable_auto_merge.""" + step = any_recipe.steps["route_queue_mode"] + cond = next( + c + for c in step.on_result.conditions + if c.when + and "queue_available" in c.when + and "merge_group_trigger" in c.when + and "auto_merge_available" in c.when + and "== true" in c.when.split("auto_merge_available")[1] + ) + assert cond.route == "enable_auto_merge" + + +def test_route_queue_mode_queue_without_auto_routes_to_queue_enqueue_no_auto( + any_recipe, +) -> None: + """queue+no-auto cell must route to queue_enqueue_no_auto.""" + step = any_recipe.steps["route_queue_mode"] + cond = next( + c + for c in step.on_result.conditions + if c.when + and "queue_available" in c.when + and "merge_group_trigger" in c.when + and "auto_merge_available" in c.when + and "== false" in c.when.split("auto_merge_available")[1] + ) + assert cond.route == "queue_enqueue_no_auto" + + +def test_route_queue_mode_no_queue_with_auto_routes_to_direct_merge(any_recipe) -> None: + """no-queue+auto cell must route to direct_merge.""" + step = any_recipe.steps["route_queue_mode"] + cond = next( + c + for c in step.on_result.conditions + if c.when and "auto_merge_available" in c.when and "queue_available" not in c.when + ) + assert cond.route == "direct_merge" + + +def test_route_queue_mode_no_queue_no_auto_falls_through_to_immediate_merge( + any_recipe, +) -> None: + """Default (when is None) condition must route to immediate_merge.""" + step = any_recipe.steps["route_queue_mode"] + cond = next(c for c in step.on_result.conditions if c.when is None) + assert cond.route == "immediate_merge" + + +def test_route_queue_mode_never_routes_to_enable_auto_merge_when_auto_unavailable( + any_recipe, +) -> None: + """Every condition routing to enable_auto_merge must require auto_merge_available == true.""" + step = any_recipe.steps["route_queue_mode"] + for cond in step.on_result.conditions: + if cond.route == "enable_auto_merge": + assert cond.when is not None + assert "auto_merge_available" in cond.when + assert "}} == true" in cond.when.split("auto_merge_available")[1], ( + "enable_auto_merge route must require auto_merge_available == true; " + f"got: {cond.when}" + ) + + +def test_enable_auto_merge_route_count(any_recipe) -> None: + """Exactly one condition must route to enable_auto_merge.""" + step = any_recipe.steps["route_queue_mode"] + count = sum(1 for c in step.on_result.conditions if c.route == "enable_auto_merge") + assert count == 1, f"Expected exactly 1 enable_auto_merge route, got {count}" + + +# --------------------------------------------------------------------------- +# New step: queue_enqueue_no_auto +# --------------------------------------------------------------------------- + + +def test_queue_enqueue_no_auto_step_exists(any_recipe) -> None: + assert "queue_enqueue_no_auto" in any_recipe.steps + + +def test_queue_enqueue_no_auto_is_run_cmd(any_recipe) -> None: + step = any_recipe.steps["queue_enqueue_no_auto"] + assert step.tool == "run_cmd" + + +def test_queue_enqueue_no_auto_uses_plain_squash(any_recipe) -> None: + """queue_enqueue_no_auto must use --squash without --auto.""" + step = any_recipe.steps["queue_enqueue_no_auto"] + cmd = step.with_args.get("cmd", "") + assert "--squash" in cmd + assert "--auto" not in cmd + + +def test_queue_enqueue_no_auto_routes_to_wait_for_queue(any_recipe) -> None: + step = any_recipe.steps["queue_enqueue_no_auto"] + assert step.on_success == "wait_for_queue" + + +def test_queue_enqueue_no_auto_failure_routes_to_register_clone_success(any_recipe) -> None: + step = any_recipe.steps["queue_enqueue_no_auto"] + assert step.on_failure == "register_clone_success" + + +def test_queue_enqueue_no_auto_skip_when_false(any_recipe) -> None: + step = any_recipe.steps["queue_enqueue_no_auto"] + assert step.skip_when_false == "inputs.open_pr" + + +def test_queue_enqueue_no_auto_step_name(any_recipe) -> None: + step = any_recipe.steps["queue_enqueue_no_auto"] + assert step.with_args["step_name"] == "queue_enqueue_no_auto" + + +# --------------------------------------------------------------------------- +# --------------------------------------------------------------------------- +# T12: Regression — remediation.yaml timeout arm and correct fallback +# --------------------------------------------------------------------------- + + +def test_remediation_wait_for_queue_has_timeout_arm_and_release_timeout_fallback( + remed_recipe, +) -> None: + """remediation.yaml wait_for_queue must have explicit timeout arm and correct fallback.""" + step = remed_recipe.steps["wait_for_queue"] + assert step.on_result is not None, "wait_for_queue must have on_result" + conditions = step.on_result.conditions + + # Must have an explicit timeout arm routing to release_issue_timeout + timeout_conditions = [ + c + for c in conditions + if c.when is not None and "timeout" in c.when and c.route == "release_issue_timeout" + ] + assert timeout_conditions, ( + "remediation.yaml wait_for_queue must have explicit " + "'${{ result.pr_state }} == timeout -> release_issue_timeout' arm" + ) + + # Fallback (when=None) must route to release_issue_timeout, not register_clone_success + fallback_conditions = [c for c in conditions if c.when is None] + assert fallback_conditions, "wait_for_queue must have a fallback condition (when=None)" + assert fallback_conditions[0].route == "release_issue_timeout", ( + f"remediation.yaml wait_for_queue fallback must be release_issue_timeout, " + f"got: {fallback_conditions[0].route!r}" + ) + + # on_failure must route to release_issue_timeout, not register_clone_success + assert step.on_failure == "release_issue_timeout", ( + f"remediation.yaml wait_for_queue on_failure must be release_issue_timeout, " + f"got: {step.on_failure!r}" + ) + + +# --------------------------------------------------------------------------- +# T9: Full routing parity — every PRState covered, fallback and on_failure identical +# --------------------------------------------------------------------------- + +_REQUIRED_PR_STATE_VALUES = frozenset(s.value for s in PRState if s != PRState.ERROR) + + +@pytest.mark.parametrize("recipe_fixture", QUEUE_RECIPES) +def test_wait_for_queue_routing_covers_every_pr_state(recipe_fixture, request) -> None: + """wait_for_queue.on_result must cover every non-error PRState with explicit when arms.""" + recipe = request.getfixturevalue(recipe_fixture) + step = recipe.steps["wait_for_queue"] + assert step.on_result is not None, "wait_for_queue must have on_result" + conditions = step.on_result.conditions + + # Collect the explicit when values by extracting the value after '==' + import re + + _PR_STATE_WHEN_RE = re.compile(r"\$\{\{\s*result\.pr_state\s*\}\}\s*==\s*(\w+)") + covered: set[str] = set() + for c in conditions: + if c.when is None: + continue + m = _PR_STATE_WHEN_RE.search(c.when) + if m: + covered.add(m.group(1)) + + missing = _REQUIRED_PR_STATE_VALUES - covered + assert not missing, ( + f"{recipe_fixture}: wait_for_queue.on_result is missing explicit routing arms " + f"for PRState values: {sorted(missing)}. Every non-error PRState must have a " + f"when condition." + ) + + # Fallback target must be release_issue_timeout + fallback_conditions = [c for c in conditions if c.when is None] + assert fallback_conditions, ( + f"{recipe_fixture}: wait_for_queue.on_result must have a fallback condition" + ) + assert fallback_conditions[0].route == "release_issue_timeout", ( + f"{recipe_fixture}: wait_for_queue fallback must route to release_issue_timeout, " + f"got: {fallback_conditions[0].route!r}" + ) + + # on_failure target must be release_issue_timeout + assert step.on_failure == "release_issue_timeout", ( + f"{recipe_fixture}: wait_for_queue on_failure must be release_issue_timeout, " + f"got: {step.on_failure!r}" + ) + + # ejected_ci_failure must precede generic ejected (existing invariant preserved) + whens = [c.when or "" for c in conditions] + ci_fail_idx = next((i for i, w in enumerate(whens) if "ejected_ci_failure" in w), None) + ejected_idx = next( + (i for i, w in enumerate(whens) if w.strip() == "${{ result.pr_state }} == ejected"), + None, + ) + assert ci_fail_idx is not None, f"{recipe_fixture}: ejected_ci_failure route must exist" + assert ejected_idx is not None, f"{recipe_fixture}: ejected route must exist" + assert ci_fail_idx < ejected_idx, ( + f"{recipe_fixture}: ejected_ci_failure route must appear before generic ejected route" + ) + + # reenter_merge_queue_cheap must exist and be reachable from dropped_healthy + assert "reenter_merge_queue_cheap" in recipe.steps, ( + f"{recipe_fixture}: reenter_merge_queue_cheap step must exist" + ) + dropped_routes = [ + c + for c in conditions + if c.when is not None + and "dropped_healthy" in c.when + and c.route == "reenter_merge_queue_cheap" + ] + assert dropped_routes, ( + f"{recipe_fixture}: dropped_healthy must route to reenter_merge_queue_cheap" + ) diff --git a/tests/recipe/test_merge_sub_recipe_hidden.py b/tests/recipe/test_merge_sub_recipe_hidden.py index 7f79f9c1b2..ccb3a730a5 100644 --- a/tests/recipe/test_merge_sub_recipe_hidden.py +++ b/tests/recipe/test_merge_sub_recipe_hidden.py @@ -4,7 +4,9 @@ from autoskillit.recipe.schema import Recipe, RecipeIngredient, RecipeStep -def _recipe(ingredients: dict, steps: dict | None = None) -> Recipe: +def _recipe( + ingredients: dict, steps: dict | None = None, requires_packs: list[str] | None = None +) -> Recipe: return Recipe( name="test", description="", @@ -12,6 +14,7 @@ def _recipe(ingredients: dict, steps: dict | None = None) -> Recipe: steps=steps or {}, kitchen_rules=[], version=None, + requires_packs=requires_packs or [], ) @@ -50,3 +53,43 @@ def test_merge_sub_recipe_keeps_non_hidden_ingredients(): ) merged = _merge_sub_recipe(parent, "sub_entry", sub) assert "shared_param" in merged.ingredients + + +def test_merge_sub_recipe_unions_requires_packs(): + """_merge_sub_recipe unions requires_packs parent-first, no duplicates.""" + parent = _recipe( + {}, + steps={"sub_entry": RecipeStep(sub_recipe="sub", on_success="done")}, + requires_packs=["github"], + ) + sub = _recipe( + { + "shared_param": RecipeIngredient(description="Shared across sub-recipes", default="v"), + }, + requires_packs=["research", "github"], # "github" is a duplicate + ) + merged = _merge_sub_recipe(parent, "sub_entry", sub) + assert merged.requires_packs == ["github", "research"] + + +def test_merge_sub_recipe_requires_packs_empty_sub(): + """When sub-recipe has no requires_packs, parent's list is preserved.""" + parent = _recipe( + {}, + steps={"sub_entry": RecipeStep(sub_recipe="sub", on_success="done")}, + requires_packs=["telemetry"], + ) + sub = _recipe({}) + merged = _merge_sub_recipe(parent, "sub_entry", sub) + assert merged.requires_packs == ["telemetry"] + + +def test_merge_sub_recipe_requires_packs_empty_parent(): + """When parent has no requires_packs, sub-recipe's list is adopted.""" + parent = _recipe( + {}, + steps={"sub_entry": RecipeStep(sub_recipe="sub", on_success="done")}, + ) + sub = _recipe({}, requires_packs=["research"]) + merged = _merge_sub_recipe(parent, "sub_entry", sub) + assert merged.requires_packs == ["research"] diff --git a/tests/recipe/test_plan_visualization_step.py b/tests/recipe/test_plan_visualization_step.py new file mode 100644 index 0000000000..5dce46b396 --- /dev/null +++ b/tests/recipe/test_plan_visualization_step.py @@ -0,0 +1,66 @@ +"""Tests for plan_visualization step wiring in the research recipe.""" + +from __future__ import annotations + +import pytest + +from autoskillit.core.paths import pkg_root +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe + +RESEARCH_RECIPE_PATH = builtin_recipes_dir() / "research.yaml" + + +@pytest.fixture(scope="module") +def recipe(): + return load_recipe(RESEARCH_RECIPE_PATH) + + +def test_plan_visualization_runs_after_design_review_go(recipe) -> None: + """review_design GO verdict must route to plan_visualization, not create_worktree.""" + step = recipe.steps["review_design"] + assert step.on_result is not None + go_condition = next(c for c in step.on_result.conditions if c.when and "GO" in c.when) + assert go_condition.route == "plan_visualization", ( + "review_design GO verdict must route to plan_visualization; " + "direct routing to create_worktree skips visualization plan generation" + ) + + +def test_plan_visualization_step_exists(recipe) -> None: + """research.yaml must include a plan_visualization step.""" + assert "plan_visualization" in recipe.steps + + +def test_plan_visualization_step_routes_to_create_worktree(recipe) -> None: + """plan_visualization on_success must route to create_worktree.""" + step = recipe.steps["plan_visualization"] + assert step.on_success == "create_worktree" + + +def test_plan_visualization_step_captures_paths(recipe) -> None: + """plan_visualization must capture visualization_plan_path and report_plan_path.""" + step = recipe.steps["plan_visualization"] + assert "visualization_plan_path" in step.capture + assert "report_plan_path" in step.capture + + +def test_create_worktree_copies_viz_plan(recipe) -> None: + """create_worktree cmd must copy visualization-plan.md and report-plan.md.""" + step = recipe.steps["create_worktree"] + cmd = step.with_args.get("cmd", "") + assert "VISUALIZATION_PLAN" in cmd, ( + "create_worktree must reference VISUALIZATION_PLAN context variable" + ) + assert "REPORT_PLAN" in cmd, "create_worktree must reference REPORT_PLAN context variable" + assert "visualization-plan.md" in cmd, ( + "create_worktree must copy visualization-plan.md into the research dir" + ) + assert "report-plan.md" in cmd, ( + "create_worktree must copy report-plan.md into the research dir" + ) + + +def test_plan_visualization_skill_dir_exists() -> None: + """src/autoskillit/skills_extended/plan-visualization/SKILL.md must exist.""" + skill_path = pkg_root() / "skills_extended" / "plan-visualization" / "SKILL.md" + assert skill_path.exists(), f"plan-visualization skill directory not found at {skill_path}" diff --git a/tests/recipe/test_recipe_temp_substitution.py b/tests/recipe/test_recipe_temp_substitution.py new file mode 100644 index 0000000000..4050349ce0 --- /dev/null +++ b/tests/recipe/test_recipe_temp_substitution.py @@ -0,0 +1,81 @@ +"""Tests for recipe-loader temp-dir placeholder substitution.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +from autoskillit.recipe.io import load_recipe + +_RECIPE_TEMPLATE = """\ +name: temp_subst_demo +description: demo recipe for temp dir substitution +ingredients: + task: + description: free-form task description + required: true +steps: + setup: + tool: run_cmd + with: + cmd: 'mkdir -p "{{AUTOSKILLIT_TEMP}}/worktrees"' + on_success: end + on_failure: end + end: + tool: run_cmd + with: + cmd: echo done +output_dir: "{{AUTOSKILLIT_TEMP}}/review-pr" +""" + + +def _write_recipe(tmp_path: Path) -> Path: + p = tmp_path / "demo.yaml" + p.write_text(_RECIPE_TEMPLATE) + return p + + +def test_load_recipe_substitutes_placeholder_in_string_value(tmp_path: Path) -> None: + path = _write_recipe(tmp_path) + recipe = load_recipe(path) + # Default substitution → ".autoskillit/temp" + assert "{{AUTOSKILLIT_TEMP}}" not in str(recipe.steps["setup"].with_args) + assert ".autoskillit/temp/worktrees" in str(recipe.steps["setup"].with_args) + + +def test_load_recipe_substitutes_placeholder_in_inline_shell(tmp_path: Path) -> None: + path = _write_recipe(tmp_path) + recipe = load_recipe(path) + cmd = recipe.steps["setup"].with_args["cmd"] + assert cmd == 'mkdir -p ".autoskillit/temp/worktrees"' + + +def test_load_recipe_custom_temp_dir_substituted(tmp_path: Path) -> None: + path = _write_recipe(tmp_path) + recipe = load_recipe(path, temp_dir_relpath="custom/x") + cmd = recipe.steps["setup"].with_args["cmd"] + assert cmd == 'mkdir -p "custom/x/worktrees"' + + +def test_load_recipe_rejects_yaml_unsafe_temp_dir_relpath(tmp_path: Path) -> None: + path = _write_recipe(tmp_path) + with pytest.raises(ValueError, match="YAML-unsafe"): + load_recipe(path, temp_dir_relpath="bad\nvalue") + with pytest.raises(ValueError, match="YAML-unsafe"): + load_recipe(path, temp_dir_relpath="bad: value") + + +def test_no_recipe_yaml_contains_literal_temp_path() -> None: + """Bundled recipe YAMLs must use {{AUTOSKILLIT_TEMP}}, never the literal.""" + recipes_root = Path(__file__).resolve().parents[2] / "src" / "autoskillit" / "recipes" + assert recipes_root.is_dir(), f"recipes root not found: {recipes_root}" + + offenders: list[str] = [] + for yaml_path in recipes_root.rglob("*.yaml"): + if ".autoskillit/temp" in yaml_path.read_text(encoding="utf-8"): + offenders.append(yaml_path.relative_to(recipes_root).as_posix()) + assert not offenders, ( + f"Recipe YAMLs contain literal '.autoskillit/temp' (must use " + f"'{{{{AUTOSKILLIT_TEMP}}}}' instead): {offenders}" + ) diff --git a/tests/recipe/test_remediation_pr_decomposition.py b/tests/recipe/test_remediation_pr_decomposition.py new file mode 100644 index 0000000000..5f1f5d86da --- /dev/null +++ b/tests/recipe/test_remediation_pr_decomposition.py @@ -0,0 +1,65 @@ +"""Verify remediation.yaml has the three-step PR decomposition.""" + +import pytest + +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe +from autoskillit.recipe.validator import validate_recipe + +RECIPE_PATH = builtin_recipes_dir() / "remediation.yaml" + + +@pytest.fixture(scope="module") +def recipe(): + return load_recipe(RECIPE_PATH) + + +def test_remediation_recipe_has_three_pr_steps(recipe): + step_names = list(recipe.steps.keys()) + assert "open_pr_step" not in step_names + assert "prepare_pr" in step_names + assert "run_arch_lenses" in step_names + assert "compose_pr" in step_names + + +def test_prepare_pr_routes_to_run_arch_lenses(recipe): + step = recipe.steps["prepare_pr"] + assert step.on_success == "run_arch_lenses" + + +def test_run_arch_lenses_routes_to_compose_on_success(recipe): + step = recipe.steps["run_arch_lenses"] + assert step.on_success == "compose_pr" + + +def test_run_arch_lenses_routes_to_compose_on_failure(recipe): + step = recipe.steps["run_arch_lenses"] + assert step.on_failure == "compose_pr" + + +def test_compose_pr_routes_to_extract_pr_number(recipe): + step = recipe.steps["compose_pr"] + assert step.on_success == "extract_pr_number" + + +def test_prepare_pr_captures_three_context_vars(recipe): + step = recipe.steps["prepare_pr"] + capture = step.capture or {} + assert "prep_path" in capture + assert "selected_lenses" in capture + assert "lens_context_paths" in capture + + +def test_run_arch_lenses_uses_capture_list(recipe): + step = recipe.steps["run_arch_lenses"] + assert step.capture_list is not None + assert "all_diagram_paths" in (step.capture_list or {}) + + +def test_compose_pr_captures_pr_url(recipe): + step = recipe.steps["compose_pr"] + assert "pr_url" in (step.capture or {}) + + +def test_remediation_recipe_validates_after_decomposition(recipe): + errors = validate_recipe(recipe) + assert not errors, f"Validation errors: {errors}" diff --git a/tests/recipe/test_repository.py b/tests/recipe/test_repository.py index 48989f7a86..c42edc6570 100644 --- a/tests/recipe/test_repository.py +++ b/tests/recipe/test_repository.py @@ -168,7 +168,7 @@ def test_validate_from_path_delegates_to_api(tmp_path: Path) -> None: result = repo.validate_from_path(script_path) assert result == expected - mock_api.assert_called_once_with(script_path) + mock_api.assert_called_once_with(script_path, temp_dir_relpath=".autoskillit/temp") def test_list_all_delegates_to_api() -> None: diff --git a/tests/recipe/test_research_bundle_lifecycle.py b/tests/recipe/test_research_bundle_lifecycle.py new file mode 100644 index 0000000000..5ded9c33ff --- /dev/null +++ b/tests/recipe/test_research_bundle_lifecycle.py @@ -0,0 +1,84 @@ +import pytest + +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe + +RESEARCH_RECIPE_PATH = builtin_recipes_dir() / "research.yaml" + + +@pytest.fixture(scope="module") +def recipe(): + return load_recipe(RESEARCH_RECIPE_PATH) + + +def test_stage_bundle_is_idempotent(recipe): + """stage_bundle cmd uses cp (idempotent); no mv/rename, no compression.""" + step = recipe.steps["stage_bundle"] + cmd = step.with_args.get("cmd", "") + assert "cp " in cmd, "stage_bundle must use cp for idempotent file copying" + assert "tar czf" not in cmd and "tar -czf" not in cmd, ( + "stage_bundle must NOT compress — second run must be a no-op" + ) + assert "git commit" not in cmd, "stage_bundle must NOT commit" + + +def test_stage_bundle_does_not_compress(recipe): + """stage_bundle must not create artifacts.tar.gz, rename report.md, or commit.""" + step = recipe.steps["stage_bundle"] + cmd = step.with_args.get("cmd", "") + assert "artifacts.tar.gz" not in cmd, "stage_bundle must not reference artifacts.tar.gz" + assert "README.md" not in cmd, "stage_bundle must not rename report.md to README.md" + assert "git commit" not in cmd, "stage_bundle must not commit" + + +def test_finalize_bundle_pr_mode(recipe): + """finalize_bundle must rename report.md→README.md, compress, append manifest, commit.""" + step = recipe.steps["finalize_bundle"] + cmd = step.with_args.get("cmd", "") + # rename + assert "README.md" in cmd and "report.md" in cmd, ( + "finalize_bundle must rename report.md to README.md" + ) + # compression + assert "tar czf" in cmd or "tar -czf" in cmd, "finalize_bundle must create tarball" + assert "-C" in cmd or "--directory" in cmd, "finalize_bundle must use -C for relative paths" + # manifest + assert "tar tzf" in cmd, "finalize_bundle must generate archive manifest" + assert "Archive Manifest" in cmd, "finalize_bundle manifest section header required" + assert ">> " in cmd and "README.md" in cmd, "manifest must be appended (>>) to README.md" + # post-compression guard + assert "artifacts.tar.gz" in cmd and "exit 1" in cmd, ( + "finalize_bundle must guard that artifacts.tar.gz exists or exit 1" + ) + # commit + assert "git commit" in cmd, "finalize_bundle must commit the result" + # dynamic tar inputs + assert "ls -1" in cmd and "grep -vE" in cmd, ( + "finalize_bundle must use ls -1 | grep -vE for dynamic TAR_ITEMS" + ) + # cleanup loop + assert "for item in" in cmd and "rm -rf" in cmd, ( + "finalize_bundle must rm -rf each archived item" + ) + # rename before archive (rename_pos < tar_pos) + rename_pos = cmd.find("report.md") + tar_pos = cmd.find("tar czf") + assert rename_pos < tar_pos, ( + "report.md rename must appear before tar czf so README.md is excluded" + ) + + +def test_finalize_bundle_runs_exactly_once_after_rerun(recipe): + """finalize_bundle is only reachable via re_push_research.on_success.""" + # only entry point is re_push_research.on_success + re_push = recipe.steps["re_push_research"] + assert re_push.on_success == "finalize_bundle", ( + "re_push_research.on_success must be finalize_bundle" + ) + # test and retest do NOT route to finalize_bundle (they route to push_branch) + assert recipe.steps["test"].on_success != "finalize_bundle" + assert recipe.steps["retest"].on_success != "finalize_bundle" + # stage_bundle does not compress — guarantee that the early staging can't trigger finalize + stage_cmd = recipe.steps["stage_bundle"].with_args.get("cmd", "") + assert "tar czf" not in stage_cmd and "tar -czf" not in stage_cmd, ( + "stage_bundle must not compress — only finalize_bundle may produce artifacts.tar.gz" + ) diff --git a/tests/recipe/test_research_output_mode.py b/tests/recipe/test_research_output_mode.py new file mode 100644 index 0000000000..95530cad30 --- /dev/null +++ b/tests/recipe/test_research_output_mode.py @@ -0,0 +1,257 @@ +# tests/recipe/test_research_output_mode.py +import pytest + +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe + +RESEARCH_RECIPE_PATH = builtin_recipes_dir() / "research.yaml" + + +@pytest.fixture(scope="module") +def recipe(): + return load_recipe(RESEARCH_RECIPE_PATH) + + +# --- REQ-R741-H01: ingredient exists with default "local" --- + + +def test_default_mode_is_local(recipe): + """ingredients.output_mode must exist with default == 'local' (issue body).""" + assert "output_mode" in recipe.ingredients, "output_mode ingredient missing" + ing = recipe.ingredients["output_mode"] + assert ing.default == "local", ( + f"output_mode default must be 'local' (issue body override), got {ing.default!r}" + ) + + +# --- REQ-R741-H04/H05: route_pr_or_local exists and is wired --- + + +def test_route_pr_or_local_exists(recipe): + assert "route_pr_or_local" in recipe.steps, "route_pr_or_local step missing" + + +def test_stage_bundle_routes_to_route_pr_or_local(recipe): + """stage_bundle.on_success must be route_pr_or_local after groupH.""" + stage = recipe.steps["stage_bundle"] + assert stage.on_success == "route_pr_or_local", ( + f"stage_bundle.on_success must be 'route_pr_or_local', got {stage.on_success!r}" + ) + + +def test_route_pr_or_local_local_branch(recipe): + """route_pr_or_local must route to finalize_bundle when output_mode == local.""" + step = recipe.steps["route_pr_or_local"] + assert step.action == "route", "route_pr_or_local must use action: route" + conditions = step.on_result.conditions if step.on_result else [] + when_conditions = [c for c in conditions if c.when is not None] + local_routes = [c for c in when_conditions if "local" in (c.when or "")] + assert any(c.route == "finalize_bundle" for c in local_routes), ( + "route_pr_or_local must route to finalize_bundle when output_mode == local" + ) + + +def test_route_pr_or_local_pr_fallthrough(recipe): + """route_pr_or_local fall-through (no when) must route to compose_research_pr.""" + step = recipe.steps["route_pr_or_local"] + conditions = step.on_result.conditions if step.on_result else [] + fallthrough = [c for c in conditions if c.when is None] + assert len(fallthrough) == 1 and fallthrough[0].route == "compose_research_pr", ( + "route_pr_or_local must fall through to compose_research_pr for pr mode" + ) + + +# --- REQ-R741-H06/H07: route_archive_or_export exists and is wired --- + + +def test_route_archive_or_export_exists(recipe): + assert "route_archive_or_export" in recipe.steps, "route_archive_or_export step missing" + + +def test_finalize_bundle_render_routes_to_route_archive_or_export(recipe): + """finalize_bundle_render.on_success and on_failure must be route_archive_or_export.""" + fbr = recipe.steps["finalize_bundle_render"] + assert fbr.on_success == "route_archive_or_export", ( + "finalize_bundle_render.on_success must be 'route_archive_or_export'," + f" got {fbr.on_success!r}" + ) + assert fbr.on_failure == "route_archive_or_export", ( + "finalize_bundle_render.on_failure must be 'route_archive_or_export'," + f" got {fbr.on_failure!r}" + ) + + +def test_route_archive_or_export_local_branch(recipe): + """route_archive_or_export must route to export_local_bundle when local.""" + step = recipe.steps["route_archive_or_export"] + conditions = step.on_result.conditions if step.on_result else [] + when_conditions = [c for c in conditions if c.when is not None] + local_routes = [c for c in when_conditions if "local" in (c.when or "")] + assert any(c.route == "export_local_bundle" for c in local_routes), ( + "route_archive_or_export must route to export_local_bundle when output_mode == local" + ) + + +def test_route_archive_or_export_pr_fallthrough(recipe): + """route_archive_or_export fall-through must route to begin_archival.""" + step = recipe.steps["route_archive_or_export"] + conditions = step.on_result.conditions if step.on_result else [] + fallthrough = [c for c in conditions if c.when is None] + assert len(fallthrough) == 1 and fallthrough[0].route == "begin_archival", ( + "route_archive_or_export must fall through to begin_archival for pr mode" + ) + + +# --- REQ-R741-H09: export_local_bundle step --- + + +def test_export_local_bundle_exists(recipe): + assert "export_local_bundle" in recipe.steps, "export_local_bundle step missing" + + +def test_export_local_bundle_emits_local_bundle_path(recipe): + step = recipe.steps["export_local_bundle"] + cmd = step.with_args.get("cmd", "") + assert "local_bundle_path=" in cmd, ( + "export_local_bundle cmd must emit local_bundle_path= for capture" + ) + + +def test_export_local_bundle_uses_source_dir_research_bundles(recipe): + step = recipe.steps["export_local_bundle"] + cmd = step.with_args.get("cmd", "") + assert "research-bundles" in cmd, ( + "export_local_bundle must export to {source_dir}/research-bundles/" + ) + assert "source_dir" in cmd, "export_local_bundle cmd must reference inputs.source_dir" + + +def test_export_local_bundle_routes_to_research_complete(recipe): + step = recipe.steps["export_local_bundle"] + assert step.on_success == "research_complete", ( + "export_local_bundle.on_success must be research_complete" + ) + assert step.on_failure == "research_complete", ( + "export_local_bundle.on_failure must be research_complete" + ) + + +# --- REQ-R741-H08: finalize_bundle local mode --- + + +def test_finalize_bundle_reads_output_mode(recipe): + """finalize_bundle cmd must read OUTPUT_MODE from inputs.output_mode.""" + step = recipe.steps["finalize_bundle"] + cmd = step.with_args.get("cmd", "") + assert "OUTPUT_MODE" in cmd, "finalize_bundle must set OUTPUT_MODE from inputs.output_mode" + assert "inputs.output_mode" in cmd or "inputs.output_mode" in cmd, ( + "finalize_bundle cmd must reference ${{ inputs.output_mode }}" + ) + + +def test_finalize_bundle_skips_commit_in_local_mode(recipe): + """finalize_bundle cmd must gate git commit behind OUTPUT_MODE != local.""" + step = recipe.steps["finalize_bundle"] + cmd = step.with_args.get("cmd", "") + # git commit must exist (for pr mode) but be conditional + assert "git commit" in cmd, "finalize_bundle must still have git commit (for pr mode)" + commit_pos = cmd.find("git commit") + output_mode_check_pos = cmd.rfind("OUTPUT_MODE", 0, commit_pos) + assert output_mode_check_pos != -1, ( + "git commit block in finalize_bundle must be guarded by OUTPUT_MODE check" + ) + + +def test_finalize_bundle_preserves_html_in_local_mode(recipe): + """finalize_bundle tar exclusion must include report.html for local mode browsing.""" + step = recipe.steps["finalize_bundle"] + cmd = step.with_args.get("cmd", "") + assert r"report\.html" in cmd, ( + r"finalize_bundle must reference report\.html (escaped) in tar exclusion for local mode" + ) + + +def test_finalize_bundle_render_always_runs(recipe): + """finalize_bundle.on_success must always be finalize_bundle_render (no skip).""" + fb = recipe.steps["finalize_bundle"] + assert fb.on_success == "finalize_bundle_render", ( + "finalize_bundle.on_success must be finalize_bundle_render (always runs)" + ) + fbr = recipe.steps["finalize_bundle_render"] + assert not getattr(fbr, "skip_when_false", None), ( + "finalize_bundle_render must never have skip_when_false" + ) + + +# --- REQ-R741-H15: research-bundles kitchen rule --- + + +def test_research_bundles_documented_in_kitchen_rules(recipe): + """research.yaml kitchen_rules must document research-bundles/ directory.""" + rules_text = " ".join(recipe.kitchen_rules or []) + assert "research-bundles" in rules_text, ( + "kitchen_rules must document the research-bundles/ output directory" + ) + + +# --- REQ-R741-H02: semantic validator rule --- + + +def test_research_output_mode_enum_rule_fires_for_invalid_value(): + """research-output-mode-enum rule must fire ERROR when output_mode.default is invalid.""" + import yaml + + from autoskillit.core import Severity + from autoskillit.recipe._analysis import make_validation_context + from autoskillit.recipe.io import _parse_recipe + from autoskillit.recipe.validator import run_semantic_rules + + src = RESEARCH_RECIPE_PATH.read_text() + data = yaml.safe_load(src) + data["ingredients"]["output_mode"] = {"default": "bogus", "required": False} + bad_recipe = _parse_recipe(data) + ctx = make_validation_context(bad_recipe) + findings = run_semantic_rules(ctx) + rule_findings = [f for f in findings if f.rule == "research-output-mode-enum"] + assert rule_findings, ( + "research-output-mode-enum rule must fire for invalid output_mode default" + ) + assert any(f.severity == Severity.ERROR for f in rule_findings), ( + "research-output-mode-enum finding must be ERROR severity" + ) + + +def test_research_output_mode_enum_rule_clean_for_valid_values(): + """research-output-mode-enum rule must NOT fire for 'local' or 'pr'.""" + import yaml + + from autoskillit.recipe._analysis import make_validation_context + from autoskillit.recipe.io import _parse_recipe + from autoskillit.recipe.validator import run_semantic_rules + + for valid in ("local", "pr"): + src = RESEARCH_RECIPE_PATH.read_text() + data = yaml.safe_load(src) + data["ingredients"]["output_mode"] = {"default": valid, "required": False} + recipe = _parse_recipe(data) + ctx = make_validation_context(recipe) + findings = run_semantic_rules(ctx) + rule_findings = [f for f in findings if f.rule == "research-output-mode-enum"] + assert not rule_findings, ( + f"research-output-mode-enum must not fire for valid value {valid!r}" + ) + + +def test_generate_report_steps_pass_output_mode(recipe): + """All generate_report steps must pass --output-mode flag in skill_command.""" + for step_name in ("generate_report", "generate_report_inconclusive", "re_generate_report"): + step = recipe.steps[step_name] + cmd = step.with_args.get("skill_command", "") + assert "--output-mode" in cmd, f"{step_name} skill_command must include --output-mode flag" + + +def test_generate_report_steps_pass_issue_url(recipe): + """generate_report, generate_report_inconclusive, re_generate_report must pass --issue-url.""" + for step_name in ("generate_report", "generate_report_inconclusive", "re_generate_report"): + step = recipe.steps[step_name] + cmd = step.with_args.get("skill_command", "") + assert "--issue-url" in cmd, f"{step_name} skill_command must include --issue-url flag" diff --git a/tests/recipe/test_research_recipe_diag.py b/tests/recipe/test_research_recipe_diag.py new file mode 100644 index 0000000000..2b26cb335e --- /dev/null +++ b/tests/recipe/test_research_recipe_diag.py @@ -0,0 +1,115 @@ +import pytest + +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe +from autoskillit.recipe.validator import validate_recipe + +RESEARCH_RECIPE_PATH = builtin_recipes_dir() / "research.yaml" + + +@pytest.fixture(scope="module") +def recipe(): + return load_recipe(RESEARCH_RECIPE_PATH) + + +def test_research_recipe_validates_after_diag_changes(recipe): + """research.yaml must pass structural validation with new troubleshoot steps.""" + errors = validate_recipe(recipe) + assert not errors, f"Validation errors: {errors}" + + +def test_research_recipe_has_troubleshoot_step(recipe): + """research.yaml must contain the troubleshoot_implement_failure step.""" + step_names = list(recipe.steps.keys()) + assert "troubleshoot_implement_failure" in step_names + assert "route_implement_failure" in step_names + + +def test_implement_phase_failure_routes_to_troubleshoot(recipe): + """implement_phase on_failure must route to troubleshoot_implement_failure.""" + step = recipe.steps["implement_phase"] + assert step.on_failure == "troubleshoot_implement_failure" + + +def test_implement_phase_exhausted_routes_to_run_experiment(recipe): + """implement_phase on_exhausted must route to run_experiment (not escalate).""" + step = recipe.steps["implement_phase"] + assert step.on_exhausted == "run_experiment" + + +def test_implement_phase_uses_implement_experiment(recipe): + """implement_phase must use implement-experiment, not retry-worktree.""" + step = recipe.steps["implement_phase"] + skill_cmd = step.with_args.get("skill_command", "") + assert "implement-experiment" in skill_cmd + assert "retry-worktree" not in skill_cmd + + +def test_troubleshoot_step_captures_required_tokens(recipe): + """troubleshoot_implement_failure must capture is_fixable for downstream routing.""" + step = recipe.steps["troubleshoot_implement_failure"] + capture = step.capture or {} + assert "is_fixable" in capture + + +def test_research_recipe_has_three_pr_prep_steps(recipe): + """open_research_pr is replaced by three decomposed steps.""" + step_names = list(recipe.steps.keys()) + assert "open_research_pr" not in step_names + assert "prepare_research_pr" in step_names + assert "run_experiment_lenses" in step_names + assert "compose_research_pr" in step_names + + +def test_push_branch_routes_to_prepare_research_pr(recipe): + """push_branch.on_success must route to prepare_research_pr.""" + step = recipe.steps["push_branch"] + assert step.on_success == "prepare_research_pr" + + +def test_prepare_research_pr_routes_to_run_experiment_lenses(recipe): + """prepare_research_pr.on_success must route to run_experiment_lenses.""" + step = recipe.steps["prepare_research_pr"] + assert step.on_success == "run_experiment_lenses" + + +def test_run_experiment_lenses_routes_to_stage_bundle_on_success(recipe): + """run_experiment_lenses.on_success routes to stage_bundle.""" + step = recipe.steps["run_experiment_lenses"] + assert step.on_success == "stage_bundle" + + +def test_run_experiment_lenses_routes_to_stage_bundle_on_failure(recipe): + """run_experiment_lenses.on_failure routes to stage_bundle (partial diagrams OK).""" + step = recipe.steps["run_experiment_lenses"] + assert step.on_failure == "stage_bundle" + + +def test_compose_research_pr_routes_to_guard_pr_url(recipe): + """compose_research_pr.on_success routes to guard_pr_url.""" + step = recipe.steps["compose_research_pr"] + assert step.on_success == "guard_pr_url" + + +def test_prepare_research_pr_captures_prep_path(recipe): + """prepare_research_pr must capture prep_path for compose step.""" + step = recipe.steps["prepare_research_pr"] + assert "prep_path" in (step.capture or {}) + + +def test_prepare_research_pr_uses_context_experiment_plan(recipe): + """prepare_research_pr must pass ${{ context.experiment_plan }}, not a hardcoded path.""" + step = recipe.steps["prepare_research_pr"] + skill_cmd = step.with_args.get("skill_command", "") + assert "context.experiment_plan" in skill_cmd + assert ".autoskillit/temp/experiment-plan.md" not in skill_cmd + + +def test_run_experiment_lenses_has_capture_list_for_diagram_paths(recipe): + """run_experiment_lenses accumulates diagram paths via capture_list.""" + step = recipe.steps["run_experiment_lenses"] + assert "all_diagram_paths" in (step.capture_list or {}) + + +def test_stage_bundle_exists(recipe): + """stage_bundle step must exist in the recipe.""" + assert "stage_bundle" in recipe.steps, "research.yaml must have a stage_bundle step" diff --git a/tests/recipe/test_research_stage_data_step.py b/tests/recipe/test_research_stage_data_step.py new file mode 100644 index 0000000000..d6adedb7b6 --- /dev/null +++ b/tests/recipe/test_research_stage_data_step.py @@ -0,0 +1,88 @@ +"""Tests for stage_data step wiring in the research recipe.""" + +from __future__ import annotations + +import pytest + +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe + +RESEARCH_RECIPE_PATH = builtin_recipes_dir() / "research.yaml" + + +@pytest.fixture(scope="module") +def recipe(): + return load_recipe(RESEARCH_RECIPE_PATH) + + +def test_stage_data_step_exists(recipe) -> None: + """research.yaml must include a stage_data step.""" + assert "stage_data" in recipe.steps + + +def test_create_worktree_routes_to_stage_data(recipe) -> None: + """create_worktree on_success must route to stage_data, not decompose_phases.""" + assert recipe.steps["create_worktree"].on_success == "stage_data" + + +def test_stage_data_uses_run_skill_tool(recipe) -> None: + """stage_data step must use the run_skill tool.""" + assert recipe.steps["stage_data"].tool == "run_skill" + + +def test_stage_data_skill_command_references_stage_data_skill(recipe) -> None: + """stage_data skill_command must reference the stage-data skill.""" + step = recipe.steps["stage_data"] + assert "stage-data" in step.with_args["skill_command"] + + +def test_stage_data_cwd_is_worktree_path(recipe) -> None: + """stage_data cwd must reference context.worktree_path.""" + step = recipe.steps["stage_data"] + assert "worktree_path" in step.with_args.get("cwd", "") + + +def test_stage_data_captures_verdict(recipe) -> None: + """stage_data must capture the verdict token.""" + step = recipe.steps["stage_data"] + assert "verdict" in step.capture + + +def test_stage_data_captures_resource_report(recipe) -> None: + """stage_data must capture the resource_report token.""" + step = recipe.steps["stage_data"] + assert "resource_report" in step.capture + + +def test_stage_data_pass_routes_to_decompose_phases(recipe) -> None: + """stage_data PASS verdict must route to decompose_phases.""" + step = recipe.steps["stage_data"] + assert step.on_result is not None + assert step.on_result.routes["PASS"] == "decompose_phases" + + +def test_stage_data_warn_routes_to_decompose_phases(recipe) -> None: + """stage_data WARN verdict must route to decompose_phases.""" + step = recipe.steps["stage_data"] + assert step.on_result is not None + assert step.on_result.routes["WARN"] == "decompose_phases" + + +def test_stage_data_fail_does_not_route_to_decompose_phases(recipe) -> None: + """stage_data FAIL verdict must not route to decompose_phases.""" + step = recipe.steps["stage_data"] + assert step.on_result is not None + assert step.on_result.routes["FAIL"] == "escalate_stop" + + +def test_stage_data_on_failure_escalates(recipe) -> None: + """stage_data on_failure must escalate_stop.""" + step = recipe.steps["stage_data"] + assert step.on_failure == "escalate_stop" + + +def test_research_recipe_still_validates(recipe) -> None: + """research.yaml must pass structural validation after stage_data is added.""" + from autoskillit.recipe.validator import validate_recipe + + errors = validate_recipe(recipe) + assert errors == [], f"Validation errors: {errors}" diff --git a/tests/recipe/test_resolve_ci_routing_invariant.py b/tests/recipe/test_resolve_ci_routing_invariant.py new file mode 100644 index 0000000000..6c386e0a34 --- /dev/null +++ b/tests/recipe/test_resolve_ci_routing_invariant.py @@ -0,0 +1,188 @@ +"""Routing invariant: resolve_ci / resolve_review must use verdict-gated on_result. + +Every step invoking resolve-failures or resolve-review across the three main +pipeline recipes (implementation.yaml, implementation-groups.yaml, remediation.yaml) +must route via on_result: with at least one condition referencing result.verdict. +Unconditional on_success: re_push is rejected. +""" + +from __future__ import annotations + +import pytest + +from autoskillit.core import pkg_root +from autoskillit.recipe.io import load_recipe + +_RECIPES_DIR = pkg_root() / "recipes" +_PIPELINE_RECIPES = [ + "implementation.yaml", + "implementation-groups.yaml", + "remediation.yaml", +] + +_CI_FIX_SKILLS = {"resolve-failures", "resolve-review"} + + +def _has_verdict_on_result(step) -> bool: + """Return True if the step uses on_result: with at least one verdict-reference condition.""" + if step.on_result is None: + return False + for cond in step.on_result.conditions or []: + if cond.when and "result.verdict" in cond.when: + return True + return False + + +def _step_reaches_push(recipe, start_name: str, max_hops: int = 5) -> bool: + """Return True if push_to_remote is reachable from start_name within max_hops.""" + visited: set[str] = set() + queue = [(start_name, 0)] + while queue: + name, hops = queue.pop(0) + if name in visited or hops > max_hops: + continue + visited.add(name) + step = recipe.steps.get(name) + if step is None: + continue + if step.tool == "push_to_remote": + return True + # Expand successors + successors: list[str] = [] + if step.on_success: + successors.append(step.on_success) + if step.on_failure: + successors.append(step.on_failure) + if step.on_result: + for cond in step.on_result.conditions or []: + if cond.route: + successors.append(cond.route) + for s in successors: + if s in recipe.steps: + queue.append((s, hops + 1)) + return False + + +_CI_RECOVERY_STEP_NAMES = {"resolve_ci", "resolve_review"} + + +def _find_resolve_steps_reaching_push(recipe) -> list[tuple[str, object]]: + """Return (step_name, step) pairs for CI-recovery skill steps that reach push_to_remote. + + Only checks steps named resolve_ci or resolve_review — the CI recovery path + specifically identified as the deadlock source. Other resolve-failures steps + (e.g. pre-merge worktree fixing) are intentionally excluded. + """ + results = [] + for step_name, step in recipe.steps.items(): + if step_name not in _CI_RECOVERY_STEP_NAMES: + continue + if step.tool != "run_skill": + continue + cmd = step.with_args.get("skill_command", "") + if not any(skill in cmd for skill in _CI_FIX_SKILLS): + continue + results.append((step_name, step)) + return results + + +@pytest.mark.parametrize("recipe_name", _PIPELINE_RECIPES) +def test_resolve_ci_steps_have_no_unconditional_on_success_to_push( + recipe_name: str, +) -> None: + """resolve-failures / resolve-review steps must NOT use on_success: re_push[_review].""" + recipe_path = _RECIPES_DIR / recipe_name + recipe = load_recipe(recipe_path) + resolve_steps = _find_resolve_steps_reaching_push(recipe) + assert resolve_steps, ( + f"{recipe_name}: expected to find at least one resolve-failures or resolve-review step" + ) + violations = [] + for step_name, step in resolve_steps: + if step.on_success is not None: + violations.append( + f"{step_name}: on_success={step.on_success!r} (must use on_result: instead)" + ) + assert not violations, ( + f"{recipe_name} has resolve-ci/review steps with unconditional on_success: " + f"These must route via on_result: with verdict dispatch to prevent the " + f"unconditional re-push loop:\n" + "\n".join(violations) + ) + + +@pytest.mark.parametrize("recipe_name", _PIPELINE_RECIPES) +def test_resolve_ci_steps_use_verdict_gated_on_result(recipe_name: str) -> None: + """Every resolve-failures / resolve-review step must have verdict-gated on_result.""" + recipe_path = _RECIPES_DIR / recipe_name + recipe = load_recipe(recipe_path) + resolve_steps = _find_resolve_steps_reaching_push(recipe) + assert resolve_steps, ( + f"{recipe_name}: expected to find at least one resolve-failures or resolve-review step" + ) + not_gated = [] + for step_name, step in resolve_steps: + if not _has_verdict_on_result(step): + not_gated.append(step_name) + assert not not_gated, ( + f"{recipe_name}: these resolve steps lack verdict-gated on_result: {not_gated}. " + "Each step must include at least one condition matching " + "'${{ result.verdict }} == ...'" + ) + + +@pytest.mark.parametrize("recipe_name", _PIPELINE_RECIPES) +def test_resolve_ci_on_result_routes_real_fix_to_re_push(recipe_name: str) -> None: + """The verdict=real_fix condition must route to re_push (or re_push_review).""" + recipe_path = _RECIPES_DIR / recipe_name + recipe = load_recipe(recipe_path) + resolve_steps = _find_resolve_steps_reaching_push(recipe) + for step_name, step in resolve_steps: + if step.on_result is None: + continue + real_fix_routes = [ + cond.route + for cond in (step.on_result.conditions or []) + if cond.when and "real_fix" in cond.when + ] + if not real_fix_routes: + continue # no explicit real_fix route yet — other tests catch this + assert any("re_push" in r for r in real_fix_routes), ( + f"{recipe_name}/{step_name}: verdict=real_fix must route to a re_push step, " + f"got routes: {real_fix_routes}" + ) + + +@pytest.mark.parametrize("recipe_name", _PIPELINE_RECIPES) +def test_resolve_ci_on_result_routes_escalation_verdicts_to_failure( + recipe_name: str, +) -> None: + """flake_suspected and ci_only_failure must route to release_issue_failure.""" + recipe_path = _RECIPES_DIR / recipe_name + recipe = load_recipe(recipe_path) + resolve_steps = _find_resolve_steps_reaching_push(recipe) + for step_name, step in resolve_steps: + if step.on_result is None: + continue + for verdict in ("flake_suspected", "ci_only_failure"): + routes = [ + cond.route + for cond in (step.on_result.conditions or []) + if cond.when and verdict in cond.when + ] + if not routes: + continue # if not present yet, other tests catch missing verdict + assert any("failure" in r or "escalat" in r for r in routes), ( + f"{recipe_name}/{step_name}: verdict={verdict} must route to " + f"a failure/escalation step, got routes: {routes}" + ) + + +@pytest.mark.parametrize("recipe_name", _PIPELINE_RECIPES) +def test_pre_resolve_rebase_step_exists(recipe_name: str) -> None: + """pre_resolve_rebase step must exist for already_green re-entry path.""" + recipe_path = _RECIPES_DIR / recipe_name + recipe = load_recipe(recipe_path) + assert "pre_resolve_rebase" in recipe.steps, ( + f"{recipe_name}: missing 'pre_resolve_rebase' step. " + "This step is required for the already_green verdict re-entry path." + ) diff --git a/tests/recipe/test_rule_decomposition.py b/tests/recipe/test_rule_decomposition.py index 33d6610a2b..5b70b33d6e 100644 --- a/tests/recipe/test_rule_decomposition.py +++ b/tests/recipe/test_rule_decomposition.py @@ -24,7 +24,7 @@ def test_no_deferred_validator_imports_in_rule_modules() -> None: def test_all_rules_registered_across_submodules() -> None: - """T2: All 27 rules registered, distributed across sub-modules.""" + """T2: All 28 rules registered, distributed across sub-modules.""" import autoskillit.recipe # noqa: F401 -- triggers rule registration from autoskillit.recipe.registry import _RULE_REGISTRY @@ -35,7 +35,7 @@ def test_all_rules_registered_across_submodules() -> None: "shadowed-required-input", "unreachable-step", "model-on-non-skill-step", - "retries-on-worktree-creating-skill", + "retries-on-worktree-modifying-skill", "retry-worktree-cwd", "weak-constraint-text", "undeclared-capture-key", @@ -57,6 +57,7 @@ def test_all_rules_registered_across_submodules() -> None: "unknown-skill-command", "missing-output-patterns", "ci-failure-missing-conflict-gate", + "unknown-required-pack", } assert expected <= rule_names diff --git a/tests/recipe/test_rules_blocks.py b/tests/recipe/test_rules_blocks.py new file mode 100644 index 0000000000..d94499929f --- /dev/null +++ b/tests/recipe/test_rules_blocks.py @@ -0,0 +1,95 @@ +"""Block-budget regression guards for the pre_queue_gate block.""" + +from __future__ import annotations + +import pytest + +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe +from autoskillit.recipe.registry import run_semantic_rules + +_QUEUE_CAPABLE = ("implementation.yaml", "remediation.yaml", "implementation-groups.yaml") + + +@pytest.mark.parametrize("recipe_name", _QUEUE_CAPABLE) +def test_pre_queue_gate_block_contains_at_most_one_run_cmd(recipe_name): + recipe = load_recipe(builtin_recipes_dir() / recipe_name) + block = next((b for b in recipe.blocks if b.name == "pre_queue_gate"), None) + assert block is not None, f"{recipe_name} must declare pre_queue_gate block anchors" + run_cmd_count = block.tool_counts.get("run_cmd", 0) + assert run_cmd_count <= 1, ( + f"{recipe_name}: pre_queue_gate contains {run_cmd_count} run_cmd steps; " + f"consolidate into a single MCP tool (check_repo_merge_state)." + ) + + +@pytest.mark.parametrize("recipe_name", _QUEUE_CAPABLE) +def test_pre_queue_gate_block_has_zero_gh_api_shell_patterns(recipe_name): + recipe = load_recipe(builtin_recipes_dir() / recipe_name) + block = next((b for b in recipe.blocks if b.name == "pre_queue_gate"), None) + assert block is not None, f"{recipe_name} must declare pre_queue_gate block anchors" + assert block.gh_api_occurrences == 0, ( + f"{recipe_name}: pre_queue_gate has {block.gh_api_occurrences} 'gh api' shell " + f"invocations; MCP tools must own all GitHub API calls in declared blocks." + ) + + +@pytest.mark.parametrize("recipe_name", _QUEUE_CAPABLE) +def test_pre_queue_gate_block_produces_three_captures_from_one_step(recipe_name): + recipe = load_recipe(builtin_recipes_dir() / recipe_name) + block = next((b for b in recipe.blocks if b.name == "pre_queue_gate"), None) + assert block is not None, f"{recipe_name} must declare pre_queue_gate block anchors" + producers = { + cap: [s.name for s in block.members if cap in (s.capture or {})] + for cap in ("queue_available", "merge_group_trigger", "auto_merge_available") + } + for cap, producer_names in producers.items(): + assert len(producer_names) == 1, ( + f"{recipe_name}: capture {cap!r} produced by {len(producer_names)} steps " + f"(expected exactly 1): {producer_names}" + ) + unique_producers = {p[0] for p in producers.values()} + assert len(unique_producers) == 1, ( + f"{recipe_name}: three captures come from {len(unique_producers)} steps; " + f"expected single-producer consolidation (check_repo_merge_state)." + ) + + +def _make_synthetic_recipe_with_two_gh_api_run_cmds_in_block(block_name: str): + """Build a minimal Recipe with two run_cmd gh api steps in a declared block. + + Used by the synthetic block budget test below. + """ + from autoskillit.recipe.schema import Recipe, RecipeStep + + step_a = RecipeStep( + tool="run_cmd", + with_args={"cmd": "gh api /repos/o/r/pulls"}, + block=block_name, + on_success="step_b", + ) + step_b = RecipeStep( + tool="run_cmd", + with_args={"cmd": "gh api graphql -f query='...' "}, + block=block_name, + ) + return Recipe( + name="synthetic", + description="synthetic test recipe", + ingredients={}, + steps={"step_a": step_a, "step_b": step_b}, + kitchen_rules=[], + version=None, + experimental=False, + requires_packs=[], + ) + + +def test_synthetic_block_with_two_run_cmds_emits_block_run_cmd_budget_finding(): + """Independent verification: a minimal synthetic recipe with two run_cmd steps + in a declared block must produce exactly one block-run-cmd-budget finding from + run_semantic_rules.""" + recipe = _make_synthetic_recipe_with_two_gh_api_run_cmds_in_block("test_block") + findings = run_semantic_rules(recipe) + matching = [f for f in findings if f.rule == "block-run-cmd-budget"] + assert len(matching) == 1 + assert "test_block" in matching[0].message diff --git a/tests/recipe/test_rules_ci.py b/tests/recipe/test_rules_ci.py index 09d4e1c843..ca5b257f6c 100644 --- a/tests/recipe/test_rules_ci.py +++ b/tests/recipe/test_rules_ci.py @@ -2,10 +2,10 @@ from __future__ import annotations -from autoskillit.core import Severity +from autoskillit.core import PRState, Severity from autoskillit.recipe.io import _parse_step, builtin_recipes_dir, load_recipe from autoskillit.recipe.registry import run_semantic_rules -from autoskillit.recipe.schema import Recipe, RecipeStep +from autoskillit.recipe.schema import Recipe, RecipeStep, StepResultCondition, StepResultRoute def _make_recipe(steps: dict[str, RecipeStep]) -> Recipe: @@ -236,3 +236,246 @@ def test_ci_failure_no_on_failure_skips_rule() -> None: findings = run_semantic_rules(wf) names = [f.rule for f in findings] assert "ci-failure-missing-conflict-gate" not in names + + +# --------------------------------------------------------------------------- +# ci-missing-event-scope rule tests +# --------------------------------------------------------------------------- + + +def test_wait_for_ci_without_event_is_warning() -> None: + """wait_for_ci step with no event param should trigger ci-missing-event-scope.""" + recipe = _make_recipe( + { + "ci": RecipeStep( + tool="wait_for_ci", + with_args={"branch": "main", "workflow": "tests.yml", "timeout_seconds": 300}, + on_success="done", + on_failure="done", + ), + "done": RecipeStep(action="stop", message="done"), + } + ) + findings = run_semantic_rules(recipe) + event_findings = [f for f in findings if f.rule == "ci-missing-event-scope"] + assert len(event_findings) == 1 + assert event_findings[0].severity == Severity.WARNING + + +def test_wait_for_ci_with_event_is_clean() -> None: + """wait_for_ci step with event param should not trigger ci-missing-event-scope.""" + recipe = _make_recipe( + { + "ci": RecipeStep( + tool="wait_for_ci", + with_args={"branch": "main", "event": "push", "timeout_seconds": 300}, + on_success="done", + on_failure="done", + ), + "done": RecipeStep(action="stop", message="done"), + } + ) + findings = run_semantic_rules(recipe) + event_findings = [f for f in findings if f.rule == "ci-missing-event-scope"] + assert event_findings == [] + + +def test_get_ci_status_without_event_is_warning() -> None: + """get_ci_status step with no event param should trigger ci-missing-event-scope.""" + recipe = _make_recipe( + { + "ci": RecipeStep( + tool="get_ci_status", + with_args={"branch": "main"}, + on_success="done", + on_failure="done", + ), + "done": RecipeStep(action="stop", message="done"), + } + ) + findings = run_semantic_rules(recipe) + event_findings = [f for f in findings if f.rule == "ci-missing-event-scope"] + assert len(event_findings) == 1 + assert event_findings[0].severity == Severity.WARNING + assert "get_ci_status" in event_findings[0].message + + +def test_get_ci_status_with_event_is_clean() -> None: + """get_ci_status step with event param should not trigger ci-missing-event-scope.""" + recipe = _make_recipe( + { + "ci": RecipeStep( + tool="get_ci_status", + with_args={"branch": "main", "event": "push"}, + on_success="done", + on_failure="done", + ), + "done": RecipeStep(action="stop", message="done"), + } + ) + findings = run_semantic_rules(recipe) + event_findings = [f for f in findings if f.rule == "ci-missing-event-scope"] + assert event_findings == [] + + +# --------------------------------------------------------------------------- +# ci-hardcoded-workflow rule tests +# --------------------------------------------------------------------------- + + +def test_wait_for_ci_hardcoded_workflow_is_warning() -> None: + """wait_for_ci with literal workflow value should trigger ci-hardcoded-workflow.""" + recipe = _make_recipe( + { + "ci": RecipeStep( + tool="wait_for_ci", + with_args={"branch": "main", "workflow": "tests.yml", "timeout_seconds": 300}, + on_success="done", + on_failure="done", + ), + "done": RecipeStep(action="stop", message="done"), + } + ) + findings = run_semantic_rules(recipe) + wf_findings = [f for f in findings if f.rule == "ci-hardcoded-workflow"] + assert len(wf_findings) == 1 + assert wf_findings[0].severity == Severity.WARNING + + +def test_wait_for_ci_no_workflow_is_clean() -> None: + """wait_for_ci without workflow param (uses config fallback) is clean.""" + recipe = _make_recipe( + { + "ci": RecipeStep( + tool="wait_for_ci", + with_args={"branch": "main", "timeout_seconds": 300}, + on_success="done", + on_failure="done", + ), + "done": RecipeStep(action="stop", message="done"), + } + ) + findings = run_semantic_rules(recipe) + wf_findings = [f for f in findings if f.rule == "ci-hardcoded-workflow"] + assert wf_findings == [] + + +# --------------------------------------------------------------------------- +# T11 + T13: wait-for-merge-queue-routing-covers-all-pr-states rule +# --------------------------------------------------------------------------- + +_COVERAGE_RULE = "wait-for-merge-queue-routing-covers-all-pr-states" +_CONFORMANCE_RULE = "wait-for-merge-queue-routing-conforms-to-expected-targets" + + +def _make_mq_conditions( + *, + exclude: set[str] | None = None, + fallback_route: str = "release_issue_timeout", +) -> list[StepResultCondition]: + """Build a complete wait_for_merge_queue on_result conditions list. + + Args: + exclude: set of PRState.value strings to leave out of the explicit arms. + fallback_route: the route for the catch-all (when=None) condition. + """ + exclude = exclude or set() + conditions = [] + for state in PRState: + if state == PRState.ERROR: + continue + if state.value in exclude: + continue + conditions.append( + StepResultCondition( + when=f"${{{{ result.pr_state }}}} == {state.value}", + route="some_target", + ) + ) + conditions.append(StepResultCondition(when=None, route=fallback_route)) + return conditions + + +def _make_mq_step( + *, + exclude: set[str] | None = None, + fallback_route: str = "release_issue_timeout", + on_failure: str = "release_issue_timeout", +) -> RecipeStep: + return RecipeStep( + tool="wait_for_merge_queue", + on_result=StepResultRoute( + conditions=_make_mq_conditions(exclude=exclude, fallback_route=fallback_route) + ), + on_failure=on_failure, + ) + + +def _make_mq_recipe( + *, + exclude: set[str] | None = None, + fallback_route: str = "release_issue_timeout", + on_failure: str = "release_issue_timeout", +) -> Recipe: + """Build a recipe that includes release_issue_timeout so the new rules activate.""" + return _make_recipe( + { + "wait_for_queue": _make_mq_step( + exclude=exclude, fallback_route=fallback_route, on_failure=on_failure + ), + "release_issue_timeout": RecipeStep(action="stop", message="timeout"), + "done": RecipeStep(action="stop", message="done"), + } + ) + + +def test_coverage_rule_flags_missing_pr_state_arm() -> None: + """T11: coverage rule fires when an explicit PRState arm is missing.""" + recipe = _make_mq_recipe(exclude={"dropped_healthy"}) + findings = run_semantic_rules(recipe) + coverage_findings = [f for f in findings if f.rule == _COVERAGE_RULE] + assert len(coverage_findings) >= 1, f"Expected coverage rule finding, got: {findings}" + assert coverage_findings[0].severity == Severity.ERROR + assert "dropped_healthy" in coverage_findings[0].message + + +def test_coverage_rule_clean_when_all_pr_states_present() -> None: + """T11 negative: coverage rule is silent when all non-error PRState values are present.""" + recipe = _make_mq_recipe() + findings = run_semantic_rules(recipe) + coverage_findings = [f for f in findings if f.rule == _COVERAGE_RULE] + assert coverage_findings == [], ( + f"Expected no coverage findings for complete routing, got: {coverage_findings}" + ) + + +def test_conformance_rule_flags_wrong_fallback_target() -> None: + """T11: conformance rule fires when fallback routes to wrong target.""" + recipe = _make_mq_recipe(fallback_route="register_clone_success") + findings = run_semantic_rules(recipe) + conformance_findings = [f for f in findings if f.rule == _CONFORMANCE_RULE] + assert len(conformance_findings) >= 1, ( + f"Expected conformance finding for wrong fallback, got: {findings}" + ) + assert conformance_findings[0].severity == Severity.ERROR + + +def test_conformance_rule_flags_wrong_on_failure_target() -> None: + """T11: conformance rule fires when on_failure routes to wrong target.""" + recipe = _make_mq_recipe(on_failure="register_clone_success") + findings = run_semantic_rules(recipe) + conformance_findings = [f for f in findings if f.rule == _CONFORMANCE_RULE] + assert len(conformance_findings) >= 1, ( + f"Expected conformance finding for wrong on_failure, got: {findings}" + ) + assert conformance_findings[0].severity == Severity.ERROR + + +def test_conformance_rule_clean_when_targets_correct() -> None: + """T11 negative: conformance rule is silent when targets are correct.""" + recipe = _make_mq_recipe() + findings = run_semantic_rules(recipe) + conformance_findings = [f for f in findings if f.rule == _CONFORMANCE_RULE] + assert conformance_findings == [], ( + f"Expected no conformance findings for correct targets, got: {conformance_findings}" + ) diff --git a/tests/recipe/test_rules_clone.py b/tests/recipe/test_rules_clone.py index 3b201527ba..1f5f1c581c 100644 --- a/tests/recipe/test_rules_clone.py +++ b/tests/recipe/test_rules_clone.py @@ -2,10 +2,20 @@ from __future__ import annotations +from pathlib import Path + +import pytest + from autoskillit.core import Severity +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe from autoskillit.recipe.registry import run_semantic_rules from autoskillit.recipe.schema import Recipe, RecipeStep +_BUNDLED_RECIPE_YAMLS = list(builtin_recipes_dir().rglob("*.yaml")) +assert _BUNDLED_RECIPE_YAMLS, ( + "builtin_recipes_dir() returned no YAMLs — parametrize would silently vacuous-pass" +) + def _make_recipe(steps: dict[str, RecipeStep]) -> Recipe: """Minimal recipe factory for rules_clone tests.""" @@ -224,3 +234,176 @@ def test_other_tool_not_flagged() -> None: findings = run_semantic_rules(recipe) rule_findings = [f for f in findings if f.rule == "push-missing-explicit-remote-url"] assert rule_findings == [] + + +# --------------------------------------------------------------------------- +# clone-local-strategy-with-remote-url-capture +# --------------------------------------------------------------------------- + +_RULE = "clone-local-strategy-with-remote-url-capture" +_CLONE_REPO = "autoskillit.workspace.clone.clone_repo" + + +def test_rule_rejects_clone_local_with_remote_url_capture() -> None: + """clone_local strategy + remote_url capture must fire ERROR (B1).""" + recipe = _make_recipe( + { + "clone": RecipeStep( + tool="run_python", + python=_CLONE_REPO, + with_args={"strategy": "clone_local", "run_name": "t"}, + capture={"remote_url": "${{ result.remote_url }}"}, + ), + "push": RecipeStep( + tool="push_to_remote", + with_args={ + "remote_url": "${{ context.remote_url }}", + "clone_path": "${{ context.clone_path }}", + }, + ), + } + ) + findings = run_semantic_rules(recipe) + matching = [f for f in findings if f.rule == _RULE] + assert len(matching) == 1 + assert matching[0].severity == Severity.ERROR + assert "clone_local" in matching[0].message + assert "remote_url" in matching[0].message + + +def test_rule_allows_clone_local_without_remote_url_capture() -> None: + """clone_local strategy without remote_url capture must not fire (B2).""" + recipe = _make_recipe( + { + "clone": RecipeStep( + tool="run_python", + python=_CLONE_REPO, + with_args={"strategy": "clone_local", "run_name": "t"}, + capture={"clone_path": "${{ result.clone_path }}"}, + ), + } + ) + findings = run_semantic_rules(recipe) + matching = [f for f in findings if f.rule == _RULE] + assert matching == [] + + +def test_rule_allows_proceed_strategy_with_remote_url_capture() -> None: + """proceed strategy + remote_url capture must not fire (B3).""" + recipe = _make_recipe( + { + "clone": RecipeStep( + tool="run_python", + python=_CLONE_REPO, + with_args={"strategy": "proceed", "run_name": "t"}, + capture={"remote_url": "${{ result.remote_url }}"}, + ), + } + ) + findings = run_semantic_rules(recipe) + matching = [f for f in findings if f.rule == _RULE] + assert matching == [] + + +def test_rule_allows_absent_strategy_with_remote_url_capture() -> None: + """Absent strategy (defaults to proceed) + remote_url capture must not fire (B3 variant).""" + recipe = _make_recipe( + { + "clone": RecipeStep( + tool="run_python", + python=_CLONE_REPO, + with_args={"run_name": "t"}, + capture={"remote_url": "${{ result.remote_url }}"}, + ), + } + ) + findings = run_semantic_rules(recipe) + matching = [f for f in findings if f.rule == _RULE] + assert matching == [] + + +def test_rule_warns_on_context_templated_strategy_with_remote_url_capture() -> None: + """Templated strategy + remote_url capture must fire WARNING (B4).""" + recipe = _make_recipe( + { + "clone": RecipeStep( + tool="run_python", + python=_CLONE_REPO, + with_args={ + "strategy": "${{ context.cloning_mode }}", + "run_name": "t", + }, + capture={"remote_url": "${{ result.remote_url }}"}, + ), + } + ) + findings = run_semantic_rules(recipe) + matching = [f for f in findings if f.rule == _RULE] + assert len(matching) == 1 + assert matching[0].severity == Severity.WARNING + assert "statically" in matching[0].message or "templated" in matching[0].message + + +def test_rule_ignores_non_clone_repo_python_steps() -> None: + """run_python step calling a different module must not fire (B5).""" + recipe = _make_recipe( + { + "prep": RecipeStep( + tool="run_python", + python="autoskillit.smoke_utils.prepare", + with_args={"strategy": "clone_local"}, + capture={"remote_url": "${{ result.remote_url }}"}, + ), + } + ) + findings = run_semantic_rules(recipe) + matching = [f for f in findings if f.rule == _RULE] + assert matching == [] + + +def test_rule_fires_on_result_dot_remote_url_alias() -> None: + """Template-expression aliasing: capture key != 'remote_url' must still fire (B6).""" + recipe = _make_recipe( + { + "clone": RecipeStep( + tool="run_python", + python=_CLONE_REPO, + with_args={"strategy": "clone_local", "run_name": "t"}, + capture={ + # Key name is different but template reads result.remote_url — still dangerous. + "alt_url": "${{ result.remote_url }}", + }, + ), + } + ) + findings = run_semantic_rules(recipe) + matching = [f for f in findings if f.rule == _RULE] + assert len(matching) == 1 + assert matching[0].severity == Severity.ERROR + + +def test_rule_does_not_fire_when_capture_reads_different_field() -> None: + """Capture key named remote_url but reads result.clone_path — must not fire (B6 complement).""" + recipe = _make_recipe( + { + "clone": RecipeStep( + tool="run_python", + python=_CLONE_REPO, + with_args={"strategy": "clone_local", "run_name": "t"}, + # Key is named remote_url but expression does NOT read result.remote_url. + capture={"remote_url": "${{ result.clone_path }}"}, + ), + } + ) + findings = run_semantic_rules(recipe) + matching = [f for f in findings if f.rule == _RULE] + assert matching == [] + + +@pytest.mark.parametrize("recipe_path", _BUNDLED_RECIPE_YAMLS) +def test_bundled_recipes_pass_new_rule(recipe_path: Path) -> None: + """Every bundled recipe YAML must emit zero clone-local-strategy findings (B7).""" + recipe = load_recipe(recipe_path) + findings = run_semantic_rules(recipe) + matching = [f for f in findings if f.rule == _RULE] + assert matching == [], f"{recipe_path}: {matching}" diff --git a/tests/recipe/test_rules_cmd.py b/tests/recipe/test_rules_cmd.py new file mode 100644 index 0000000000..9e94ff249b --- /dev/null +++ b/tests/recipe/test_rules_cmd.py @@ -0,0 +1,134 @@ +"""Tests for run_cmd echo-capture alignment rules.""" + +from __future__ import annotations + +from autoskillit.recipe.validator import run_semantic_rules +from tests.recipe.conftest import _make_workflow + + +def _make_recipe(steps: dict) -> object: + """Build a minimal Recipe from a dict of step dicts, with a terminal END step.""" + all_steps = {**steps, "END": {"action": "stop", "message": "Done"}} + return _make_workflow(all_steps) + + +def test_emit_alignment_errors_on_missing_echo(): + """run_cmd with capture key K but no echo "K=..." in cmd → ERROR.""" + recipe = _make_recipe( + { + "step_a": { + "tool": "run_cmd", + "with": {"cmd": "RESULT=$(compute_it)"}, + "capture": {"my_path": "${{ result.my_path }}"}, + "on_success": "END", + } + } + ) + findings = run_semantic_rules(recipe) + codes = [f.rule for f in findings] + assert "run-cmd-emit-alignment" in codes + finding = next(f for f in findings if f.rule == "run-cmd-emit-alignment") + assert "step_a" in finding.step_name + assert "my_path" in finding.message + + +def test_emit_alignment_passes_with_echo(): + """run_cmd with matching echo "K=..." → no alignment error.""" + recipe = _make_recipe( + { + "step_a": { + "tool": "run_cmd", + "with": {"cmd": 'RESULT=$(compute_it) && echo "my_path=${RESULT}"'}, + "capture": {"my_path": "${{ result.my_path }}"}, + "on_success": "END", + } + } + ) + findings = run_semantic_rules(recipe) + codes = [f.rule for f in findings] + assert "run-cmd-emit-alignment" not in codes + + +def test_emit_alignment_ignores_stdout_capture(): + """capture: {K: "${{ result.stdout }}"} does not require echo.""" + recipe = _make_recipe( + { + "step_a": { + "tool": "run_cmd", + "with": {"cmd": "git rev-parse HEAD"}, + "capture": {"sha": "${{ result.stdout | trim }}"}, + "on_success": "END", + } + } + ) + findings = run_semantic_rules(recipe) + codes = [f.rule for f in findings] + assert "run-cmd-emit-alignment" not in codes + + +def test_emit_alignment_ignores_exit_code_capture(): + """capture: {K: "${{ result.exit_code }}"} does not require echo.""" + recipe = _make_recipe( + { + "step_a": { + "tool": "run_cmd", + "with": {"cmd": "test -f something"}, + "capture": {"ok": "${{ result.exit_code }}"}, + "on_success": "END", + } + } + ) + findings = run_semantic_rules(recipe) + assert all(f.rule != "run-cmd-emit-alignment" for f in findings) + + +def test_emit_alignment_ignores_run_skill(): + """run_skill steps are not subject to the emit-alignment rule.""" + recipe = _make_recipe( + { + "step_a": { + "tool": "run_skill", + "with": {"skill_command": "/foo:bar"}, + "capture": {"plan_path": "${{ result.plan_path }}"}, + "on_success": "END", + } + } + ) + findings = run_semantic_rules(recipe) + assert all(f.rule != "run-cmd-emit-alignment" for f in findings) + + +def test_find_rediscovery_warns_on_find_sort_tail(): + """find|sort|tail -1 in run_cmd cmd → WARNING.""" + recipe = _make_recipe( + { + "step_a": { + "tool": "run_cmd", + "with": { + "cmd": ( + "DIR=$(find /some/path -maxdepth 1 -type d" + " -name '????-??-??-*' | sort | tail -1)" + ) + }, + "on_success": "END", + } + } + ) + findings = run_semantic_rules(recipe) + codes = [f.rule for f in findings] + assert "run-cmd-find-rediscovery" in codes + + +def test_find_rediscovery_no_warning_without_heuristic(): + """find without sort|tail does not trigger the warning.""" + recipe = _make_recipe( + { + "step_a": { + "tool": "run_cmd", + "with": {"cmd": "find /path -name '*.md' | xargs wc -l"}, + "on_success": "END", + } + } + ) + findings = run_semantic_rules(recipe) + assert all(f.rule != "run-cmd-find-rediscovery" for f in findings) diff --git a/tests/recipe/test_rules_conditional_push.py b/tests/recipe/test_rules_conditional_push.py new file mode 100644 index 0000000000..deb2f35e41 --- /dev/null +++ b/tests/recipe/test_rules_conditional_push.py @@ -0,0 +1,263 @@ +"""Tests for the conditional-skill-ungated-push semantic rule. + +A step invoking a write_behavior='conditional' skill must not reach a +push_to_remote tool step without passing through an on_result: edge that +dispatches on a declared verdict-like output. +""" + +from __future__ import annotations + +import autoskillit.recipe.rules_fixing as _rf +from autoskillit.core.types import Severity +from autoskillit.recipe.schema import ( + Recipe, + RecipeStep, + StepResultCondition, + StepResultRoute, +) +from autoskillit.recipe.validator import run_semantic_rules + +_RULE = "conditional-skill-ungated-push" + +# Minimal manifest with a fake conditional-write skill and a declared verdict output. +_FAKE_MANIFEST: dict = { + "version": "0.1.0", + "skills": { + "fake_fixer": { + "inputs": [{"name": "worktree_path", "type": "directory_path", "required": True}], + "outputs": [ + { + "name": "verdict", + "type": "string", + "allowed_values": ["real_fix", "no_fix"], + } + ], + "write_behavior": "conditional", + "write_expected_when": ["verdict\\s*=\\s*real_fix"], + }, + # Include a non-conditional skill so the rule skips it cleanly. + "smoke-task": { + "inputs": [], + "outputs": [], + "write_behavior": "always", + "write_expected_when": [], + }, + }, +} + + +def _make_recipe(steps: dict[str, RecipeStep]) -> Recipe: + return Recipe(name="test", description="test", steps=steps, kitchen_rules=["test"]) + + +def _push_step(name: str = "push") -> RecipeStep: + return RecipeStep( + tool="push_to_remote", + with_args={ + "clone_path": "${{ context.work_dir }}", + "remote_url": "${{ context.remote_url }}", + "branch": "${{ context.branch }}", + }, + on_success="done", + on_failure="escalate", + ) + + +def _terminal_steps() -> dict[str, RecipeStep]: + return { + "done": RecipeStep(action="stop", with_args={"message": "Done."}), + "escalate": RecipeStep(action="stop", with_args={"message": "Escalate."}), + } + + +def _fix_step_unconditional(on_success: str = "push") -> RecipeStep: + """fix step: unconditional on_success → violation.""" + return RecipeStep( + tool="run_skill", + with_args={"skill_command": "/autoskillit:fake_fixer /tmp/wt"}, + on_success=on_success, + on_failure="escalate", + ) + + +def _fix_step_gated() -> RecipeStep: + """fix step: on_result with verdict dispatch → compliant.""" + return RecipeStep( + tool="run_skill", + with_args={"skill_command": "/autoskillit:fake_fixer /tmp/wt"}, + on_result=StepResultRoute( + conditions=[ + StepResultCondition( + when="${{ result.verdict }} == 'real_fix'", + route="push", + ), + StepResultCondition( + when="${{ result.verdict }} == 'no_fix'", + route="escalate", + ), + ] + ), + on_failure="escalate", + ) + + +# --------------------------------------------------------------------------- +# Case A — unconditional on_success → push (violation) +# --------------------------------------------------------------------------- + + +def test_case_a_unconditional_on_success_to_push_fires(monkeypatch) -> None: + """Case A: unconditional on_success to push_to_remote must fire ERROR.""" + monkeypatch.setattr(_rf, "load_bundled_manifest", lambda: _FAKE_MANIFEST) + steps = {"fix": _fix_step_unconditional(), "push": _push_step(), **_terminal_steps()} + recipe = _make_recipe(steps) + findings = [f for f in run_semantic_rules(recipe) if f.rule == _RULE] + assert len(findings) >= 1, ( + "conditional-skill-ungated-push must fire when a conditional-write skill " + "routes unconditionally to push_to_remote" + ) + assert any(f.severity == Severity.ERROR for f in findings), ( + "conditional-skill-ungated-push findings must have ERROR severity" + ) + # Finding must reference the offending step + assert any("fix" in f.step_name for f in findings), "finding must reference the 'fix' step" + + +# --------------------------------------------------------------------------- +# Case B — on_result with verdict dispatch → compliant (no finding) +# --------------------------------------------------------------------------- + + +def test_case_b_verdict_gated_on_result_passes(monkeypatch) -> None: + """Case B: on_result with explicit verdict conditions must NOT fire.""" + monkeypatch.setattr(_rf, "load_bundled_manifest", lambda: _FAKE_MANIFEST) + steps = {"fix": _fix_step_gated(), "push": _push_step(), **_terminal_steps()} + recipe = _make_recipe(steps) + findings = [f for f in run_semantic_rules(recipe) if f.rule == _RULE] + assert len(findings) == 0, ( + "conditional-skill-ungated-push must NOT fire when verdict-gated on_result " + f"is present; got findings: {findings}" + ) + + +# --------------------------------------------------------------------------- +# Case C — on_result present but no when: (catch-all only) → violation +# --------------------------------------------------------------------------- + + +def test_case_c_catchall_only_on_result_fires(monkeypatch) -> None: + """Case C: on_result with only a catch-all condition must fire.""" + monkeypatch.setattr(_rf, "load_bundled_manifest", lambda: _FAKE_MANIFEST) + # on_result with only a when-less catch-all → not a real gate + catchall_step = RecipeStep( + tool="run_skill", + with_args={"skill_command": "/autoskillit:fake_fixer /tmp/wt"}, + on_result=StepResultRoute( + conditions=[ + StepResultCondition(when=None, route="push"), # catch-all, no when + ] + ), + on_failure="escalate", + ) + steps = {"fix": catchall_step, "push": _push_step(), **_terminal_steps()} + recipe = _make_recipe(steps) + findings = [f for f in run_semantic_rules(recipe) if f.rule == _RULE] + assert len(findings) >= 1, ( + "conditional-skill-ungated-push must fire when on_result has only a " + "catch-all condition with no verdict reference" + ) + + +# --------------------------------------------------------------------------- +# Case D — indirect path (fix → verify → push) → violation +# --------------------------------------------------------------------------- + + +def test_case_d_indirect_path_fires(monkeypatch) -> None: + """Case D: rule must fire even when push is 2 hops away via an intermediate step.""" + monkeypatch.setattr(_rf, "load_bundled_manifest", lambda: _FAKE_MANIFEST) + # fix → verify → push (2 hops; no on_result gate on fix) + fix_step = RecipeStep( + tool="run_skill", + with_args={"skill_command": "/autoskillit:fake_fixer /tmp/wt"}, + on_success="verify", + on_failure="escalate", + ) + verify_step = RecipeStep( + tool="run_skill", + with_args={"skill_command": "/autoskillit:smoke-task"}, + on_success="push", + on_failure="escalate", + ) + steps = { + "fix": fix_step, + "verify": verify_step, + "push": _push_step(), + **_terminal_steps(), + } + recipe = _make_recipe(steps) + findings = [f for f in run_semantic_rules(recipe) if f.rule == _RULE] + assert len(findings) >= 1, ( + "conditional-skill-ungated-push must walk multi-hop paths and fire " + "when fix → verify → push has no verdict gate" + ) + + +# --------------------------------------------------------------------------- +# Case E — on_result gates on undeclared field → violation +# --------------------------------------------------------------------------- + + +def test_case_e_on_result_gates_on_undeclared_field_fires(monkeypatch) -> None: + """Case E: on_result referencing a field not in the contract's outputs must fire.""" + monkeypatch.setattr(_rf, "load_bundled_manifest", lambda: _FAKE_MANIFEST) + # Gates on ${{ result.fixes_applied }} which is NOT declared in fake_fixer's outputs + bad_gate_step = RecipeStep( + tool="run_skill", + with_args={"skill_command": "/autoskillit:fake_fixer /tmp/wt"}, + on_result=StepResultRoute( + conditions=[ + StepResultCondition( + when="${{ result.fixes_applied }} > 0", + route="push", + ), + StepResultCondition(when=None, route="escalate"), + ] + ), + on_failure="escalate", + ) + steps = {"fix": bad_gate_step, "push": _push_step(), **_terminal_steps()} + recipe = _make_recipe(steps) + findings = [f for f in run_semantic_rules(recipe) if f.rule == _RULE] + assert len(findings) >= 1, ( + "conditional-skill-ungated-push must fire when on_result gates on a field " + "that is not declared in the skill contract's outputs" + ) + + +# --------------------------------------------------------------------------- +# Severity and step_name contract +# --------------------------------------------------------------------------- + + +def test_finding_severity_is_error(monkeypatch) -> None: + """All findings from this rule must have ERROR severity.""" + monkeypatch.setattr(_rf, "load_bundled_manifest", lambda: _FAKE_MANIFEST) + steps = {"fix": _fix_step_unconditional(), "push": _push_step(), **_terminal_steps()} + recipe = _make_recipe(steps) + findings = [f for f in run_semantic_rules(recipe) if f.rule == _RULE] + assert len(findings) >= 1 + for f in findings: + assert f.severity == Severity.ERROR, f"Expected ERROR severity, got {f.severity}" + + +def test_finding_message_references_fix_and_push(monkeypatch) -> None: + """Finding message must reference both the fix step and the push step.""" + monkeypatch.setattr(_rf, "load_bundled_manifest", lambda: _FAKE_MANIFEST) + steps = {"fix": _fix_step_unconditional(), "push": _push_step(), **_terminal_steps()} + recipe = _make_recipe(steps) + findings = [f for f in run_semantic_rules(recipe) if f.rule == _RULE] + assert len(findings) >= 1 + messages = " ".join(f.message for f in findings) + assert "fix" in messages, "Finding message must reference the 'fix' step" + assert "push" in messages, "Finding message must reference the 'push' step" diff --git a/tests/recipe/test_rules_contracts.py b/tests/recipe/test_rules_contracts.py index afba12d134..bab4b6d553 100644 --- a/tests/recipe/test_rules_contracts.py +++ b/tests/recipe/test_rules_contracts.py @@ -194,3 +194,28 @@ def test_valid_write_behavior_no_findings_on_bundled_recipes() -> None: f"write-behavior-consistency fired on {recipe_path.name}: " + "; ".join(f.message for f in wb_findings) ) + + +# --------------------------------------------------------------------------- +# always-has-no-write-exit rule tests +# --------------------------------------------------------------------------- + + +def test_always_write_skill_with_documented_no_write_exit_flagged() -> None: + """Phrase set for always-has-no-write-exit rule is populated with expected patterns. + + Verifies that the frozenset contains phrases covering the known no-write exit + patterns (e.g. 'may be 0' from resolve-failures, graceful degradation from + resolve-review). An empty or incomplete set would silently miss all bugs. + """ + from autoskillit.recipe.rules_contracts import _ALWAYS_WITH_NO_WRITE_EXIT_PHRASES + + # Verify the phrase set is populated (not empty — would miss all bugs) + assert len(_ALWAYS_WITH_NO_WRITE_EXIT_PHRASES) > 0 + assert any("may be 0" in p for p in _ALWAYS_WITH_NO_WRITE_EXIT_PHRASES), ( + "Must detect 'may be 0' — the exact phrase in resolve-failures Step 4 " + "that the investigation identified as the no-write exit signal" + ) + assert any( + "graceful" in p.lower() or "skip" in p.lower() for p in _ALWAYS_WITH_NO_WRITE_EXIT_PHRASES + ), "Must detect graceful degradation phrases — the exact pattern in resolve-review Step 1" diff --git a/tests/recipe/test_rules_dataflow.py b/tests/recipe/test_rules_dataflow.py index 73fc970b85..ab4e7ba4d2 100644 --- a/tests/recipe/test_rules_dataflow.py +++ b/tests/recipe/test_rules_dataflow.py @@ -315,18 +315,21 @@ def test_ih3_does_not_fire_when_capture_block_present(self) -> None: assert ih == [] def test_ih4_does_not_fire_for_skill_with_empty_outputs(self) -> None: - """T_IH4: implicit-handoff does NOT fire for a skill with outputs: [].""" + """T_IH4: implicit-handoff does NOT fire for a skill with outputs: []. + + dry-walkthrough has outputs: [] — no fields to capture, so no finding. + """ steps = { - "assess": { + "walkthrough": { "tool": "run_skill", - "with": {"skill_command": "/autoskillit:resolve-failures worktree plan main"}, + "with": {"skill_command": "/autoskillit:dry-walkthrough plan"}, "on_success": "done", }, "done": {"action": "stop", "message": "Done."}, } recipe = _make_workflow(steps) findings = run_semantic_rules(recipe) - ih = [f for f in findings if f.rule == "implicit-handoff" and f.step_name == "assess"] + ih = [f for f in findings if f.rule == "implicit-handoff" and f.step_name == "walkthrough"] assert ih == [] def test_ih5_does_not_fire_for_unknown_skill(self) -> None: @@ -715,11 +718,8 @@ def test_ip_push_after_audit_now_correctly_has_violation(self) -> None: """T_IP_PBA: bypass path via skip_when_false makes push-before-audit fire. Uses a synthetic recipe mirroring implementation topology: - start → audit_impl (optional, skip_when_false) → open_pr_step → push + start → audit_impl (optional, skip_when_false) → compose_pr → push The skip_when_false bypass allows push to be reached without audit. - - The real recipe YAML will have skip_when_false added in Part B, at which - point the TestImplementationPipelineStructure fixture will also trigger this rule. """ recipe = _make_workflow( { @@ -732,15 +732,15 @@ def test_ip_push_after_audit_now_correctly_has_violation(self) -> None: "skill_command": "/autoskillit:audit-impl plan.md", "cwd": "/tmp", }, - "on_success": "open_pr_step", + "on_success": "compose_pr", "on_failure": "done", }, - "open_pr_step": { + "compose_pr": { "tool": "run_skill", "optional": True, "skip_when_false": "inputs.open_pr", "with": { - "skill_command": "/autoskillit:open-pr", + "skill_command": "/autoskillit:compose-pr", "cwd": "/tmp", }, "on_success": "push", diff --git a/tests/recipe/test_rules_graph.py b/tests/recipe/test_rules_graph.py index 74ce015501..e807537856 100644 --- a/tests/recipe/test_rules_graph.py +++ b/tests/recipe/test_rules_graph.py @@ -58,7 +58,7 @@ def test_cycle_with_only_on_failure_exit_is_warning() -> None: def test_cycle_with_retry_exit_is_clean() -> None: - """Cycle with retries>0, tool=run_skill, and on_exhausted outside cycle → no finding.""" + """Cycle where retrying step's success path stays in cycle → WARNING (outer loop unbounded).""" recipe = _make_recipe( { "A": RecipeStep( @@ -74,7 +74,47 @@ def test_cycle_with_retry_exit_is_clean() -> None: ) findings = run_semantic_rules(recipe) cycle_findings = [f for f in findings if f.rule == "unbounded-cycle"] - assert cycle_findings == [] + assert len(cycle_findings) == 1 + assert cycle_findings[0].severity == Severity.WARNING + + +def test_cycle_with_retry_exit_but_success_reenters_is_warning() -> None: + """A→B(retries=2, on_exhausted=done)→C→A: B exits on exhaustion but + success path C→A re-enters the cycle. Must produce WARNING.""" + recipe = _make_recipe( + { + "A": RecipeStep( + tool="wait_for_ci", + with_args={"branch": "main", "timeout_seconds": 300}, + on_success="B", + on_failure="B", + ), + "B": RecipeStep( + tool="run_skill", + with_args={"skill_command": "/autoskillit:resolve-failures /tmp", "cwd": "/tmp"}, + retries=2, + on_exhausted="done", + on_success="C", + on_failure="done", + ), + "C": RecipeStep( + tool="push_to_remote", + with_args={ + "clone_path": "/tmp", + "remote_url": "https://github.com/o/r.git", + "branch": "b", + }, + on_success="A", # RE-ENTERS THE CYCLE + on_failure="done", + ), + "done": RecipeStep(action="stop", message="done"), + } + ) + findings = run_semantic_rules(recipe) + cycle_findings = [f for f in findings if f.rule == "unbounded-cycle"] + assert len(cycle_findings) >= 1 + # Must be WARNING (has conditional exit but no outer bound) + assert any(f.severity == Severity.WARNING for f in cycle_findings) def test_no_cycle_is_clean() -> None: diff --git a/tests/recipe/test_rules_inputs.py b/tests/recipe/test_rules_inputs.py index 604ce20e62..1e9bf91c77 100644 --- a/tests/recipe/test_rules_inputs.py +++ b/tests/recipe/test_rules_inputs.py @@ -5,6 +5,53 @@ import ast import pathlib +from autoskillit.core import Severity +from autoskillit.recipe.registry import run_semantic_rules +from autoskillit.recipe.schema import Recipe, RecipeStep + + +def _make_recipe_with_skill_step(skill_command: str) -> Recipe: + """Build a minimal Recipe with a single run_skill step.""" + step = RecipeStep( + tool="run_skill", + with_args={"skill_command": skill_command}, + ) + return Recipe( + name="test-recipe", + description="Test recipe for rule validation", + steps={"review_step": step}, + ) + + +def test_missing_recommended_input_fires_warning_when_not_passed(): + """A skill with recommended=True inputs should produce a WARNING + when the recipe step's skill_command does not contain `name=` for them.""" + recipe = _make_recipe_with_skill_step( + "/autoskillit:review-pr ${{ context.merge_target }} ${{ inputs.base_branch }}" + ) + findings = run_semantic_rules(recipe) + rec_findings = [f for f in findings if f.rule == "missing-recommended-input"] + assert len(rec_findings) > 0, ( + "Expected at least one missing-recommended-input WARNING when " + "annotated_diff_path= is not in skill_command" + ) + assert all(f.severity == Severity.WARNING for f in rec_findings) + + +def test_missing_recommended_input_passes_when_input_provided(): + """No WARNING when the step's skill_command contains the recommended input as name=.""" + recipe = _make_recipe_with_skill_step( + "/autoskillit:review-pr ${{ context.merge_target }} ${{ inputs.base_branch }} " + "annotated_diff_path=${{ context.annotated_diff_path }} " + "hunk_ranges_path=${{ context.hunk_ranges_path }}" + ) + findings = run_semantic_rules(recipe) + rec_findings = [f for f in findings if f.rule == "missing-recommended-input"] + assert rec_findings == [], ( + f"Expected no missing-recommended-input findings when inputs are provided, " + f"got: {rec_findings}" + ) + def test_rules_inputs_terminal_targets_match_schema(): """rules_inputs.py unreachable-step rule uses the same sentinel set as schema.""" @@ -35,3 +82,88 @@ def test_rules_inputs_terminal_targets_match_schema(): f"rules_inputs.py hardcodes {len(hardcoded_discards)} sentinel string(s) via " ".discard(). Use _TERMINAL_TARGETS from schema instead." ) + + +def test_required_ingredient_without_default_emits_warning(): + """A recipe ingredient with required=True and no default must produce + a validator WARNING, not pass silently.""" + from autoskillit.recipe.schema import RecipeIngredient + + recipe = Recipe( + name="test-recipe", + description="Test recipe", + ingredients={ + "source_dir": RecipeIngredient( + description="A required input", + required=True, + default=None, + hidden=False, + ) + }, + steps={ + "step1": RecipeStep( + tool="run_skill", + with_args={"skill_command": "/test"}, + ) + }, + ) + findings = run_semantic_rules(recipe) + warning_findings = [f for f in findings if f.rule == "required-ingredient-no-default"] + assert len(warning_findings) > 0 + assert all(f.severity == Severity.WARNING for f in warning_findings) + + +def test_required_ingredient_with_default_no_warning(): + """A recipe ingredient with required=True and a default value should NOT + produce a required-ingredient-no-default warning.""" + from autoskillit.recipe.schema import RecipeIngredient + + recipe = Recipe( + name="test-recipe", + description="Test recipe", + ingredients={ + "source_dir": RecipeIngredient( + description="A required input with default", + required=True, + default="some-value", + hidden=False, + ) + }, + steps={ + "step1": RecipeStep( + tool="run_skill", + with_args={"skill_command": "/test"}, + ) + }, + ) + findings = run_semantic_rules(recipe) + warning_findings = [f for f in findings if f.rule == "required-ingredient-no-default"] + assert len(warning_findings) == 0 + + +def test_required_hidden_ingredient_without_default_no_warning(): + """A hidden ingredient with required=True and no default should NOT trigger + the warning because hidden ingredients are not shown to the agent.""" + from autoskillit.recipe.schema import RecipeIngredient + + recipe = Recipe( + name="test-recipe", + description="Test recipe", + ingredients={ + "source_dir": RecipeIngredient( + description="A hidden required input", + required=True, + default=None, + hidden=True, + ) + }, + steps={ + "step1": RecipeStep( + tool="run_skill", + with_args={"skill_command": "/test"}, + ) + }, + ) + findings = run_semantic_rules(recipe) + warning_findings = [f for f in findings if f.rule == "required-ingredient-no-default"] + assert len(warning_findings) == 0 diff --git a/tests/recipe/test_rules_isolation.py b/tests/recipe/test_rules_isolation.py new file mode 100644 index 0000000000..9ca21970ff --- /dev/null +++ b/tests/recipe/test_rules_isolation.py @@ -0,0 +1,182 @@ +"""Tests for workspace isolation semantic rules. + +Covers source-isolation-violation and git-mutation-on-source rules. +""" + +from __future__ import annotations + +from autoskillit.core.types import Severity +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe +from autoskillit.recipe.registry import _RULE_REGISTRY, run_semantic_rules +from tests.recipe.conftest import _make_workflow + +# --------------------------------------------------------------------------- +# Test 1a: Rule registration +# --------------------------------------------------------------------------- + + +def test_source_isolation_rule_registered() -> None: + """source-isolation-violation must be in the rule registry.""" + names = {spec.name for spec in _RULE_REGISTRY} + assert "source-isolation-violation" in names + + +# --------------------------------------------------------------------------- +# Test 1b: create_unique_branch with inputs.* cwd fires ERROR +# --------------------------------------------------------------------------- + + +def test_create_unique_branch_with_inputs_cwd_fires_error() -> None: + wf = _make_workflow( + { + "create_branch": { + "tool": "create_unique_branch", + "with": { + "base_branch_name": "smoke/canary", + "cwd": "${{ inputs.workspace }}", + }, + "capture": {"branch_name": "${{ result.branch_name }}"}, + "on_success": "done", + }, + "done": {"action": "stop", "message": "Done."}, + } + ) + findings = run_semantic_rules(wf) + errors = [f for f in findings if f.rule == "source-isolation-violation"] + assert len(errors) == 1 + assert errors[0].severity == Severity.ERROR + assert errors[0].step_name == "create_branch" + + +# --------------------------------------------------------------------------- +# Test 1c: create_unique_branch with context.* cwd passes +# --------------------------------------------------------------------------- + + +def test_create_unique_branch_with_context_cwd_passes() -> None: + wf = _make_workflow( + { + "create_branch": { + "tool": "create_unique_branch", + "with": { + "base_branch_name": "smoke/canary", + "cwd": "${{ context.work_dir }}", + }, + "capture": {"branch_name": "${{ result.branch_name }}"}, + "on_success": "done", + }, + "done": {"action": "stop", "message": "Done."}, + } + ) + findings = run_semantic_rules(wf) + isolation = [f for f in findings if f.rule == "source-isolation-violation"] + assert isolation == [] + + +# --------------------------------------------------------------------------- +# Test 1d: run_cmd git checkout on inputs.* fires WARNING +# --------------------------------------------------------------------------- + + +def test_run_cmd_git_checkout_on_inputs_fires_warning() -> None: + wf = _make_workflow( + { + "checkout": { + "tool": "run_cmd", + "with": { + "cmd": 'git checkout -b "my-branch"', + "cwd": "${{ inputs.source_dir }}", + }, + "on_success": "done", + }, + "done": {"action": "stop", "message": "Done."}, + } + ) + findings = run_semantic_rules(wf) + warnings = [f for f in findings if f.rule == "git-mutation-on-source"] + assert len(warnings) == 1 + assert warnings[0].severity == Severity.WARNING + assert warnings[0].step_name == "checkout" + + +# --------------------------------------------------------------------------- +# Test 1e: run_cmd git checkout after clone passes +# --------------------------------------------------------------------------- + + +def test_run_cmd_git_checkout_after_clone_passes() -> None: + wf = _make_workflow( + { + "clone": { + "tool": "clone_repo", + "with": { + "source_dir": "${{ inputs.source_dir }}", + "run_name": "test", + "branch": "main", + }, + "capture": {"work_dir": "${{ result.clone_path }}"}, + "on_success": "checkout", + }, + "checkout": { + "tool": "run_cmd", + "with": { + "cmd": 'git checkout -b "my-branch"', + "cwd": "${{ context.work_dir }}", + }, + "on_success": "done", + }, + "done": {"action": "stop", "message": "Done."}, + } + ) + findings = run_semantic_rules(wf) + mutation = [f for f in findings if f.rule == "git-mutation-on-source"] + assert mutation == [] + + +# --------------------------------------------------------------------------- +# Test 1f: run_skill with inputs.* cwd fires WARNING (no clone) +# --------------------------------------------------------------------------- + + +def test_run_skill_with_inputs_cwd_fires_warning() -> None: + wf = _make_workflow( + { + "impl": { + "tool": "run_skill", + "with": { + "skill_command": "/autoskillit:implement-worktree plan.md", + "cwd": "${{ inputs.workspace }}", + }, + "on_success": "done", + }, + "done": {"action": "stop", "message": "Done."}, + } + ) + findings = run_semantic_rules(wf) + warnings = [f for f in findings if f.rule == "source-isolation-violation"] + assert len(warnings) == 1 + assert warnings[0].severity == Severity.WARNING + + +# --------------------------------------------------------------------------- +# Test 1g: All bundled recipes pass isolation rules +# --------------------------------------------------------------------------- + + +def test_bundled_recipes_pass_isolation_rules() -> None: + """No bundled recipe may trigger an ERROR-level isolation finding. + + WARNINGs are advisory (e.g. research.yaml legitimately operates on the + source directory without cloning). + """ + bd = builtin_recipes_dir() + for yaml_path in sorted(bd.glob("*.yaml")): + recipe = load_recipe(yaml_path) + findings = run_semantic_rules(recipe) + errors = [ + f + for f in findings + if f.rule in ("source-isolation-violation", "git-mutation-on-source") + and f.severity == Severity.ERROR + ] + assert errors == [], f"{yaml_path.name} triggered isolation ERROR: {errors}" diff --git a/tests/recipe/test_rules_merge.py b/tests/recipe/test_rules_merge.py index 0d97621e9a..5409dbd8d4 100644 --- a/tests/recipe/test_rules_merge.py +++ b/tests/recipe/test_rules_merge.py @@ -135,6 +135,97 @@ def test_merge_worktree_missing_all_recoverable_steps_is_error() -> None: assert step_value in flagged[0].message +def test_merge_without_commit_guard_fires() -> None: + """test_check → merge_worktree with no commit_guard predecessor → ERROR.""" + recipe = _make_recipe( + { + "test": RecipeStep( + tool="test_check", + with_args={"worktree_path": "/tmp/wt"}, + on_success="merge", + on_failure="abort", + ), + "merge": RecipeStep( + tool="merge_worktree", + with_args={"worktree_path": "/tmp/wt", "base_branch": "main"}, + on_success="done", + on_failure="done", + ), + "done": RecipeStep(action="stop", message="done"), + "abort": RecipeStep(action="stop", message="abort"), + } + ) + findings = run_semantic_rules(recipe) + flagged = [f for f in findings if f.rule == "merge-without-commit-guard"] + assert len(flagged) == 1, ( + f"Expected exactly 1 merge-without-commit-guard ERROR, got: {flagged}" + ) + assert flagged[0].severity == Severity.ERROR + assert flagged[0].step_name == "merge" + + +def test_merge_with_commit_guard_step_name_is_clean() -> None: + """Step named commit_guard* immediately before merge_worktree → no finding.""" + recipe = _make_recipe( + { + "test": RecipeStep( + tool="test_check", + with_args={"worktree_path": "/tmp/wt"}, + on_success="commit_guard", + on_failure="abort", + ), + "commit_guard": RecipeStep( + tool="run_cmd", + with_args={ + "cmd": ( + "cd /tmp/wt && " + 'if [ -n "$(git status --porcelain)" ]; ' + "then git add -A && git commit -m 'chore: pending'; fi" + ), + "cwd": "/tmp/wt", + }, + on_success="merge", + on_failure="merge", + ), + "merge": RecipeStep( + tool="merge_worktree", + with_args={"worktree_path": "/tmp/wt", "base_branch": "main"}, + on_success="done", + on_failure="done", + ), + "done": RecipeStep(action="stop", message="done"), + "abort": RecipeStep(action="stop", message="abort"), + } + ) + findings = run_semantic_rules(recipe) + flagged = [f for f in findings if f.rule == "merge-without-commit-guard"] + assert flagged == [], f"Unexpected merge-without-commit-guard finding: {flagged}" + + +def test_merge_with_git_commit_in_cmd_is_clean() -> None: + """run_cmd step with 'git commit' in cmd immediately before merge → no finding.""" + recipe = _make_recipe( + { + "pre_merge": RecipeStep( + tool="run_cmd", + with_args={"cmd": "git add -A && git commit -m 'fix' || true"}, + on_success="merge", + on_failure="merge", + ), + "merge": RecipeStep( + tool="merge_worktree", + with_args={"worktree_path": "/tmp/wt", "base_branch": "main"}, + on_success="done", + on_failure="done", + ), + "done": RecipeStep(action="stop", message="done"), + } + ) + findings = run_semantic_rules(recipe) + flagged = [f for f in findings if f.rule == "merge-without-commit-guard"] + assert flagged == [], f"Unexpected merge-without-commit-guard finding: {flagged}" + + def test_multiple_merge_steps_each_checked_independently() -> None: """Two merge_worktree steps: one complete, one incomplete → one ERROR.""" all_values = list(_RECOVERABLE_FAILED_STEPS) diff --git a/tests/recipe/test_rules_packs.py b/tests/recipe/test_rules_packs.py new file mode 100644 index 0000000000..e40fbf3a6c --- /dev/null +++ b/tests/recipe/test_rules_packs.py @@ -0,0 +1,64 @@ +"""Tests for the unknown-required-pack semantic rule.""" + +from autoskillit.core import Severity +from autoskillit.recipe.registry import run_semantic_rules +from autoskillit.recipe.schema import Recipe, RecipeStep + + +def _make_recipe(requires_packs: list[str]) -> Recipe: + return Recipe( + name="test", + description="test recipe", + version="0.7.2", + requires_packs=requires_packs, + steps={"stop": RecipeStep(action="stop")}, + ) + + +def test_unknown_pack_produces_warning(): + """Pack name not in PACK_REGISTRY produces a WARNING finding.""" + import autoskillit.recipe # noqa: F401 -- triggers rule registration + + recipe = _make_recipe(["nonexistent-pack"]) + findings = [f for f in run_semantic_rules(recipe) if f.rule == "unknown-required-pack"] + assert findings + assert findings[0].severity == Severity.WARNING + assert "nonexistent-pack" in findings[0].message + + +def test_known_pack_produces_no_finding(): + """Known pack name (in PACK_REGISTRY) produces no finding.""" + import autoskillit.recipe # noqa: F401 -- triggers rule registration + + recipe = _make_recipe(["research"]) + findings = [f for f in run_semantic_rules(recipe) if f.rule == "unknown-required-pack"] + assert not findings + + +def test_mixed_packs_flags_only_unknown(): + """Only unknown packs are flagged; known packs pass silently.""" + import autoskillit.recipe # noqa: F401 -- triggers rule registration + + recipe = _make_recipe(["research", "bogus-pack"]) + findings = [f for f in run_semantic_rules(recipe) if f.rule == "unknown-required-pack"] + assert len(findings) == 1 + assert "bogus-pack" in findings[0].message + + +def test_empty_requires_packs_produces_no_finding(): + """Recipes without requires_packs produce no finding.""" + import autoskillit.recipe # noqa: F401 -- triggers rule registration + + recipe = _make_recipe([]) + findings = [f for f in run_semantic_rules(recipe) if f.rule == "unknown-required-pack"] + assert not findings + + +def test_all_builtin_packs_pass(): + """Every pack in PACK_REGISTRY is a valid name (no self-flagging).""" + import autoskillit.recipe # noqa: F401 -- triggers rule registration + from autoskillit.core import PACK_REGISTRY + + recipe = _make_recipe(list(PACK_REGISTRY.keys())) + findings = [f for f in run_semantic_rules(recipe) if f.rule == "unknown-required-pack"] + assert not findings, f"Built-in packs must not trigger unknown-required-pack: {findings}" diff --git a/tests/recipe/test_rules_reachability.py b/tests/recipe/test_rules_reachability.py new file mode 100644 index 0000000000..71b50d1337 --- /dev/null +++ b/tests/recipe/test_rules_reachability.py @@ -0,0 +1,178 @@ +"""Capture-inversion and event-scope reachability guards. + +Tests verify that: +1. Bundled recipes produce zero inversion findings after Part B remediation. +2. Synthetic recipes with inversions are correctly flagged. +3. _bfs_with_facts correctly intersects facts at join points. +""" + +from __future__ import annotations + +import pytest + +from autoskillit.recipe._analysis import _bfs_with_facts, _build_step_graph +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe +from autoskillit.recipe.registry import run_semantic_rules +from autoskillit.recipe.schema import ( + Recipe, + RecipeStep, + StepResultCondition, + StepResultRoute, +) + +_QUEUE_CAPABLE = ("implementation.yaml", "remediation.yaml", "implementation-groups.yaml") + + +# --------------------------------------------------------------------------- +# Bundled recipe guards (post-Part-B: must be clean) +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("recipe_name", _QUEUE_CAPABLE) +def test_bundled_recipe_wait_for_ci_has_no_inversion_findings(recipe_name): + """Post-Part-B: ci_watch reads ${{ context.ci_event }} and the producer + (check_repo_merge_state) is upstream — no capture-inversion or event-scope + finding is expected. This test enforces the correct end state.""" + recipe = load_recipe(builtin_recipes_dir() / recipe_name) + findings = run_semantic_rules(recipe) + inversions = [ + f + for f in findings + if f.rule in ("capture-inversion-detection", "event-scope-requires-upstream-capture") + ] + assert inversions == [], f"{recipe_name}: {[f.message for f in inversions]}" + + +# --------------------------------------------------------------------------- +# Synthetic recipe tests +# --------------------------------------------------------------------------- + + +def test_synthetic_recipe_with_inversion_is_flagged(): + """Independent: a minimal recipe with entry → wait_for_ci(event='push') → + check_merge_group_trigger must produce exactly one capture-inversion finding.""" + recipe = _make_synthetic_recipe_with_inversion() + findings = run_semantic_rules(recipe) + matching = [f for f in findings if f.rule == "event-scope-requires-upstream-capture"] + assert len(matching) == 1 + assert "merge_group_trigger" in matching[0].message + + +def test_synthetic_recipe_without_inversion_passes(): + """Reverse the order: entry → check_repo_merge_state → wait_for_ci(event from + context.ci_event). No finding.""" + recipe = _make_synthetic_recipe_upstream_capture() + findings = run_semantic_rules(recipe) + matching = [f for f in findings if f.rule == "event-scope-requires-upstream-capture"] + assert matching == [] + + +def test_bfs_with_facts_intersects_at_joins(): + """Unit: on a recipe where branch A establishes (X, 'a') and branch B establishes + nothing, the join point has facts = {} (conservative intersection). Downstream + of the join, X is not known.""" + recipe = _make_branching_recipe() + graph = _build_step_graph(recipe) + facts = _bfs_with_facts(graph, recipe, start="entry") + assert facts["join"] == {frozenset()} # no fact holds on every path + assert frozenset([("X", "a")]) in facts["on_branch_a"] # fact holds here + + +# --------------------------------------------------------------------------- +# Synthetic recipe builders +# --------------------------------------------------------------------------- + + +def _make_synthetic_recipe_with_inversion() -> Recipe: + """entry → wait_for_ci(event='push') → check_merge_group_trigger. + + The wait_for_ci step hardcodes event='push' but the producer of + merge_group_trigger (check_merge_group_trigger) runs strictly downstream. + This represents the pre-Part-B bug in the bundled recipes. + """ + entry = RecipeStep(name="entry", action="route", on_success="ci_watch") + ci_watch = RecipeStep( + name="ci_watch", + tool="wait_for_ci", + with_args={"branch": "main", "event": "push"}, + on_success="check_merge_group_trigger", + ) + check_step = RecipeStep( + name="check_merge_group_trigger", + tool="check_repo_merge_state", + capture={"merge_group_trigger": "${{ result.merge_group_trigger }}"}, + ) + return Recipe( + name="synthetic-inversion", + description="test recipe with capture inversion", + steps={ + "entry": entry, + "ci_watch": ci_watch, + "check_merge_group_trigger": check_step, + }, + ) + + +def _make_synthetic_recipe_upstream_capture() -> Recipe: + """entry → check_repo_merge_state(captures ci_event, merge_group_trigger) → + wait_for_ci(event=${{ context.ci_event }}). + + The producer of ci_event is upstream; event is a template reference, not a + literal. No finding expected. + """ + entry = RecipeStep(name="entry", action="route", on_success="check_repo_merge_state") + check_step = RecipeStep( + name="check_repo_merge_state", + tool="check_repo_merge_state", + capture={ + "ci_event": "${{ result.ci_event }}", + "merge_group_trigger": "${{ result.merge_group_trigger }}", + }, + on_success="ci_watch", + ) + ci_watch = RecipeStep( + name="ci_watch", + tool="wait_for_ci", + with_args={"branch": "main", "event": "${{ context.ci_event }}"}, + ) + return Recipe( + name="synthetic-no-inversion", + description="test recipe without capture inversion", + steps={ + "entry": entry, + "check_repo_merge_state": check_step, + "ci_watch": ci_watch, + }, + ) + + +def _make_branching_recipe() -> Recipe: + """entry (routes conditionally) → on_branch_a + on_branch_b → join. + + Branch A carries fact (X, 'a') via on_result.when = "context.X == 'a'". + Branch B carries no fact (default route). + At join: intersection gives empty fact set (X is not known on every path). + """ + entry = RecipeStep( + name="entry", + action="route", + on_result=StepResultRoute( + conditions=[ + StepResultCondition(route="on_branch_a", when="context.X == 'a'"), + StepResultCondition(route="on_branch_b"), # default, no when + ] + ), + ) + on_branch_a = RecipeStep(name="on_branch_a", action="route", on_success="join") + on_branch_b = RecipeStep(name="on_branch_b", action="route", on_success="join") + join = RecipeStep(name="join", action="stop", message="done") + return Recipe( + name="synthetic-branching", + description="test recipe with branching for BFS fact intersection", + steps={ + "entry": entry, + "on_branch_a": on_branch_a, + "on_branch_b": on_branch_b, + "join": join, + }, + ) diff --git a/tests/recipe/test_rules_recipe.py b/tests/recipe/test_rules_recipe.py index 7ab250af59..a79bae35a6 100644 --- a/tests/recipe/test_rules_recipe.py +++ b/tests/recipe/test_rules_recipe.py @@ -155,3 +155,18 @@ def test_all_bundled_recipes_pass_rules_recipe() -> None: f"Recipe '{recipe_path.name}' has rules_recipe findings: " f"{[f.message for f in recipe_rules]}" ) + + +# --------------------------------------------------------------------------- +# T8 — rules_recipe.py functions use _check_* prefix +# --------------------------------------------------------------------------- + + +def test_rules_recipe_uses_check_prefix() -> None: + """Rule functions in rules_recipe.py must use the _check_* naming convention.""" + import autoskillit.recipe.rules_recipe as m + + assert hasattr(m, "_check_unknown_sub_recipe"), "_check_unknown_sub_recipe not found" + assert hasattr(m, "_check_circular_sub_recipe"), "_check_circular_sub_recipe not found" + assert not hasattr(m, "_unknown_sub_recipe"), "_unknown_sub_recipe should be renamed" + assert not hasattr(m, "_circular_sub_recipe"), "_circular_sub_recipe should be renamed" diff --git a/tests/recipe/test_rules_skill_content.py b/tests/recipe/test_rules_skill_content.py index 4d92e8b6af..e2e68c6058 100644 --- a/tests/recipe/test_rules_skill_content.py +++ b/tests/recipe/test_rules_skill_content.py @@ -354,9 +354,9 @@ def test_hardcoded_origin_does_not_fire_on_fixed_resolve_merge_conflicts(tmp_pat Uses SKILL_SEARCH_DIRS isolation: copies the real bundled skill content into tmp_path so the test fails with a clear assertion error (not an opaque ENOENT) if the skill is renamed. """ - from autoskillit.workspace import SkillResolver # noqa: PLC0415 + from autoskillit.workspace import DefaultSkillResolver # noqa: PLC0415 - skill_info = SkillResolver().resolve("resolve-merge-conflicts") + skill_info = DefaultSkillResolver().resolve("resolve-merge-conflicts") assert skill_info is not None, "bundled resolve-merge-conflicts skill not found" skill_dir = tmp_path / "resolve-merge-conflicts" skill_dir.mkdir() @@ -385,9 +385,9 @@ def test_hardcoded_origin_does_not_fire_on_fixed_retry_worktree(tmp_path: Path) Uses SKILL_SEARCH_DIRS isolation: copies the real bundled skill content into tmp_path so the test fails with a clear assertion error (not an opaque ENOENT) if the skill is renamed. """ - from autoskillit.workspace import SkillResolver # noqa: PLC0415 + from autoskillit.workspace import DefaultSkillResolver # noqa: PLC0415 - skill_info = SkillResolver().resolve("retry-worktree") + skill_info = DefaultSkillResolver().resolve("retry-worktree") assert skill_info is not None, "bundled retry-worktree skill not found" skill_dir = tmp_path / "retry-worktree" skill_dir.mkdir() diff --git a/tests/recipe/test_rules_skills.py b/tests/recipe/test_rules_skills.py index 7cd371e65b..e6339613b1 100644 --- a/tests/recipe/test_rules_skills.py +++ b/tests/recipe/test_rules_skills.py @@ -99,7 +99,7 @@ def test_bundled_skill_names_not_computed_at_import_v2() -> None: mod_name = "autoskillit.recipe.rules_skills" sys.modules.pop(mod_name, None) - with patch("autoskillit.workspace.skills.SkillResolver.list_all") as mock_list: + with patch("autoskillit.workspace.skills.DefaultSkillResolver.list_all") as mock_list: importlib.import_module(mod_name) mock_list.assert_not_called() diff --git a/tests/recipe/test_rules_structure.py b/tests/recipe/test_rules_structure.py index 333cefbb12..382076f667 100644 --- a/tests/recipe/test_rules_structure.py +++ b/tests/recipe/test_rules_structure.py @@ -741,8 +741,10 @@ def test_unbounded_cycle_without_retries_produces_warning(self) -> None: "unbounded" in f.message.lower() or "cycle" in f.message.lower() for f in warnings ) - def test_bounded_cycle_with_retries_does_not_warn(self) -> None: - """A cycle with retries > 0 on the cycling step should NOT warn.""" + def test_cycle_with_retries_warns_when_success_stays_in_cycle(self) -> None: + """A cycle where the retrying step's success path stays inside the cycle + must emit a WARNING. fix → test → fix: fix.on_success='test' re-enters + the cycle, so the outer loop is unbounded despite the retry exit.""" recipe = Recipe( name="test", description="test", @@ -772,7 +774,8 @@ def test_bounded_cycle_with_retries_does_not_warn(self) -> None: cycle_warnings = [ f for f in findings if "cycle" in f.message.lower() or "unbounded" in f.message.lower() ] - assert not cycle_warnings, f"Expected no cycle warnings but got: {cycle_warnings}" + assert len(cycle_warnings) >= 1, "Expected a cycle WARNING but got none" + assert any(f.severity == Severity.WARNING for f in cycle_warnings) def test_truly_trapped_cycle_without_exit_produces_error(self) -> None: """A cycle where every step's edges stay inside the cycle must produce an ERROR.""" @@ -832,7 +835,11 @@ def test_scp1_prose_run_skill_warns(self) -> None: ), "Expected skill-command-missing-prefix WARNING for prose skill_command" def test_scp2_prose_run_skill_warns(self) -> None: - """SCP2: run_skill with prose skill_command → WARNING finding.""" + """SCP2: prose skill_command with on_failure step → WARNING finding. + + Distinguishing input: step has both on_success and on_failure transitions, + and skill_command is a plain prose string without /autoskillit: prefix. + """ wf = _make_workflow( { "step": { diff --git a/tests/recipe/test_rules_subset_disabled.py b/tests/recipe/test_rules_subset_disabled.py index c15b8a2fda..8f867bf0e6 100644 --- a/tests/recipe/test_rules_subset_disabled.py +++ b/tests/recipe/test_rules_subset_disabled.py @@ -43,7 +43,7 @@ def test_subset_disabled_skill_finding() -> None: from autoskillit.recipe._analysis import make_validation_context from autoskillit.recipe.registry import run_semantic_rules - recipe = _make_skill_recipe("/autoskillit:open-pr") + recipe = _make_skill_recipe("/autoskillit:prepare-pr") ctx = make_validation_context(recipe, disabled_subsets=frozenset({"github"})) findings = run_semantic_rules(ctx) disabled = [f for f in findings if f.rule == "subset-disabled-skill"] @@ -108,7 +108,7 @@ def test_disabled_subset_skill_vs_unknown_skill() -> None: from autoskillit.recipe.registry import run_semantic_rules # A known skill in disabled subset → subset-disabled-skill, not unknown-skill-command - recipe_disabled = _make_skill_recipe("/autoskillit:open-pr") + recipe_disabled = _make_skill_recipe("/autoskillit:prepare-pr") ctx1 = make_validation_context(recipe_disabled, disabled_subsets=frozenset({"github"})) findings1 = run_semantic_rules(ctx1) rule_names1 = {f.rule for f in findings1} diff --git a/tests/recipe/test_rules_tools.py b/tests/recipe/test_rules_tools.py index 740949f065..2d90741dae 100644 --- a/tests/recipe/test_rules_tools.py +++ b/tests/recipe/test_rules_tools.py @@ -262,6 +262,21 @@ def test_wait_for_ci_rejects_poll_interval() -> None: assert dead, "phantom param 'poll_interval' must trigger dead-with-param on wait_for_ci" +def test_rules_tools_batch_cleanup_clones_accepts_all_owners_param() -> None: + """T20 — batch_cleanup_clones with all_owners param must not trigger dead-with-param.""" + from autoskillit.recipe.rules_tools import _TOOL_PARAMS + + assert "all_owners" in _TOOL_PARAMS["batch_cleanup_clones"] + + recipe = _make_recipe_with_args( + "batch_cleanup_clones", + {"all_owners": "true", "registry_path": "/tmp/reg.json"}, + ) + findings = run_semantic_rules(recipe) + dead = [f for f in findings if f.rule == "dead-with-param"] + assert not dead, f"all_owners must not trigger dead-with-param: {dead}" + + # --------------------------------------------------------------------------- # rebase-then-push-requires-force rule tests (T6, T7) # --------------------------------------------------------------------------- diff --git a/tests/recipe/test_rules_verdict.py b/tests/recipe/test_rules_verdict.py index b0f29dba7b..1a5684dc73 100644 --- a/tests/recipe/test_rules_verdict.py +++ b/tests/recipe/test_rules_verdict.py @@ -8,6 +8,7 @@ from __future__ import annotations from autoskillit.core.types import Severity +from autoskillit.recipe.io import builtin_recipes_dir, load_recipe from autoskillit.recipe.schema import ( Recipe, RecipeStep, @@ -126,3 +127,19 @@ def test_unrouted_verdict_value_severity_is_error() -> None: assert finding.severity == Severity.ERROR, ( f"unrouted-verdict-value must be ERROR severity, got {finding.severity}" ) + + +def test_unrouted_verdict_passes_for_review_design_in_research_recipe() -> None: + """The unrouted-verdict-value rule must not fire for review-design in research.yaml. + + All three verdict values (GO, REVISE, STOP) have explicit on_result conditions. + This test ensures the rule exercises review-design, not just review-pr. + """ + recipe = load_recipe(builtin_recipes_dir() / "research.yaml") + findings = run_semantic_rules(recipe) + unrouted = [ + f + for f in findings + if f.rule == "unrouted-verdict-value" and f.step_name == "review_design" + ] + assert not unrouted, f"unrouted-verdict-value fired for review_design step: {unrouted}" diff --git a/tests/recipe/test_rules_worktree.py b/tests/recipe/test_rules_worktree.py index 97aaad2859..87c2653855 100644 --- a/tests/recipe/test_rules_worktree.py +++ b/tests/recipe/test_rules_worktree.py @@ -111,7 +111,7 @@ def test_retry_worktree_cwd_non_skill_step_ignored() -> None: # --------------------------------------------------------------------------- -# retries-on-worktree-creating-skill tests (new rules replacing old worktree-retry-creates-new) +# retries-on-worktree-modifying-skill tests (new rules replacing old worktree-retry-creates-new) # --------------------------------------------------------------------------- @@ -139,9 +139,9 @@ def test_retries_on_worktree_creating_skill_triggers() -> None: findings = run_semantic_rules(wf) errors = [f for f in findings if f.severity == Severity.ERROR] assert any( - f.rule == "retries-on-worktree-creating-skill" and "implement" in f.step_name + f.rule == "retries-on-worktree-modifying-skill" and "implement" in f.step_name for f in errors - ), f"Expected retries-on-worktree-creating-skill ERROR on implement step, got: {findings}" + ), f"Expected retries-on-worktree-modifying-skill ERROR on implement step, got: {findings}" def test_retries_zero_on_worktree_creating_skill_is_clean() -> None: @@ -179,8 +179,8 @@ def test_retries_zero_on_worktree_creating_skill_is_clean() -> None: ) findings = run_semantic_rules(wf) errors = [f for f in findings if f.severity == Severity.ERROR] - assert not any(f.rule == "retries-on-worktree-creating-skill" for f in errors), ( - f"Unexpected retries-on-worktree-creating-skill ERROR with retries=0: {findings}" + assert not any(f.rule == "retries-on-worktree-modifying-skill" for f in errors), ( + f"Unexpected retries-on-worktree-modifying-skill ERROR with retries=0: {findings}" ) @@ -218,7 +218,7 @@ def test_on_context_limit_on_worktree_skill_is_clean() -> None: kitchen_rules=["test"], ) findings = run_semantic_rules(wf) - assert not any(f.rule == "retries-on-worktree-creating-skill" for f in findings) + assert not any(f.rule == "retries-on-worktree-modifying-skill" for f in findings) # --------------------------------------------------------------------------- @@ -531,3 +531,107 @@ def test_crw5_bundled_recipes_pass_clone_root_rule(self) -> None: findings = run_semantic_rules(recipe) crw = [f for f in findings if f.rule == "clone-root-as-worktree"] assert crw == [], f"{yaml_path.name} triggered clone-root-as-worktree: {crw}" + + +# --------------------------------------------------------------------------- +# _WORKTREE_MODIFYING_SKILLS membership guard +# --------------------------------------------------------------------------- + + +def test_worktree_modifying_skills_includes_experiment() -> None: + """_WORKTREE_MODIFYING_SKILLS must include implement-experiment. + + implement-experiment creates a worktree and emits early tokens; excluding it + means recipes using it without on_context_limit silently bypass the + missing-context-limit-on-worktree rule. + """ + from autoskillit.recipe.rules_worktree import _WORKTREE_MODIFYING_SKILLS + + assert "implement-experiment" in _WORKTREE_MODIFYING_SKILLS, ( + "_WORKTREE_MODIFYING_SKILLS must include implement-experiment so that the " + "missing-context-limit-on-worktree rule fires for recipes using it without " + "on_context_limit." + ) + + +# --------------------------------------------------------------------------- +# file-writing-skill-missing-context-limit rule tests +# --------------------------------------------------------------------------- + + +def test_file_writing_skill_missing_context_limit_fires() -> None: + """run_skill step with write_behavior=always and no on_context_limit → WARNING. + + Uses generate-report which has write_behavior=always in the bundled manifest. + """ + wf = _make_workflow( + { + "report": { + "tool": "run_skill", + "with": { + "skill_command": "/autoskillit:generate-report /tmp/wt /tmp/results.json" + }, + "on_success": "done", + "on_failure": "done", + # on_context_limit deliberately absent + }, + "done": {"action": "stop", "message": "Done."}, + } + ) + findings = run_semantic_rules(wf) + assert any(f.rule == "file-writing-skill-missing-context-limit" for f in findings), ( + f"Expected file-writing-skill-missing-context-limit WARNING for generate-report " + f"step (write_behavior=always) without on_context_limit. Got: {findings}" + ) + matched = next(f for f in findings if f.rule == "file-writing-skill-missing-context-limit") + assert matched.severity == Severity.WARNING + + +def test_file_writing_skill_with_context_limit_no_warning() -> None: + """run_skill step with write_behavior=always and on_context_limit set → no warning.""" + wf = _make_workflow( + { + "report": { + "tool": "run_skill", + "with": { + "skill_command": "/autoskillit:generate-report /tmp/wt /tmp/results.json" + }, + "on_context_limit": "done", + "on_success": "done", + "on_failure": "done", + }, + "done": {"action": "stop", "message": "Done."}, + } + ) + findings = run_semantic_rules(wf) + assert not any(f.rule == "file-writing-skill-missing-context-limit" for f in findings), ( + f"Unexpected file-writing-skill-missing-context-limit finding when " + f"on_context_limit is set: {findings}" + ) + + +def test_file_writing_skill_advisory_step_not_flagged() -> None: + """run_skill step with skip_when_false (advisory) is NOT flagged by this rule. + + Advisory steps are already covered by advisory-step-missing-context-limit. + """ + wf = _make_workflow( + { + "report": { + "tool": "run_skill", + "with": { + "skill_command": "/autoskillit:generate-report /tmp/wt /tmp/results.json" + }, + "skip_when_false": "inputs.run_report", + "on_success": "done", + "on_failure": "done", + # on_context_limit absent but advisory → should not fire this rule + }, + "done": {"action": "stop", "message": "Done."}, + } + ) + findings = run_semantic_rules(wf) + assert not any(f.rule == "file-writing-skill-missing-context-limit" for f in findings), ( + f"Advisory steps (skip_when_false) should not trigger " + f"file-writing-skill-missing-context-limit: {findings}" + ) diff --git a/tests/recipe/test_schema.py b/tests/recipe/test_schema.py index be8608de8f..505de2efae 100644 --- a/tests/recipe/test_schema.py +++ b/tests/recipe/test_schema.py @@ -288,3 +288,12 @@ def test_terminal_targets_defined_in_schema(): assert "escalate" in _TERMINAL_TARGETS assert "done" in _TERMINAL_TARGETS + + +def test_recipe_dataclass_has_requires_packs_field(): + from autoskillit.recipe.schema import Recipe + + fields = {f.name for f in dataclasses.fields(Recipe)} + assert "requires_packs" in fields + r = Recipe(name="x", description="y") + assert r.requires_packs == [] diff --git a/tests/recipe/test_smoke_pipeline.py b/tests/recipe/test_smoke_pipeline.py index 9a16ee9270..9820b38057 100644 --- a/tests/recipe/test_smoke_pipeline.py +++ b/tests/recipe/test_smoke_pipeline.py @@ -1,188 +1,33 @@ """Smoke-test pipeline: structural validation and end-to-end execution tests. -Exercises the full orchestration path: script loading, step routing, tool -dispatch, capture/context threading, retry logic, bugfix loop pattern, and merge. +The smoke-test recipe is a lightweight end-to-end sanity check that clones the +repository, creates an isolated branch, implements a trivial micro-task +(smoke_canary), runs the full project test suite, pushes to remote, opens a +GitHub PR, and immediately closes it without merging. **Running tests:** - Structural tests (no API): ``task test-all`` (included automatically) -- Smoke execution test (requires API): ``task test-smoke`` - - Requires ``ANTHROPIC_API_KEY`` in the environment - - Expected duration: ~60-90 seconds +- Smoke execution test (requires API + GitHub auth): ``task test-smoke`` + - Requires ``ANTHROPIC_API_KEY`` and authenticated ``gh`` CLI + - Expected duration: under 10 minutes - Excluded from ``task test-all`` to avoid API costs in routine development """ from __future__ import annotations -import asyncio import json import os import re -import subprocess from pathlib import Path -from unittest.mock import patch import pytest -import yaml -from autoskillit import server -from autoskillit.config import AutomationConfig, TestCheckConfig from autoskillit.recipe.io import builtin_recipes_dir -from autoskillit.server.tools_execution import run_cmd, run_python, run_skill -from autoskillit.server.tools_git import classify_fix, merge_worktree -from autoskillit.server.tools_recipe import list_recipes, load_recipe, validate_recipe -from autoskillit.server.tools_workspace import test_check - -test_check.__test__ = False # type: ignore[attr-defined] +from autoskillit.server.tools_recipe import list_recipes, validate_recipe PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent -SMOKE_SCRIPT = builtin_recipes_dir() / "smoke-test.yaml" - -_TOOL_MAP = { - "run_cmd": run_cmd, - "run_skill": run_skill, - "test_check": test_check, - "merge_worktree": merge_worktree, - "classify_fix": classify_fix, -} - - -class SmokeExecutor: - """Minimal pipeline executor for smoke-test validation. - - Parses YAML step definitions, interpolates context variables, dispatches - to server tools, captures results, and routes based on success/failure/on_result. - """ - - def __init__(self, steps: dict, inputs: dict) -> None: - self.steps = steps - self.inputs = inputs - self.context: dict[str, str] = {} - self.visited: list[str] = [] - - async def run(self, start: str = "setup", max_steps: int = 30) -> tuple[str | None, str]: - """Execute the pipeline from *start*, returning (terminal_step, message).""" - current: str | None = start - for _ in range(max_steps): - if current is None: - return None, "Routing returned None — pipeline stalled." - self.visited.append(current) - step_def = self.steps[current] - - if step_def.get("action") == "stop": - return current, step_def.get("message", "") - - if step_def.get("action") == "route": - current = step_def.get("on_success") - continue - - if "python" in step_def: - result = await self._execute_python(step_def) - current = self._route(step_def, result) - continue - - result = await self._execute(step_def) - self._capture(step_def, result) - current = self._route(step_def, result) - return None, "Max steps exceeded." - - async def _execute(self, step_def: dict) -> dict: - """Dispatch to the appropriate tool, handling retries.""" - tool_name = step_def["tool"] - raw_args = step_def.get("with", {}) - args = self._interpolate(raw_args) - - if "retries" in step_def: - return await self._run_with_retry(step_def, args) - - tool_fn = _TOOL_MAP[tool_name] - raw_result = await tool_fn(**args) - return json.loads(raw_result) - - async def _execute_python(self, step_def: dict) -> dict: - """Dispatch a python: step to the run_python MCP tool.""" - raw_args = step_def.get("with", {}) - args = self._interpolate(raw_args) - callable_path = step_def["python"] - raw_result = await run_python(callable=callable_path, args=args) - return json.loads(raw_result) - - async def _run_with_retry(self, step_def: dict, args: dict) -> dict: - """Execute a tool with retry logic using the flat retries: schema.""" - max_retries = step_def.get("retries", 0) - tool_fn = _TOOL_MAP[step_def["tool"]] - - raw_result = await tool_fn(**args) - result = json.loads(raw_result) - if self._is_success(step_def, result): - return result - - for _ in range(max_retries): - raw_result = await tool_fn(**args) - result = json.loads(raw_result) - if self._is_success(step_def, result): - return result - - result["_retries_exhausted"] = True - return result - - def _interpolate(self, with_args: dict) -> dict: - """Resolve ${{ inputs.X }} and ${{ context.X }} references.""" - resolved = {} - for key, value in with_args.items(): - if isinstance(value, str): - resolved[key] = re.sub( - r"\$\{\{\s*(inputs|context)\.(\w+)\s*\}\}", - lambda m: (self.inputs if m.group(1) == "inputs" else self.context)[ - m.group(2) - ], - value, - ) - else: - resolved[key] = value - return resolved - - def _capture(self, step_def: dict, result: dict) -> None: - """Extract key=value pairs from result text into context.""" - capture = step_def.get("capture", {}) - if not capture: - return - result_text = result.get("result", "") - if isinstance(result_text, str): - for ctx_key, pattern in capture.items(): - match = re.search(r"\$\{\{\s*result\.(\w+)\s*\}\}", pattern) - if match: - field = match.group(1) - kv_match = re.search(rf"(?:^|\n)\s*{field}\s*[=:]\s*(.+)", result_text) - if kv_match: - self.context[ctx_key] = kv_match.group(1).strip() - - def _route(self, step_def: dict, result: dict) -> str | None: - """Determine the next step based on result and routing rules.""" - if "on_result" in step_def: - on_result = step_def["on_result"] - field = on_result["field"] - value = result.get(field) - routes = on_result.get("routes", {}) - if value in routes: - return routes[value] - return step_def.get("on_failure") - - if step_def.get("on_exhausted") and result.get("_retries_exhausted"): - return step_def["on_exhausted"] - - if self._is_success(step_def, result): - return step_def.get("on_success") - return step_def.get("on_failure") - - def _is_success(self, step_def: dict, result: dict) -> bool: - """Tool-specific success predicate.""" - tool = step_def["tool"] - if tool == "test_check": - return result.get("passed", False) - if tool in ("merge_worktree", "classify_fix"): - return "error" not in result - return result.get("success", True) +SMOKE_SCRIPT = PROJECT_ROOT / ".autoskillit" / "recipes" / "smoke-test.yaml" # --------------------------------------------------------------------------- @@ -194,7 +39,7 @@ def _is_success(self, step_def: dict, result: dict) -> bool: def smoke_recipe(): from autoskillit.recipe.io import load_recipe as _load_recipe - return _load_recipe(builtin_recipes_dir() / "smoke-test.yaml") + return _load_recipe(SMOKE_SCRIPT) @pytest.fixture() @@ -204,45 +49,27 @@ def smoke_script_path() -> Path: @pytest.fixture() def smoke_project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: - """Create a temp project dir for smoke tests. + """Create a temp project dir with smoke-test as a project-local recipe. - Bundled recipes (including smoke-test) are discovered via recipe_parser, - so no recipe files need to be copied into the project dir. + smoke-test is a project-local recipe (not bundled), so it must be copied + into the temp dir's .autoskillit/recipes/ for discovery via list_recipes(). """ + import shutil + + recipes_dir = tmp_path / ".autoskillit" / "recipes" + recipes_dir.mkdir(parents=True) + shutil.copy2(SMOKE_SCRIPT, recipes_dir / "smoke-test.yaml") monkeypatch.chdir(tmp_path) return tmp_path -@pytest.fixture() -def smoke_workspace(tmp_path: Path) -> Path: - ws = tmp_path / "smoke_ws" - ws.mkdir() - env = { - **os.environ, - "GIT_AUTHOR_NAME": "test", - "GIT_AUTHOR_EMAIL": "t@t", - "GIT_COMMITTER_NAME": "test", - "GIT_COMMITTER_EMAIL": "t@t", - } - subprocess.run(["git", "init", "-b", "main"], cwd=ws, check=True, capture_output=True) - subprocess.run( - ["git", "commit", "--allow-empty", "-m", "initial"], - cwd=ws, - check=True, - capture_output=True, - env=env, - ) - (ws / ".autoskillit-workspace").touch() - return ws - - # --------------------------------------------------------------------------- # Structural Validation Tests (no API required) # --------------------------------------------------------------------------- class TestSmokeScriptValidation: - """Validate the smoke-test pipeline YAML structure and executor logic.""" + """Validate the smoke-test pipeline YAML structure.""" @pytest.fixture(autouse=True) def _setup_ctx(self, tool_ctx): @@ -263,154 +90,210 @@ async def test_script_discoverable(self, smoke_project: Path) -> None: names = [s["name"] for s in result["recipes"]] assert "smoke-test" in names - async def test_script_loads_with_expected_structure(self, smoke_project: Path) -> None: - result = json.loads(await load_recipe(name="smoke-test")) - assert "content" in result - assert "suggestions" in result - pipeline = yaml.safe_load(result["content"]) - assert "steps" in pipeline - assert "ingredients" in pipeline - assert "kitchen_rules" in pipeline - assert pipeline["steps"]["setup"]["tool"] == "run_cmd" - assert pipeline["steps"]["investigate"]["tool"] == "run_skill" - assert pipeline["steps"]["implement"]["tool"] == "run_skill" - assert pipeline["steps"]["test"]["tool"] == "test_check" - assert pipeline["steps"]["merge"]["tool"] == "merge_worktree" - assert pipeline["steps"]["classify"]["tool"] == "classify_fix" - assert pipeline["steps"]["create_branch"]["tool"] == "run_cmd" - assert ( - pipeline["steps"]["check_summary"]["python"] - == "autoskillit.smoke_utils.check_bug_report_non_empty" - ) - assert pipeline["steps"]["create_summary"]["tool"] == "run_skill" + def test_smoke_test_not_in_bundled_dir(self) -> None: + """smoke-test.yaml must not exist in the bundled recipes directory.""" + assert not (builtin_recipes_dir() / "smoke-test.yaml").exists() - def test_executor_interpolation(self) -> None: - executor = SmokeExecutor(steps={}, inputs={"workspace": "/tmp/ws"}) - executor.context["plan_path"] = "/tmp/ws/plan.md" - result = executor._interpolate( - {"cwd": "${{ inputs.workspace }}", "path": "${{ context.plan_path }}"} - ) - assert result == {"cwd": "/tmp/ws", "path": "/tmp/ws/plan.md"} - - def test_executor_routing_success_failure(self) -> None: - executor = SmokeExecutor(steps={}, inputs={}) - step = {"tool": "run_cmd", "on_success": "next", "on_failure": "escalate"} - assert executor._route(step, {"success": True}) == "next" - assert executor._route(step, {"success": False}) == "escalate" - - def test_executor_routing_on_result(self) -> None: - executor = SmokeExecutor(steps={}, inputs={}) - step = { - "tool": "classify_fix", - "on_result": { - "field": "restart_scope", - "routes": { - "full_restart": "investigate", - "partial_restart": "implement", - }, - }, - "on_failure": "escalate", - } - assert executor._route(step, {"restart_scope": "full_restart"}) == "investigate" - assert executor._route(step, {"restart_scope": "partial_restart"}) == "implement" - - def test_executor_capture(self) -> None: - executor = SmokeExecutor(steps={}, inputs={}) - step = {"capture": {"plan_path": "${{ result.plan_path }}"}} - result = {"success": True, "result": "Done.\nplan_path=/tmp/ws/plan.md\n"} - executor._capture(step, result) - assert executor.context["plan_path"] == "/tmp/ws/plan.md" - - async def test_executor_retry_logic(self) -> None: - call_count = 0 - - async def mock_run_skill(**kwargs: object) -> str: - nonlocal call_count - call_count += 1 - if call_count == 1: - return json.dumps( - {"success": False, "needs_retry": True, "result": "context full"} - ) - return json.dumps( - {"success": True, "needs_retry": False, "result": "worktree_path=/tmp/wt"} - ) + def test_smoke_test_exists_in_project_local(self) -> None: + """smoke-test.yaml must exist in the project-local recipes directory.""" + assert SMOKE_SCRIPT.exists(), f"Expected smoke-test at {SMOKE_SCRIPT}" - step_def = { - "tool": "run_skill", - "with": {"skill_command": "test", "cwd": "/tmp"}, - "retries": 3, - "on_exhausted": "escalate", - } - executor = SmokeExecutor(steps={}, inputs={}) - with patch.dict(_TOOL_MAP, {"run_skill": mock_run_skill}): - result = await executor._execute(step_def) - assert call_count == 2 - assert result["success"] is True - - async def test_executor_max_attempts_zero_routes_to_on_exhausted(self) -> None: - """With retries=0, the first failure must route to on_exhausted.""" - steps = { - "implement": { - "tool": "run_skill", - "with": {"skill_command": "/autoskillit:implement-worktree-no-merge plan.md"}, - "retries": 0, - "on_exhausted": "retry_wt", - "capture": {"worktree_path": "${{ result.worktree_path }}"}, - "on_success": "done", - "on_failure": "done", - }, - "retry_wt": {"action": "stop", "message": "reached retry_wt"}, - "done": {"action": "stop", "message": "reached done"}, - } - call_log: list[dict] = [] - - async def mock_run_skill(**kwargs: object) -> str: - call_log.append(dict(kwargs)) - return json.dumps( - { - "success": False, - "needs_retry": True, - "result": "context limit", - "retry_reason": "resume", - "session_id": "", - "subtype": "error_max_turns", - "is_error": True, - "exit_code": -1, - "stderr": "", - "token_usage": None, - } - ) + async def test_smoke_test_source_is_project(self, smoke_project: Path) -> None: + """smoke-test must be listed with source PROJECT, not BUILTIN.""" + result = json.loads(await list_recipes()) + smoke = next((r for r in result["recipes"] if r["name"] == "smoke-test"), None) + assert smoke is not None, "smoke-test not found in list_recipes output" + assert smoke["source"] == "project" + + async def test_smoke_test_invisible_from_external_project( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """smoke-test must NOT appear in list_recipes from a project without it.""" + bare_dir = tmp_path / "external" + bare_dir.mkdir() + monkeypatch.chdir(bare_dir) + result = json.loads(await list_recipes()) + names = [r["name"] for r in result["recipes"]] + assert "smoke-test" not in names - with patch.dict(_TOOL_MAP, {"run_skill": mock_run_skill}): - executor = SmokeExecutor(steps, inputs={}) - terminal_step, message = await executor.run(start="implement") - assert len(call_log) == 1, "Tool must be called exactly once with max_attempts=0" - assert terminal_step == "retry_wt", ( - f"Expected on_exhausted route to 'retry_wt', got '{terminal_step}': {message}" +# --------------------------------------------------------------------------- +# New structural tests for rewritten recipe (T_SP_NEW_1 through T_SP_NEW_12+) +# --------------------------------------------------------------------------- + + +# T_SP_NEW_1 +def test_required_lifecycle_steps_present(smoke_recipe) -> None: + """All new lifecycle steps must exist in the recipe.""" + required = { + "clone", + "create_branch", + "setup", + "implement_task", + "run_tests", + "push_branch", + "create_pr", + "close_pr", + "delete_remote_branch", + "register_clone_success", + "fail_delete_remote_branch", + "register_clone_failure", + "done", + "escalate", + } + missing = required - set(smoke_recipe.steps) + assert not missing, f"Missing steps: {missing}" + + +# T_SP_NEW_2 +def test_no_merge_worktree_step(smoke_recipe) -> None: + """REQ-GUARD-001: No step may use the merge_worktree tool.""" + for name, step in smoke_recipe.steps.items(): + assert step.tool != "merge_worktree", ( + f"Step '{name}' uses merge_worktree — REQ-GUARD-001 violation" ) - async def test_script_has_collect_on_branch_input(self, smoke_project: Path) -> None: - result = json.loads(await load_recipe(name="smoke-test")) - pipeline = yaml.safe_load(result["content"]) - inputs = pipeline["ingredients"] - assert "collect_on_branch" in inputs - assert inputs["collect_on_branch"]["default"] == "true" - assert "original_base_branch" in inputs - assert inputs["original_base_branch"]["default"] == "main" - - async def test_assess_step_references_bug_report(self) -> None: - pipeline = yaml.safe_load(SMOKE_SCRIPT.read_text()) - assess_cmd = pipeline["steps"]["assess"]["with"]["skill_command"] - assert "bug_report.json" in assess_cmd - - -def test_smoke_commit_dirty_step_exists(smoke_recipe) -> None: - """commit_dirty step must exist and route back to merge.""" - assert "commit_dirty" in smoke_recipe.steps - step = smoke_recipe.steps["commit_dirty"] + +# T_SP_NEW_3 +def test_no_legacy_pipeline_steps(smoke_recipe) -> None: + """Old investigate/rectify/assess/classify/merge steps must be absent.""" + legacy = {"investigate", "rectify", "assess", "classify", "merge"} + present = legacy & set(smoke_recipe.steps) + assert not present, f"Legacy steps still present: {present}" + + +# T_SP_NEW_4 +def test_implement_task_references_smoke_canary(smoke_recipe) -> None: + """REQ-TASK-001: implement_task skill_command must reference smoke_canary.""" + step = smoke_recipe.steps["implement_task"] + cmd = step.with_args.get("skill_command", "") + assert "smoke_canary" in cmd, "implement_task must describe the smoke_canary micro-task" + + +# T_SP_NEW_5 +def test_create_pr_step_uses_gh_pr_create(smoke_recipe) -> None: + """REQ-PIPE-003: create_pr step must invoke gh pr create.""" + step = smoke_recipe.steps["create_pr"] + assert step.tool == "run_cmd" + assert "gh pr create" in step.with_args.get("cmd", "") + + +# T_SP_NEW_6 +def test_close_pr_step_uses_gh_pr_close(smoke_recipe) -> None: + """REQ-PIPE-004: close_pr step must invoke gh pr close.""" + step = smoke_recipe.steps["close_pr"] assert step.tool == "run_cmd" - assert step.on_success == "merge" + assert "gh pr close" in step.with_args.get("cmd", "") + + +# T_SP_NEW_7 +def test_close_pr_routes_to_delete_remote_branch_on_both_outcomes(smoke_recipe) -> None: + """REQ-GUARD-002: cleanup must be reached regardless of close_pr result.""" + step = smoke_recipe.steps["close_pr"] + assert step.on_success == "delete_remote_branch" + assert step.on_failure == "delete_remote_branch" + + +# T_SP_NEW_8 +def test_delete_remote_branch_routes_to_register_clone_success(smoke_recipe) -> None: + """delete_remote_branch is non-critical — routes to register_clone_success.""" + step = smoke_recipe.steps["delete_remote_branch"] + assert step.on_success == "register_clone_success" + assert step.on_failure == "register_clone_success" + + +# T_SP_NEW_9 +def test_register_clone_failure_routes_to_escalate(smoke_recipe) -> None: + """register_clone_failure preserves failure semantics — must route to escalate.""" + step = smoke_recipe.steps["register_clone_failure"] + assert step.on_success == "escalate" + assert step.on_failure == "escalate" + + +# T_SP_NEW_10 +def test_test_step_routes_to_fail_delete_on_failure(smoke_recipe) -> None: + """REQ-GUARD-002: test failure must clean up before escalating.""" + step = smoke_recipe.steps["run_tests"] + assert step.tool == "run_cmd" + assert "task test-check" in step.with_args.get("cmd", "") + assert step.on_failure == "fail_delete_remote_branch" + + +# T_SP_NEW_11 +def test_recipe_has_no_collect_on_branch_ingredient(smoke_recipe) -> None: + """Old collect_on_branch complexity is gone — ingredient must be absent.""" + assert "collect_on_branch" not in smoke_recipe.ingredients + + +# T_SP_NEW_12 +def test_done_and_escalate_are_stop_actions(smoke_recipe) -> None: + """Both terminal steps must have action=stop.""" + assert smoke_recipe.steps["done"].action == "stop" + assert smoke_recipe.steps["escalate"].action == "stop" + + +# T_SP_NEW_13 +def test_clone_step_is_first_and_uses_clone_repo(smoke_recipe) -> None: + """The first step must be clone using clone_repo tool.""" + first_step_name = next(iter(smoke_recipe.steps)) + assert first_step_name == "clone" + step = smoke_recipe.steps["clone"] + assert step.tool == "clone_repo" + assert step.with_args["source_dir"] == "${{ inputs.source_dir }}" + + +# T_SP_NEW_14 +def test_push_branch_uses_push_to_remote(smoke_recipe) -> None: + """push_branch must use push_to_remote tool (not run_cmd git push).""" + step = smoke_recipe.steps["push_branch"] + assert step.tool == "push_to_remote" + assert step.with_args["clone_path"] == "${{ context.work_dir }}" + assert step.with_args["branch"] == "${{ context.branch_name }}" + assert step.with_args["remote_url"] == "${{ context.remote_url }}" + + +# T_SP_NEW_15 +def test_ingredient_renamed_to_source_dir(smoke_recipe) -> None: + """Ingredient must be source_dir, not workspace.""" + assert "source_dir" in smoke_recipe.ingredients + assert "workspace" not in smoke_recipe.ingredients + + +# T_SP_NEW_16 +def test_register_clone_success_routes_to_done(smoke_recipe) -> None: + """register_clone_success must route to done.""" + step = smoke_recipe.steps["register_clone_success"] + assert step.tool == "register_clone_status" + assert step.on_success == "done" + assert step.on_failure == "done" + + +# T_SP_NEW_17 +def test_no_step_uses_inputs_as_cwd_after_clone(smoke_recipe) -> None: + """No step after clone should use inputs.* as cwd.""" + input_re = re.compile(r"\$\{\{\s*inputs\.\w+\s*\}\}") + seen_clone = False + for name, step in smoke_recipe.steps.items(): + if step.tool == "clone_repo": + seen_clone = True + continue + if seen_clone and step.with_args: + cwd = step.with_args.get("cwd", "") + assert not input_re.search(cwd), ( + f"Step '{name}' uses inputs.* as cwd after clone: {cwd}" + ) + + +# T_SP_NEW_18 +def test_smoke_recipe_passes_isolation_rules(smoke_recipe) -> None: + """Smoke recipe must pass all isolation semantic rules.""" + from autoskillit.recipe.validator import run_semantic_rules + + findings = run_semantic_rules(smoke_recipe) + isolation_findings = [ + f for f in findings if f.rule in ("source-isolation-violation", "git-mutation-on-source") + ] + assert isolation_findings == [] # --------------------------------------------------------------------------- @@ -419,39 +302,11 @@ def test_smoke_commit_dirty_step_exists(smoke_recipe) -> None: class TestSmokePipelineExecution: - """Full end-to-end pipeline execution with real API calls. + """Full end-to-end smoke execution. - Skipped unless SMOKE_TEST=1 is set (``task test-smoke`` sets this). + Run via ``task test-smoke`` which sets SMOKE_TEST=1 and invokes the + recipe against the actual project repository. This class is a + documentation anchor — the execution itself uses `autoskillit cook`. """ pytestmark = pytest.mark.skipif(not os.environ.get("SMOKE_TEST"), reason="SMOKE_TEST not set") - - @pytest.fixture(autouse=True) - def _smoke_config(self, monkeypatch: pytest.MonkeyPatch) -> None: - cfg = AutomationConfig( - test_check=TestCheckConfig(command=["python", "-c", "pass"], timeout=30), - ) - monkeypatch.setattr(server, "_config", cfg) - - async def _run_pipeline(self, workspace: Path, script_path: Path) -> tuple[str | None, str]: - raw = script_path.read_text() - pipeline = yaml.safe_load(raw) - executor = SmokeExecutor( - steps=pipeline["steps"], - inputs={ - "workspace": str(workspace), - "base_branch": "main", - "collect_on_branch": "true", - "original_base_branch": "main", - }, - ) - terminal, message = await executor.run() - return terminal, message - - @pytest.mark.smoke - async def test_happy_path(self, smoke_workspace: Path, smoke_script_path: Path) -> None: - terminal, _message = await asyncio.wait_for( - self._run_pipeline(smoke_workspace, smoke_script_path), - timeout=180, - ) - assert terminal == "done" diff --git a/tests/recipe/test_validator.py b/tests/recipe/test_validator.py index ba95c303bc..aa321648ab 100644 --- a/tests/recipe/test_validator.py +++ b/tests/recipe/test_validator.py @@ -36,12 +36,6 @@ def test_valid_recipe_no_errors(self, tmp_path: Path) -> None: errors = validate_recipe(wf) assert errors == [] - def test_missing_name_produces_error(self) -> None: - data = {**VALID_RECIPE, "name": ""} - wf = _parse_recipe(data) - errors = validate_recipe(wf) - assert any("name" in e.lower() for e in errors) - # WF2 def test_recipe_requires_name(self, tmp_path: Path) -> None: data = {**VALID_RECIPE, "name": ""} @@ -373,6 +367,67 @@ def test_version_does_not_cause_validation_errors(self) -> None: errors = validate_recipe(wf) assert errors == [] + def test_validator_rejects_zero_stale_threshold(self) -> None: + recipe = Recipe( + name="test", + description="test", + steps={"s": RecipeStep(tool="run_skill", on_success="done", stale_threshold=0)}, + kitchen_rules=["test"], + ) + errors = validate_recipe(recipe) + assert any("stale_threshold" in e for e in errors) + + def test_validator_rejects_negative_stale_threshold(self) -> None: + recipe = Recipe( + name="test", + description="test", + steps={"s": RecipeStep(tool="run_skill", on_success="done", stale_threshold=-1)}, + kitchen_rules=["test"], + ) + errors = validate_recipe(recipe) + assert any("stale_threshold" in e for e in errors) + + def test_validator_accepts_positive_stale_threshold(self) -> None: + recipe = Recipe( + name="test", + description="test", + steps={"s": RecipeStep(tool="run_skill", on_success="done", stale_threshold=2400)}, + kitchen_rules=["test"], + ) + errors = validate_recipe(recipe) + assert not any("stale_threshold" in e for e in errors) + + def test_validator_rejects_negative_idle_output_timeout(self) -> None: + recipe = Recipe( + name="test", + description="test", + steps={"s": RecipeStep(tool="run_skill", on_success="done", idle_output_timeout=-1)}, + kitchen_rules=["test"], + ) + errors = validate_recipe(recipe) + assert any("idle_output_timeout" in e for e in errors) + + def test_validator_accepts_zero_idle_output_timeout(self) -> None: + # 0 = disabled, must NOT be rejected + recipe = Recipe( + name="test", + description="test", + steps={"s": RecipeStep(tool="run_skill", on_success="done", idle_output_timeout=0)}, + kitchen_rules=["test"], + ) + errors = validate_recipe(recipe) + assert not any("idle_output_timeout" in e for e in errors) + + def test_validator_accepts_positive_idle_output_timeout(self) -> None: + recipe = Recipe( + name="test", + description="test", + steps={"s": RecipeStep(tool="run_skill", on_success="done", idle_output_timeout=120)}, + kitchen_rules=["test"], + ) + errors = validate_recipe(recipe) + assert not any("idle_output_timeout" in e for e in errors) + # --------------------------------------------------------------------------- # TestDataFlowQuality — migrated from test_recipe_parser.py @@ -586,6 +641,9 @@ def test_gv1_validate_recipe_no_raise_on_bool_with_arg(self) -> None: recipe = _parse_recipe(data) result = validate_recipe(recipe) assert isinstance(result, list) + assert not any("dead" in str(f).lower() for f in result), ( + "DEAD_OUTPUT rule fired on a valid recipe — false positive" + ) # --------------------------------------------------------------------------- diff --git a/tests/server/_helpers.py b/tests/server/_helpers.py new file mode 100644 index 0000000000..665b636c13 --- /dev/null +++ b/tests/server/_helpers.py @@ -0,0 +1,34 @@ +"""Shared test builder utilities for tests/server/.""" + +from __future__ import annotations + +from autoskillit.core import SkillResult +from autoskillit.core.types import RetryReason + + +def _skill_ok(report_text: str = "## Bug Report\ndetails") -> SkillResult: + return SkillResult( + success=True, + result=report_text, + session_id="sid", + subtype="success", + is_error=False, + exit_code=0, + needs_retry=False, + retry_reason=RetryReason.NONE, + stderr="", + ) + + +def _skill_fail() -> SkillResult: + return SkillResult( + success=False, + result="", + session_id="", + subtype="error", + is_error=True, + exit_code=1, + needs_retry=False, + retry_reason=RetryReason.NONE, + stderr="something went wrong", + ) diff --git a/tests/server/conftest.py b/tests/server/conftest.py new file mode 100644 index 0000000000..6338ccb00a --- /dev/null +++ b/tests/server/conftest.py @@ -0,0 +1,25 @@ +"""Shared fixtures for tests/server/.""" + +from __future__ import annotations + +import pytest + + +@pytest.fixture() +def kitchen_enabled(): + """Enable the kitchen tag on the MCP server for the duration of the test.""" + from autoskillit.server import mcp + + mcp.enable(tags={"kitchen"}) + yield + mcp.disable(tags={"kitchen"}) + + +@pytest.fixture() +def headless_enabled(): + """Enable the headless tag on the MCP server for the duration of the test.""" + from autoskillit.server import mcp + + mcp.enable(tags={"headless"}) + yield + mcp.disable(tags={"headless"}) diff --git a/tests/server/test_factory.py b/tests/server/test_factory.py index 77215169de..a5301dbf4f 100644 --- a/tests/server/test_factory.py +++ b/tests/server/test_factory.py @@ -4,6 +4,8 @@ from pathlib import Path +import pytest + from autoskillit.config import AutomationConfig from autoskillit.core.types import SkillResult, SubprocessResult, TerminationReason from autoskillit.execution.db import DefaultDatabaseReader @@ -18,7 +20,7 @@ resolve_skill_name, ) from autoskillit.recipe.repository import DefaultRecipeRepository -from autoskillit.server._factory import _gh_cli_token, make_context +from autoskillit.server._factory import TokenFactory, _gh_cli_token, make_context from autoskillit.workspace import DefaultCloneManager, SkillResolver from autoskillit.workspace.cleanup import DefaultWorkspaceManager from tests.conftest import MockSubprocessRunner @@ -41,6 +43,8 @@ def _runner() -> MockSubprocessRunner: def test_make_context_returns_toolcontext(): ctx = make_context(AutomationConfig(), runner=_runner()) assert isinstance(ctx, ToolContext) + assert ctx.gate is not None + assert ctx.runner is not None def test_make_context_gate_starts_closed(monkeypatch): @@ -122,7 +126,8 @@ def test_make_context_github_client_config_token_takes_priority_over_gh_cli(monk config.github.token = "config-token" ctx = make_context(config, runner=None, plugin_dir=".") assert ctx.github_client.has_token is True - assert ctx.github_client._token == "config-token" + # After lazy resolution via has_token, verify the resolved value + assert ctx.github_client._resolve_token() == "config-token" def test_make_context_github_client_token_snapshot_is_immutable(monkeypatch): @@ -230,6 +235,62 @@ def test_write_expected_resolver_conditional_skill() -> None: assert len(spec.expected_when) > 0 +@pytest.mark.parametrize( + "invocation,expected_mode,required_tokens", + [ + ( + "/autoskillit:resolve-failures /tmp/wt .autoskillit/temp/plan.md main", + "conditional", + ["verdict"], + ), + ( + "/autoskillit:retry-worktree .autoskillit/temp/plan.md /tmp/wt", + "conditional", + ["phases_implemented"], + ), + ( + "/autoskillit:resolve-review feature-branch main", + "conditional", + ["verdict"], + ), + ( + "/autoskillit:audit-claims /tmp/wt main https://github.com/o/r/pull/1", + None, + [], + ), + ( + "/autoskillit:review-research-pr /tmp/wt main https://github.com/o/r/pull/1", + None, + [], + ), + ( + "/autoskillit:resolve-claims-review /tmp/wt main", + "conditional", + ["verdict"], + ), + ( + "/autoskillit:resolve-research-review /tmp/wt main", + "conditional", + ["verdict"], + ), + ], +) +def test_write_expected_resolver_mode( + invocation: str, expected_mode: str | None, required_tokens: list[str] +) -> None: + """write_expected_resolver returns the correct mode and token patterns per skill.""" + ctx = make_context(AutomationConfig(), runner=_runner()) + assert ctx.write_expected_resolver is not None + spec = ctx.write_expected_resolver(invocation) + assert spec.mode == expected_mode + if expected_mode is None: + assert spec.expected_when == () + else: + assert len(spec.expected_when) > 0 + for token in required_tokens: + assert any(token in p for p in spec.expected_when) + + def test_cook_and_factory_session_skill_manager_ctor_args_in_sync() -> None: """Sync test: _cook.py and _factory.py must call DefaultSessionSkillManager with the same number of positional arguments. @@ -306,3 +367,94 @@ def fake_run(cmd, *, capture_output, text, timeout): monkeypatch.setattr("autoskillit.server._factory.subprocess.run", fake_run) assert _gh_cli_token() is None + + +# --------------------------------------------------------------------------- +# TokenFactory unit tests +# --------------------------------------------------------------------------- + + +def test_token_factory_resolves_lazily(): + """TokenFactory must not resolve until first call, then cache.""" + call_count = 0 + + def _resolver(): + nonlocal call_count + call_count += 1 + return "ghp_test_token" + + factory = TokenFactory(_resolver) + assert call_count == 0, "TokenFactory resolved eagerly at construction" + assert not factory.is_resolved + + token = factory() + assert token == "ghp_test_token" + assert call_count == 1 + assert factory.is_resolved + + # Second call uses cache + token2 = factory() + assert token2 == "ghp_test_token" + assert call_count == 1, "TokenFactory resolved twice instead of caching" + + +def test_token_factory_caches_none(): + """TokenFactory caches None results (gh CLI not available).""" + call_count = 0 + + def _resolver(): + nonlocal call_count + call_count += 1 + return None + + factory = TokenFactory(_resolver) + assert factory() is None + assert call_count == 1 + assert factory() is None + assert call_count == 1, "TokenFactory resolved twice for None result" + + +def test_gh_cli_token_not_called_during_make_context(monkeypatch): + """make_context() must not call _gh_cli_token() — token resolves lazily.""" + monkeypatch.delenv("GITHUB_TOKEN", raising=False) + + calls: list[object] = [] + original_run = __import__("subprocess").run + + def tracking_run(*args, **kwargs): + calls.append(args) + return original_run(*args, **kwargs) + + monkeypatch.setattr("autoskillit.server._factory.subprocess.run", tracking_run) + + config = AutomationConfig() + make_context(config, runner=None, plugin_dir=".") + + gh_calls = [c for c in calls if "gh" in str(c)] + assert gh_calls == [], f"_gh_cli_token() called during make_context: {gh_calls}" + + +def test_make_context_sets_plugin_dir_none_when_plugin_installed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """make_context() sets plugin_dir=None when marketplace plugin is installed.""" + monkeypatch.setattr("autoskillit.server._factory._check_plugin_installed", lambda: True) + ctx = make_context(AutomationConfig(), runner=None) + assert ctx.plugin_dir is None + + +def test_make_context_sets_plugin_dir_when_plugin_not_installed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """make_context() sets plugin_dir to package root when plugin is not installed.""" + monkeypatch.setattr("autoskillit.server._factory._check_plugin_installed", lambda: False) + ctx = make_context(AutomationConfig(), runner=None) + assert ctx.plugin_dir is not None + assert ctx.plugin_dir != "" + + +def test_make_context_sets_token_factory(tmp_path): + """make_context() sets token_factory on the returned ToolContext.""" + cfg = AutomationConfig() + ctx = make_context(cfg, runner=None, plugin_dir=str(tmp_path)) + assert callable(ctx.token_factory) diff --git a/tests/server/test_git.py b/tests/server/test_git.py index 55f130b00c..79292e24e1 100644 --- a/tests/server/test_git.py +++ b/tests/server/test_git.py @@ -1,12 +1,19 @@ """Tests for server/git.py perform_merge().""" +from pathlib import Path from unittest.mock import AsyncMock, patch import pytest from autoskillit.config import AutomationConfig from autoskillit.core import CleanupResult -from autoskillit.core.types import SubprocessResult, TerminationReason, TestResult +from autoskillit.core.types import ( + MergeFailedStep, + MergeState, + SubprocessResult, + TerminationReason, + TestResult, +) from tests.conftest import MockSubprocessRunner, StatefulMockTester @@ -161,6 +168,7 @@ async def test_perform_merge_returns_success_on_green_tests( conftest_mock_runner.push(_make_result(0, "", "")) # rebase conftest_mock_runner.push(_make_result(0, "", "")) # git ls-files (generated file check) conftest_mock_runner.push(_make_result(0, f"worktree {fake_wt}\n", "")) # wt list + conftest_mock_runner.push(_make_result(0, "dev\n", "")) # step 7.5: branch --show-current conftest_mock_runner.push(_make_result(0, "", "")) # merge conftest_mock_runner.push(_make_result(0, "", "")) # wt remove conftest_mock_runner.push(_make_result(0, "", "")) # branch -D @@ -174,7 +182,15 @@ async def test_perform_merge_returns_success_on_green_tests( ) assert result.get("merge_succeeded") is True assert result["merged_branch"] == "feature-branch" + assert result["into_branch"] == "dev" assert tester.call_count == 2 # both pre- and post-rebase gates ran + # Verify merge command cwd is the main_repo (same as worktree root for this test) + merge_call = next( + args + for args in conftest_mock_runner.call_args_list + if len(args[0]) > 1 and args[0][1] == "merge" + ) + assert merge_call[1] == Path(fake_wt) @pytest.mark.anyio @@ -231,6 +247,7 @@ async def test_perform_merge_uses_no_edit_flag(default_config, conftest_mock_run conftest_mock_runner.push(_make_result(0, "", "")) # rebase conftest_mock_runner.push(_make_result(0, "", "")) # git ls-files (generated file check) conftest_mock_runner.push(_make_result(0, f"worktree {fake_wt}\n", "")) # wt list + conftest_mock_runner.push(_make_result(0, "dev\n", "")) # step 7.5: branch --show-current conftest_mock_runner.push(_make_result(0, "", "")) # merge conftest_mock_runner.push(_make_result(0, "", "")) # wt remove conftest_mock_runner.push(_make_result(0, "", "")) # branch -D @@ -318,6 +335,7 @@ async def test_perform_merge_strips_tracked_generated_files( conftest_mock_runner.push(_make_result(0, "", "")) # git log --merges (5.6 — no merge commits) conftest_mock_runner.push(_make_result(0, "", "")) # rebase conftest_mock_runner.push(_make_result(0, f"worktree {fake_wt}\n", "")) # wt list + conftest_mock_runner.push(_make_result(0, "dev\n", "")) # step 7.5: branch --show-current conftest_mock_runner.push(_make_result(0, "", "")) # merge conftest_mock_runner.push(_make_result(0, "", "")) # wt remove conftest_mock_runner.push(_make_result(0, "", "")) # branch -D @@ -367,6 +385,7 @@ async def test_perform_merge_noop_when_no_generated_files_tracked( conftest_mock_runner.push(_make_result(0, "", "")) # git log --merges (5.6 — no merge commits) conftest_mock_runner.push(_make_result(0, "", "")) # rebase conftest_mock_runner.push(_make_result(0, f"worktree {fake_wt}\n", "")) # wt list + conftest_mock_runner.push(_make_result(0, "dev\n", "")) # step 7.5: branch --show-current conftest_mock_runner.push(_make_result(0, "", "")) # merge conftest_mock_runner.push(_make_result(0, "", "")) # wt remove conftest_mock_runner.push(_make_result(0, "", "")) # branch -D @@ -434,6 +453,7 @@ async def test_perform_merge_dirty_check_ignores_generated_files( conftest_mock_runner.push(_make_result(0, "", "")) # git log --merges conftest_mock_runner.push(_make_result(0, "", "")) # rebase conftest_mock_runner.push(_make_result(0, f"worktree {fake_wt}\n", "")) # wt list + conftest_mock_runner.push(_make_result(0, "dev\n", "")) # step 7.5: branch --show-current conftest_mock_runner.push(_make_result(0, "", "")) # merge conftest_mock_runner.push(_make_result(0, "", "")) # wt remove conftest_mock_runner.push(_make_result(0, "", "")) # branch -D @@ -471,6 +491,7 @@ async def test_perform_merge_strips_generated_files_before_dirty_check( conftest_mock_runner.push(_make_result(0, "", "")) # git log --merges conftest_mock_runner.push(_make_result(0, "", "")) # rebase conftest_mock_runner.push(_make_result(0, f"worktree {fake_wt}\n", "")) # wt list + conftest_mock_runner.push(_make_result(0, "dev\n", "")) # step 7.5: branch --show-current conftest_mock_runner.push(_make_result(0, "", "")) # merge conftest_mock_runner.push(_make_result(0, "", "")) # wt remove conftest_mock_runner.push(_make_result(0, "", "")) # branch -D @@ -501,6 +522,7 @@ def _push_full_success_sequence( runner: "MockSubprocessRunner", *, worktree_path: "Path", # noqa: F821 + base_branch: str = "dev", ) -> None: """Push the git subprocess sequence for a successful merge onto runner. @@ -509,7 +531,7 @@ def _push_full_success_sequence( Cleanup steps (remove_git_worktree, branch -D) use the runner default (rc=0). """ runner.push(_make_result(0, "/repo/.git/worktrees/impl-test\n")) # rev-parse --git-dir - runner.push(_make_result(0, "impl-test\n")) # branch --show-current + runner.push(_make_result(0, "impl-test\n")) # branch --show-current (worktree) runner.push(_make_result(0, "")) # git ls-files (generated) runner.push(_make_result(0, "")) # git status --porcelain runner.push(_make_result(0, "")) # git fetch @@ -517,9 +539,10 @@ def _push_full_success_sequence( runner.push(_make_result(0, "")) # git log --merges runner.push(_make_result(0, "")) # git rebase runner.push( # worktree list --porcelain - _make_result(0, "worktree /repo\nHEAD abc123\nbranch refs/heads/main\n\n") + _make_result(0, f"worktree /repo\nHEAD abc123\nbranch refs/heads/{base_branch}\n\n") ) - runner.push(_make_result(0, "")) # git merge --no-ff + runner.push(_make_result(0, f"{base_branch}\n")) # step 7.5: branch --show-current (main_repo) + runner.push(_make_result(0, "")) # git merge --no-edit class TestPerformMergeSidecarCleanup: @@ -552,7 +575,13 @@ async def test_sidecar_removed_on_successful_merge(self, tmp_path): ) assert result["merge_succeeded"] is True + assert result["into_branch"] == "dev" assert "impl-test" in sidecar_calls + # Verify merge command cwd is main_repo (/repo) + merge_call = next( + args for args in runner.call_args_list if len(args[0]) > 1 and args[0][1] == "merge" + ) + assert merge_call[1] == Path("/repo") @pytest.mark.anyio async def test_sidecar_cleanup_failure_does_not_block_merge_result(self, tmp_path): @@ -608,3 +637,168 @@ async def _fake_remove(path, repo, runner): ) assert wt in remove_calls + + +class TestPerformMergeTargetBranchVerification: + """perform_merge must verify main_repo's checked-out branch matches base_branch.""" + + @pytest.mark.anyio + async def test_rejects_merge_when_main_repo_on_wrong_branch(self, tmp_path): + """Test 1.1: Reproduce the primary bug — worktree list says 'main' but + base_branch='dev'. Step 7.5 must reject the mismatch.""" + from autoskillit.server.git import perform_merge + + wt = tmp_path / "worktrees" / "impl-test" + wt.mkdir(parents=True) + (wt / ".git").write_text("gitdir: /repo/.git/worktrees/impl-test") + + runner = MockSubprocessRunner() + tester = _make_tester() + + runner.push(_make_result(0, "/repo/.git/worktrees/impl-test\n")) # rev-parse + runner.push(_make_result(0, "impl-test\n")) # branch --show-current (worktree) + runner.push(_make_result(0, "")) # git ls-files (generated) + runner.push(_make_result(0, "")) # git status --porcelain + runner.push(_make_result(0, "")) # git fetch + runner.push(_make_result(0, "abc123\n")) # rev-parse --verify + runner.push(_make_result(0, "")) # git log --merges + runner.push(_make_result(0, "")) # git rebase + # worktree list says main_repo is on 'main' + runner.push(_make_result(0, "worktree /repo\nHEAD abc123\nbranch refs/heads/main\n\n")) + # Step 7.5: git branch --show-current on main_repo returns 'main' + runner.push(_make_result(0, "main\n")) + + result = await perform_merge( + str(wt), + "dev", + config=AutomationConfig(), + runner=runner, + tester=tester, + ) + + assert "error" in result + assert result["failed_step"] == MergeFailedStep.MERGE + assert result["state"] == MergeState.WORKTREE_INTACT + assert "is on branch 'main', expected 'dev'" in result["error"] + # No merge command should have been issued + merge_cmds = [ + args[0] for args in runner.call_args_list if len(args[0]) > 1 and args[0][1] == "merge" + ] + assert merge_cmds == [], f"Merge command was issued despite branch mismatch: {merge_cmds}" + + @pytest.mark.anyio + async def test_succeeds_when_main_repo_branch_matches(self, tmp_path): + """Test 1.2: Happy path — worktree list and step 7.5 both say 'dev'.""" + from autoskillit.server.git import perform_merge + + wt = tmp_path / "worktrees" / "impl-test" + wt.mkdir(parents=True) + (wt / ".git").write_text("gitdir: /repo/.git/worktrees/impl-test") + + runner = MockSubprocessRunner() + tester = _make_tester() + + runner.push(_make_result(0, "/repo/.git/worktrees/impl-test\n")) # rev-parse + runner.push(_make_result(0, "impl-test\n")) # branch --show-current (worktree) + runner.push(_make_result(0, "")) # git ls-files (generated) + runner.push(_make_result(0, "")) # git status --porcelain + runner.push(_make_result(0, "")) # git fetch + runner.push(_make_result(0, "abc123\n")) # rev-parse --verify + runner.push(_make_result(0, "")) # git log --merges + runner.push(_make_result(0, "")) # git rebase + # worktree list says main_repo is on 'dev' + runner.push(_make_result(0, "worktree /repo\nHEAD abc123\nbranch refs/heads/dev\n\n")) + # Step 7.5: git branch --show-current on main_repo returns 'dev' + runner.push(_make_result(0, "dev\n")) + runner.push(_make_result(0, "")) # git merge --no-edit + # cleanup: remove_git_worktree + branch -D use runner defaults (rc=0) + + result = await perform_merge( + str(wt), + "dev", + config=AutomationConfig(), + runner=runner, + tester=tester, + ) + + assert result["merge_succeeded"] is True + assert result["into_branch"] == "dev" + + @pytest.mark.anyio + async def test_merge_command_cwd_is_main_repo(self, tmp_path): + """Test 1.3: Assert git merge --no-edit is executed with cwd == main_repo path.""" + from autoskillit.server.git import perform_merge + + wt = tmp_path / "worktrees" / "impl-test" + wt.mkdir(parents=True) + (wt / ".git").write_text("gitdir: /repo/.git/worktrees/impl-test") + + runner = MockSubprocessRunner() + tester = _make_tester() + + runner.push(_make_result(0, "/repo/.git/worktrees/impl-test\n")) # rev-parse + runner.push(_make_result(0, "impl-test\n")) # branch --show-current (worktree) + runner.push(_make_result(0, "")) # git ls-files (generated) + runner.push(_make_result(0, "")) # git status --porcelain + runner.push(_make_result(0, "")) # git fetch + runner.push(_make_result(0, "abc123\n")) # rev-parse --verify + runner.push(_make_result(0, "")) # git log --merges + runner.push(_make_result(0, "")) # git rebase + runner.push(_make_result(0, "worktree /repo\nHEAD abc123\nbranch refs/heads/dev\n\n")) + # Step 7.5: branch verification + runner.push(_make_result(0, "dev\n")) + runner.push(_make_result(0, "")) # git merge --no-edit + + result = await perform_merge( + str(wt), + "dev", + config=AutomationConfig(), + runner=runner, + tester=tester, + ) + + assert result["merge_succeeded"] is True + # Find the merge command and assert its cwd + merge_call = next( + args for args in runner.call_args_list if len(args[0]) > 1 and args[0][1] == "merge" + ) + assert merge_call[1] == Path("/repo"), ( + f"Merge command cwd should be /repo (main_repo), got {merge_call[1]}" + ) + + @pytest.mark.anyio + async def test_into_branch_reflects_verified_state(self, tmp_path): + """Test 1.4: into_branch must come from verified git state, not echoed input.""" + from autoskillit.server.git import perform_merge + + wt = tmp_path / "worktrees" / "impl-test" + wt.mkdir(parents=True) + (wt / ".git").write_text("gitdir: /repo/.git/worktrees/impl-test") + + runner = MockSubprocessRunner() + tester = _make_tester() + + runner.push(_make_result(0, "/repo/.git/worktrees/impl-test\n")) # rev-parse + runner.push(_make_result(0, "impl-test\n")) # branch --show-current (worktree) + runner.push(_make_result(0, "")) # git ls-files (generated) + runner.push(_make_result(0, "")) # git status --porcelain + runner.push(_make_result(0, "")) # git fetch + runner.push(_make_result(0, "abc123\n")) # rev-parse --verify + runner.push(_make_result(0, "")) # git log --merges + runner.push(_make_result(0, "")) # git rebase + runner.push(_make_result(0, "worktree /repo\nHEAD abc123\nbranch refs/heads/dev\n\n")) + # Step 7.5: verified branch + runner.push(_make_result(0, "dev\n")) + runner.push(_make_result(0, "")) # merge + + result = await perform_merge( + str(wt), + "dev", + config=AutomationConfig(), + runner=runner, + tester=tester, + ) + + assert result["merge_succeeded"] is True + # into_branch must match the verified branch from step 7.5 + assert result["into_branch"] == "dev" diff --git a/tests/server/test_headless_session.py b/tests/server/test_headless_session.py index f373e1dbfc..f98b50b1b1 100644 --- a/tests/server/test_headless_session.py +++ b/tests/server/test_headless_session.py @@ -6,27 +6,18 @@ @pytest.mark.anyio -async def test_headless_session_kitchen_visible_from_startup( - monkeypatch: pytest.MonkeyPatch, -) -> None: - """When AUTOSKILLIT_HEADLESS=1, kitchen tools are pre-revealed. +async def test_mcp_enable_kitchen_reveals_gated_tools(kitchen_enabled) -> None: + """mcp.enable(tags={'kitchen'}) reveals all GATED_TOOLS to the client. - Uses FastMCP Client to assert that GATED_TOOLS are visible after - mcp.enable(tags={'kitchen'}), which is the startup behavior for - headless sessions. + Uses FastMCP Client to assert that every tool in GATED_TOOLS is visible + after mcp.enable(tags={'kitchen'}), which is the manual reveal step used + in headless sessions. """ from fastmcp.client import Client from autoskillit.pipeline.gate import GATED_TOOLS from autoskillit.server import mcp - monkeypatch.setenv("AUTOSKILLIT_HEADLESS", "1") - mcp.enable(tags={"kitchen"}) - try: - async with Client(mcp) as client: - tool_names = {t.name for t in await client.list_tools()} - assert any(name in GATED_TOOLS for name in tool_names), ( - "Kitchen tools must be enabled when AUTOSKILLIT_HEADLESS=1" - ) - finally: - mcp.disable(tags={"kitchen"}) + async with Client(mcp) as client: + tool_names = {t.name for t in await client.list_tools()} + assert GATED_TOOLS.issubset(tool_names), f"Missing gated tools: {GATED_TOOLS - tool_names}" diff --git a/tests/server/test_lifespan.py b/tests/server/test_lifespan.py new file mode 100644 index 0000000000..5fd28d8d08 --- /dev/null +++ b/tests/server/test_lifespan.py @@ -0,0 +1,129 @@ +"""Tests that the FastMCP lifespan calls recorder.finalize() on server shutdown.""" + +import asyncio +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest + +from autoskillit.execution.recording import RecordingSubprocessRunner + + +@pytest.mark.asyncio +async def test_lifespan_calls_finalize_on_recording_runner(): + """lifespan __aexit__ calls recorder.finalize() when runner is RecordingSubprocessRunner.""" + from autoskillit.server import _autoskillit_lifespan + + mock_recorder = MagicMock() + mock_runner = MagicMock(spec=RecordingSubprocessRunner) + mock_runner.recorder = mock_recorder + mock_ctx = MagicMock() + mock_ctx.runner = mock_runner + + with patch("autoskillit.server._lifespan._get_ctx_or_none", return_value=mock_ctx): + async with _autoskillit_lifespan(MagicMock()): + pass # server running phase + + mock_recorder.finalize.assert_called_once() + + +@pytest.mark.asyncio +async def test_lifespan_skips_finalize_when_not_recording(): + """lifespan __aexit__ does not error when runner is not RecordingSubprocessRunner.""" + from autoskillit.server import _autoskillit_lifespan + + mock_ctx = MagicMock() + mock_ctx.runner = MagicMock() # plain runner, not RecordingSubprocessRunner + + with patch("autoskillit.server._lifespan._get_ctx_or_none", return_value=mock_ctx): + async with _autoskillit_lifespan(MagicMock()): + pass # must not raise + + +@pytest.mark.asyncio +async def test_lifespan_skips_finalize_when_ctx_is_none(): + """lifespan __aexit__ is safe when _get_ctx_or_none() returns None (non-recording mode).""" + from autoskillit.server import _autoskillit_lifespan + + with patch("autoskillit.server._lifespan._get_ctx_or_none", return_value=None): + async with _autoskillit_lifespan(MagicMock()): + pass # must not raise + + +@pytest.mark.asyncio +async def test_lifespan_calls_finalize_on_cancellation(): + """finalize() is called even when the lifespan task is cancelled (SIGTERM path). + + Regression guard for issue #745: the try/finally in _autoskillit_lifespan must + ensure finalize() runs when CancelledError is thrown at the yield point, which + is exactly what anyio does when KeyboardInterrupt cancels the running task group. + """ + from autoskillit.server import _autoskillit_lifespan + + mock_recorder = MagicMock() + mock_runner = MagicMock(spec=RecordingSubprocessRunner) + mock_runner.recorder = mock_recorder + mock_ctx = MagicMock() + mock_ctx.runner = mock_runner + + with patch("autoskillit.server._lifespan._get_ctx_or_none", return_value=mock_ctx): + with pytest.raises(asyncio.CancelledError): + async with _autoskillit_lifespan(MagicMock()): + raise asyncio.CancelledError + + mock_recorder.finalize.assert_called_once() + + +@pytest.mark.asyncio +async def test_lifespan_sets_startup_ready_event(): + """_startup_ready must be set to a real Event and signalled after lifespan yield.""" + from autoskillit.server import _autoskillit_lifespan, _state + + mock_ctx = MagicMock() + mock_ctx.runner = MagicMock() + mock_ctx.config.linux_tracing.tmpfs_path = "/tmp" + mock_ctx.config.linux_tracing.log_dir = None + mock_ctx.audit = MagicMock() + mock_ctx.audit.load_from_log_dir = MagicMock(return_value=0) + mock_ctx.session_skill_manager = None + + # Reset _startup_ready to None before test + original = _state._startup_ready + _state._startup_ready = None + + try: + with patch("autoskillit.server._lifespan._get_ctx_or_none", return_value=mock_ctx): + async with _autoskillit_lifespan(MagicMock()): + # _startup_ready is assigned synchronously before yield + assert _state._startup_ready is not None, ( + "_startup_ready must be assigned an asyncio.Event during lifespan" + ) + # Background task may not have completed yet — await the event + await asyncio.wait_for(_state._startup_ready.wait(), timeout=5.0) + assert _state._startup_ready.is_set(), ( + "_startup_ready event must be signalled after deferred_initialize completes" + ) + finally: + _state._startup_ready = original + + +def test_serve_startup_regenerates_on_hash_mismatch(tmp_path: Path, monkeypatch) -> None: + """run_startup_drift_check() regenerates hooks.json when hash is mismatched.""" + import json as _json + + import autoskillit.core.paths as _paths + from autoskillit.hook_registry import HOOK_REGISTRY_HASH + from autoskillit.server._lifespan import run_startup_drift_check + + fake_pkg_root = tmp_path / "pkg" + hooks_dir = fake_pkg_root / "hooks" + hooks_dir.mkdir(parents=True) + stale_json = {"_autoskillit_registry_hash": "deadbeef", "hooks": {}} + (hooks_dir / "hooks.json").write_text(_json.dumps(stale_json)) + + monkeypatch.setattr(_paths, "pkg_root", lambda: fake_pkg_root) + + run_startup_drift_check() + + updated = _json.loads((hooks_dir / "hooks.json").read_text()) + assert updated.get("_autoskillit_registry_hash") == HOOK_REGISTRY_HASH diff --git a/tests/server/test_lifespan_readiness_structural.py b/tests/server/test_lifespan_readiness_structural.py new file mode 100644 index 0000000000..a552072fb1 --- /dev/null +++ b/tests/server/test_lifespan_readiness_structural.py @@ -0,0 +1,129 @@ +"""AST structural guard for _autoskillit_lifespan readiness invariants. + +Fails RED if: + A) the first statement in _autoskillit_lifespan is not a try: block + B) the try: body contains no call to a sentinel/readiness write helper + C) any logger call uses a retired readiness token as its message + +These are static structure tests — no subprocess or import of the module under +test. They enforce architectural rules that were previously only expressed in +comments, making regression by accident impossible. +""" + +from __future__ import annotations + +import ast +from pathlib import Path + +import pytest + +from autoskillit.core._type_constants import RETIRED_READINESS_TOKENS + +_LIFESPAN_PATH = ( + Path(__file__).parent.parent.parent / "src" / "autoskillit" / "server" / "_lifespan.py" +) + + +def _find_lifespan_func(tree: ast.Module) -> ast.AsyncFunctionDef: + for node in ast.walk(tree): + if isinstance(node, ast.AsyncFunctionDef) and node.name == "_autoskillit_lifespan": + return node + pytest.fail("_autoskillit_lifespan not found in _lifespan.py") + + +def _call_func_name(node: ast.Call) -> str: + """Return a dotted name string for the function being called.""" + func = node.func + if isinstance(func, ast.Attribute): + return f"{_expr_name(func.value)}.{func.attr}" + if isinstance(func, ast.Name): + return func.id + return "" + + +def _expr_name(node: ast.expr) -> str: + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + return f"{_expr_name(node.value)}.{node.attr}" + return "" + + +def _first_arg_str(node: ast.Call) -> str | None: + """Return the string value of the first positional argument if it's a constant.""" + if node.args and isinstance(node.args[0], ast.Constant): + return str(node.args[0].value) + return None + + +def _first_real_stmt(body: list) -> ast.stmt | None: + """Return the first non-docstring statement in a function body. + + A leading docstring is an ast.Expr whose value is an ast.Constant string. + It is not executable code, so tests that guard against "code before try:" + must skip it. + """ + for stmt in body: + if ( + isinstance(stmt, ast.Expr) + and isinstance(stmt.value, ast.Constant) + and isinstance(stmt.value.value, str) + ): + continue # skip leading docstring + return stmt + return None + + +class TestLifespanReadinessStructural: + def setup_method(self): + source = _LIFESPAN_PATH.read_text(encoding="utf-8") + self.tree = ast.parse(source) + self.func = _find_lifespan_func(self.tree) + + def test_body_contains_try(self): + """Assertion A: _autoskillit_lifespan body must contain a try: block.""" + body = self.func.body + assert body, "_autoskillit_lifespan has an empty body" + try_nodes = [s for s in body if isinstance(s, (ast.Try, ast.TryStar))] + assert try_nodes, ( + "Expected _autoskillit_lifespan to contain a try: block. " + "Readiness sentinel must be written inside try: to ensure cleanup runs in finally:." + ) + + def test_try_body_contains_sentinel_call(self): + """Assertion B: try: body must call a sentinel/readiness write helper.""" + body = self.func.body + try_nodes = [s for s in body if isinstance(s, (ast.Try, ast.TryStar))] + assert try_nodes, "Pre-condition failed: no try: block found (see test_body_contains_try)" + try_node = try_nodes[0] + sentinel_calls = [] + for node in ast.walk(try_node): + if isinstance(node, ast.Call): + name = _call_func_name(node) + if "sentinel" in name.lower() or "readiness" in name.lower(): + sentinel_calls.append(name) + assert sentinel_calls, ( + "No call to a sentinel/readiness write helper found inside the try: block of " + "_autoskillit_lifespan. The readiness sentinel must be written before yield " + "so tests can synchronize without polling log lines." + ) + + def test_no_retired_token_logger_calls(self): + """Assertion C: no logger call uses a retired readiness token as first arg.""" + bad_calls: list[str] = [] + for node in ast.walk(self.func): + if not isinstance(node, ast.Call): + continue + name = _call_func_name(node) + if not name.startswith("logger."): + continue + first_arg = _first_arg_str(node) + if first_arg in RETIRED_READINESS_TOKENS: + bad_calls.append( + f"logger call with retired token {first_arg!r} at col {node.col_offset}" + ) + assert not bad_calls, ( + "Found logger call(s) using retired readiness tokens in _autoskillit_lifespan:\n" + + "\n".join(f" {c}" for c in bad_calls) + + f"\nRetired tokens: {sorted(RETIRED_READINESS_TOKENS)}" + ) diff --git a/tests/server/test_mcp_overrides.py b/tests/server/test_mcp_overrides.py index d31d3b1a6c..761d683bfd 100644 --- a/tests/server/test_mcp_overrides.py +++ b/tests/server/test_mcp_overrides.py @@ -80,6 +80,7 @@ async def test_open_kitchen_accepts_overrides_param(tmp_path: Path) -> None: patch( "autoskillit.server.tools_kitchen._open_kitchen_handler", new_callable=AsyncMock, + return_value=None, ), patch("autoskillit.server._get_ctx", return_value=mock_tool_ctx), patch( diff --git a/tests/server/test_no_raw_signal_handler.py b/tests/server/test_no_raw_signal_handler.py new file mode 100644 index 0000000000..cd0df12fce --- /dev/null +++ b/tests/server/test_no_raw_signal_handler.py @@ -0,0 +1,72 @@ +"""AST guard: no raw signal.signal(SIGTERM, ...) in cli/app.py. + +SIGTERM must be handled via anyio.open_signal_receiver (event-loop-routed +callback), not via signal.signal() (frame-interrupting KeyboardInterrupt that +escapes the C-level event-loop runner before finally: blocks can fire). + +This guard is paired with the ruff TID251 ban in pyproject.toml which catches +the pattern at lint time. The AST test provides exact SIGTERM-specific matching +as a regression gate. +""" + +from __future__ import annotations + +import ast +import re +from pathlib import Path + +_APP_PATH = Path(__file__).parent.parent.parent / "src" / "autoskillit" / "cli" / "app.py" +_SRC_ROOT = Path(__file__).parent.parent.parent / "src" / "autoskillit" + + +def _is_sigterm_call(node: ast.Call) -> bool: + """Return True if this is signal.signal(, ...).""" + func = node.func + # Must be signal.signal(...) + if not ( + isinstance(func, ast.Attribute) + and func.attr == "signal" + and isinstance(func.value, ast.Name) + and func.value.id == "signal" + ): + return False + if not node.args: + return False + first_arg = node.args[0] + # signal.SIGTERM or bare SIGTERM + if isinstance(first_arg, ast.Attribute) and first_arg.attr == "SIGTERM": + return True + if isinstance(first_arg, ast.Name) and first_arg.id == "SIGTERM": + return True + return False + + +class TestNoRawSignalHandler: + def test_ast_no_signal_signal_sigterm_in_app_py(self): + """AST walk: cli/app.py must not call signal.signal(SIGTERM, ...).""" + source = _APP_PATH.read_text(encoding="utf-8") + tree = ast.parse(source) + bad_calls = [ + node + for node in ast.walk(tree) + if isinstance(node, ast.Call) and _is_sigterm_call(node) + ] + assert not bad_calls, ( + f"Found {len(bad_calls)} raw signal.signal(SIGTERM, ...) call(s) in cli/app.py. " + "Use anyio.open_signal_receiver instead — see _serve_with_signal_guard." + ) + + def test_grep_no_signal_signal_sigterm_in_src(self): + """Regex grep: no signal.signal(...SIGTERM...) pattern across src/autoskillit.""" + pattern = re.compile(r"signal\.signal\s*\(.*SIGTERM") + violations: list[str] = [] + for py_file in _SRC_ROOT.rglob("*.py"): + source = py_file.read_text(encoding="utf-8") + for lineno, line in enumerate(source.splitlines(), start=1): + if pattern.search(line): + violations.append(f"{py_file.relative_to(_SRC_ROOT)}:{lineno}: {line.strip()}") + assert not violations, ( + "Found raw signal.signal(SIGTERM, ...) usage in src/autoskillit:\n" + + "\n".join(f" {v}" for v in violations) + + "\nUse anyio.open_signal_receiver(signal.SIGTERM) — see _serve_with_signal_guard." + ) diff --git a/tests/server/test_perform_merge_editable_guard.py b/tests/server/test_perform_merge_editable_guard.py index d4c186e1ba..2cc351ad40 100644 --- a/tests/server/test_perform_merge_editable_guard.py +++ b/tests/server/test_perform_merge_editable_guard.py @@ -59,6 +59,7 @@ async def test_perform_merge_aborts_before_cleanup_on_poisoned_install( runner.push(_make_result(0, "")) # git log --merges (step 5.6 — no merge commits) runner.push(_make_result(0, "")) # git rebase (step 6) runner.push(_make_result(0, f"worktree {fake_wt}\n")) # git worktree list (step 7) + runner.push(_make_result(0, "dev\n")) # git branch --show-current (step 7.5) runner.push(_make_result(0, "")) # git merge (step 8) # Step 8.5: editable guard fires (mocked above) — cleanup steps never reached @@ -115,6 +116,7 @@ async def test_perform_merge_proceeds_normally_when_guard_returns_empty( runner.push(_make_result(0, "")) # git log --merges (step 5.6) runner.push(_make_result(0, "")) # git rebase (step 6) runner.push(_make_result(0, f"worktree {fake_wt}\n")) # git worktree list (step 7) + runner.push(_make_result(0, "dev\n")) # git branch --show-current (step 7.5) runner.push(_make_result(0, "")) # git merge (step 8) # Step 8.5: guard returns [] — cleanup proceeds # Steps 9-10 (wt remove, branch -D) use MockSubprocessRunner default (rc=0, stdout="") diff --git a/tests/server/test_quota_refresh_loop.py b/tests/server/test_quota_refresh_loop.py new file mode 100644 index 0000000000..b40f1d876c --- /dev/null +++ b/tests/server/test_quota_refresh_loop.py @@ -0,0 +1,83 @@ +"""Tests for _quota_refresh_loop in server/helpers.py.""" + +from __future__ import annotations + +import asyncio +from unittest.mock import AsyncMock + +import pytest + +from autoskillit.config.settings import QuotaGuardConfig + + +@pytest.mark.anyio +async def test_quota_refresh_loop_calls_refresh_at_each_interval(monkeypatch): + """Loop calls _refresh_quota_cache once per cache_refresh_interval sleep.""" + from autoskillit.server.helpers import _quota_refresh_loop + + call_count = 0 + sleep_count = 0 + + async def fake_sleep(n): + nonlocal sleep_count + sleep_count += 1 + if sleep_count >= 3: + raise asyncio.CancelledError + + async def fake_refresh(config): + nonlocal call_count + call_count += 1 + + monkeypatch.setattr("autoskillit.server.helpers.asyncio.sleep", fake_sleep) + monkeypatch.setattr("autoskillit.server.helpers._refresh_quota_cache", fake_refresh) + + config = QuotaGuardConfig(cache_refresh_interval=240) + with pytest.raises(asyncio.CancelledError): + await _quota_refresh_loop(config) + + assert call_count == 2 # one refresh per completed sleep + + +@pytest.mark.anyio +async def test_quota_refresh_loop_exits_cleanly_on_cancel(monkeypatch): + """CancelledError from asyncio.sleep propagates; loop does not swallow it.""" + from autoskillit.server.helpers import _quota_refresh_loop + + async def immediate_cancel(n): + raise asyncio.CancelledError + + monkeypatch.setattr("autoskillit.server.helpers.asyncio.sleep", immediate_cancel) + monkeypatch.setattr("autoskillit.server.helpers._refresh_quota_cache", AsyncMock()) + task = asyncio.create_task(_quota_refresh_loop(QuotaGuardConfig())) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + + +@pytest.mark.anyio +async def test_quota_refresh_loop_continues_after_refresh_exception(monkeypatch): + """A transient error in _refresh_quota_cache does not kill the loop.""" + from autoskillit.server.helpers import _quota_refresh_loop + + call_count = 0 + sleep_count = 0 + + async def fake_sleep(n): + nonlocal sleep_count + sleep_count += 1 + if sleep_count >= 3: + raise asyncio.CancelledError + + async def flaky_refresh(config): + nonlocal call_count + call_count += 1 + if call_count == 1: + raise OSError("network blip") + + monkeypatch.setattr("autoskillit.server.helpers.asyncio.sleep", fake_sleep) + monkeypatch.setattr("autoskillit.server.helpers._refresh_quota_cache", flaky_refresh) + + with pytest.raises(asyncio.CancelledError): + await _quota_refresh_loop(QuotaGuardConfig()) + + assert call_count == 2 # loop continued after the first OSError diff --git a/tests/server/test_server_init.py b/tests/server/test_server_init.py index 97ebcd6d18..7d467e2f5e 100644 --- a/tests/server/test_server_init.py +++ b/tests/server/test_server_init.py @@ -1,4 +1,4 @@ -"""Tests for autoskillit server initialization and metadata.""" +"""Tests for kitchen gate access, visibility, and subset management.""" from __future__ import annotations @@ -9,294 +9,9 @@ import pytest import structlog.testing -from autoskillit.config import ( - AutomationConfig, - SafetyConfig, -) from autoskillit.pipeline.gate import DefaultGateState from autoskillit.server.helpers import _require_enabled from autoskillit.server.tools_kitchen import _close_kitchen_handler, _open_kitchen_handler -from autoskillit.server.tools_status import ( - get_quota_events, - get_token_summary, -) - - -class TestPluginMetadataExists: - """T1: Plugin metadata files are shipped in the package.""" - - def test_plugin_json_exists(self): - """Package contains .claude-plugin/plugin.json with correct fields.""" - import autoskillit - - pkg = Path(autoskillit.__file__).parent - manifest = pkg / ".claude-plugin" / "plugin.json" - assert manifest.is_file() - data = json.loads(manifest.read_text()) - assert data["name"] == "autoskillit" - assert data["version"] == autoskillit.__version__ - - def test_mcp_json_exists(self): - """Package contains .mcp.json with autoskillit server entry.""" - import autoskillit - - pkg = Path(autoskillit.__file__).parent - mcp_cfg = pkg / ".mcp.json" - assert mcp_cfg.is_file() - data = json.loads(mcp_cfg.read_text()) - assert "autoskillit" in data["mcpServers"] - assert data["mcpServers"]["autoskillit"]["command"] == "autoskillit" - - -class TestNoSkillsDirectoryProvider: - """T3: SkillsDirectoryProvider is not used in the new plugin architecture.""" - - def test_no_skills_directory_provider(self): - """server.py must not reference SkillsDirectoryProvider.""" - import autoskillit.server as server_module - - source = Path(server_module.__file__).read_text() - assert "SkillsDirectoryProvider" not in source - - -class TestPluginDirConstant: - """T6: tool_ctx.plugin_dir defaults to the package root directory.""" - - def test_plugin_dir_assignment_is_visible_via_get_ctx(self, tool_ctx): - """By default tool_ctx.plugin_dir is set to tmp_path by the fixture. - - The real package dir is what the server uses at runtime (set by cli.py serve()). - This test verifies that the fixture wires plugin_dir through _ctx correctly. - """ - import autoskillit - - # The real package dir is what the server sets at startup. - # We verify the attribute path works (tool_ctx.plugin_dir is accessible). - real_pkg_dir = str(Path(autoskillit.__file__).parent) - # tool_ctx uses tmp_path; set it to verify end-to-end wiring - tool_ctx.plugin_dir = real_pkg_dir - from autoskillit.server import _get_ctx - - assert _get_ctx().plugin_dir == real_pkg_dir - - -class TestVersionInfo: - """version_info() returns package and plugin.json versions.""" - - def test_version_info_returns_package_and_plugin_versions(self): - from autoskillit import __version__ - from autoskillit.server import version_info - - info = version_info() - assert isinstance(info["package_version"], str) - assert isinstance(info["plugin_json_version"], str) - assert info["package_version"] == __version__ - assert info["match"] is True - - def test_version_info_detects_mismatch(self, tmp_path, tool_ctx): - from autoskillit.server import version_info - - plugin_dir = tmp_path / ".claude-plugin" - plugin_dir.mkdir() - (plugin_dir / "plugin.json").write_text( - json.dumps({"name": "autoskillit", "version": "0.0.0"}) - ) - tool_ctx.plugin_dir = str(tmp_path) - info = version_info() - assert info["match"] is False - assert info["package_version"] != info["plugin_json_version"] - assert info["plugin_json_version"] == "0.0.0" - - def test_version_info_handles_missing_plugin_json(self, tmp_path, tool_ctx): - from autoskillit.server import version_info - - tool_ctx.plugin_dir = str(tmp_path) - info = version_info() - assert info["plugin_json_version"] is None - assert info["match"] is False - - def test_version_info_is_public(self): - """version_info must be a public function — no underscore prefix.""" - from autoskillit import server - - assert hasattr(server, "version_info"), "server.version_info must exist" - assert not hasattr(server, "_version_info"), "server._version_info must be removed" - result = server.version_info() - assert set(result.keys()) >= {"package_version", "plugin_json_version", "match"} - - -class TestToolRegistration: - """All 40 tools are registered on the MCP server.""" - - @pytest.mark.anyio - async def test_all_tools_exist(self): - from fastmcp.client import Client - - from autoskillit.server import mcp - - try: - mcp.enable(tags={"kitchen"}) - async with Client(mcp) as client: - all_tools = await client.list_tools() - finally: - mcp.disable(tags={"kitchen"}) - tool_names = {t.name for t in all_tools} - - expected = { - "run_cmd", - "run_python", - "run_skill", - "test_check", - "reset_test_dir", - "classify_fix", - "reset_workspace", - "merge_worktree", - "read_db", - "list_recipes", - "load_recipe", - "migrate_recipe", - "kitchen_status", - "validate_recipe", - "get_pipeline_report", - "get_token_summary", - "get_timing_summary", - "get_quota_events", - "clone_repo", - "remove_clone", - "push_to_remote", - "fetch_github_issue", - "get_issue_title", - "report_bug", - "prepare_issue", - "enrich_issues", - "claim_issue", - "release_issue", - "wait_for_ci", - "wait_for_merge_queue", - "toggle_auto_merge", - "get_ci_status", - "open_kitchen", - "close_kitchen", - "create_unique_branch", - "check_pr_mergeable", - "write_telemetry_files", - "get_pr_reviews", - "bulk_close_issues", - "set_commit_status", - "register_clone_status", - "batch_cleanup_clones", - } - assert expected == tool_names - - @pytest.mark.anyio - async def test_ungated_tools_lack_kitchen_tag(self): - """Ungated (free-range) tools are visible without kitchen and carry no 'kitchen' tag.""" - from fastmcp.client import Client - - from autoskillit.pipeline.gate import UNGATED_TOOLS - from autoskillit.server import mcp - - async with Client(mcp) as client: - visible_names = {t.name for t in await client.list_tools()} - for name in UNGATED_TOOLS: - assert name in visible_names, f"{name} should be visible without kitchen" - - # Verify no ungated tool carries the kitchen tag (internal registry check) - all_tools = {t.name: t for t in await mcp.list_tools()} - for name in UNGATED_TOOLS: - tool = all_tools.get(name) - if tool is not None: - assert "kitchen" not in tool.tags, ( - f"Ungated tool '{name}' must not carry the 'kitchen' tag" - ) - - # test_check now has the kitchen tag (it's headless-tier, not free-range) - try: - mcp.enable(tags={"kitchen"}) - all_tools_with_kitchen = {t.name: t for t in await mcp.list_tools()} - finally: - mcp.disable(tags={"kitchen"}) - tc = all_tools_with_kitchen.get("test_check") - assert tc is not None, "test_check must be registered" - assert "kitchen" in tc.tags, "test_check must carry the 'kitchen' tag" - - @pytest.mark.anyio - async def test_kitchen_tools_have_autoskillit_and_kitchen_tags(self): - """Every tool in GATED_TOOLS carries both 'autoskillit' and 'kitchen' tags.""" - from autoskillit.pipeline.gate import GATED_TOOLS - from autoskillit.server import mcp - - try: - mcp.enable(tags={"kitchen"}) - all_tools = {t.name: t for t in await mcp.list_tools()} - finally: - mcp.disable(tags={"kitchen"}) - for name in GATED_TOOLS: - tool = all_tools.get(name) - assert tool is not None, f"Gated tool '{name}' not registered on server" - assert "autoskillit" in tool.tags, f"Gated tool '{name}' missing 'autoskillit' tag" - assert "kitchen" in tool.tags, f"Gated tool '{name}' missing 'kitchen' tag" - assert "automation" not in tool.tags, ( - f"Gated tool '{name}' still has deprecated 'automation' tag" - ) - - @pytest.mark.anyio - async def test_all_tools_tagged_autoskillit(self): - """Every registered tool carries the 'autoskillit' tag.""" - from autoskillit.server import mcp - - try: - mcp.enable(tags={"kitchen", "headless"}) - all_tools = await mcp.list_tools() - finally: - mcp.disable(tags={"kitchen"}) - mcp.disable(tags={"headless"}) - for tool in all_tools: - assert "autoskillit" in tool.tags, f"Tool '{tool.name}' missing 'autoskillit' tag" - assert "automation" not in tool.tags, f"Tool '{tool.name}' still has 'automation' tag" - - def test_ungated_tools_docstrings_state_notification_free(self): - """P5-1: Free-range tool docstrings state they send no MCP notifications.""" - - for tool_fn in [get_token_summary, get_quota_events]: - doc = tool_fn.__doc__ or "" - assert "no MCP" in doc or "no progress notification" in doc.lower(), ( - f"{tool_fn.__name__} must document notification-free behavior" - ) - - @pytest.mark.anyio - async def test_test_check_has_headless_tag(self): - from autoskillit.server import mcp - - try: - mcp.enable(tags={"kitchen"}) - all_tools = {t.name: t for t in await mcp.list_tools()} - finally: - mcp.disable(tags={"kitchen"}) - tc = all_tools.get("test_check") - assert tc is not None - assert "headless" in tc.tags - assert "kitchen" in tc.tags - assert "autoskillit" in tc.tags - - @pytest.mark.anyio - async def test_headless_enable_reveals_only_headless_tagged_tools(self): - from fastmcp.client import Client - - from autoskillit.pipeline.gate import GATED_TOOLS - from autoskillit.server import mcp - - try: - mcp.enable(tags={"headless"}) - async with Client(mcp) as client: - visible = {t.name for t in await client.list_tools()} - finally: - mcp.disable(tags={"headless"}) - assert "test_check" in visible - # Kitchen-only tools (no headless tag) must NOT be revealed - kitchen_only = GATED_TOOLS - {"test_check"} - for name in kitchen_only: - assert name not in visible, f"{name} should not be revealed by headless-only enable" class TestKitchenVisibility: @@ -508,8 +223,13 @@ def _close_kitchen(self, tool_ctx): @staticmethod def _prompt_text(result) -> str: - """Extract text from open_kitchen result (now returns str directly).""" - return result + import json as _json + + try: + parsed = _json.loads(result) + return parsed.get("content", result) + except (ValueError, TypeError): + return result @pytest.mark.anyio async def test_open_kitchen_instructs_status_call(self): @@ -589,7 +309,13 @@ def _close_kitchen(self, tool_ctx): @staticmethod def _prompt_text(result) -> str: - return result + import json as _json + + try: + parsed = _json.loads(result) + return parsed.get("content", result) + except (ValueError, TypeError): + return result @pytest.mark.anyio async def test_sous_chef_rules_injected_at_open_kitchen(self): @@ -627,634 +353,6 @@ async def test_open_kitchen_degrades_gracefully_without_sous_chef(self, monkeypa assert "kitchen_status" in text -class TestServerLazyInit: - """Tests for the _ctx / _initialize() / _get_ctx() / _get_config() pattern.""" - - def test_server_import_does_not_call_load_config(self, monkeypatch): - """Importing server.py must not trigger load_config() as a side effect.""" - import sys - - import autoskillit - - # Restore both the package attribute and sys.modules entry after the test so - # later tests in the same xdist worker see the original module object. - monkeypatch.setattr(autoskillit, "server", autoskillit.server) - monkeypatch.delitem(sys.modules, "autoskillit.server", raising=False) - - with patch("autoskillit.config.load_config") as mock_load: - import autoskillit.server # noqa: F401 - assert not mock_load.called - - def test_get_ctx_raises_before_initialize(self, monkeypatch): - """_get_ctx() raises RuntimeError when _ctx is None.""" - from autoskillit.server import _state - - monkeypatch.setattr(_state, "_ctx", None) - with pytest.raises(RuntimeError, match="serve\\(\\) must be called"): - _state._get_ctx() - - def test_get_config_raises_before_initialize(self, monkeypatch): - """_get_config() raises RuntimeError when _ctx is None.""" - from autoskillit.server import _state - - monkeypatch.setattr(_state, "_ctx", None) - with pytest.raises(RuntimeError, match="serve\\(\\) must be called"): - _state._get_config() - - -class TestInitializeClearMarker: - """_initialize respects telemetry_cleared_at fence for drift prevention.""" - - def test_initialize_uses_clear_marker_as_since_bound(self, tool_ctx, tmp_path, monkeypatch): - from datetime import UTC, datetime, timedelta - - from autoskillit.execution.session_log import ( - flush_session_log, - ) - from autoskillit.server import _state - - log_dir = tmp_path / "logs" - log_dir.mkdir() - - # Write a session that completed 5 hours ago (within 24h window) - five_hours_ago = datetime.now(UTC) - timedelta(hours=5) - flush_session_log( - log_dir=str(log_dir), - cwd="/tmp", - session_id="old-session", - pid=999, - skill_command="/autoskillit:foo", - success=True, - subtype="completed", - exit_code=0, - start_ts=five_hours_ago.isoformat(), - proc_snapshots=None, - step_name="old-step", - token_usage={ - "input_tokens": 1000, - "output_tokens": 500, - "cache_creation_input_tokens": 0, - "cache_read_input_tokens": 0, - }, - timing_seconds=10.0, - ) - - # Write a clear marker 3 hours ago (after the session completed) - three_hours_ago = datetime.now(UTC) - timedelta(hours=3) - (log_dir / ".telemetry_cleared_at").write_text(three_hours_ago.isoformat()) - - monkeypatch.setattr(tool_ctx.config.linux_tracing, "log_dir", str(log_dir)) - _state._initialize(tool_ctx) - - # The old-session happened before the clear marker → should NOT be replayed - report = tool_ctx.token_log.get_report() - assert all(s["step_name"] != "old-step" for s in report) - - -class TestConfigDrivenBehavior: - """S1-S10: Verify tools use config instead of hardcoded values.""" - - @pytest.mark.anyio - async def test_test_check_uses_config_command(self, tool_ctx): - """S1: test_check runs config.test_check.command.""" - from autoskillit.config import TestCheckConfig - from autoskillit.execution import DefaultTestRunner - from autoskillit.server.tools_workspace import test_check - from tests.conftest import _make_result - - tool_ctx.config = AutomationConfig( - test_check=TestCheckConfig(command=["pytest", "-x"], timeout=300) - ) - # Re-create tester with updated config so it reads the new command - tool_ctx.tester = DefaultTestRunner(config=tool_ctx.config, runner=tool_ctx.runner) - - tool_ctx.runner.push(_make_result(0, "= 100 passed =\n", "")) - await test_check(worktree_path="/tmp/wt") - - assert tool_ctx.runner.call_args_list[0][0] == ["pytest", "-x"] - assert tool_ctx.runner.call_args_list[0][2] == 300.0 - - @pytest.mark.anyio - async def test_classify_fix_uses_config_prefixes(self, tool_ctx, tmp_path): - """S2: classify_fix uses config.classify_fix.path_prefixes.""" - from autoskillit.config import ClassifyFixConfig - from autoskillit.core.types import RestartScope - from autoskillit.server.tools_git import classify_fix - from tests.conftest import _make_result - - tool_ctx.config = AutomationConfig( - classify_fix=ClassifyFixConfig(path_prefixes=["src/custom/"]) - ) - - changed = "src/custom/handler.py\nsrc/other/util.py\n" - tool_ctx.runner.push(_make_result(0, "", "")) # git fetch succeeds - tool_ctx.runner.push(_make_result(0, changed, "")) - result = json.loads(await classify_fix(worktree_path=str(tmp_path), base_branch="main")) - - assert result["restart_scope"] == RestartScope.FULL_RESTART - assert "src/custom/handler.py" in result["critical_files"] - - @pytest.mark.anyio - async def test_classify_fix_empty_prefixes_always_partial(self, tool_ctx, tmp_path): - """S3: Empty prefix list -> always returns partial_restart.""" - from autoskillit.config import ClassifyFixConfig - from autoskillit.core.types import RestartScope - from autoskillit.server.tools_git import classify_fix - from tests.conftest import _make_result - - tool_ctx.config = AutomationConfig(classify_fix=ClassifyFixConfig(path_prefixes=[])) - - changed = "src/core/handler.py\n" - tool_ctx.runner.push(_make_result(0, "", "")) # git fetch succeeds - tool_ctx.runner.push(_make_result(0, changed, "")) - result = json.loads(await classify_fix(worktree_path=str(tmp_path), base_branch="main")) - - assert result["restart_scope"] == RestartScope.PARTIAL_RESTART - - @pytest.mark.anyio - async def test_reset_workspace_uses_config_command(self, tool_ctx, tmp_path): - """S4: reset_workspace runs config.reset_workspace.command.""" - from autoskillit.config import ResetWorkspaceConfig - from autoskillit.server.tools_workspace import reset_workspace - from tests.conftest import _make_result - - tool_ctx.config = AutomationConfig( - reset_workspace=ResetWorkspaceConfig(command=["make", "reset"]) - ) - - workspace = tmp_path / "workspace" - workspace.mkdir(parents=True) - (workspace / ".autoskillit-workspace").write_text("# marker\n") - tool_ctx.runner.push(_make_result(0, "", "")) - - await reset_workspace(test_dir=str(workspace)) - assert tool_ctx.runner.call_args_list[0][0] == ["make", "reset"] - - @pytest.mark.anyio - async def test_reset_workspace_not_configured_returns_error(self, tool_ctx, tmp_path): - """S5: command=None -> returns not-configured error.""" - from autoskillit.config import ResetWorkspaceConfig - from autoskillit.server.tools_workspace import reset_workspace - - tool_ctx.config = AutomationConfig(reset_workspace=ResetWorkspaceConfig(command=None)) - - workspace = tmp_path / "workspace" - workspace.mkdir(parents=True) - (workspace / ".autoskillit-workspace").write_text("# marker\n") - result = json.loads(await reset_workspace(test_dir=str(workspace))) - - assert result["error"] == "reset_workspace not configured for this project" - - @pytest.mark.anyio - async def test_reset_workspace_uses_config_preserve_dirs(self, tool_ctx, tmp_path): - """S6: Preserves config.reset_workspace.preserve_dirs.""" - from autoskillit.config import ResetWorkspaceConfig - from autoskillit.server.tools_workspace import reset_workspace - from tests.conftest import _make_result - - tool_ctx.config = AutomationConfig( - reset_workspace=ResetWorkspaceConfig( - command=["true"], - preserve_dirs={"keep_me"}, - ) - ) - - workspace = tmp_path / "workspace" - workspace.mkdir(parents=True) - (workspace / ".autoskillit-workspace").write_text("# marker\n") - (workspace / "keep_me").mkdir() - (workspace / "delete_me").touch() - tool_ctx.runner.push(_make_result(0, "", "")) - - result = json.loads(await reset_workspace(test_dir=str(workspace))) - - assert "keep_me" in result["skipped"] - assert "delete_me" in result["deleted"] - assert (workspace / "keep_me").exists() - assert not (workspace / "delete_me").exists() - - def test_dry_walkthrough_uses_config_marker(self, tool_ctx, tmp_path): - """S7: Gate checks config.implement_gate.marker.""" - from autoskillit.config import ImplementGateConfig - from autoskillit.server.helpers import _check_dry_walkthrough - - tool_ctx.config = AutomationConfig( - implement_gate=ImplementGateConfig(marker="CUSTOM MARKER") - ) - - plan = tmp_path / "plan.md" - plan.write_text("CUSTOM MARKER\n# Plan content") - result = _check_dry_walkthrough(f"/autoskillit:implement-worktree {plan}", str(tmp_path)) - assert result is None # passes with custom marker - - plan.write_text("Dry-walkthrough verified = TRUE\n# Plan content") - result = _check_dry_walkthrough(f"/autoskillit:implement-worktree {plan}", str(tmp_path)) - assert result is not None # fails — marker doesn't match - - def test_dry_walkthrough_uses_config_skill_names(self, tool_ctx, tmp_path): - """S8: Gate checks config.implement_gate.skill_names.""" - from autoskillit.config import ImplementGateConfig - from autoskillit.server.helpers import _check_dry_walkthrough - - tool_ctx.config = AutomationConfig( - implement_gate=ImplementGateConfig(skill_names={"/custom-impl"}) - ) - - plan = tmp_path / "plan.md" - plan.write_text("# No marker") - - result = _check_dry_walkthrough(f"/custom-impl {plan}", str(tmp_path)) - assert result is not None # /custom-impl is gated - - result = _check_dry_walkthrough(f"/autoskillit:implement-worktree {plan}", str(tmp_path)) - assert result is None # /autoskillit:implement-worktree is NOT gated (not in skill_names) - - @pytest.mark.anyio - async def test_merge_worktree_uses_config_test_command(self, tool_ctx, tmp_path): - """S9: Merge's test gate runs config.test_check.command.""" - from autoskillit.config import TestCheckConfig - from autoskillit.core.types import MergeFailedStep - from autoskillit.execution import DefaultTestRunner - from autoskillit.server.tools_git import merge_worktree - from tests.conftest import _make_result - - tool_ctx.config = AutomationConfig( - test_check=TestCheckConfig(command=["make", "test"], timeout=120) - ) - # Re-create tester with updated config so it reads the new command - tool_ctx.tester = DefaultTestRunner(config=tool_ctx.config, runner=tool_ctx.runner) - - wt = tmp_path / "worktree" - wt.mkdir() - (wt / ".git").write_text("gitdir: /repo/.git/worktrees/wt") - - tool_ctx.runner.push(_make_result(0, "/repo/.git/worktrees/wt\n", "")) # rev-parse - tool_ctx.runner.push(_make_result(0, "impl-branch\n", "")) # branch - tool_ctx.runner.push(_make_result(0, "", "")) # git ls-files (pre-dirty-tree check) - tool_ctx.runner.push(_make_result(0, "", "")) # git status --porcelain (clean) - tool_ctx.runner.push(_make_result(1, "FAIL", "")) # test gate fails - result = json.loads(await merge_worktree(str(wt), "dev")) - assert result["failed_step"] == MergeFailedStep.TEST_GATE - - # Verify the test command was ["make", "test"] (5th call, after ls-files + porcelain) - test_call = tool_ctx.runner.call_args_list[4] - assert test_call[0] == ["make", "test"] - - @pytest.mark.anyio - async def test_require_enabled_still_gates_execution(self, tool_ctx): - """S10: _require_enabled() defense-in-depth still works with config.""" - from autoskillit.server.tools_execution import run_cmd - - tool_ctx.gate = DefaultGateState(enabled=False) - result = json.loads(await run_cmd(cmd="echo hi", cwd="/tmp")) - assert result["success"] is False - assert result["is_error"] is True - assert "not enabled" in result["result"].lower() - - -class TestSafetyConfigWiring: - """Safety config fields are read at the point of enforcement.""" - - @pytest.mark.anyio - async def test_reset_test_dir_allows_with_marker(self, tool_ctx, tmp_path): - """2a: Directory with marker passes the reset guard.""" - from autoskillit.server.tools_workspace import reset_test_dir - - target = tmp_path / "my_project" - target.mkdir() - (target / ".autoskillit-workspace").write_text("# marker\n") - (target / "file.txt").touch() - - result = json.loads(await reset_test_dir(test_dir=str(target), force=False)) - assert result["success"] is True - - @pytest.mark.anyio - async def test_reset_test_dir_enforces_marker_when_missing(self, tool_ctx, tmp_path): - """2b: Missing marker blocks reset_test_dir.""" - from autoskillit.server.tools_workspace import reset_test_dir - - target = tmp_path / "unmarked" - target.mkdir() - result = json.loads(await reset_test_dir(test_dir=str(target))) - assert "error" in result - assert "marker" in result["error"].lower() - - @pytest.mark.anyio - async def test_reset_workspace_enforces_marker(self, tool_ctx, tmp_path): - """2c: reset_workspace requires marker, then checks command config.""" - from autoskillit.config import ResetWorkspaceConfig - from autoskillit.server.tools_workspace import reset_workspace - - tool_ctx.config = AutomationConfig(reset_workspace=ResetWorkspaceConfig(command=None)) - - target = tmp_path / "my_project" - target.mkdir() - (target / ".autoskillit-workspace").write_text("# marker\n") - - result = json.loads(await reset_workspace(test_dir=str(target))) - # Should pass marker guard but fail on "not configured" - assert result["error"] == "reset_workspace not configured for this project" - - @pytest.mark.anyio - async def test_merge_worktree_skips_test_gate_when_disabled(self, tool_ctx, tmp_path): - """2d: test_gate_on_merge=False skips test execution.""" - from autoskillit.server.tools_git import merge_worktree - from tests.conftest import _make_result - - tool_ctx.config = AutomationConfig(safety=SafetyConfig(test_gate_on_merge=False)) - - wt = tmp_path / "worktree" - wt.mkdir() - (wt / ".git").write_text("gitdir: /repo/.git/worktrees/wt") - - tool_ctx.runner.push(_make_result(0, "/repo/.git/worktrees/wt\n", "")) # rev-parse - tool_ctx.runner.push(_make_result(0, "impl-branch\n", "")) # branch - tool_ctx.runner.push(_make_result(0, "", "")) # git ls-files (pre-dirty-tree check) - tool_ctx.runner.push(_make_result(0, "", "")) # git status --porcelain (clean) - # NO test-check call — skipped - tool_ctx.runner.push(_make_result(0, "", "")) # git fetch - tool_ctx.runner.push(_make_result(0, "abc123\n", "")) # rev-parse --verify (step 5.5) - tool_ctx.runner.push( - _make_result(0, "", "") - ) # git log --merges (step 5.6 — no merge commits) - tool_ctx.runner.push(_make_result(0, "", "")) # git rebase - tool_ctx.runner.push( - _make_result( - 0, - "worktree /repo\nHEAD abc\nbranch refs/heads/main\n\n", - "", - ) - ) # worktree list - tool_ctx.runner.push(_make_result(0, "", "")) # git merge - tool_ctx.runner.push(_make_result(0, "", "")) # worktree remove - tool_ctx.runner.push(_make_result(0, "", "")) # branch -D - result = json.loads(await merge_worktree(str(wt), "dev")) - assert result["merge_succeeded"] is True - - # Verify no test command was called — the 5th call should be git fetch, not test - fifth_call_cmd = tool_ctx.runner.call_args_list[4][0] - assert fifth_call_cmd == ["git", "fetch", "origin"] - - @pytest.mark.anyio - async def test_run_skill_2e_skips_dry_walkthrough_when_disabled(self, tool_ctx, tmp_path): - """2e: require_dry_walkthrough=False bypasses dry-walkthrough gate (using run_skill).""" - from autoskillit.server.tools_execution import run_skill - from tests.conftest import _make_result - - tool_ctx.config = AutomationConfig(safety=SafetyConfig(require_dry_walkthrough=False)) - - plan = tmp_path / "plan.md" - plan.write_text("# No marker plan") - - tool_ctx.runner.push(_make_result(0, '{"result": "done"}', "")) - result = json.loads( - await run_skill(f"/autoskillit:implement-worktree {plan}", str(tmp_path)) - ) - assert result["subtype"] != "gate_error" - assert result["exit_code"] == 0 - - @pytest.mark.anyio - async def test_run_skill_enforces_dry_walkthrough_when_enabled(self, tool_ctx, tmp_path): - """2f: run_skill enforces dry-walkthrough gate when enabled (default).""" - from autoskillit.server.tools_execution import run_skill - - plan = tmp_path / "plan.md" - plan.write_text("# No marker plan") - - result = json.loads( - await run_skill(f"/autoskillit:implement-worktree {plan}", str(tmp_path)) - ) - assert result["success"] is False - assert result["is_error"] is True - assert "dry-walked" in result["result"].lower() - - @pytest.mark.anyio - async def test_run_skill_skips_dry_walkthrough_when_disabled(self, tool_ctx, tmp_path): - """2g: run_skill skips dry-walkthrough gate when disabled.""" - from autoskillit.server.tools_execution import run_skill - from tests.conftest import _make_result - - tool_ctx.config = AutomationConfig(safety=SafetyConfig(require_dry_walkthrough=False)) - - plan = tmp_path / "plan.md" - plan.write_text("# No marker plan") - - tool_ctx.runner.push(_make_result(0, '{"result": "done"}', "")) - result = json.loads( - await run_skill(f"/autoskillit:implement-worktree {plan}", str(tmp_path)) - ) - assert result["subtype"] != "gate_error" - - -class TestToolSchemas: - """Regression guard: tool descriptions must not contain legacy terminology.""" - - FORBIDDEN_TERMS = { - "executor", - "planner", - "automation-mcp", - "ai-executor", - "enable_tools", # old open_kitchen prompt name - "disable_tools", # old close_kitchen prompt name - "autoskillit_status", # old kitchen_status tool name - } - - REQUIRED_CROSS_REFS: dict[str, list[str]] = { - "list_recipes": [ - "write-recipe", - ], - "load_recipe": [ - "write-recipe", - ], - "validate_recipe": [ - "write-recipe", - ], - } - - @property - def FORBIDDEN_NATIVE_TOOLS(self) -> list[str]: # noqa: N802 - from autoskillit.server import PIPELINE_FORBIDDEN_TOOLS - - return list(PIPELINE_FORBIDDEN_TOOLS) - - PIPELINE_TOOLS_WITH_GUIDANCE: dict[str, list[str]] = { - "run_skill": ["MCP tool", "delegate"], - } - - async def _get_all_tools(self) -> dict: - """Return dict of tool_name -> tool for all tools, including kitchen-gated ones.""" - from fastmcp.client import Client - - from autoskillit.server import mcp - - try: - mcp.enable(tags={"kitchen"}) - async with Client(mcp) as client: - tools = await client.list_tools() - finally: - mcp.disable(tags={"kitchen"}) - return {t.name: t for t in tools} - - @pytest.mark.anyio - async def test_tool_descriptions_contain_no_legacy_terms(self): - """No registered tool should reference old package terminology.""" - all_tools_dict = await self._get_all_tools() - all_tools = list(all_tools_dict.values()) - for tool in all_tools: - desc = (tool.description or "").lower() - for term in self.FORBIDDEN_TERMS: - assert term not in desc, ( - f"Tool '{tool.name}' description contains legacy term '{term}'" - ) - - @pytest.mark.anyio - async def test_tool_docstrings_contain_required_cross_refs(self): - """Tool docstrings must contain required cross-references.""" - tools = await self._get_all_tools() - for tool_name, required_terms in self.REQUIRED_CROSS_REFS.items(): - tool = tools.get(tool_name) - assert tool is not None, f"Tool '{tool_name}' not found in server" - desc = tool.description or "" - for term in required_terms: - assert term in desc, f"Tool '{tool_name}' description must reference '{term}'" - - @pytest.mark.anyio - async def test_classify_fix_docstring_has_routing_guidance(self): - """classify_fix must explain what to do with each return value.""" - tools = await self._get_all_tools() - assert "classify_fix" in tools, "Tool 'classify_fix' not found in server" - desc = tools["classify_fix"].description or "" - # Must mention both routing outcomes - assert "full_restart" in desc - assert "partial_restart" in desc - # Must mention at least one skill as routing target - assert "investigate" in desc or "implement" in desc - - @pytest.mark.anyio - async def test_recipe_tools_have_disambiguation(self): - """All recipe-related tools must carry the 'NOT slash commands' disclaimer.""" - tools = await self._get_all_tools() - recipe_tools = ["list_recipes", "load_recipe", "validate_recipe"] - for tool_name in recipe_tools: - tool = tools.get(tool_name) - assert tool is not None, f"Tool '{tool_name}' not found" - desc = tool.description or "" - assert "NOT slash commands" in desc, ( - f"Tool '{tool_name}' must contain 'NOT slash commands' disclaimer" - ) - - @pytest.mark.anyio - async def test_load_recipe_names_all_forbidden_tools(self): - """load_recipe must enumerate all forbidden native tools.""" - tools = await self._get_all_tools() - desc = tools["load_recipe"].description or "" - - missing = [t for t in self.FORBIDDEN_NATIVE_TOOLS if t not in desc] - assert not missing, ( - f"load_recipe docstring must name all forbidden tools. Missing: {missing}" - ) - - @pytest.mark.anyio - async def test_pipeline_tools_have_orchestrator_guidance(self): - """run_skill must reinforce MCP-only delegation.""" - tools = await self._get_all_tools() - failures = [] - for tool_name, required_terms in self.PIPELINE_TOOLS_WITH_GUIDANCE.items(): - desc = tools[tool_name].description or "" - for term in required_terms: - if term.lower() not in desc.lower(): - failures.append(f"Tool '{tool_name}' missing orchestrator term '{term}'") - assert not failures, "Pipeline tools missing orchestrator guidance:\n" + "\n".join( - f" - {f}" for f in failures - ) - - def test_pipeline_forbidden_tools_constant_is_complete(self): - """PIPELINE_FORBIDDEN_TOOLS must contain all 10 native Claude Code tools. - - "Agent" replaces the stale "Task" and "Explore" names — Agent is the - actual tool name; Explore is a subagent_type parameter, not a tool name..""" - from autoskillit.server import PIPELINE_FORBIDDEN_TOOLS - - expected = { - "Read", - "Grep", - "Glob", - "Edit", - "Write", - "Bash", - "Agent", - "WebFetch", - "WebSearch", - "NotebookEdit", - } - actual = set(PIPELINE_FORBIDDEN_TOOLS) - missing = expected - actual - assert not missing, f"PIPELINE_FORBIDDEN_TOOLS missing tools: {missing}" - - @pytest.mark.anyio - async def test_run_skill_names_all_forbidden_tools(self): - """run_skill docstring must name all forbidden tools.""" - from autoskillit.server import PIPELINE_FORBIDDEN_TOOLS - - tools = await self._get_all_tools() - for tool_name in ("run_skill",): - desc = tools[tool_name].description or "" - missing = [t for t in PIPELINE_FORBIDDEN_TOOLS if t not in desc] - assert not missing, ( - f"{tool_name} docstring must name all forbidden tools. Missing: {missing}" - ) - - def test_bundled_recipe_kitchen_rules_name_all_forbidden_tools(self): - """All bundled recipe kitchen_rules blocks must name every forbidden tool.""" - from autoskillit.recipe.io import builtin_recipes_dir, load_recipe - from autoskillit.server import PIPELINE_FORBIDDEN_TOOLS - - wf_dir = builtin_recipes_dir() - for path in sorted(wf_dir.glob("*.yaml")): - wf = load_recipe(path) - all_constraint_text = " ".join(wf.kitchen_rules) - missing = [t for t in PIPELINE_FORBIDDEN_TOOLS if t not in all_constraint_text] - assert not missing, f"{path.name} kitchen_rules missing forbidden tools: {missing}" - - -def test_server_init_has_no_shim_reexports(): - """server/__init__.py must not re-export tool symbols (shim removed).""" - import autoskillit.server as srv - - # These symbols must NOT be in the server package namespace after shim removal. - # They should only be accessible via their actual submodule paths. - shim_symbols = [ - "_check_dry_walkthrough", - "_require_enabled", - "_run_subprocess", - "_open_kitchen_handler", - "_close_kitchen_handler", - "run_cmd", - "run_python", - "run_skill", - "run_skill_retry", - "test_check", - "reset_test_dir", - "reset_workspace", - "merge_worktree", - "classify_fix", - "clone_repo", - "remove_clone", - "push_to_remote", - "list_recipes", - "load_recipe", - "migrate_recipe", - "validate_recipe", - "get_pipeline_report", - "get_token_summary", - "kitchen_status", - "read_db", - "fetch_github_issue", - ] - present = [sym for sym in shim_symbols if hasattr(srv, sym)] - assert not present, f"Shim re-exports found in server namespace (must be removed): {present}" - - @pytest.mark.anyio async def test_open_kitchen_has_no_update_advisory(tool_ctx): """REQ-APP-004: open_kitchen tool contains no recipe update advisory.""" @@ -1289,6 +387,7 @@ def test_initialize_applies_subset_disables(monkeypatch): ctx = MagicMock(spec=ToolContext) ctx.config = AutomationConfig(subsets=SubsetsConfig(disabled=["github", "ci"])) ctx.session_skill_manager = None + ctx.runner = None with patch("autoskillit.server._ctx", None): with patch("autoskillit.server.mcp", mock_mcp): @@ -1313,6 +412,7 @@ def test_initialize_skips_subset_disable_when_empty(monkeypatch): ctx = MagicMock(spec=ToolContext) ctx.config = AutomationConfig(subsets=SubsetsConfig(disabled=[])) ctx.session_skill_manager = None + ctx.runner = None with patch("autoskillit.server.mcp", mock_mcp): from autoskillit.server._state import _initialize @@ -1320,3 +420,139 @@ def test_initialize_skips_subset_disable_when_empty(monkeypatch): _initialize(ctx) mock_mcp.disable.assert_not_called() + + +# --------------------------------------------------------------------------- +# T9 — server/__init__.py has no shebang +# --------------------------------------------------------------------------- + + +def test_server_init_no_shebang() -> None: + """server/__init__.py must not have a shebang line.""" + import autoskillit.server as server_pkg + + src_path = Path(server_pkg.__file__) # type: ignore[arg-type] + src = src_path.read_text(encoding="utf-8") + assert not src.startswith("#!"), "server/__init__.py must not have a shebang" + + +# --------------------------------------------------------------------------- +# Wire-format compliance (Claude Code #25081) +# --------------------------------------------------------------------------- + +# Fields that Claude Code #25081 silently rejects on tools/list responses. +# If any tool carries a non-None value for these fields, Claude Code drops +# the ENTIRE tool list from that server. +_REJECTED_FIELDS = {"outputSchema", "annotations"} + + +class TestWireFormatCompliance: + """tools/list wire response must be compatible with Claude Code's MCP parser.""" + + @pytest.mark.anyio + async def test_tools_list_contains_no_rejected_fields(self): + """tools/list wire response must not contain fields that trigger + Claude Code #25081 (silent full-tool-list rejection).""" + from fastmcp.client import Client + + from autoskillit.server import mcp + + async with Client(mcp) as client: + tools = await client.list_tools() + for tool in tools: + for field in _REJECTED_FIELDS: + # FastMCP Tool objects use snake_case attrs for camelCase wire fields + attr = "output_schema" if field == "outputSchema" else field + value = getattr(tool, attr, None) + assert value is None, ( + f"Tool '{tool.name}' has non-None {field}={value!r}. " + f"Claude Code #25081 silently drops ALL tools when this field is present." + ) + + +class TestClaudeCodeCompatMiddleware: + """Unit tests for the wire-format sanitization middleware.""" + + @pytest.mark.anyio + async def test_middleware_strips_output_schema(self): + """Middleware must strip outputSchema from every tool.""" + from unittest.mock import AsyncMock, MagicMock + + from autoskillit.server._wire_compat import ClaudeCodeCompatMiddleware + + mw = ClaudeCodeCompatMiddleware() + tool = MagicMock() + tool.name = "test_tool" + tool.output_schema = {"type": "string"} + tool.annotations = None + tool.model_copy.return_value = MagicMock( + name="test_tool", + output_schema=None, + annotations=None, + title=None, + ) + + ctx = MagicMock() + call_next = AsyncMock(return_value=[tool]) + + result = await mw.on_list_tools(ctx, call_next) + tool.model_copy.assert_called_once_with( + update={"output_schema": None, "annotations": None, "title": None}, + ) + assert result[0].output_schema is None + + @pytest.mark.anyio + async def test_middleware_strips_annotations(self): + """Middleware must strip annotations from every tool.""" + from unittest.mock import AsyncMock, MagicMock + + from autoskillit.server._wire_compat import ClaudeCodeCompatMiddleware + + mw = ClaudeCodeCompatMiddleware() + tool = MagicMock() + tool.name = "test_tool" + tool.output_schema = None + tool.annotations = MagicMock(readOnlyHint=True) + tool.model_copy.return_value = MagicMock( + name="test_tool", + output_schema=None, + annotations=None, + title=None, + ) + + ctx = MagicMock() + call_next = AsyncMock(return_value=[tool]) + + result = await mw.on_list_tools(ctx, call_next) + assert result[0].annotations is None + + @pytest.mark.anyio + async def test_middleware_preserves_tool_identity(self): + """Middleware must not alter tool name, description, or inputSchema.""" + from unittest.mock import AsyncMock, MagicMock + + from autoskillit.server._wire_compat import ClaudeCodeCompatMiddleware + + mw = ClaudeCodeCompatMiddleware() + tool = MagicMock() + tool.name = "my_tool" + tool.description = "Does things" + tool.parameters = {"type": "object", "properties": {}} + tool.output_schema = {"type": "string"} + tool.annotations = MagicMock() + copy_mock = MagicMock() + copy_mock.name = "my_tool" + copy_mock.description = "Does things" + copy_mock.parameters = {"type": "object", "properties": {}} + copy_mock.output_schema = None + copy_mock.annotations = None + copy_mock.title = None + tool.model_copy.return_value = copy_mock + + ctx = MagicMock() + call_next = AsyncMock(return_value=[tool]) + + result = await mw.on_list_tools(ctx, call_next) + assert result[0].name == "my_tool" + assert result[0].description == "Does things" + assert result[0].parameters == {"type": "object", "properties": {}} diff --git a/tests/server/test_server_tool_registration.py b/tests/server/test_server_tool_registration.py new file mode 100644 index 0000000000..4241f50f39 --- /dev/null +++ b/tests/server/test_server_tool_registration.py @@ -0,0 +1,721 @@ +"""Tests for MCP tool registration, config-driven behavior, and schema contracts.""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from autoskillit.config import ( + AutomationConfig, + SafetyConfig, +) +from autoskillit.pipeline.gate import DefaultGateState +from autoskillit.server.tools_status import ( + get_quota_events, + get_token_summary, +) + + +class TestNoSkillsDirectoryProvider: + """T3: SkillsDirectoryProvider is not used in the new plugin architecture.""" + + def test_no_skills_directory_provider(self): + """server.py must not reference SkillsDirectoryProvider.""" + import autoskillit.server as server_module + + source = Path(server_module.__file__).read_text() + assert "SkillsDirectoryProvider" not in source + + +class TestToolRegistration: + """All 44 tools are registered on the MCP server.""" + + @pytest.mark.anyio + async def test_all_tools_exist(self, kitchen_enabled): + from fastmcp.client import Client + + from autoskillit.server import mcp + + async with Client(mcp) as client: + all_tools = await client.list_tools() + tool_names = {t.name for t in all_tools} + + expected = { + "run_cmd", + "run_python", + "run_skill", + "test_check", + "reset_test_dir", + "classify_fix", + "reset_workspace", + "merge_worktree", + "read_db", + "list_recipes", + "load_recipe", + "migrate_recipe", + "kitchen_status", + "validate_recipe", + "get_pipeline_report", + "get_token_summary", + "get_timing_summary", + "get_quota_events", + "clone_repo", + "remove_clone", + "push_to_remote", + "fetch_github_issue", + "get_issue_title", + "report_bug", + "prepare_issue", + "enrich_issues", + "claim_issue", + "release_issue", + "wait_for_ci", + "wait_for_merge_queue", + "check_repo_merge_state", + "toggle_auto_merge", + "get_ci_status", + "open_kitchen", + "close_kitchen", + "disable_quota_guard", + "create_unique_branch", + "check_pr_mergeable", + "write_telemetry_files", + "get_pr_reviews", + "bulk_close_issues", + "set_commit_status", + "register_clone_status", + "batch_cleanup_clones", + } + assert expected == tool_names + + @pytest.mark.anyio + async def test_ungated_tools_lack_kitchen_tag(self, kitchen_enabled): + """Ungated (free-range) tools are visible without kitchen and carry no 'kitchen' tag.""" + from fastmcp.client import Client + + from autoskillit.pipeline.gate import UNGATED_TOOLS + from autoskillit.server import mcp + + async with Client(mcp) as client: + visible_names = {t.name for t in await client.list_tools()} + for name in UNGATED_TOOLS: + assert name in visible_names, f"{name} should be visible without kitchen" + + # Verify no ungated tool carries the kitchen tag (internal registry check) + all_tools = {t.name: t for t in await mcp.list_tools()} + for name in UNGATED_TOOLS: + tool = all_tools.get(name) + if tool is not None: + assert "kitchen" not in tool.tags, ( + f"Ungated tool '{name}' must not carry the 'kitchen' tag" + ) + + # test_check now has the kitchen tag (it's headless-tier, not free-range) + all_tools_with_kitchen = {t.name: t for t in await mcp.list_tools()} + tc = all_tools_with_kitchen.get("test_check") + assert tc is not None, "test_check must be registered" + assert "kitchen" in tc.tags, "test_check must carry the 'kitchen' tag" + + @pytest.mark.anyio + async def test_kitchen_tools_have_autoskillit_and_kitchen_tags(self, kitchen_enabled): + """Every tool in GATED_TOOLS carries both 'autoskillit' and 'kitchen' tags.""" + from autoskillit.pipeline.gate import GATED_TOOLS + from autoskillit.server import mcp + + all_tools = {t.name: t for t in await mcp.list_tools()} + for name in GATED_TOOLS: + tool = all_tools.get(name) + assert tool is not None, f"Gated tool '{name}' not registered on server" + assert "autoskillit" in tool.tags, f"Gated tool '{name}' missing 'autoskillit' tag" + assert "kitchen" in tool.tags, f"Gated tool '{name}' missing 'kitchen' tag" + assert "automation" not in tool.tags, ( + f"Gated tool '{name}' still has deprecated 'automation' tag" + ) + + @pytest.mark.anyio + async def test_all_tools_tagged_autoskillit(self, kitchen_enabled, headless_enabled): + """Every registered tool carries the 'autoskillit' tag.""" + from autoskillit.server import mcp + + all_tools = await mcp.list_tools() + for tool in all_tools: + assert "autoskillit" in tool.tags, f"Tool '{tool.name}' missing 'autoskillit' tag" + assert "automation" not in tool.tags, f"Tool '{tool.name}' still has 'automation' tag" + + def test_ungated_tools_docstrings_state_notification_free(self): + """P5-1: Free-range tool docstrings state they send no MCP notifications.""" + + for tool_fn in [get_token_summary, get_quota_events]: + doc = tool_fn.__doc__ or "" + assert "no MCP" in doc or "no progress notification" in doc.lower(), ( + f"{tool_fn.__name__} must document notification-free behavior" + ) + + @pytest.mark.anyio + async def test_test_check_has_headless_tag(self, kitchen_enabled): + from autoskillit.server import mcp + + all_tools = {t.name: t for t in await mcp.list_tools()} + tc = all_tools.get("test_check") + assert tc is not None + assert "headless" in tc.tags + assert "kitchen" in tc.tags + assert "autoskillit" in tc.tags + + @pytest.mark.anyio + async def test_headless_enable_reveals_only_headless_tagged_tools(self, headless_enabled): + from fastmcp.client import Client + + from autoskillit.pipeline.gate import GATED_TOOLS + from autoskillit.server import mcp + + async with Client(mcp) as client: + visible = {t.name for t in await client.list_tools()} + assert "test_check" in visible + # Kitchen-only tools (no headless tag) must NOT be revealed + kitchen_only = GATED_TOOLS - {"test_check"} + for name in kitchen_only: + assert name not in visible, f"{name} should not be revealed by headless-only enable" + + +class TestConfigDrivenBehavior: + """S1-S10: Verify tools use config instead of hardcoded values.""" + + @pytest.mark.anyio + async def test_test_check_uses_config_command(self, tool_ctx): + """S1: test_check runs config.test_check.command.""" + from autoskillit.config import TestCheckConfig + from autoskillit.execution import DefaultTestRunner + from autoskillit.server.tools_workspace import test_check + from tests.conftest import _make_result + + tool_ctx.config = AutomationConfig( + test_check=TestCheckConfig(command=["pytest", "-x"], timeout=300) + ) + # Re-create tester with updated config so it reads the new command + tool_ctx.tester = DefaultTestRunner(config=tool_ctx.config, runner=tool_ctx.runner) + + tool_ctx.runner.push(_make_result(0, "= 100 passed =\n", "")) + await test_check(worktree_path="/tmp/wt") + + assert tool_ctx.runner.call_args_list[0][0] == ["pytest", "-x"] + assert tool_ctx.runner.call_args_list[0][2] == 300.0 + + @pytest.mark.anyio + async def test_classify_fix_uses_config_prefixes(self, tool_ctx, tmp_path): + """S2: classify_fix uses config.classify_fix.path_prefixes.""" + from autoskillit.config import ClassifyFixConfig + from autoskillit.core.types import RestartScope + from autoskillit.server.tools_git import classify_fix + from tests.conftest import _make_result + + tool_ctx.config = AutomationConfig( + classify_fix=ClassifyFixConfig(path_prefixes=["src/custom/"]) + ) + + changed = "src/custom/handler.py\nsrc/other/util.py\n" + tool_ctx.runner.push(_make_result(0, "", "")) # git fetch succeeds + tool_ctx.runner.push(_make_result(0, changed, "")) + result = json.loads(await classify_fix(worktree_path=str(tmp_path), base_branch="main")) + + assert result["restart_scope"] == RestartScope.FULL_RESTART + assert "src/custom/handler.py" in result["critical_files"] + + @pytest.mark.anyio + async def test_classify_fix_empty_prefixes_always_partial(self, tool_ctx, tmp_path): + """S3: Empty prefix list -> always returns partial_restart.""" + from autoskillit.config import ClassifyFixConfig + from autoskillit.core.types import RestartScope + from autoskillit.server.tools_git import classify_fix + from tests.conftest import _make_result + + tool_ctx.config = AutomationConfig(classify_fix=ClassifyFixConfig(path_prefixes=[])) + + changed = "src/core/handler.py\n" + tool_ctx.runner.push(_make_result(0, "", "")) # git fetch succeeds + tool_ctx.runner.push(_make_result(0, changed, "")) + result = json.loads(await classify_fix(worktree_path=str(tmp_path), base_branch="main")) + + assert result["restart_scope"] == RestartScope.PARTIAL_RESTART + + @pytest.mark.anyio + async def test_reset_workspace_uses_config_command(self, tool_ctx, tmp_path): + """S4: reset_workspace runs config.reset_workspace.command.""" + from autoskillit.config import ResetWorkspaceConfig + from autoskillit.server.tools_workspace import reset_workspace + from tests.conftest import _make_result + + tool_ctx.config = AutomationConfig( + reset_workspace=ResetWorkspaceConfig(command=["make", "reset"]) + ) + + workspace = tmp_path / "workspace" + workspace.mkdir(parents=True) + (workspace / ".autoskillit-workspace").write_text("# marker\n") + tool_ctx.runner.push(_make_result(0, "", "")) + + await reset_workspace(test_dir=str(workspace)) + assert tool_ctx.runner.call_args_list[0][0] == ["make", "reset"] + + @pytest.mark.anyio + async def test_reset_workspace_not_configured_returns_error(self, tool_ctx, tmp_path): + """S5: command=None -> returns not-configured error.""" + from autoskillit.config import ResetWorkspaceConfig + from autoskillit.server.tools_workspace import reset_workspace + + tool_ctx.config = AutomationConfig(reset_workspace=ResetWorkspaceConfig(command=None)) + + workspace = tmp_path / "workspace" + workspace.mkdir(parents=True) + (workspace / ".autoskillit-workspace").write_text("# marker\n") + result = json.loads(await reset_workspace(test_dir=str(workspace))) + + assert result["error"] == "reset_workspace not configured for this project" + + @pytest.mark.anyio + async def test_reset_workspace_uses_config_preserve_dirs(self, tool_ctx, tmp_path): + """S6: Preserves config.reset_workspace.preserve_dirs.""" + from autoskillit.config import ResetWorkspaceConfig + from autoskillit.server.tools_workspace import reset_workspace + from tests.conftest import _make_result + + tool_ctx.config = AutomationConfig( + reset_workspace=ResetWorkspaceConfig( + command=["true"], + preserve_dirs={"keep_me"}, + ) + ) + + workspace = tmp_path / "workspace" + workspace.mkdir(parents=True) + (workspace / ".autoskillit-workspace").write_text("# marker\n") + (workspace / "keep_me").mkdir() + (workspace / "delete_me").touch() + tool_ctx.runner.push(_make_result(0, "", "")) + + result = json.loads(await reset_workspace(test_dir=str(workspace))) + + assert "keep_me" in result["skipped"] + assert "delete_me" in result["deleted"] + assert (workspace / "keep_me").exists() + assert not (workspace / "delete_me").exists() + + def test_dry_walkthrough_uses_config_marker(self, tool_ctx, tmp_path): + """S7: Gate checks config.implement_gate.marker.""" + from autoskillit.config import ImplementGateConfig + from autoskillit.server.helpers import _check_dry_walkthrough + + tool_ctx.config = AutomationConfig( + implement_gate=ImplementGateConfig(marker="CUSTOM MARKER") + ) + + plan = tmp_path / "plan.md" + plan.write_text("CUSTOM MARKER\n# Plan content") + result = _check_dry_walkthrough(f"/autoskillit:implement-worktree {plan}", str(tmp_path)) + assert result is None # passes with custom marker + + plan.write_text("Dry-walkthrough verified = TRUE\n# Plan content") + result = _check_dry_walkthrough(f"/autoskillit:implement-worktree {plan}", str(tmp_path)) + assert result is not None # fails — marker doesn't match + + def test_dry_walkthrough_uses_config_skill_names(self, tool_ctx, tmp_path): + """S8: Gate checks config.implement_gate.skill_names.""" + from autoskillit.config import ImplementGateConfig + from autoskillit.server.helpers import _check_dry_walkthrough + + tool_ctx.config = AutomationConfig( + implement_gate=ImplementGateConfig(skill_names={"/custom-impl"}) + ) + + plan = tmp_path / "plan.md" + plan.write_text("# No marker") + + result = _check_dry_walkthrough(f"/custom-impl {plan}", str(tmp_path)) + assert result is not None # /custom-impl is gated + + result = _check_dry_walkthrough(f"/autoskillit:implement-worktree {plan}", str(tmp_path)) + assert result is None # /autoskillit:implement-worktree is NOT gated (not in skill_names) + + @pytest.mark.anyio + async def test_merge_worktree_uses_config_test_command(self, tool_ctx, tmp_path): + """S9: Merge's test gate runs config.test_check.command.""" + from autoskillit.config import TestCheckConfig + from autoskillit.core.types import MergeFailedStep + from autoskillit.execution import DefaultTestRunner + from autoskillit.server.tools_git import merge_worktree + from tests.conftest import _make_result + + tool_ctx.config = AutomationConfig( + test_check=TestCheckConfig(command=["make", "test"], timeout=120) + ) + # Re-create tester with updated config so it reads the new command + tool_ctx.tester = DefaultTestRunner(config=tool_ctx.config, runner=tool_ctx.runner) + + wt = tmp_path / "worktree" + wt.mkdir() + (wt / ".git").write_text("gitdir: /repo/.git/worktrees/wt") + + tool_ctx.runner.push(_make_result(0, "/repo/.git/worktrees/wt\n", "")) # rev-parse + tool_ctx.runner.push(_make_result(0, "impl-branch\n", "")) # branch + tool_ctx.runner.push(_make_result(0, "", "")) # git ls-files (pre-dirty-tree check) + tool_ctx.runner.push(_make_result(0, "", "")) # git status --porcelain (clean) + tool_ctx.runner.push(_make_result(1, "FAIL", "")) # test gate fails + result = json.loads(await merge_worktree(str(wt), "dev")) + assert result["failed_step"] == MergeFailedStep.TEST_GATE + + # Verify the test command was ["make", "test"] (5th call, after ls-files + porcelain) + test_call = tool_ctx.runner.call_args_list[4] + assert test_call[0] == ["make", "test"] + + @pytest.mark.anyio + async def test_require_enabled_still_gates_execution(self, tool_ctx): + """S10: _require_enabled() defense-in-depth still works with config.""" + from autoskillit.server.tools_execution import run_cmd + + tool_ctx.gate = DefaultGateState(enabled=False) + result = json.loads(await run_cmd(cmd="echo hi", cwd="/tmp")) + assert result["success"] is False + assert result["is_error"] is True + assert "not enabled" in result["result"].lower() + + +class TestSafetyConfigWiring: + """Safety config fields are read at the point of enforcement.""" + + @pytest.mark.anyio + async def test_reset_test_dir_allows_with_marker(self, tool_ctx, tmp_path): + """2a: Directory with marker passes the reset guard.""" + from autoskillit.server.tools_workspace import reset_test_dir + + target = tmp_path / "my_project" + target.mkdir() + (target / ".autoskillit-workspace").write_text("# marker\n") + (target / "file.txt").touch() + + result = json.loads(await reset_test_dir(test_dir=str(target), force=False)) + assert result["success"] is True + + @pytest.mark.anyio + async def test_reset_test_dir_enforces_marker_when_missing(self, tool_ctx, tmp_path): + """2b: Missing marker blocks reset_test_dir.""" + from autoskillit.server.tools_workspace import reset_test_dir + + target = tmp_path / "unmarked" + target.mkdir() + result = json.loads(await reset_test_dir(test_dir=str(target))) + assert "error" in result + assert "marker" in result["error"].lower() + + @pytest.mark.anyio + async def test_reset_workspace_enforces_marker(self, tool_ctx, tmp_path): + """2c: reset_workspace requires marker, then checks command config.""" + from autoskillit.config import ResetWorkspaceConfig + from autoskillit.server.tools_workspace import reset_workspace + + tool_ctx.config = AutomationConfig(reset_workspace=ResetWorkspaceConfig(command=None)) + + target = tmp_path / "my_project" + target.mkdir() + (target / ".autoskillit-workspace").write_text("# marker\n") + + result = json.loads(await reset_workspace(test_dir=str(target))) + # Should pass marker guard but fail on "not configured" + assert result["error"] == "reset_workspace not configured for this project" + + @pytest.mark.anyio + async def test_merge_worktree_skips_test_gate_when_disabled(self, tool_ctx, tmp_path): + """2d: test_gate_on_merge=False skips test execution.""" + from autoskillit.server.tools_git import merge_worktree + from tests.conftest import _make_result + + tool_ctx.config = AutomationConfig(safety=SafetyConfig(test_gate_on_merge=False)) + + wt = tmp_path / "worktree" + wt.mkdir() + (wt / ".git").write_text("gitdir: /repo/.git/worktrees/wt") + + tool_ctx.runner.push(_make_result(0, "/repo/.git/worktrees/wt\n", "")) # rev-parse + tool_ctx.runner.push(_make_result(0, "impl-branch\n", "")) # branch + tool_ctx.runner.push(_make_result(0, "", "")) # git ls-files (pre-dirty-tree check) + tool_ctx.runner.push(_make_result(0, "", "")) # git status --porcelain (clean) + # NO test-check call — skipped + tool_ctx.runner.push(_make_result(0, "", "")) # git fetch + tool_ctx.runner.push(_make_result(0, "abc123\n", "")) # rev-parse --verify (step 5.5) + tool_ctx.runner.push( + _make_result(0, "", "") + ) # git log --merges (step 5.6 — no merge commits) + tool_ctx.runner.push(_make_result(0, "", "")) # git rebase + tool_ctx.runner.push( + _make_result( + 0, + "worktree /repo\nHEAD abc\nbranch refs/heads/dev\n\n", + "", + ) + ) # worktree list + tool_ctx.runner.push(_make_result(0, "dev\n", "")) # git branch --show-current (step 7.5) + tool_ctx.runner.push(_make_result(0, "", "")) # git merge + tool_ctx.runner.push(_make_result(0, "", "")) # worktree remove + tool_ctx.runner.push(_make_result(0, "", "")) # branch -D + result = json.loads(await merge_worktree(str(wt), "dev")) + assert result["merge_succeeded"] is True + + # Verify no test command was called — the 5th call should be git fetch, not test + fifth_call_cmd = tool_ctx.runner.call_args_list[4][0] + assert fifth_call_cmd == ["git", "fetch", "origin"] + + @pytest.mark.anyio + async def test_run_skill_2e_skips_dry_walkthrough_when_disabled(self, tool_ctx, tmp_path): + """2e: require_dry_walkthrough=False bypasses dry-walkthrough gate (using run_skill).""" + from autoskillit.server.tools_execution import run_skill + from tests.conftest import _make_result + + tool_ctx.config = AutomationConfig(safety=SafetyConfig(require_dry_walkthrough=False)) + + plan = tmp_path / "plan.md" + plan.write_text("# No marker plan") + + tool_ctx.runner.push(_make_result(0, '{"result": "done"}', "")) + result = json.loads( + await run_skill(f"/autoskillit:implement-worktree {plan}", str(tmp_path)) + ) + assert result["subtype"] != "gate_error" + assert result["exit_code"] == 0 + + @pytest.mark.anyio + async def test_run_skill_enforces_dry_walkthrough_when_enabled(self, tool_ctx, tmp_path): + """2f: run_skill enforces dry-walkthrough gate when enabled (default).""" + from autoskillit.server.tools_execution import run_skill + + plan = tmp_path / "plan.md" + plan.write_text("# No marker plan") + + result = json.loads( + await run_skill(f"/autoskillit:implement-worktree {plan}", str(tmp_path)) + ) + assert result["success"] is False + assert result["is_error"] is True + assert "dry-walked" in result["result"].lower() + + @pytest.mark.anyio + async def test_run_skill_skips_dry_walkthrough_when_disabled(self, tool_ctx, tmp_path): + """2g: run_skill skips dry-walkthrough gate when disabled.""" + from autoskillit.server.tools_execution import run_skill + from tests.conftest import _make_result + + tool_ctx.config = AutomationConfig(safety=SafetyConfig(require_dry_walkthrough=False)) + + plan = tmp_path / "plan.md" + plan.write_text("# No marker plan") + + tool_ctx.runner.push(_make_result(0, '{"result": "done"}', "")) + result = json.loads( + await run_skill(f"/autoskillit:implement-worktree {plan}", str(tmp_path)) + ) + assert result["subtype"] != "gate_error" + + +class TestToolSchemas: + """Regression guard: tool descriptions must not contain legacy terminology.""" + + FORBIDDEN_TERMS = { + "executor", + "planner", + "automation-mcp", + "ai-executor", + "enable_tools", # old open_kitchen prompt name + "disable_tools", # old close_kitchen prompt name + "autoskillit_status", # old kitchen_status tool name + } + + REQUIRED_CROSS_REFS: dict[str, list[str]] = { + "list_recipes": [ + "write-recipe", + ], + "load_recipe": [ + "write-recipe", + ], + "validate_recipe": [ + "write-recipe", + ], + } + + @property + def FORBIDDEN_NATIVE_TOOLS(self) -> list[str]: # noqa: N802 + from autoskillit.server import PIPELINE_FORBIDDEN_TOOLS + + return list(PIPELINE_FORBIDDEN_TOOLS) + + PIPELINE_TOOLS_WITH_GUIDANCE: dict[str, list[str]] = { + "run_skill": ["MCP tool", "delegate"], + } + + async def _get_all_tools(self, kitchen_enabled) -> dict: + """Return dict of tool_name -> tool for all tools, including kitchen-gated ones.""" + from fastmcp.client import Client + + from autoskillit.server import mcp + + async with Client(mcp) as client: + tools = await client.list_tools() + return {t.name: t for t in tools} + + @pytest.mark.anyio + async def test_tool_descriptions_contain_no_legacy_terms(self, kitchen_enabled): + """No registered tool should reference old package terminology.""" + all_tools_dict = await self._get_all_tools(kitchen_enabled) + all_tools = list(all_tools_dict.values()) + for tool in all_tools: + desc = (tool.description or "").lower() + for term in self.FORBIDDEN_TERMS: + assert term not in desc, ( + f"Tool '{tool.name}' description contains legacy term '{term}'" + ) + + @pytest.mark.anyio + async def test_tool_docstrings_contain_required_cross_refs(self, kitchen_enabled): + """Tool docstrings must contain required cross-references.""" + tools = await self._get_all_tools(kitchen_enabled) + for tool_name, required_terms in self.REQUIRED_CROSS_REFS.items(): + tool = tools.get(tool_name) + assert tool is not None, f"Tool '{tool_name}' not found in server" + desc = tool.description or "" + for term in required_terms: + assert term in desc, f"Tool '{tool_name}' description must reference '{term}'" + + @pytest.mark.anyio + async def test_classify_fix_docstring_has_routing_guidance(self, kitchen_enabled): + """classify_fix must explain what to do with each return value.""" + tools = await self._get_all_tools(kitchen_enabled) + assert "classify_fix" in tools, "Tool 'classify_fix' not found in server" + desc = tools["classify_fix"].description or "" + # Must mention both routing outcomes + assert "full_restart" in desc + assert "partial_restart" in desc + # Must mention at least one skill as routing target + assert "investigate" in desc or "implement" in desc + + @pytest.mark.anyio + async def test_recipe_tools_have_disambiguation(self, kitchen_enabled): + """All recipe-related tools must carry the 'NOT slash commands' disclaimer.""" + tools = await self._get_all_tools(kitchen_enabled) + recipe_tools = ["list_recipes", "load_recipe", "validate_recipe"] + for tool_name in recipe_tools: + tool = tools.get(tool_name) + assert tool is not None, f"Tool '{tool_name}' not found" + desc = tool.description or "" + assert "NOT slash commands" in desc, ( + f"Tool '{tool_name}' must contain 'NOT slash commands' disclaimer" + ) + + @pytest.mark.anyio + async def test_load_recipe_names_all_forbidden_tools(self, kitchen_enabled): + """load_recipe must enumerate all forbidden native tools.""" + tools = await self._get_all_tools(kitchen_enabled) + desc = tools["load_recipe"].description or "" + + missing = [t for t in self.FORBIDDEN_NATIVE_TOOLS if t not in desc] + assert not missing, ( + f"load_recipe docstring must name all forbidden tools. Missing: {missing}" + ) + + @pytest.mark.anyio + async def test_pipeline_tools_have_orchestrator_guidance(self, kitchen_enabled): + """run_skill must reinforce MCP-only delegation.""" + tools = await self._get_all_tools(kitchen_enabled) + failures = [] + for tool_name, required_terms in self.PIPELINE_TOOLS_WITH_GUIDANCE.items(): + desc = tools[tool_name].description or "" + for term in required_terms: + if term.lower() not in desc.lower(): + failures.append(f"Tool '{tool_name}' missing orchestrator term '{term}'") + assert not failures, "Pipeline tools missing orchestrator guidance:\n" + "\n".join( + f" - {f}" for f in failures + ) + + def test_pipeline_forbidden_tools_constant_is_complete(self): + """PIPELINE_FORBIDDEN_TOOLS must contain all 10 native Claude Code tools. + + "Agent" replaces the stale "Task" and "Explore" names — Agent is the + actual tool name; Explore is a subagent_type parameter, not a tool name..""" + from autoskillit.server import PIPELINE_FORBIDDEN_TOOLS + + expected = { + "Read", + "Grep", + "Glob", + "Edit", + "Write", + "Bash", + "Agent", + "WebFetch", + "WebSearch", + "NotebookEdit", + } + actual = set(PIPELINE_FORBIDDEN_TOOLS) + missing = expected - actual + assert not missing, f"PIPELINE_FORBIDDEN_TOOLS missing tools: {missing}" + + @pytest.mark.anyio + async def test_run_skill_names_all_forbidden_tools(self, kitchen_enabled): + """run_skill docstring must name all forbidden tools.""" + from autoskillit.server import PIPELINE_FORBIDDEN_TOOLS + + tools = await self._get_all_tools(kitchen_enabled) + for tool_name in ("run_skill",): + desc = tools[tool_name].description or "" + missing = [t for t in PIPELINE_FORBIDDEN_TOOLS if t not in desc] + assert not missing, ( + f"{tool_name} docstring must name all forbidden tools. Missing: {missing}" + ) + + def test_bundled_recipe_kitchen_rules_name_all_forbidden_tools(self): + """All bundled recipe kitchen_rules blocks must name every forbidden tool.""" + from autoskillit.recipe.io import builtin_recipes_dir, load_recipe + from autoskillit.server import PIPELINE_FORBIDDEN_TOOLS + + wf_dir = builtin_recipes_dir() + for path in sorted(wf_dir.glob("*.yaml")): + wf = load_recipe(path) + all_constraint_text = " ".join(wf.kitchen_rules) + missing = [t for t in PIPELINE_FORBIDDEN_TOOLS if t not in all_constraint_text] + assert not missing, f"{path.name} kitchen_rules missing forbidden tools: {missing}" + + +def test_server_init_has_no_shim_reexports(): + """server/__init__.py must not re-export tool symbols (shim removed).""" + import autoskillit.server as srv + + # These symbols must NOT be in the server package namespace after shim removal. + # They should only be accessible via their actual submodule paths. + shim_symbols = [ + "_check_dry_walkthrough", + "_require_enabled", + "_run_subprocess", + "_open_kitchen_handler", + "_close_kitchen_handler", + "run_cmd", + "run_python", + "run_skill", + "run_skill_retry", + "test_check", + "reset_test_dir", + "reset_workspace", + "merge_worktree", + "classify_fix", + "clone_repo", + "remove_clone", + "push_to_remote", + "list_recipes", + "load_recipe", + "migrate_recipe", + "validate_recipe", + "get_pipeline_report", + "get_token_summary", + "kitchen_status", + "read_db", + "fetch_github_issue", + ] + present = [sym for sym in shim_symbols if hasattr(srv, sym)] + assert not present, f"Shim re-exports found in server namespace (must be removed): {present}" diff --git a/tests/server/test_server_version_telemetry.py b/tests/server/test_server_version_telemetry.py new file mode 100644 index 0000000000..f81fad3ba0 --- /dev/null +++ b/tests/server/test_server_version_telemetry.py @@ -0,0 +1,188 @@ +"""Tests for server version info, plugin metadata, lazy init, and telemetry.""" + +from __future__ import annotations + +import json +from pathlib import Path +from unittest.mock import patch + +import pytest + + +class TestPluginMetadataExists: + """T1: Plugin metadata files are shipped in the package.""" + + def test_plugin_json_exists(self): + """Package contains .claude-plugin/plugin.json with correct fields.""" + import autoskillit + + pkg = Path(autoskillit.__file__).parent + manifest = pkg / ".claude-plugin" / "plugin.json" + assert manifest.is_file() + data = json.loads(manifest.read_text()) + assert data["name"] == "autoskillit" + assert data["version"] == autoskillit.__version__ + + def test_mcp_json_exists(self): + """Package contains .mcp.json with autoskillit server entry.""" + import autoskillit + + pkg = Path(autoskillit.__file__).parent + mcp_cfg = pkg / ".mcp.json" + assert mcp_cfg.is_file() + data = json.loads(mcp_cfg.read_text()) + assert "autoskillit" in data["mcpServers"] + assert data["mcpServers"]["autoskillit"]["command"] == "autoskillit" + + +class TestPluginDirConstant: + """T6: tool_ctx.plugin_dir defaults to the package root directory.""" + + def test_plugin_dir_assignment_is_visible_via_get_ctx(self, tool_ctx): + """By default tool_ctx.plugin_dir is set to tmp_path by the fixture. + + The real package dir is what the server uses at runtime (set by cli.py serve()). + This test verifies that the fixture wires plugin_dir through _ctx correctly. + """ + import autoskillit + + # The real package dir is what the server sets at startup. + # We verify the attribute path works (tool_ctx.plugin_dir is accessible). + real_pkg_dir = str(Path(autoskillit.__file__).parent) + # tool_ctx uses tmp_path; set it to verify end-to-end wiring + tool_ctx.plugin_dir = real_pkg_dir + from autoskillit.server import _get_ctx + + assert _get_ctx().plugin_dir == real_pkg_dir + + +class TestVersionInfo: + """version_info() returns package and plugin.json versions.""" + + def test_version_info_returns_package_and_plugin_versions(self, monkeypatch): + from autoskillit import __version__ + from autoskillit.server import _state, version_info + + monkeypatch.setattr(_state, "_ctx", None) + info = version_info() + assert isinstance(info["package_version"], str) + assert isinstance(info["plugin_json_version"], str) + assert info["package_version"] == __version__ + assert info["match"] is True + + def test_version_info_detects_mismatch(self, tmp_path, tool_ctx): + from autoskillit.server import version_info + + plugin_dir = tmp_path / ".claude-plugin" + plugin_dir.mkdir() + (plugin_dir / "plugin.json").write_text( + json.dumps({"name": "autoskillit", "version": "0.0.0"}) + ) + tool_ctx.plugin_dir = str(tmp_path) + info = version_info() + assert info["match"] is False + assert info["package_version"] != info["plugin_json_version"] + assert info["plugin_json_version"] == "0.0.0" + + def test_version_info_handles_missing_plugin_json(self, tmp_path, tool_ctx): + from autoskillit.server import version_info + + tool_ctx.plugin_dir = str(tmp_path) + info = version_info() + assert info["plugin_json_version"] is None + assert info["match"] is False + + def test_version_info_is_public(self, monkeypatch): + """version_info must be a public function — no underscore prefix.""" + from autoskillit import server + from autoskillit.server import _state + + monkeypatch.setattr(_state, "_ctx", None) + assert hasattr(server, "version_info"), "server.version_info must exist" + assert not hasattr(server, "_version_info"), "server._version_info must be removed" + result = server.version_info() + assert set(result.keys()) >= {"package_version", "plugin_json_version", "match"} + + +class TestServerLazyInit: + """Tests for the _ctx / _initialize() / _get_ctx() / _get_config() pattern.""" + + def test_server_import_does_not_call_load_config(self, monkeypatch): + """Importing server.py must not trigger load_config() as a side effect.""" + import sys + + import autoskillit + + # Restore both the package attribute and sys.modules entry after the test so + # later tests in the same xdist worker see the original module object. + monkeypatch.setattr(autoskillit, "server", autoskillit.server) + monkeypatch.delitem(sys.modules, "autoskillit.server", raising=False) + + with patch("autoskillit.config.load_config") as mock_load: + import autoskillit.server # noqa: F401 + assert not mock_load.called + + def test_get_ctx_raises_before_initialize(self, monkeypatch): + """_get_ctx() raises RuntimeError when _ctx is None.""" + from autoskillit.server import _state + + monkeypatch.setattr(_state, "_ctx", None) + with pytest.raises(RuntimeError, match="serve\\(\\) must be called"): + _state._get_ctx() + + def test_get_config_raises_before_initialize(self, monkeypatch): + """_get_config() raises RuntimeError when _ctx is None.""" + from autoskillit.server import _state + + monkeypatch.setattr(_state, "_ctx", None) + with pytest.raises(RuntimeError, match="serve\\(\\) must be called"): + _state._get_config() + + +class TestInitializeClearMarker: + """_initialize respects telemetry_cleared_at fence for drift prevention.""" + + def test_initialize_uses_clear_marker_as_since_bound(self, tool_ctx, tmp_path, monkeypatch): + from datetime import UTC, datetime, timedelta + + from autoskillit.execution.session_log import ( + flush_session_log, + ) + from autoskillit.server import _state + + log_dir = tmp_path / "logs" + log_dir.mkdir() + + # Write a session that completed 5 hours ago (within 24h window) + five_hours_ago = datetime.now(UTC) - timedelta(hours=5) + flush_session_log( + log_dir=str(log_dir), + cwd="/tmp", + session_id="old-session", + pid=999, + skill_command="/autoskillit:foo", + success=True, + subtype="completed", + exit_code=0, + start_ts=five_hours_ago.isoformat(), + proc_snapshots=None, + step_name="old-step", + token_usage={ + "input_tokens": 1000, + "output_tokens": 500, + "cache_creation_input_tokens": 0, + "cache_read_input_tokens": 0, + }, + timing_seconds=10.0, + ) + + # Write a clear marker 3 hours ago (after the session completed) + three_hours_ago = datetime.now(UTC) - timedelta(hours=3) + (log_dir / ".telemetry_cleared_at").write_text(three_hours_ago.isoformat()) + + monkeypatch.setattr(tool_ctx.config.linux_tracing, "log_dir", str(log_dir)) + _state._initialize(tool_ctx) + + # The old-session happened before the clear marker → should NOT be replayed + report = tool_ctx.token_log.get_report() + assert all(s["step_name"] != "old-step" for s in report) diff --git a/tests/server/test_service_wrappers.py b/tests/server/test_service_wrappers.py index f1eacd7461..67bfd2878a 100644 --- a/tests/server/test_service_wrappers.py +++ b/tests/server/test_service_wrappers.py @@ -28,6 +28,8 @@ def test_list_all_returns_recipes_key(self, tmp_path: Path) -> None: result = self.repo.list_all(project_dir=tmp_path) assert isinstance(result, dict), "list_all() must return a dict" assert "recipes" in result, f"Expected 'recipes' key, got: {list(result)}" + assert isinstance(result["recipes"], list) + assert len(result["recipes"]) >= 1 def test_load_and_validate_returns_content_and_valid(self, tmp_path: Path) -> None: """load_and_validate() for a bundled recipe returns 'content' and 'valid' keys.""" @@ -35,6 +37,8 @@ def test_load_and_validate_returns_content_and_valid(self, tmp_path: Path) -> No assert isinstance(result, dict), "load_and_validate() must return a dict" assert "content" in result, f"Expected 'content' key in result, got: {list(result)}" assert "valid" in result, f"Expected 'valid' key in result, got: {list(result)}" + assert isinstance(result["valid"], bool) + assert result["content"] def test_validate_from_path_returns_findings(self) -> None: """validate_from_path() returns a dict with 'valid' and 'findings' keys.""" @@ -45,6 +49,8 @@ def test_validate_from_path_returns_findings(self) -> None: assert isinstance(result, dict), "validate_from_path() must return a dict" assert "valid" in result, f"Expected 'valid' key in result, got: {list(result)}" assert "findings" in result, f"Expected 'findings' key in result, got: {list(result)}" + assert isinstance(result["valid"], bool) + assert isinstance(result["findings"], list) class TestDefaultMigrationService: diff --git a/tests/server/test_set_commit_status.py b/tests/server/test_set_commit_status.py index 8a20915c6c..3e84f084a7 100644 --- a/tests/server/test_set_commit_status.py +++ b/tests/server/test_set_commit_status.py @@ -2,12 +2,20 @@ from __future__ import annotations +import json + import pytest from autoskillit.pipeline.gate import GATED_TOOLS, DefaultGateState from autoskillit.server.tools_ci import set_commit_status from tests.conftest import _make_result + +async def _async_return(value: object) -> object: + """Minimal async helper returning a fixed value — for monkeypatching async callables.""" + return value + + # --------------------------------------------------------------------------- # Gate membership # --------------------------------------------------------------------------- @@ -27,11 +35,12 @@ def test_set_commit_status_is_kitchen_gated(): async def test_set_commit_status_gate_check(tool_ctx): """Gate-closed returns gate_error, never calls subprocess.""" tool_ctx.gate = DefaultGateState(enabled=False) - result = await set_commit_status( + raw = await set_commit_status( sha="abc123", state="pending", context="autoskillit/ai-review", ) + result = json.loads(raw) assert result["success"] is False assert result.get("subtype") == "gate_error" # set_commit_status calls _run_subprocess → tool_ctx.runner (confirmed wired by @@ -46,20 +55,22 @@ async def test_set_commit_status_gate_check(tool_ctx): @pytest.mark.anyio -async def test_set_commit_status_posts_pending(tool_ctx): +async def test_set_commit_status_posts_pending(tool_ctx, monkeypatch): """Tool posts gh api with state=pending to the correct endpoint.""" - # First call: gh repo view (repo inference) - tool_ctx.runner.push(_make_result(0, "owner/repo\n", "")) - # Second call: gh api POST + monkeypatch.setattr( + "autoskillit.server.tools_ci.infer_repo_from_remote", + lambda cwd, hint=None: _async_return("owner/repo"), + ) tool_ctx.runner.push(_make_result(0, "", "")) - result = await set_commit_status( + raw = await set_commit_status( sha="deadbeef", state="pending", context="autoskillit/ai-review", description="AI review in progress", cwd="/some/repo", ) + result = json.loads(raw) assert result["success"] is True assert result["sha"] == "deadbeef" @@ -67,8 +78,7 @@ async def test_set_commit_status_posts_pending(tool_ctx): assert result["context"] == "autoskillit/ai-review" # Verify the POST call went to the right endpoint - # MockSubprocessRunner stores (cmd, cwd, timeout, kwargs) tuples - cmd, *_ = tool_ctx.runner.call_args_list[1] + cmd, *_ = tool_ctx.runner.call_args_list[0] cmd_str = " ".join(cmd) assert "/repos/owner/repo/statuses/deadbeef" in cmd_str assert "pending" in cmd_str @@ -80,23 +90,27 @@ async def test_set_commit_status_posts_pending(tool_ctx): @pytest.mark.anyio -async def test_set_commit_status_posts_success(tool_ctx): +async def test_set_commit_status_posts_success(tool_ctx, monkeypatch): """Tool posts gh api with state=success and context preserved.""" - tool_ctx.runner.push(_make_result(0, "myorg/myrepo\n", "")) + monkeypatch.setattr( + "autoskillit.server.tools_ci.infer_repo_from_remote", + lambda cwd, hint=None: _async_return("myorg/myrepo"), + ) tool_ctx.runner.push(_make_result(0, "", "")) - result = await set_commit_status( + raw = await set_commit_status( sha="cafebabe", state="success", context="autoskillit/ai-review", cwd="/some/repo", ) + result = json.loads(raw) assert result["success"] is True assert result["state"] == "success" assert result["context"] == "autoskillit/ai-review" - post_cmd = " ".join(tool_ctx.runner.call_args_list[1][0]) + post_cmd = " ".join(tool_ctx.runner.call_args_list[0][0]) assert "success" in post_cmd @@ -106,22 +120,26 @@ async def test_set_commit_status_posts_success(tool_ctx): @pytest.mark.anyio -async def test_set_commit_status_posts_failure(tool_ctx): +async def test_set_commit_status_posts_failure(tool_ctx, monkeypatch): """Tool posts gh api with state=failure.""" - tool_ctx.runner.push(_make_result(0, "owner/repo\n", "")) + monkeypatch.setattr( + "autoskillit.server.tools_ci.infer_repo_from_remote", + lambda cwd, hint=None: _async_return("owner/repo"), + ) tool_ctx.runner.push(_make_result(0, "", "")) - result = await set_commit_status( + raw = await set_commit_status( sha="feedface", state="failure", context="autoskillit/ai-review", cwd="/some/repo", ) + result = json.loads(raw) assert result["success"] is True assert result["state"] == "failure" - post_cmd = " ".join(tool_ctx.runner.call_args_list[1][0]) + post_cmd = " ".join(tool_ctx.runner.call_args_list[0][0]) assert "failure" in post_cmd @@ -131,71 +149,84 @@ async def test_set_commit_status_posts_failure(tool_ctx): @pytest.mark.anyio -async def test_set_commit_status_infers_repo_from_cwd(tool_ctx): - """Tool infers owner/repo from cwd git remote when repo param is absent.""" - tool_ctx.runner.push(_make_result(0, "inferred/repo\n", "")) +async def test_set_commit_status_infers_repo_from_cwd(tool_ctx, monkeypatch): + """Tool infers owner/repo via infer_repo_from_remote when repo param is absent.""" + infer_calls: list[str] = [] + + async def fake_infer(cwd: str, hint: object = None) -> str: + infer_calls.append(cwd) + return "inferred/repo" + + monkeypatch.setattr("autoskillit.server.tools_ci.infer_repo_from_remote", fake_infer) tool_ctx.runner.push(_make_result(0, "", "")) - result = await set_commit_status( + raw = await set_commit_status( sha="abc001", state="success", context="autoskillit/ai-review", # repo not provided — must infer from cwd cwd="/some/repo", ) + result = json.loads(raw) assert result["success"] is True - # First subprocess call must be gh repo view - first_cmd = tool_ctx.runner.call_args_list[0][0] - assert "gh" in first_cmd - assert "repo" in first_cmd - assert "view" in first_cmd + assert infer_calls, "infer_repo_from_remote was not called" # POST must use the inferred repo - post_cmd = tool_ctx.runner.call_args_list[1][0] + post_cmd = tool_ctx.runner.call_args_list[0][0] assert "inferred/repo" in " ".join(post_cmd) @pytest.mark.anyio -async def test_set_commit_status_falls_back_to_plugin_dir_when_no_cwd(tool_ctx): +async def test_set_commit_status_falls_back_to_plugin_dir_when_no_cwd(tool_ctx, monkeypatch): """When neither repo nor cwd is provided, tool falls back to plugin_dir for inference.""" - from tests.conftest import _make_result + infer_calls: list[str] = [] + + async def fake_infer(cwd: str, hint: object = None) -> str: + infer_calls.append(cwd) + return "fallback/repo" - tool_ctx.runner.push(_make_result(0, "fallback/repo\n", "")) + monkeypatch.setattr("autoskillit.server.tools_ci.infer_repo_from_remote", fake_infer) tool_ctx.runner.push(_make_result(0, "", "")) - result = await set_commit_status( + raw = await set_commit_status( sha="abc003", state="pending", context="autoskillit/ai-review", # neither repo nor cwd — falls back to tool_ctx.plugin_dir ) + result = json.loads(raw) assert result["success"] is True - # Inference call must have happened (gh repo view) - first_cmd, *_ = tool_ctx.runner.call_args_list[0] - assert "gh" in first_cmd and "repo" in first_cmd and "view" in first_cmd + assert infer_calls, "infer_repo_from_remote was not called for fallback" # POST must reference the fallback repo - post_cmd, *_ = tool_ctx.runner.call_args_list[1] + post_cmd, *_ = tool_ctx.runner.call_args_list[0] assert "fallback/repo" in " ".join(post_cmd) @pytest.mark.anyio -async def test_set_commit_status_uses_explicit_repo_without_inference(tool_ctx): - """When repo is provided explicitly, gh repo view is not called.""" +async def test_set_commit_status_uses_explicit_repo_without_inference(tool_ctx, monkeypatch): + """When repo is provided explicitly, infer_repo_from_remote is not called.""" + infer_calls: list[str] = [] + + async def fake_infer(cwd: str, hint: object = None) -> str: + infer_calls.append(cwd) + return "should-not-be-used/repo" + + monkeypatch.setattr("autoskillit.server.tools_ci.infer_repo_from_remote", fake_infer) tool_ctx.runner.push(_make_result(0, "", "")) - result = await set_commit_status( + raw = await set_commit_status( sha="abc002", state="success", context="autoskillit/ai-review", repo="explicit/repo", cwd="/some/repo", ) + result = json.loads(raw) assert result["success"] is True - # Only one subprocess call (the POST, not gh repo view) - assert len(tool_ctx.runner.call_args_list) == 1 + assert not infer_calls, "infer_repo_from_remote should not be called when repo is explicit" post_cmd = tool_ctx.runner.call_args_list[0][0] assert "explicit/repo" in " ".join(post_cmd) @@ -206,33 +237,115 @@ async def test_set_commit_status_uses_explicit_repo_without_inference(tool_ctx): @pytest.mark.anyio -async def test_set_commit_status_on_gh_failure_returns_error_dict(tool_ctx): +async def test_set_commit_status_on_gh_failure_returns_error_dict(tool_ctx, monkeypatch): """When gh api returns non-zero, tool returns success=false, never raises.""" - tool_ctx.runner.push(_make_result(0, "owner/repo\n", "")) + monkeypatch.setattr( + "autoskillit.server.tools_ci.infer_repo_from_remote", + lambda cwd, hint=None: _async_return("owner/repo"), + ) tool_ctx.runner.push(_make_result(1, "", "API rate limit exceeded")) - result = await set_commit_status( + raw = await set_commit_status( sha="baadf00d", state="success", context="autoskillit/ai-review", cwd="/some/repo", ) + result = json.loads(raw) assert result["success"] is False assert isinstance(result["error"], str) and result["error"] @pytest.mark.anyio -async def test_set_commit_status_repo_inference_failure_returns_error(tool_ctx): - """When repo inference fails, tool returns success=false.""" - tool_ctx.runner.push(_make_result(1, "", "not a git repository")) +async def test_set_commit_status_repo_inference_failure_returns_error(tool_ctx, monkeypatch): + """When repo inference returns empty string, tool returns success=false.""" + monkeypatch.setattr( + "autoskillit.server.tools_ci.infer_repo_from_remote", + lambda cwd, hint=None: _async_return(""), + ) - result = await set_commit_status( + raw = await set_commit_status( sha="baadf00d", state="pending", context="autoskillit/ai-review", cwd="/some/repo", ) + result = json.loads(raw) assert result["success"] is False assert "error" in result + + +# --------------------------------------------------------------------------- +# T1 — Return type is str throughout +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +async def test_set_commit_status_gate_returns_str(tool_ctx): + """Gate-closed path must return str, not dict.""" + import json + + tool_ctx.gate = DefaultGateState(enabled=False) + result = await set_commit_status(sha="abc", state="pending", context="ctx") + assert isinstance(result, str) + parsed = json.loads(result) + assert parsed["success"] is False + + +@pytest.mark.anyio +async def test_set_commit_status_validation_errors_return_str(tool_ctx): + """Validation error paths (empty sha) return str.""" + import json + + result = await set_commit_status(sha="", state="pending", context="ctx") + assert isinstance(result, str) + parsed = json.loads(result) + assert parsed["success"] is False + + +@pytest.mark.anyio +async def test_set_commit_status_success_returns_str(tool_ctx, monkeypatch): + """Success path returns str.""" + import json + + from tests.conftest import _make_result + + async def fake_infer(cwd: str, hint: object = None) -> str: + return "owner/repo" + + monkeypatch.setattr("autoskillit.server.tools_ci.infer_repo_from_remote", fake_infer) + tool_ctx.runner.push(_make_result(0, "", "")) + result = await set_commit_status(sha="abc123", state="success", context="ci", cwd="/tmp") + assert isinstance(result, str) + parsed = json.loads(result) + assert parsed["success"] is True + + +# --------------------------------------------------------------------------- +# T2 — Uses infer_repo_from_remote, not gh repo view subprocess +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +async def test_set_commit_status_uses_infer_repo_not_gh_subprocess(tool_ctx, monkeypatch): + """Must call infer_repo_from_remote, not launch gh repo view subprocess.""" + from tests.conftest import _make_result + + calls: list[str] = [] + + async def fake_infer(cwd: str, hint: object = None) -> str: + calls.append(cwd) + return "owner/repo" + + monkeypatch.setattr("autoskillit.server.tools_ci.infer_repo_from_remote", fake_infer) + # Only one runner push needed (the POST call, repo already resolved) + tool_ctx.runner.push(_make_result(0, "", "")) + await set_commit_status(sha="abc", state="success", context="ci", cwd="/tmp") + assert calls, "infer_repo_from_remote was never called" + # gh repo view must NOT have been invoked as a subprocess + for cmd_args, *_ in tool_ctx.runner.call_args_list: + assert not ("repo" in cmd_args and "view" in cmd_args), ( + "gh repo view subprocess was invoked; infer_repo_from_remote should be used instead" + ) diff --git a/tests/server/test_state.py b/tests/server/test_state.py index 32f017a879..bd5e9776a4 100644 --- a/tests/server/test_state.py +++ b/tests/server/test_state.py @@ -2,10 +2,14 @@ from __future__ import annotations +import asyncio import json +import sys from datetime import UTC, datetime from pathlib import Path -from unittest.mock import MagicMock, patch +from unittest.mock import MagicMock, Mock, patch + +import pytest def _make_mock_ctx(tmp_path: Path) -> MagicMock: @@ -98,3 +102,171 @@ def test_initialize_does_not_load_token_log(tmp_path): "_initialize() must not populate DefaultTimingLog from disk; " "timing telemetry is per-pipeline only" ) + + +# --- T-INIT-1: McpRecordingMiddleware registered for RecordingSubprocessRunner --- + + +def test_initialize_registers_mcp_recording_middleware(tmp_path, monkeypatch): + """_initialize() registers McpRecordingMiddleware when runner is RecordingSubprocessRunner.""" + from autoskillit.execution.recording import RecordingSubprocessRunner + from autoskillit.server._state import _initialize + + mock_atexit = Mock() + monkeypatch.setattr("atexit.register", mock_atexit) + mock_recorder = Mock() + recording_runner = RecordingSubprocessRunner(recorder=mock_recorder) + + mock_ctx = _make_mock_ctx(tmp_path) + mock_ctx.runner = recording_runner + mock_ctx.config.subsets.disabled = [] + mock_ctx.session_skill_manager = None + + mock_mcp = MagicMock() + mock_middleware_cls = MagicMock() + + import api_simulator.mcp as _api_sim_mcp + + monkeypatch.setattr("autoskillit.server.mcp", mock_mcp) + monkeypatch.setattr(_api_sim_mcp, "McpRecordingMiddleware", mock_middleware_cls) + + with patch("autoskillit.execution.recover_crashed_sessions", return_value=0): + _initialize(mock_ctx) + + mock_middleware_cls.assert_called_once_with(mock_recorder) + mock_mcp.add_middleware.assert_called_once_with(mock_middleware_cls.return_value) + mock_atexit.assert_not_called() + + +# --- T-INIT-2: No middleware registered for non-recording runner --- + + +def test_initialize_skips_middleware_for_non_recording_runner(tmp_path, monkeypatch): + """_initialize() does not call mcp.add_middleware() for a non-recording runner.""" + from autoskillit.server._state import _initialize + + mock_ctx = _make_mock_ctx(tmp_path) + mock_ctx.runner = MagicMock() + mock_ctx.config.subsets.disabled = [] + mock_ctx.session_skill_manager = None + + mock_mcp = MagicMock() + monkeypatch.setattr("autoskillit.server.mcp", mock_mcp) + + with patch("autoskillit.execution.recover_crashed_sessions", return_value=0): + _initialize(mock_ctx) + + mock_mcp.add_middleware.assert_not_called() + + +# --- T-INIT-3: ImportError from api_simulator.mcp does not raise --- + + +def test_initialize_recording_middleware_import_error_does_not_raise(tmp_path, monkeypatch): + """_initialize() degrades gracefully when api_simulator.mcp is unavailable.""" + from autoskillit.execution.recording import RecordingSubprocessRunner + from autoskillit.server._state import _initialize + + mock_atexit = Mock() + monkeypatch.setattr("atexit.register", mock_atexit) + mock_recorder = Mock() + recording_runner = RecordingSubprocessRunner(recorder=mock_recorder) + + mock_ctx = _make_mock_ctx(tmp_path) + mock_ctx.runner = recording_runner + mock_ctx.config.subsets.disabled = [] + mock_ctx.session_skill_manager = None + + monkeypatch.setitem(sys.modules, "api_simulator.mcp", None) + + with patch("autoskillit.execution.recover_crashed_sessions", return_value=0): + _initialize(mock_ctx) # Must not raise + + mock_atexit.assert_not_called() + + +# --- T-INIT-4: McpReplayMiddleware registered for ReplayingSubprocessRunner --- + + +def test_initialize_registers_mcp_replay_middleware(tmp_path, monkeypatch): + """_initialize() registers McpReplayMiddleware when runner is ReplayingSubprocessRunner.""" + from autoskillit.execution.recording import ReplayingSubprocessRunner + from autoskillit.server._state import _initialize + + mock_player = Mock() + replaying_runner = ReplayingSubprocessRunner({}, {}, player=mock_player) + + mock_ctx = _make_mock_ctx(tmp_path) + mock_ctx.runner = replaying_runner + mock_ctx.config.subsets.disabled = [] + mock_ctx.session_skill_manager = None + + mock_mcp = MagicMock() + mock_middleware_cls = MagicMock() + + import api_simulator.mcp as _api_sim_mcp + + monkeypatch.setattr("autoskillit.server.mcp", mock_mcp) + monkeypatch.setattr(_api_sim_mcp, "McpReplayMiddleware", mock_middleware_cls) + + with patch("autoskillit.execution.recover_crashed_sessions", return_value=0): + _initialize(mock_ctx) + + mock_middleware_cls.assert_called_once_with(mock_player) + mock_mcp.add_middleware.assert_called_once_with(mock_middleware_cls.return_value) + + +# --- T-INIT-5: Critical _initialize does not perform deferrable I/O --- + + +def test_initialize_critical_does_not_call_recovery(tmp_path, monkeypatch): + """Critical _initialize path must not perform deferrable I/O.""" + from autoskillit.server._state import _initialize + + calls: list[str] = [] + monkeypatch.setattr( + "autoskillit.execution.recover_crashed_sessions", + lambda **kw: calls.append("recover") or 0, + ) + + mock_ctx = _make_mock_ctx(tmp_path) + mock_ctx.config.subsets.disabled = [] + mock_ctx.session_skill_manager = MagicMock() + + monkeypatch.setattr( + mock_ctx.audit, + "load_from_log_dir", + lambda *a, **kw: calls.append("audit_load") or 0, + ) + monkeypatch.setattr( + mock_ctx.session_skill_manager, + "cleanup_stale", + lambda: calls.append("cleanup_stale") or [], + ) + + _initialize(mock_ctx) + + assert "recover" not in calls, "Critical _initialize called recover_crashed_sessions" + assert "audit_load" not in calls, "Critical _initialize called audit.load_from_log_dir" + assert "cleanup_stale" not in calls, "Critical _initialize called cleanup_stale" + + +# --- T-INIT-6: deferred_initialize runs recovery operations --- + + +@pytest.mark.asyncio +async def test_deferred_initialize_runs_recovery_operations(tmp_path): + """deferred_initialize() must run recovery, audit load, and stale cleanup.""" + from autoskillit.server._state import deferred_initialize + + mock_ctx = _make_mock_ctx(tmp_path) + mock_ctx.config.subsets.disabled = [] + mock_ctx.session_skill_manager = MagicMock() + mock_ctx.session_skill_manager.cleanup_stale.return_value = [] + mock_ctx.audit.load_from_log_dir.return_value = 0 + + event = asyncio.Event() + with patch("autoskillit.execution.recover_crashed_sessions", return_value=0): + await deferred_initialize(mock_ctx, ready_event=event) + + assert event.is_set(), "deferred_initialize did not signal readiness" diff --git a/tests/server/test_tools_ci.py b/tests/server/test_tools_ci.py index 358dd947ac..57364c4348 100644 --- a/tests/server/test_tools_ci.py +++ b/tests/server/test_tools_ci.py @@ -5,11 +5,17 @@ import json from unittest.mock import AsyncMock, patch +import httpx import pytest -from autoskillit.core import SubprocessResult, TerminationReason +from autoskillit.core import PRState, SubprocessResult, TerminationReason from autoskillit.pipeline.gate import GATED_TOOLS, UNGATED_TOOLS, DefaultGateState -from autoskillit.server.tools_ci import get_ci_status, wait_for_ci, wait_for_merge_queue +from autoskillit.server.tools_ci import ( + check_repo_merge_state, + get_ci_status, + wait_for_ci, + wait_for_merge_queue, +) # --------------------------------------------------------------------------- # Gate membership @@ -201,6 +207,29 @@ async def test_get_ci_status_no_watcher(tool_ctx): assert "not configured" in result["error"] +# --------------------------------------------------------------------------- +# wait_for_ci event param propagation +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +async def test_wait_for_ci_passes_event_to_scope(tool_ctx): + """wait_for_ci must propagate event param into CIRunScope.""" + captured_scope = None + + async def _side_effect(branch, *, repo, scope, **kw): + nonlocal captured_scope + captured_scope = scope + return {"run_id": 1, "conclusion": "success", "failed_jobs": []} + + mock_watcher = AsyncMock() + mock_watcher.wait = AsyncMock(side_effect=_side_effect) + tool_ctx.ci_watcher = mock_watcher + await wait_for_ci(branch="main", event="push", cwd="/tmp") + assert captured_scope is not None + assert captured_scope.event == "push" + + # --------------------------------------------------------------------------- # wait_for_merge_queue # --------------------------------------------------------------------------- @@ -578,4 +607,203 @@ async def test_wait_for_merge_queue_watcher_exception_returns_structured_json(to assert result["success"] is False assert "connection refused" in result["error"] assert "subtype" not in result + + +# --------------------------------------------------------------------------- +# wait_for_ci head_sha enrichment (Gap 5) +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +async def test_wait_for_ci_includes_head_sha_in_result(tool_ctx): + """wait_for_ci result includes head_sha when git rev-parse HEAD succeeds.""" + mock_watcher = AsyncMock() + mock_watcher.wait = AsyncMock( + return_value={"run_id": 1, "conclusion": "success", "failed_jobs": []} + ) + tool_ctx.ci_watcher = mock_watcher + tool_ctx.runner.push( + SubprocessResult( + returncode=0, + stdout="deadbeef1234\n", + stderr="", + termination=TerminationReason.NATURAL_EXIT, + pid=0, + ) + ) + + result = json.loads(await wait_for_ci("main", cwd="/some/repo")) + + assert result["head_sha"] == "deadbeef1234" + + +@pytest.mark.anyio +async def test_wait_for_ci_omits_head_sha_when_git_fails(tool_ctx): + """wait_for_ci result omits head_sha when git rev-parse fails.""" + mock_watcher = AsyncMock() + mock_watcher.wait = AsyncMock( + return_value={"run_id": 1, "conclusion": "success", "failed_jobs": []} + ) + tool_ctx.ci_watcher = mock_watcher + tool_ctx.runner.push( + SubprocessResult( + returncode=128, + stdout="", + stderr="fatal: not a git repository", + termination=TerminationReason.NATURAL_EXIT, + pid=0, + ) + ) + + result = json.loads(await wait_for_ci("main", cwd="/some/repo")) + + assert "head_sha" not in result assert "exit_code" not in result + + +# --------------------------------------------------------------------------- +# T10: MCP round-trip exhaustiveness — parametrized over list(PRState) +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +@pytest.mark.parametrize("pr_state", list(PRState)) +async def test_wait_for_merge_queue_serializes_every_pr_state(pr_state, tool_ctx): + """Every PRState value round-trips faithfully through the MCP handler. + + Adding a new PRState member without a handler test fails this parametrized suite. + """ + mock_watcher = AsyncMock() + mock_watcher.wait = AsyncMock( + return_value={ + "success": pr_state == PRState.MERGED, + "pr_state": pr_state.value, + "reason": f"test reason for {pr_state.value}", + } + ) + tool_ctx.merge_queue_watcher = mock_watcher + + with patch( + "autoskillit.execution.remote_resolver.asyncio.create_subprocess_exec", + new_callable=AsyncMock, + ) as mock_proc: + proc_inst = AsyncMock() + proc_inst.communicate = AsyncMock( + return_value=(b"https://github.com/owner/repo.git\n", b"") + ) + proc_inst.returncode = 0 + mock_proc.return_value = proc_inst + + result = json.loads(await wait_for_merge_queue(pr_number=1, target_branch="main", cwd=".")) + + assert result["pr_state"] == pr_state.value, ( + f"Expected pr_state={pr_state.value!r} in response, got: {result.get('pr_state')!r}" + ) + expected_success = pr_state == PRState.MERGED + assert result["success"] == expected_success, ( + f"Expected success={expected_success!r} for pr_state={pr_state.value!r}, " + f"got: {result.get('success')!r}" + ) + + +def test_pr_state_docstring_documents_all_members(): + """T10: wait_for_merge_queue docstring must name every PRState member value. + + Prevents silent docstring drift when new PRState members are added. + """ + doc = wait_for_merge_queue.__doc__ or "" + for state in PRState: + assert state.value in doc, ( + f"PRState.{state.name} ({state.value!r}) is not documented in the " + f"wait_for_merge_queue docstring. Update the Returns section to include it." + ) + + +# --------------------------------------------------------------------------- +# check_repo_merge_state: token_factory and http_status +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +async def test_check_repo_merge_state_uses_token_factory(tool_ctx, monkeypatch): + """check_repo_merge_state calls token_factory() when set, not config.github.token.""" + resolved_calls = [] + + def factory(): + resolved_calls.append(1) + return "factory-token" + + tool_ctx.token_factory = factory + tool_ctx.config.github.token = "config-token" + + captured_tokens = [] + + async def fake_fetch(owner, repo, branch, token): + captured_tokens.append(token) + return { + "queue_available": False, + "merge_group_trigger": False, + "auto_merge_available": False, + "ci_event": None, + } + + monkeypatch.setattr("autoskillit.server.tools_ci.fetch_repo_merge_state", fake_fetch) + monkeypatch.setattr( + "autoskillit.server.tools_ci.infer_repo_from_remote", + AsyncMock(return_value="owner/repo"), + ) + + await check_repo_merge_state(branch="main") + assert captured_tokens == ["factory-token"] + assert resolved_calls == [1] + + +@pytest.mark.anyio +async def test_check_repo_merge_state_falls_back_to_config_token_when_no_factory( + tool_ctx, monkeypatch +): + """When token_factory is None, config.github.token is used.""" + tool_ctx.token_factory = None + tool_ctx.config.github.token = "config-token" + + captured_tokens = [] + + async def fake_fetch(owner, repo, branch, token): + captured_tokens.append(token) + return { + "queue_available": False, + "merge_group_trigger": False, + "auto_merge_available": False, + "ci_event": None, + } + + monkeypatch.setattr("autoskillit.server.tools_ci.fetch_repo_merge_state", fake_fetch) + monkeypatch.setattr( + "autoskillit.server.tools_ci.infer_repo_from_remote", + AsyncMock(return_value="owner/repo"), + ) + + await check_repo_merge_state(branch="main") + assert captured_tokens == ["config-token"] + + +@pytest.mark.anyio +async def test_check_repo_merge_state_error_includes_http_status(tool_ctx, monkeypatch): + """HTTP error response envelope contains http_status field.""" + + async def fake_fetch(owner, repo, branch, token): + response = httpx.Response( + 403, + request=httpx.Request("POST", "https://api.github.com/graphql"), + ) + raise httpx.HTTPStatusError("403 Forbidden", request=response.request, response=response) + + monkeypatch.setattr("autoskillit.server.tools_ci.fetch_repo_merge_state", fake_fetch) + monkeypatch.setattr( + "autoskillit.server.tools_ci.infer_repo_from_remote", + AsyncMock(return_value="owner/repo"), + ) + + result = json.loads(await check_repo_merge_state(branch="main")) + assert "http_status" in result + assert result["http_status"] == 403 diff --git a/tests/server/test_tools_clone.py b/tests/server/test_tools_clone.py index 1a18c6458d..7ae9f30984 100644 --- a/tests/server/test_tools_clone.py +++ b/tests/server/test_tools_clone.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +from pathlib import Path from unittest.mock import MagicMock import pytest @@ -273,6 +274,7 @@ class TestRegisterCloneStatusTool: @pytest.mark.anyio async def test_register_clone_status_success(self, tool_ctx, tmp_path): """register_clone_status status='success' writes registry and returns registered=true.""" + tool_ctx.kitchen_id = "kit-test" registry_path = str(tmp_path / "registry.json") result = json.loads( await register_clone_status( @@ -287,6 +289,7 @@ async def test_register_clone_status_success(self, tool_ctx, tmp_path): @pytest.mark.anyio async def test_register_clone_status_error(self, tool_ctx, tmp_path): """register_clone_status status='error' writes registry and returns registered=true.""" + tool_ctx.kitchen_id = "kit-test" registry_path = str(tmp_path / "registry.json") result = json.loads( await register_clone_status( @@ -309,7 +312,8 @@ async def test_register_clone_status_invalid_status(self, tool_ctx, tmp_path): registry_path=registry_path, ) ) - assert "error" in result + assert result["registered"] == "false" + assert "reason" in result # Registry file must not have been created assert not (tmp_path / "registry.json").exists() @@ -318,13 +322,14 @@ class TestBatchCleanupClonesTool: @pytest.mark.anyio async def test_batch_cleanup_clones_deletes_success_preserves_error(self, tool_ctx, tmp_path): """batch_cleanup_clones removes success clones, skips error clones.""" + tool_ctx.kitchen_id = "kit-test" registry_path = str(tmp_path / "registry.json") success_path = str(tmp_path / "success_clone") error_path = str(tmp_path / "error_clone") # Pre-populate registry with one success and one error entry - clone_registry.register_clone(success_path, "success", registry_path) - clone_registry.register_clone(error_path, "error", registry_path) + clone_registry.register_clone(success_path, "success", "kit-test", registry_path) + clone_registry.register_clone(error_path, "error", "kit-test", registry_path) # Mock clone_mgr so remove_clone reports success for the success clone mock_mgr = MagicMock() @@ -341,6 +346,7 @@ async def test_batch_cleanup_clones_deletes_success_preserves_error(self, tool_c @pytest.mark.anyio async def test_batch_cleanup_clones_empty_registry(self, tool_ctx, tmp_path): """batch_cleanup_clones with missing registry returns deleted=[], preserved=[].""" + tool_ctx.kitchen_id = "kit-test" registry_path = str(tmp_path / "nonexistent.json") result = json.loads(await batch_cleanup_clones(registry_path=registry_path)) assert result == {"deleted": [], "delete_failures": [], "preserved": []} @@ -348,11 +354,12 @@ async def test_batch_cleanup_clones_empty_registry(self, tool_ctx, tmp_path): @pytest.mark.anyio async def test_batch_cleanup_clones_nonexistent_path_does_not_raise(self, tool_ctx, tmp_path): """batch_cleanup_clones reports failure gracefully when a success clone path is gone.""" + tool_ctx.kitchen_id = "kit-test" registry_path = str(tmp_path / "registry.json") missing_path = str(tmp_path / "gone_clone") # Register a success clone whose directory does not exist on disk - clone_registry.register_clone(missing_path, "success", registry_path) + clone_registry.register_clone(missing_path, "success", "kit-test", registry_path) # Mock clone_mgr to report removal failure (path not found) mock_mgr = MagicMock() @@ -365,3 +372,167 @@ async def test_batch_cleanup_clones_nonexistent_path_does_not_raise(self, tool_c assert result["deleted"] == [] # Confirm no exception was raised (we received a well-formed result dict) assert "error" not in result + + +# --------------------------------------------------------------------------- +# New tests: T12–T19 (owner-scoping feature for server tools) +# --------------------------------------------------------------------------- + + +class TestRegisterCloneStatusOwner: + """T12–T13: register_clone_status propagates kitchen_id as owner.""" + + @pytest.mark.anyio + async def test_register_clone_status_propagates_kitchen_id_as_owner(self, tool_ctx, tmp_path): + """T12 — register_clone_status writes entry with owner == kitchen_id.""" + tool_ctx.kitchen_id = "kit-xyz" + reg = str(tmp_path / "registry.json") + result = json.loads( + await register_clone_status(clone_path="/c", status="success", registry_path=reg) + ) + assert result["registered"] == "true" + + data = json.loads(Path(reg).read_text()) + assert len(data["clones"]) == 1 + assert data["clones"][0]["owner"] == "kit-xyz" + + @pytest.mark.anyio + async def test_register_clone_status_rejects_when_kitchen_id_empty(self, tool_ctx, tmp_path): + """T13 — register_clone_status returns registered=false when kitchen_id is empty.""" + tool_ctx.kitchen_id = "" + reg = str(tmp_path / "registry.json") + result = json.loads( + await register_clone_status(clone_path="/c", status="success", registry_path=reg) + ) + assert result["registered"] == "false" + assert "kitchen_id" in result["reason"] or "kitchen" in result["reason"] + assert not Path(reg).exists() + + +class TestBatchCleanupClonesOwner: + """T14–T19: batch_cleanup_clones owner-scoping and escape hatch.""" + + @pytest.mark.anyio + async def test_batch_cleanup_clones_default_scopes_to_current_kitchen_id( + self, tool_ctx, tmp_path + ): + """T14 — default call only removes current kitchen's clones.""" + reg = str(tmp_path / "registry.json") + clone_registry.register_clone("/clone-A", "success", "kit-A", reg) + clone_registry.register_clone("/clone-B", "success", "kit-B", reg) + + tool_ctx.kitchen_id = "kit-A" + mock_mgr = MagicMock() + mock_mgr.remove_clone.return_value = {"removed": "true"} + tool_ctx.clone_mgr = mock_mgr + + result = json.loads(await batch_cleanup_clones(registry_path=reg)) + + assert "/clone-A" in result["deleted"] + assert "/clone-B" not in result["deleted"] + mock_mgr.remove_clone.assert_called_once_with("/clone-A", "false") + + @pytest.mark.anyio + async def test_batch_cleanup_clones_all_owners_true_removes_every_success( + self, tool_ctx, tmp_path + ): + """T15 — all_owners='true' escape hatch removes all success entries.""" + reg = str(tmp_path / "registry.json") + clone_registry.register_clone("/clone-A", "success", "kit-A", reg) + clone_registry.register_clone("/clone-B", "success", "kit-B", reg) + + tool_ctx.kitchen_id = "kit-A" + mock_mgr = MagicMock() + mock_mgr.remove_clone.return_value = {"removed": "true"} + tool_ctx.clone_mgr = mock_mgr + + result = json.loads(await batch_cleanup_clones(registry_path=reg, all_owners="true")) + + deleted = result["deleted"] + assert "/clone-A" in deleted + assert "/clone-B" in deleted + + @pytest.mark.anyio + async def test_batch_cleanup_clones_empty_kitchen_id_and_all_owners_false_returns_error( + self, tool_ctx, tmp_path + ): + """T16 — empty kitchen_id with default all_owners='false' returns error.""" + tool_ctx.kitchen_id = "" + reg = str(tmp_path / "registry.json") + mock_mgr = MagicMock() + tool_ctx.clone_mgr = mock_mgr + + result = json.loads(await batch_cleanup_clones(registry_path=reg)) + + assert "error" in result + assert "kitchen_id" in result["error"] or "kitchen" in result["error"] + mock_mgr.remove_clone.assert_not_called() + + @pytest.mark.anyio + async def test_batch_cleanup_clones_empty_kitchen_id_with_all_owners_true_succeeds( + self, tool_ctx, tmp_path + ): + """T17 — escape hatch works even when kitchen_id is empty (legacy recovery).""" + + reg_path = tmp_path / "registry.json" + reg_path.write_text(json.dumps({"clones": [{"path": "/legacy", "status": "success"}]})) + + tool_ctx.kitchen_id = "" + mock_mgr = MagicMock() + mock_mgr.remove_clone.return_value = {"removed": "true"} + tool_ctx.clone_mgr = mock_mgr + + result = json.loads( + await batch_cleanup_clones(registry_path=str(reg_path), all_owners="true") + ) + + assert "/legacy" in result["deleted"] + mock_mgr.remove_clone.assert_called_once_with("/legacy", "false") + + @pytest.mark.anyio + async def test_batch_cleanup_clones_invalid_all_owners_literal_treated_as_false( + self, tool_ctx, tmp_path + ): + """T18 — all_owners='yes' is not the escape hatch; scoped behaviour applies.""" + reg = str(tmp_path / "registry.json") + clone_registry.register_clone("/clone-A", "success", "kit-A", reg) + clone_registry.register_clone("/clone-B", "success", "kit-B", reg) + + tool_ctx.kitchen_id = "kit-A" + mock_mgr = MagicMock() + mock_mgr.remove_clone.return_value = {"removed": "true"} + tool_ctx.clone_mgr = mock_mgr + + result = json.loads(await batch_cleanup_clones(registry_path=reg, all_owners="yes")) + + assert "/clone-A" in result["deleted"] + assert "/clone-B" not in result["deleted"] + + @pytest.mark.anyio + async def test_two_kitchens_register_and_cleanup_isolated(self, tool_ctx, tmp_path): + """T19 — kitchen A's cleanup does not touch kitchen B's registry entry.""" + reg = str(tmp_path / "registry.json") + + # Register directly via L1 to represent two independent sessions without + # mutating a shared ToolContext mid-test (a ToolContext represents one session). + clone_registry.register_clone("/clone-1", "success", "kit-1", reg) + clone_registry.register_clone("/clone-2", "success", "kit-2", reg) + + # Session 1 cleans up via the MCP tool + tool_ctx.kitchen_id = "kit-1" + mock_mgr = MagicMock() + mock_mgr.remove_clone.return_value = {"removed": "true"} + tool_ctx.clone_mgr = mock_mgr + + result = json.loads(await batch_cleanup_clones(registry_path=reg)) + + # Only kit-1's clone is removed + assert "/clone-1" in result["deleted"] + assert "/clone-2" not in result["deleted"] + mock_mgr.remove_clone.assert_called_once_with("/clone-1", "false") + + # kit-2's entry is still on disk + data = json.loads(Path(reg).read_text()) + remaining = {e["path"]: e.get("owner") for e in data["clones"]} + assert "/clone-2" in remaining + assert remaining["/clone-2"] == "kit-2" diff --git a/tests/server/test_tools_execution.py b/tests/server/test_tools_execution.py index 581b95b7bd..ae765e54be 100644 --- a/tests/server/test_tools_execution.py +++ b/tests/server/test_tools_execution.py @@ -22,7 +22,7 @@ from autoskillit.server.helpers import ( _check_dry_walkthrough, ) -from autoskillit.server.tools_execution import run_cmd, run_python, run_skill +from autoskillit.server.tools_execution import run_skill from tests.conftest import _make_result _SUCCESS_JSON = ( @@ -30,6 +30,19 @@ ' "result": "done", "session_id": "s1"}' ) +# Deterministic UUID for tests that need to predict the per-invocation marker. +_DETERMINISTIC_HEX = "a1b2c3d4e5f6a7b890123456" +_DETERMINISTIC_MARKER = f"%%ORDER_UP::{_DETERMINISTIC_HEX[:8]}%%" + + +class _FixedUUID: + hex = _DETERMINISTIC_HEX + + +def _patch_uuid4(monkeypatch): + """Monkeypatch uuid4 to return a deterministic value for marker prediction.""" + monkeypatch.setattr("uuid.uuid4", lambda: _FixedUUID()) + class TestRunSkillPluginDir: """T2: run_skill passes --plugin-dir to the claude command.""" @@ -154,7 +167,8 @@ async def test_run_skill_prefixes_skill_command(self, tool_ctx): ) await run_skill("/investigate error", "/tmp") cmd = tool_ctx.runner.call_args_list[0][0] - assert cmd[5].startswith("Use /investigate error") + prompt_idx = cmd.index("--print") + 1 if "--print" in cmd else cmd.index("-p") + 1 + assert cmd[prompt_idx].startswith("Use /investigate error") # cwd must propagate to the subprocess runner from pathlib import Path @@ -209,7 +223,8 @@ async def test_run_skill_includes_completion_directive(self, tool_ctx): ) await run_skill("/investigate error", "/tmp") cmd = tool_ctx.runner.call_args_list[0][0] - assert "%%ORDER_UP%%" in cmd[5] + prompt_idx = cmd.index("--print") + 1 if "--print" in cmd else cmd.index("-p") + 1 + assert "%%ORDER_UP::" in cmd[prompt_idx] # cwd must propagate to the subprocess runner from pathlib import Path @@ -315,10 +330,9 @@ async def test_run_skill_injects_completion_directive(self, tool_ctx): await run_skill("/investigate foo", "/tmp") cmd = tool_ctx.runner.call_args_list[-1][0] - # The prompt argument is at index 5 - # (shifted by 3 env tokens: env + AUTOSKILLIT_HEADLESS=1 + delay) - skill_arg = cmd[5] - assert "%%ORDER_UP%%" in skill_arg + prompt_idx = cmd.index("--print") + 1 if "--print" in cmd else cmd.index("-p") + 1 + skill_arg = cmd[prompt_idx] + assert "%%ORDER_UP::" in skill_arg assert "ORCHESTRATION DIRECTIVE" in skill_arg def test_inject_completion_directive_prohibits_standalone_marker(self): @@ -337,17 +351,17 @@ def test_inject_completion_directive_prohibits_standalone_marker(self): class TestRunSkillEnvPrefix: - """run_skill always injects AUTOSKILLIT_HEADLESS=1 and optionally CLAUDE_CODE_EXIT_AFTER_STOP_DELAY.""" # noqa: E501 + """run_skill always injects AUTOSKILLIT_HEADLESS=1 and optionally CLAUDE_CODE_EXIT_AFTER_STOP_DELAY via the env kwarg.""" # noqa: E501 @pytest.mark.anyio - async def test_default_delay_prepends_env_to_cmd(self, tool_ctx): + async def test_default_delay_populates_env(self, tool_ctx): tool_ctx.runner.push(_make_result(0, _SUCCESS_JSON, "")) await run_skill("/investigate something", "/tmp") - cmd = tool_ctx.runner.call_args_list[0][0] - assert cmd[0] == "env" - assert cmd[1] == "AUTOSKILLIT_HEADLESS=1" - assert cmd[2] == "CLAUDE_CODE_EXIT_AFTER_STOP_DELAY=120000" - assert "claude" in cmd + cmd, _cwd, _timeout, kwargs = tool_ctx.runner.call_args_list[0] + assert cmd[0] == "claude" + env = kwargs["env"] + assert env["AUTOSKILLIT_HEADLESS"] == "1" + assert env["CLAUDE_CODE_EXIT_AFTER_STOP_DELAY"] == "2000" @pytest.mark.anyio async def test_zero_delay_omits_delay_env_var(self, tool_ctx): @@ -357,25 +371,27 @@ async def test_zero_delay_omits_delay_env_var(self, tool_ctx): tool_ctx.config = cfg tool_ctx.runner.push(_make_result(0, _SUCCESS_JSON, "")) await run_skill("/investigate something", "/tmp") - cmd = tool_ctx.runner.call_args_list[0][0] - # AUTOSKILLIT_HEADLESS=1 is always injected; delay var is omitted when delay=0 - assert cmd[0] == "env" - assert cmd[1] == "AUTOSKILLIT_HEADLESS=1" - assert cmd[2] == "claude" - assert not any("CLAUDE_CODE_EXIT_AFTER_STOP_DELAY" in arg for arg in cmd) + cmd, _cwd, _timeout, kwargs = tool_ctx.runner.call_args_list[0] + assert cmd[0] == "claude" + env = kwargs["env"] + assert env["AUTOSKILLIT_HEADLESS"] == "1" + assert "CLAUDE_CODE_EXIT_AFTER_STOP_DELAY" not in env @pytest.mark.anyio - async def test_custom_delay_value_in_cmd(self, tool_ctx): + async def test_custom_delay_value_in_env(self, tool_ctx): cfg = AutomationConfig() - cfg.run_skill = RunSkillConfig(exit_after_stop_delay_ms=60000) + cfg.run_skill = RunSkillConfig( + exit_after_stop_delay_ms=60000, natural_exit_grace_seconds=61.0 + ) cfg.safety.require_dry_walkthrough = False tool_ctx.config = cfg tool_ctx.runner.push(_make_result(0, _SUCCESS_JSON, "")) await run_skill("/investigate something", "/tmp") - cmd = tool_ctx.runner.call_args_list[0][0] - assert cmd[0] == "env" - assert cmd[1] == "AUTOSKILLIT_HEADLESS=1" - assert cmd[2] == "CLAUDE_CODE_EXIT_AFTER_STOP_DELAY=60000" + cmd, _cwd, _timeout, kwargs = tool_ctx.runner.call_args_list[0] + assert cmd[0] == "claude" + env = kwargs["env"] + assert env["AUTOSKILLIT_HEADLESS"] == "1" + assert env["CLAUDE_CODE_EXIT_AFTER_STOP_DELAY"] == "60000" class TestRunSkillPassesSessionLogDir: @@ -608,39 +624,6 @@ def mock_ctx(self): ctx.error = AsyncMock() return ctx - @pytest.mark.anyio - async def test_run_cmd_binds_tool_contextvar_and_calls_ctx_info(self, tool_ctx, mock_ctx): - """run_cmd binds tool='run_cmd' contextvar and calls ctx.info on success.""" - tool_ctx.runner.push(_make_result(0, "ok\n", "")) - with structlog.testing.capture_logs( - processors=[structlog.contextvars.merge_contextvars] - ) as logs: - await run_cmd(cmd="echo ok", cwd="/tmp", ctx=mock_ctx) - assert any(entry.get("tool") == "run_cmd" for entry in logs) - - @pytest.mark.anyio - async def test_run_cmd_returns_failure_result_on_nonzero_exit(self, tool_ctx, mock_ctx): - """run_cmd reports failure (success=false) when subprocess exits non-zero.""" - tool_ctx.runner.push(_make_result(1, "", "err")) - result = json.loads(await run_cmd(cmd="false", cwd="/tmp", ctx=mock_ctx)) - assert result["success"] is False - assert result["exit_code"] == 1 - - @pytest.mark.anyio - async def test_run_python_binds_tool_contextvar_and_calls_ctx_info(self, tool_ctx, mock_ctx): - """run_python binds tool='run_python' contextvar and calls ctx.info on success.""" - with structlog.testing.capture_logs( - processors=[structlog.contextvars.merge_contextvars] - ) as logs: - await run_python(callable="json.dumps", args={"obj": 1}, ctx=mock_ctx) - assert any(entry.get("tool") == "run_python" for entry in logs) - - @pytest.mark.anyio - async def test_run_python_returns_failure_result_on_bad_module(self, tool_ctx, mock_ctx): - """run_python reports failure (success=false) when callable import fails.""" - result = json.loads(await run_python(callable="nonexistent.module.func", ctx=mock_ctx)) - assert result["success"] is False - @pytest.mark.anyio async def test_run_skill_binds_tool_contextvar_and_calls_ctx_info(self, tool_ctx, mock_ctx): """run_skill binds tool='run_skill' contextvar and calls ctx.info on success.""" @@ -815,8 +798,10 @@ async def run( order_id: str = "", timeout: float | None = None, stale_threshold: float | None = None, + idle_output_timeout: float | None = None, expected_output_patterns: tuple[str, ...] | list[str] = (), write_behavior=None, + completion_marker: str = "", ) -> SkillResult: calls.append((skill_command, cwd)) return SkillResult( @@ -861,8 +846,10 @@ async def run( order_id: str = "", timeout: float | None = None, stale_threshold: float | None = None, + idle_output_timeout: float | None = None, expected_output_patterns: tuple[str, ...] | list[str] = (), write_behavior=None, + completion_marker: str = "", ) -> SkillResult: captured["add_dirs"] = add_dirs captured["cwd"] = cwd @@ -943,6 +930,50 @@ async def run(self, skill_command, cwd, *, add_dirs=(), **kwargs) -> SkillResult assert fake_validated in captured["add_dirs"] +@pytest.mark.anyio +async def test_run_skill_activates_deps_for_tier3_target(tool_ctx, monkeypatch) -> None: + """run_skill calls activate_skill_deps even when target is tier3 (not in tier2 list).""" + from unittest.mock import MagicMock + + from autoskillit.core import SkillResult, ValidatedAddDir + + fake_validated = ValidatedAddDir(path="/fake/session/dir") + mock_ssm = MagicMock() + mock_ssm.init_session.return_value = fake_validated + tool_ctx.session_skill_manager = mock_ssm + + # Set up skill_resolver to produce a resolved name + mock_resolver = MagicMock() + mock_resolver.resolve.return_value = MagicMock(source=MagicMock(value="bundled_extended")) + tool_ctx.skill_resolver = mock_resolver + + class MockExecutor: + async def run(self, skill_command, cwd, *, add_dirs=(), **kwargs) -> SkillResult: + return SkillResult( + success=True, + result="ok", + session_id="", + subtype="success", + is_error=False, + exit_code=0, + needs_retry=False, + retry_reason="none", + stderr="", + token_usage=None, + ) + + tool_ctx.executor = MockExecutor() + monkeypatch.setattr("autoskillit.server._ctx", tool_ctx) + + from autoskillit.server.tools_execution import run_skill + + # Use a tier3 skill name + await run_skill("/open-pr", "/tmp") + + # activate_skill_deps must have been called regardless of tier + mock_ssm.activate_skill_deps.assert_called_once() + + @pytest.mark.anyio async def test_run_skill_result_includes_order_id_when_passed(tool_ctx, monkeypatch) -> None: """run_skill injects order_id into the result JSON when order_id is non-empty.""" @@ -1025,18 +1056,6 @@ async def test_run_skill_blocked_in_headless_session(self, tool_ctx): result = json.loads(await run_skill("/autoskillit:investigate some-error", "/tmp")) assert result["subtype"] == "headless_error" - @pytest.mark.anyio - async def test_run_cmd_blocked_in_headless_session(self, tool_ctx): - """run_cmd returns headless_error when AUTOSKILLIT_HEADLESS=1.""" - result = json.loads(await run_cmd("echo hello", "/tmp")) - assert result["subtype"] == "headless_error" - - @pytest.mark.anyio - async def test_run_python_blocked_in_headless_session(self, tool_ctx): - """run_python returns headless_error when AUTOSKILLIT_HEADLESS=1.""" - result = json.loads(await run_python("os.getcwd")) - assert result["subtype"] == "headless_error" - class TestResponseFieldsAreTypeSafe: """Every discriminator field in MCP tool responses uses enum values.""" @@ -1074,24 +1093,6 @@ async def test_retry_reason_none_is_enum_value(self, tool_ctx): assert result["retry_reason"] in {e.value for e in RetryReason} -class TestRunCmdTiming: - """run_cmd accumulates wall-clock timing when step_name is provided.""" - - @pytest.mark.anyio - async def test_run_cmd_step_name_records_timing(self, tool_ctx): - await run_cmd(cmd="echo hi", cwd="/tmp", step_name="clone") - report = tool_ctx.timing_log.get_report() - assert len(report) == 1 - assert report[0]["step_name"] == "clone" - assert report[0]["total_seconds"] >= 0.0 - assert report[0]["invocation_count"] == 1 - - @pytest.mark.anyio - async def test_run_cmd_empty_step_name_skips_timing(self, tool_ctx): - await run_cmd(cmd="echo hi", cwd="/tmp") - assert tool_ctx.timing_log.get_report() == [] - - class TestRunSkillTiming: """run_skill accumulates wall-clock timing when step_name is provided.""" @@ -1240,23 +1241,284 @@ async def test_run_skill_rejects_relative_cwd(self, tool_ctx): assert tool_ctx.runner.call_args_list == [] @pytest.mark.anyio - async def test_run_skill_accepts_empty_cwd(self, tool_ctx): + async def test_run_skill_accepts_empty_cwd(self, tool_ctx, monkeypatch): """Empty cwd is accepted (some skills have no specific cwd requirement).""" + _patch_uuid4(monkeypatch) + marker = _DETERMINISTIC_MARKER success_json = ( '{"type": "result", "subtype": "success", "is_error": false,' - ' "result": "done %%ORDER_UP%%", "session_id": "s1"}' + f' "result": "done {marker}", "session_id": "s1"}}' ) tool_ctx.runner.push(_make_result(returncode=0, stdout=success_json)) result = json.loads(await run_skill("/investigate foo", cwd="")) assert result["success"] is True @pytest.mark.anyio - async def test_run_skill_accepts_absolute_cwd(self, tool_ctx): + async def test_run_skill_accepts_absolute_cwd(self, tool_ctx, monkeypatch): """Absolute cwd passes the boundary check and proceeds normally.""" + _patch_uuid4(monkeypatch) + marker = _DETERMINISTIC_MARKER success_json = ( '{"type": "result", "subtype": "success", "is_error": false,' - ' "result": "done %%ORDER_UP%%", "session_id": "s1"}' + f' "result": "done {marker}", "session_id": "s1"}}' ) tool_ctx.runner.push(_make_result(returncode=0, stdout=success_json)) result = json.loads(await run_skill("/investigate foo", cwd="/tmp")) assert result["success"] is True + + +class TestRunSkillPerInvocationMarker: + """Per-invocation completion markers are unique across run_skill calls.""" + + @pytest.mark.anyio + async def test_run_skill_markers_are_unique_per_invocation(self, tool_ctx): + """Two run_skill calls must generate different completion_marker values.""" + success_json = ( + '{"type": "result", "subtype": "success", "is_error": false,' + ' "result": "done", "session_id": "s1"}' + ) + tool_ctx.runner.push(_make_result(returncode=0, stdout=success_json)) + tool_ctx.runner.push(_make_result(returncode=0, stdout=success_json)) + + await run_skill("/investigate a", cwd="/tmp") + await run_skill("/investigate b", cwd="/tmp") + + calls = tool_ctx.runner.call_args_list + assert len(calls) >= 2 + marker1 = calls[0][3]["completion_marker"] + marker2 = calls[1][3]["completion_marker"] + assert marker1 != marker2 + assert "%%ORDER_UP::" in marker1 + assert "%%ORDER_UP::" in marker2 + + +@pytest.mark.anyio +async def test_run_skill_passes_allow_only_to_init_session(tool_ctx, monkeypatch) -> None: + """run_skill computes the closure for the resolved target and forwards it as allow_only.""" + from unittest.mock import MagicMock + + from autoskillit.core import SkillResult, ValidatedAddDir + + fake_validated = ValidatedAddDir(path="/fake/session/dir") + expected_closure = frozenset({"investigate", "mermaid"}) + + mock_ssm = MagicMock() + mock_ssm.init_session.return_value = fake_validated + mock_ssm.compute_skill_closure.return_value = expected_closure + tool_ctx.session_skill_manager = mock_ssm + + mock_resolver = MagicMock() + mock_resolver.resolve.return_value = MagicMock(source=MagicMock(value="bundled_extended")) + tool_ctx.skill_resolver = mock_resolver + + class MockExecutor: + async def run(self, skill_command, cwd, *, add_dirs=(), **kwargs) -> SkillResult: + return SkillResult( + success=True, + result="ok", + session_id="", + subtype="success", + is_error=False, + exit_code=0, + needs_retry=False, + retry_reason="none", + stderr="", + token_usage=None, + ) + + tool_ctx.executor = MockExecutor() + monkeypatch.setattr("autoskillit.server._ctx", tool_ctx) + + from autoskillit.server.tools_execution import run_skill + + await run_skill("/autoskillit:investigate the bug", "/tmp") + + mock_ssm.compute_skill_closure.assert_called_once_with("investigate") + mock_ssm.init_session.assert_called_once() + assert mock_ssm.init_session.call_args.kwargs.get("allow_only") == expected_closure + + +@pytest.mark.anyio +async def test_run_skill_no_target_skill_passes_none_allow_only(tool_ctx, monkeypatch) -> None: + """When skill_resolver is unset, target_name is None and allow_only stays None.""" + from unittest.mock import MagicMock + + from autoskillit.core import SkillResult, ValidatedAddDir + + fake_validated = ValidatedAddDir(path="/fake/session/dir") + mock_ssm = MagicMock() + mock_ssm.init_session.return_value = fake_validated + tool_ctx.session_skill_manager = mock_ssm + tool_ctx.skill_resolver = None # disables resolve_target_skill + + class MockExecutor: + async def run(self, skill_command, cwd, *, add_dirs=(), **kwargs) -> SkillResult: + return SkillResult( + success=True, + result="ok", + session_id="", + subtype="success", + is_error=False, + exit_code=0, + needs_retry=False, + retry_reason="none", + stderr="", + token_usage=None, + ) + + tool_ctx.executor = MockExecutor() + monkeypatch.setattr("autoskillit.server._ctx", tool_ctx) + + from autoskillit.server.tools_execution import run_skill + + await run_skill("/test skill", "/tmp") + + mock_ssm.init_session.assert_called_once() + assert mock_ssm.init_session.call_args.kwargs.get("allow_only") is None + mock_ssm.compute_skill_closure.assert_not_called() + + +@pytest.mark.anyio +async def test_run_skill_make_plan_closure_includes_arch_lens_pack(tool_ctx, monkeypatch) -> None: + """End-to-end: /make-plan resolves a closure containing the entire arch-lens pack.""" + from unittest.mock import MagicMock + + from autoskillit.core import SkillResult, ValidatedAddDir + from autoskillit.workspace.session_skills import ( + DefaultSessionSkillManager, + SkillsDirectoryProvider, + ) + + real_provider = SkillsDirectoryProvider() + real_mgr = DefaultSessionSkillManager(provider=real_provider, ephemeral_root=tool_ctx.temp_dir) + + captured: dict = {} + + class _RecordingManager: + def __init__(self, real: DefaultSessionSkillManager) -> None: + self._real = real + + def init_session(self, session_id, **kwargs): + captured["allow_only"] = kwargs.get("allow_only") + return ValidatedAddDir(path="/fake/session/dir") + + def compute_skill_closure(self, target_name): + return self._real.compute_skill_closure(target_name) + + def activate_skill_deps(self, session_id, skill_name): + return True + + def cleanup_stale(self, max_age_seconds=86400): + return 0 + + tool_ctx.session_skill_manager = _RecordingManager(real_mgr) + + mock_resolver = MagicMock() + mock_resolver.resolve.return_value = MagicMock(source=MagicMock(value="bundled_extended")) + tool_ctx.skill_resolver = mock_resolver + + class MockExecutor: + async def run(self, skill_command, cwd, *, add_dirs=(), **kwargs) -> SkillResult: + return SkillResult( + success=True, + result="ok", + session_id="", + subtype="success", + is_error=False, + exit_code=0, + needs_retry=False, + retry_reason="none", + stderr="", + token_usage=None, + ) + + tool_ctx.executor = MockExecutor() + monkeypatch.setattr("autoskillit.server._ctx", tool_ctx) + + from autoskillit.server.tools_execution import run_skill + + await run_skill("/autoskillit:make-plan refactor", "/tmp") + + closure = captured["allow_only"] + assert closure is not None + assert "make-plan" in closure + assert "mermaid" in closure + arch_members = {n for n in closure if n.startswith("arch-lens-")} + assert len(arch_members) >= 1 + + +def _make_capturing_executor(): + """Return (executor, captured_dict) for testing idle_output_timeout propagation.""" + from autoskillit.core import SkillResult + + captured: dict = {} + + class MockExecutor: + async def run( + self, skill_command, cwd, *, idle_output_timeout=None, **kwargs + ) -> SkillResult: + captured["idle_output_timeout"] = idle_output_timeout + return SkillResult( + success=True, + result="ok", + session_id="", + subtype="success", + is_error=False, + exit_code=0, + needs_retry=False, + retry_reason="none", + stderr="", + token_usage=None, + ) + + return MockExecutor(), captured + + +@pytest.mark.anyio +async def test_run_skill_passes_idle_output_timeout(tool_ctx, monkeypatch) -> None: + """run_skill passes idle_output_timeout (as float) to executor.run().""" + executor, captured = _make_capturing_executor() + tool_ctx.executor = executor + monkeypatch.setattr("autoskillit.server._ctx", tool_ctx) + + from autoskillit.server.tools_execution import run_skill + + await run_skill("/test skill", "/tmp", idle_output_timeout=120) + assert captured["idle_output_timeout"] == 120.0 # int→float conversion + + +@pytest.mark.anyio +async def test_run_skill_idle_output_timeout_defaults_to_none(tool_ctx, monkeypatch) -> None: + """run_skill passes None to executor.run() when idle_output_timeout is not set.""" + executor, captured = _make_capturing_executor() + tool_ctx.executor = executor + monkeypatch.setattr("autoskillit.server._ctx", tool_ctx) + + from autoskillit.server.tools_execution import run_skill + + await run_skill("/test skill", "/tmp") + assert captured["idle_output_timeout"] is None + + +@pytest.mark.anyio +async def test_run_skill_returns_structured_error_when_executor_raises( + tool_ctx, monkeypatch, tmp_path +) -> None: + """run_skill returns SkillResult-shaped JSON even if executor.run() raises unexpectedly.""" + from autoskillit.core import SkillResult + + class ExplodingExecutor: + async def run(self, *args, **kwargs) -> SkillResult: + raise RuntimeError("unexpected executor failure") + + tool_ctx.executor = ExplodingExecutor() + monkeypatch.setattr("autoskillit.server._ctx", tool_ctx) + + from autoskillit.server.tools_execution import run_skill + + result_json = await run_skill("/test cmd", str(tmp_path)) + data = json.loads(result_json) + assert data["success"] is False + assert data["subtype"] == "crashed" + assert data["needs_retry"] is False + assert "unexpected executor failure" in data["result"] diff --git a/tests/server/test_tools_git.py b/tests/server/test_tools_git.py index 3a9c0d29dc..797fa33386 100644 --- a/tests/server/test_tools_git.py +++ b/tests/server/test_tools_git.py @@ -167,19 +167,28 @@ async def test_merge_worktree_merges_on_green(self, tool_ctx, tmp_path): tool_ctx.runner.push( _make_result( 0, - "worktree /repo\nHEAD abc123\nbranch refs/heads/main\n\n" + "worktree /repo\nHEAD abc123\nbranch refs/heads/dev\n\n" "worktree /wt\nHEAD def456\nbranch refs/heads/impl-branch\n\n", "", ) ) # worktree list --porcelain + tool_ctx.runner.push(_make_result(0, "dev\n", "")) # step 7.5: branch --show-current tool_ctx.runner.push(_make_result(0, "", "")) # git merge tool_ctx.runner.push(_make_result(0, "", "")) # worktree remove tool_ctx.runner.push(_make_result(0, "", "")) # branch -D result = json.loads(await merge_worktree(str(wt), "dev")) assert result["merge_succeeded"] is True + assert result["into_branch"] == "dev" assert result["cleanup_succeeded"] is True assert result["worktree_removed"] is True assert result["branch_deleted"] is True + # Verify merge command cwd is the main_repo (/repo) + merge_call = next( + args + for args in tool_ctx.runner.call_args_list + if len(args[0]) > 1 and args[0][1] == "merge" + ) + assert merge_call[1] == Path("/repo") @pytest.mark.anyio async def test_merge_worktree_aborts_on_rebase_failure(self, tool_ctx, tmp_path): @@ -293,10 +302,11 @@ async def test_reports_worktree_remove_failure(self, tool_ctx, tmp_path): tool_ctx.runner.push( _make_result( 0, - "worktree /repo\nHEAD abc\nbranch refs/heads/main\n\n", + "worktree /repo\nHEAD abc\nbranch refs/heads/dev\n\n", "", ) ) # worktree list + tool_ctx.runner.push(_make_result(0, "dev\n", "")) # step 7.5: branch --show-current tool_ctx.runner.push(_make_result(0, "", "")) # git merge tool_ctx.runner.push(_make_result(0, "", "")) # branch -D with patch( @@ -332,10 +342,11 @@ async def test_reports_branch_delete_failure(self, tool_ctx, tmp_path): tool_ctx.runner.push( _make_result( 0, - "worktree /repo\nHEAD abc\nbranch refs/heads/main\n\n", + "worktree /repo\nHEAD abc\nbranch refs/heads/dev\n\n", "", ) ) # worktree list + tool_ctx.runner.push(_make_result(0, "dev\n", "")) # step 7.5: branch --show-current tool_ctx.runner.push(_make_result(0, "", "")) # git merge tool_ctx.runner.push(_make_result(0, "", "")) # worktree remove tool_ctx.runner.push(_make_result(1, "", "error: branch not found")) # branch -D FAILS @@ -387,8 +398,9 @@ async def test_warns_on_worktree_remove_failure(self, tool_ctx, tmp_path): tool_ctx.runner.push(_make_result(0, "", "")) # rebase tool_ctx.runner.push(_make_result(0, "PASS\n= 100 passed =", "")) # post-rebase test-check tool_ctx.runner.push( - _make_result(0, "worktree /repo\nHEAD abc\nbranch refs/heads/main\n\n", "") + _make_result(0, "worktree /repo\nHEAD abc\nbranch refs/heads/dev\n\n", "") ) + tool_ctx.runner.push(_make_result(0, "dev\n", "")) # step 7.5: branch --show-current tool_ctx.runner.push(_make_result(0, "", "")) # merge tool_ctx.runner.push(_make_result(0, "", "")) # branch -D @@ -428,8 +440,9 @@ async def test_warns_on_branch_delete_failure(self, tool_ctx, tmp_path): tool_ctx.runner.push(_make_result(0, "", "")) # rebase tool_ctx.runner.push(_make_result(0, "PASS\n= 100 passed =", "")) # post-rebase test-check tool_ctx.runner.push( - _make_result(0, "worktree /repo\nHEAD abc\nbranch refs/heads/main\n\n", "") + _make_result(0, "worktree /repo\nHEAD abc\nbranch refs/heads/dev\n\n", "") ) + tool_ctx.runner.push(_make_result(0, "dev\n", "")) # step 7.5: branch --show-current tool_ctx.runner.push(_make_result(0, "", "")) # merge tool_ctx.runner.push(_make_result(0, "", "")) # worktree remove tool_ctx.runner.push(_make_result(1, "", "error: branch not found")) # branch -D FAILS @@ -462,8 +475,9 @@ async def test_no_warning_on_clean_cleanup(self, tool_ctx, tmp_path): tool_ctx.runner.push(_make_result(0, "", "")) # rebase tool_ctx.runner.push(_make_result(0, "PASS\n= 100 passed =", "")) # post-rebase test-check tool_ctx.runner.push( - _make_result(0, "worktree /repo\nHEAD abc\nbranch refs/heads/main\n\n", "") + _make_result(0, "worktree /repo\nHEAD abc\nbranch refs/heads/dev\n\n", "") ) + tool_ctx.runner.push(_make_result(0, "dev\n", "")) # step 7.5: branch --show-current tool_ctx.runner.push(_make_result(0, "", "")) # merge tool_ctx.runner.push(_make_result(0, "", "")) # worktree remove — success tool_ctx.runner.push(_make_result(0, "", "")) # branch -D — success @@ -705,6 +719,7 @@ class TestCreateUniqueBranch: @pytest.mark.anyio async def test_creates_branch_when_unique(self, tool_ctx): tool_ctx.runner.push(_make_result(0, "", "")) # ls-remote: empty = absent + tool_ctx.runner.push(_make_result(0, "main\n", "")) # branch --show-current (HEAD state) tool_ctx.runner.push(_make_result(0, "", "")) # git checkout -b result = json.loads(await create_unique_branch("feat-foo", 42, "origin", ".")) assert result["branch_name"] == "feat-foo-42" @@ -714,6 +729,7 @@ async def test_creates_branch_when_unique(self, tool_ctx): async def test_appends_suffix_when_branch_exists_on_remote(self, tool_ctx): tool_ctx.runner.push(_make_result(0, "abc123\trefs/heads/feat-foo-42\n", "")) # exists tool_ctx.runner.push(_make_result(0, "", "")) # -2 not found + tool_ctx.runner.push(_make_result(0, "main\n", "")) # branch --show-current (HEAD state) tool_ctx.runner.push(_make_result(0, "", "")) # checkout -b feat-foo-42-2 result = json.loads(await create_unique_branch("feat-foo", 42, "origin", ".")) assert result["branch_name"] == "feat-foo-42-2" @@ -722,6 +738,7 @@ async def test_appends_suffix_when_branch_exists_on_remote(self, tool_ctx): @pytest.mark.anyio async def test_ls_remote_auth_failure_falls_back_gracefully(self, tool_ctx): tool_ctx.runner.push(_make_result(128, "", "fatal: Authentication failed")) + tool_ctx.runner.push(_make_result(0, "main\n", "")) # branch --show-current (HEAD state) tool_ctx.runner.push(_make_result(0, "", "")) # checkout proceeds with base name result = json.loads(await create_unique_branch("feat-foo", 42, "origin", ".")) assert result["branch_name"] == "feat-foo-42" @@ -729,8 +746,9 @@ async def test_ls_remote_auth_failure_falls_back_gracefully(self, tool_ctx): @pytest.mark.anyio async def test_no_issue_uses_slug_only(self, tool_ctx): - tool_ctx.runner.push(_make_result(0, "", "")) - tool_ctx.runner.push(_make_result(0, "", "")) + tool_ctx.runner.push(_make_result(0, "", "")) # ls-remote + tool_ctx.runner.push(_make_result(0, "main\n", "")) # branch --show-current + tool_ctx.runner.push(_make_result(0, "", "")) # checkout -b result = json.loads(await create_unique_branch("feat-bar", None, "origin", ".")) assert result["branch_name"] == "feat-bar" @@ -743,8 +761,9 @@ async def test_gate_closed_returns_gate_error(self, tool_ctx): @pytest.mark.anyio async def test_timing_recorded_when_step_name_provided(self, tool_ctx): - tool_ctx.runner.push(_make_result(0, "", "")) - tool_ctx.runner.push(_make_result(0, "", "")) + tool_ctx.runner.push(_make_result(0, "", "")) # ls-remote + tool_ctx.runner.push(_make_result(0, "main\n", "")) # branch --show-current + tool_ctx.runner.push(_make_result(0, "", "")) # checkout -b await create_unique_branch("feat-x", 1, "origin", ".", step_name="branch_step") assert any(e["step_name"] == "branch_step" for e in tool_ctx.timing_log.get_report()) @@ -752,6 +771,7 @@ async def test_timing_recorded_when_step_name_provided(self, tool_ctx): async def test_create_unique_branch_uses_base_branch_name_when_provided(self, tool_ctx): """AP3: when base_branch_name is provided, use it directly as the base.""" tool_ctx.runner.push(_make_result(0, "", "")) # ls-remote: empty = absent + tool_ctx.runner.push(_make_result(0, "main\n", "")) # branch --show-current tool_ctx.runner.push(_make_result(0, "", "")) # git checkout -b result = json.loads(await create_unique_branch(base_branch_name="impl/238", cwd=".")) assert result["branch_name"] == "impl/238" @@ -763,6 +783,27 @@ async def test_create_unique_branch_uses_base_branch_name_when_provided(self, to assert ls_remote_cmd is not None, "No ls-remote subprocess call found" assert any("impl/238" in arg for arg in ls_remote_cmd) + @pytest.mark.anyio + async def test_reports_base_ref_in_return_value(self, tool_ctx): + """Test 1.6: create_unique_branch reports base_ref (the branch HEAD was on).""" + tool_ctx.runner.push(_make_result(0, "", "")) # ls-remote: empty = absent + tool_ctx.runner.push(_make_result(0, "feature-branch\n", "")) # branch --show-current + tool_ctx.runner.push(_make_result(0, "", "")) # git checkout -b + result = json.loads(await create_unique_branch("feat-foo", 42, "origin", ".")) + assert result["branch_name"] == "feat-foo-42" + assert result["was_unique"] is True + assert result["base_ref"] == "feature-branch" + + @pytest.mark.anyio + async def test_reports_detached_head_as_base_ref(self, tool_ctx): + """create_unique_branch reports DETACHED_HEAD when HEAD is detached.""" + tool_ctx.runner.push(_make_result(0, "", "")) # ls-remote: empty = absent + tool_ctx.runner.push(_make_result(0, "", "")) # branch --show-current returns empty + tool_ctx.runner.push(_make_result(0, "", "")) # git checkout -b + result = json.loads(await create_unique_branch("feat-foo", 42, "origin", ".")) + assert result["branch_name"] == "feat-foo-42" + assert result["base_ref"] == "DETACHED_HEAD" + class TestCheckPrMergeable: @pytest.mark.anyio diff --git a/tests/server/test_tools_github.py b/tests/server/test_tools_github.py index 5fb92be78a..5b4a437473 100644 --- a/tests/server/test_tools_github.py +++ b/tests/server/test_tools_github.py @@ -3,12 +3,71 @@ from __future__ import annotations import json -from unittest.mock import AsyncMock +from pathlib import Path +from unittest.mock import AsyncMock, MagicMock +import anyio import pytest -from autoskillit.pipeline.gate import DefaultGateState -from autoskillit.server.tools_github import fetch_github_issue, get_issue_title +from autoskillit.config import AutomationConfig +from autoskillit.core import SkillResult +from autoskillit.core.types import RetryReason +from autoskillit.pipeline.gate import GATED_TOOLS, UNGATED_TOOLS, DefaultGateState +from autoskillit.server.helpers import _extract_block +from autoskillit.server.tools_github import ( + _FINGERPRINT_END, + _FINGERPRINT_START, + _parse_fingerprint, + fetch_github_issue, + get_issue_title, + report_bug, +) +from autoskillit.server.tools_issue_lifecycle import ( + _ENRICH_RESULT_END, + _ENRICH_RESULT_START, + _PREPARE_RESULT_END, + _PREPARE_RESULT_START, + _parse_enrich_result, + _parse_prepare_result, +) +from tests.server._helpers import _skill_fail, _skill_ok + +# --------------------------------------------------------------------------- +# _parse_fingerprint unit tests +# --------------------------------------------------------------------------- + + +def test_parse_fingerprint_present(): + report = ( + "Some preamble\n" + f"{_FINGERPRINT_START}\n" + "KeyError in recipe/validator.py: missing ingredient ref\n" + f"{_FINGERPRINT_END}\n" + "Report written to /tmp/report.md" + ) + assert _parse_fingerprint(report) == "KeyError in recipe/validator.py: missing ingredient ref" + + +def test_parse_fingerprint_missing_returns_none(): + assert _parse_fingerprint("No fingerprint block here") is None + + +def test_parse_fingerprint_empty_block_returns_none(): + report = f"{_FINGERPRINT_START}\n{_FINGERPRINT_END}\n" + assert _parse_fingerprint(report) is None + + +def test_parse_fingerprint_first_nonempty_line(): + """Only the first non-empty line inside the block is returned.""" + report = ( + f"{_FINGERPRINT_START}\n" + "\n" + " TypeError in execution/headless.py: runner=None \n" + "extra line\n" + f"{_FINGERPRINT_END}\n" + ) + assert _parse_fingerprint(report) == "TypeError in execution/headless.py: runner=None" + # --------------------------------------------------------------------------- # fetch_github_issue @@ -89,6 +148,38 @@ async def test_fetch_github_issue_bare_number_with_default_repo( assert "owner/repo#42" in call_args.args[0] +@pytest.mark.anyio +async def test_fetch_github_issue_delegates_to_client(tool_ctx): + mock_client = AsyncMock() + mock_client.fetch_issue.return_value = { + "success": True, + "issue_number": 1, + "title": "T", + "url": "u", + "state": "open", + "labels": [], + "content": "# T", + } + tool_ctx.github_client = mock_client + result = json.loads(await fetch_github_issue("owner/repo#1")) + assert result["success"] is True + mock_client.fetch_issue.assert_called_once_with("owner/repo#1", include_comments=True) + + +@pytest.mark.anyio +async def test_fetch_github_issue_client_error_propagated(tool_ctx): + mock_client = AsyncMock() + mock_client.fetch_issue.return_value = {"success": False, "error": "Not Found"} + tool_ctx.github_client = mock_client + result = json.loads(await fetch_github_issue("owner/repo#404")) + assert result["success"] is False + + +def test_fetch_github_issue_in_gated_tools(): + assert "fetch_github_issue" in GATED_TOOLS + assert "fetch_github_issue" not in UNGATED_TOOLS + + # --------------------------------------------------------------------------- # get_issue_title # --------------------------------------------------------------------------- @@ -126,3 +217,640 @@ async def test_get_issue_title_success(tool_ctx) -> None: result = json.loads(await get_issue_title("owner/repo#42")) assert result["success"] is True assert result["title"] == "Fix the bug" + + +class TestGetIssueTitleTool: + @pytest.mark.anyio + async def test_get_issue_title_success(self, tool_ctx): + """Delegates to github_client.fetch_title; returns JSON result.""" + mock_client = AsyncMock() + mock_client.fetch_title.return_value = { + "success": True, + "number": 42, + "title": "Fix merge conflict triage", + "slug": "fix-merge-conflict-triage", + } + tool_ctx.github_client = mock_client + result = json.loads(await get_issue_title("https://github.com/owner/repo/issues/42")) + assert result["success"] is True + assert result["number"] == 42 + assert result["title"] == "Fix merge conflict triage" + assert result["slug"] == "fix-merge-conflict-triage" + mock_client.fetch_title.assert_called_once_with("https://github.com/owner/repo/issues/42") + + @pytest.mark.anyio + async def test_get_issue_title_client_error_propagated(self, tool_ctx): + """Propagates {success: False, error: ...} from fetch_title.""" + mock_client = AsyncMock() + mock_client.fetch_title.return_value = {"success": False, "error": "Not Found"} + tool_ctx.github_client = mock_client + result = json.loads(await get_issue_title("owner/repo#404")) + assert result["success"] is False + + def test_get_issue_title_is_gated(self): + """'get_issue_title' in GATED_TOOLS.""" + assert "get_issue_title" in GATED_TOOLS + assert "get_issue_title" not in UNGATED_TOOLS + + +# --------------------------------------------------------------------------- +# report_bug config defaults +# --------------------------------------------------------------------------- + + +def test_report_bug_config_defaults(): + cfg = AutomationConfig() + assert cfg.report_bug.timeout == 600 + assert cfg.report_bug.model is None + assert cfg.report_bug.report_dir is None + assert cfg.report_bug.github_filing is True + assert "autoreported" in cfg.report_bug.github_labels + assert "bug" in cfg.report_bug.github_labels + + +def test_github_config_defaults(): + config = AutomationConfig() + assert config.github.token is None + assert config.github.default_repo is None + + +# --------------------------------------------------------------------------- +# TestReportBugTool +# --------------------------------------------------------------------------- + + +class TestReportBugTool: + @pytest.mark.anyio + async def test_report_bug_failure_includes_session_id_and_stderr(self, tool_ctx, tmp_path): + """Blocking failure response must include session_id and stderr for diagnosis.""" + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = False + + mock_executor = AsyncMock() + mock_executor.run.return_value = SkillResult( + success=False, + result="", + session_id="fail-session-id", + subtype="missing_completion_marker", + is_error=True, + exit_code=1, + needs_retry=False, + retry_reason=RetryReason.NONE, + stderr="Claude crashed", + ) + tool_ctx.executor = mock_executor + + result = json.loads(await report_bug("some error", str(tmp_path), severity="blocking")) + + assert result["success"] is False + assert result["session_id"] == "fail-session-id" + assert result["stderr"] == "Claude crashed" + + @pytest.mark.anyio + async def test_report_bug_passes_expected_output_patterns_to_executor( + self, tool_ctx, tmp_path + ): + """output_pattern_resolver is consulted and patterns are passed to executor.run().""" + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = False + + mock_executor = AsyncMock() + mock_executor.run.return_value = SkillResult( + success=True, + result="## Report\nfindings", + session_id="sid", + subtype="success", + is_error=False, + exit_code=0, + needs_retry=False, + retry_reason=RetryReason.NONE, + stderr="", + ) + tool_ctx.executor = mock_executor + tool_ctx.output_pattern_resolver = lambda cmd: ["---bug-fingerprint---"] + + await report_bug("error ctx", str(tmp_path), severity="blocking") + + call_kwargs = mock_executor.run.call_args.kwargs + assert call_kwargs.get("expected_output_patterns") == ["---bug-fingerprint---"] + + +# --------------------------------------------------------------------------- +# _extract_block unit tests +# --------------------------------------------------------------------------- + + +def test_extract_block_returns_lines_within_delimiters(): + text = "preamble\n---start---\nline1\nline2\n---end---\npostamble" + assert _extract_block(text, "---start---", "---end---") == ["line1", "line2"] + + +def test_extract_block_no_start_returns_empty(): + assert _extract_block("no delimiters here", "---start---", "---end---") == [] + + +def test_extract_block_no_end_returns_empty(): + # end delimiter absent — no complete block + text = "---start---\nline1\nline2" + assert _extract_block(text, "---start---", "---end---") == [] + + +def test_extract_block_empty_block_returns_empty_list(): + text = "---start---\n---end---" + assert _extract_block(text, "---start---", "---end---") == [] + + +def test_extract_block_preserves_whitespace_in_lines(): + text = "---start---\n indented\n---end---" + assert _extract_block(text, "---start---", "---end---") == [" indented"] + + +# --------------------------------------------------------------------------- +# _parse_prepare_result unit tests +# --------------------------------------------------------------------------- + + +def test_parse_prepare_result_valid_json(): + payload = '{"success": true, "issue_url": "https://github.com/x/y/issues/1"}' + text = f"{_PREPARE_RESULT_START}\n{payload}\n{_PREPARE_RESULT_END}" + result = _parse_prepare_result(text) + assert result == {"success": True, "issue_url": "https://github.com/x/y/issues/1"} + + +def test_parse_prepare_result_no_block(): + result = _parse_prepare_result("no block here") + assert result == {"success": False, "error": "no result block found"} + + +def test_parse_prepare_result_invalid_json(): + text = f"{_PREPARE_RESULT_START}\nnot-json\n{_PREPARE_RESULT_END}" + result = _parse_prepare_result(text) + assert result == {"success": False, "error": "result block contained invalid JSON"} + + +# --------------------------------------------------------------------------- +# _parse_enrich_result unit tests +# --------------------------------------------------------------------------- + + +def test_parse_enrich_result_valid_json(): + payload = '{"enriched": [42], "skipped_already_enriched": []}' + text = f"{_ENRICH_RESULT_START}\n{payload}\n{_ENRICH_RESULT_END}" + result = _parse_enrich_result(text) + assert result == {"enriched": [42], "skipped_already_enriched": []} + + +def test_parse_enrich_result_no_block(): + result = _parse_enrich_result("no block here") + assert result == {"success": False, "error": "no result block found"} + + +def test_parse_enrich_result_invalid_json(): + text = f"{_ENRICH_RESULT_START}\nnot-json\n{_ENRICH_RESULT_END}" + result = _parse_enrich_result(text) + assert result == {"success": False, "error": "result block contained invalid JSON"} + + +# --------------------------------------------------------------------------- +# report_bug gate tests +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +async def test_report_bug_gate_closed(tool_ctx): + tool_ctx.gate.disable() + result = json.loads(await report_bug("some error", "/tmp")) + assert result["success"] is False + assert "not enabled" in result["result"].lower() or "gate" in result["result"].lower() + + +@pytest.mark.anyio +async def test_report_bug_no_executor(tool_ctx): + tool_ctx.executor = None + result = json.loads(await report_bug("error ctx", "/tmp")) + assert result["success"] is False + assert "executor" in result["error"].lower() + + +# --------------------------------------------------------------------------- +# Blocking mode +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +async def test_report_bug_blocking_success(tool_ctx, tmp_path): + """Blocking mode awaits the session and returns status=complete.""" + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = False + + mock_executor = AsyncMock() + mock_executor.run.return_value = _skill_ok("## Report\nroot cause found") + tool_ctx.executor = mock_executor + + result = json.loads(await report_bug("KeyError in foo", str(tmp_path), severity="blocking")) + + assert result["success"] is True + assert result["status"] == "complete" + assert "report" in result + assert "report_path" in result + mock_executor.run.assert_awaited_once() + + +@pytest.mark.anyio +async def test_report_bug_blocking_failure_propagated(tool_ctx, tmp_path): + """If the headless session fails, status=failed is returned.""" + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = False + + mock_executor = AsyncMock() + mock_executor.run.return_value = _skill_fail() + tool_ctx.executor = mock_executor + + result = json.loads(await report_bug("crash here", str(tmp_path), severity="blocking")) + + assert result["success"] is False + assert result["status"] == "failed" + + +@pytest.mark.anyio +async def test_report_bug_blocking_writes_report_file(tool_ctx, tmp_path): + """The report text must be written to the resolved report_path.""" + report_dir = tmp_path / "rpts" + tool_ctx.config.report_bug.report_dir = str(report_dir) + tool_ctx.config.report_bug.github_filing = False + + mock_executor = AsyncMock() + mock_executor.run.return_value = _skill_ok("# Bug Report\nfoo bar") + tool_ctx.executor = mock_executor + + result = json.loads(await report_bug("err", str(tmp_path), severity="blocking")) + + report_path = Path(result["report_path"]) + assert report_path.exists() + assert "Bug Report" in report_path.read_text() + + +# --------------------------------------------------------------------------- +# Non-blocking mode +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +async def test_report_bug_non_blocking_returns_immediately(tool_ctx, tmp_path): + """Non-blocking mode must return dispatched before the session completes.""" + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = False + + ready = anyio.Event() + + async def slow_run(*args, **kwargs): + await ready.wait() # blocks until test signals + return _skill_ok() + + mock_executor = MagicMock() + mock_executor.run = slow_run + tool_ctx.executor = mock_executor + + result = json.loads(await report_bug("error ctx", str(tmp_path), severity="non_blocking")) + + assert result["success"] is True + assert result["status"] == "dispatched" + assert "report_path" in result + + # Let the background task finish cleanly. + ready.set() + await anyio.sleep(0) + + +@pytest.mark.anyio +async def test_report_bug_non_blocking_default_severity(tool_ctx, tmp_path): + """The default severity is non_blocking.""" + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = False + + mock_executor = AsyncMock() + mock_executor.run.return_value = _skill_ok() + tool_ctx.executor = mock_executor + + result = json.loads(await report_bug("err", str(tmp_path))) + assert result["status"] == "dispatched" + + +# --------------------------------------------------------------------------- +# Non-blocking outcome tests (supervised background task) +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +async def test_report_bug_non_blocking_outcome_writes_report_file(tool_ctx, tmp_path): + """After the background task completes, report_path must exist with content.""" + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = False + + mock_executor = AsyncMock() + mock_executor.run.return_value = _skill_ok("# Bug Report\nroot cause: missing guard") + tool_ctx.executor = mock_executor + + result = json.loads( + await report_bug("KeyError in foo", str(tmp_path), severity="non_blocking") + ) + assert result["status"] == "dispatched" + + report_path = Path(result["report_path"]) + await tool_ctx.background.drain() + + assert report_path.exists(), "report_path must exist after background task completes" + assert "Bug Report" in report_path.read_text() + + +@pytest.mark.anyio +async def test_report_bug_non_blocking_writes_status_file_on_success(tool_ctx, tmp_path): + """A status.json file must be written with status='complete' after successful dispatch.""" + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = False + + mock_executor = AsyncMock() + mock_executor.run.return_value = _skill_ok("# Report\nfoo") + tool_ctx.executor = mock_executor + + result = json.loads(await report_bug("err", str(tmp_path), severity="non_blocking")) + report_path = Path(result["report_path"]) + + # Before task runs: pending status file should exist + status_path = report_path.with_suffix(".status.json") + assert status_path.exists(), "status file must be written synchronously on dispatch" + pending = json.loads(status_path.read_text()) + assert pending["status"] == "pending" + + # After task completes: status should update to complete + await tool_ctx.background.drain() + + data = json.loads(status_path.read_text()) + assert data["status"] == "complete" + assert "completed_at" in data + + +@pytest.mark.anyio +async def test_report_bug_non_blocking_writes_status_file_on_failure(tool_ctx, tmp_path): + """When the headless session fails, status.json must reflect the failure.""" + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = False + + mock_executor = AsyncMock() + mock_executor.run.return_value = _skill_fail() + tool_ctx.executor = mock_executor + + result = json.loads(await report_bug("crash here", str(tmp_path), severity="non_blocking")) + status_path = Path(result["report_path"]).with_suffix(".status.json") + + await tool_ctx.background.drain() + + data = json.loads(status_path.read_text()) + assert data["status"] == "failed" + assert "completed_at" in data + + +@pytest.mark.anyio +async def test_report_bug_non_blocking_executor_raises_is_observed(tool_ctx, tmp_path): + """If executor.run() raises, the exception must be logged — not silently dropped.""" + + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = False + + mock_executor = AsyncMock() + mock_executor.run.side_effect = RuntimeError("executor exploded") + tool_ctx.executor = mock_executor + + result = json.loads(await report_bug("error ctx", str(tmp_path), severity="non_blocking")) + assert result["status"] == "dispatched" + + await tool_ctx.background.drain() + + # The exception must be captured and logged — not silently dropped + status_path = Path(result["report_path"]).with_suffix(".status.json") + assert status_path.exists(), "status file must exist even when executor raises" + data = json.loads(status_path.read_text()) + assert data["status"] == "failed" + assert "executor exploded" in data.get("error", "") + + +@pytest.mark.anyio +async def test_report_bug_no_pending_tasks_after_completion(tool_ctx, tmp_path): + """After background task completes, no tasks remain in the supervisor's pending set.""" + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = False + + mock_executor = AsyncMock() + mock_executor.run.return_value = _skill_ok() + tool_ctx.executor = mock_executor + + await report_bug("err", str(tmp_path), severity="non_blocking") + + await tool_ctx.background.drain() + + assert tool_ctx.background.pending_count == 0 + + +# --------------------------------------------------------------------------- +# GitHub filing — blocking mode (easier to assert synchronously) +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +async def test_report_bug_creates_github_issue_on_no_duplicate(tool_ctx, tmp_path): + """When no matching issue is found, create_issue is called.""" + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = True + tool_ctx.config.github.default_repo = "owner/repo" + + report_with_fp = ( + f"{_FINGERPRINT_START}\n" + "KeyError in recipe/validator.py: missing ref\n" + f"{_FINGERPRINT_END}\n" + "## Bug Report\ndetails" + ) + mock_executor = AsyncMock() + mock_executor.run.return_value = _skill_ok(report_with_fp) + tool_ctx.executor = mock_executor + + mock_gh = AsyncMock() + mock_gh.has_token = True + mock_gh.search_issues.return_value = {"success": True, "total_count": 0, "items": []} + mock_gh.create_issue.return_value = { + "success": True, + "issue_number": 99, + "url": "https://github.com/owner/repo/issues/99", + } + tool_ctx.github_client = mock_gh + + result = json.loads(await report_bug("KeyError crash", str(tmp_path), severity="blocking")) + + assert result["success"] is True + mock_gh.search_issues.assert_awaited_once() + mock_gh.create_issue.assert_awaited_once() + assert result["github"]["duplicate"] is False + assert result["github"]["issue_url"] == "https://github.com/owner/repo/issues/99" + + +@pytest.mark.anyio +async def test_report_bug_comments_on_duplicate_issue(tool_ctx, tmp_path): + """When a matching issue exists and error_context is new, add_comment is called.""" + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = True + tool_ctx.config.github.default_repo = "owner/repo" + + mock_executor = AsyncMock() + mock_executor.run.return_value = _skill_ok( + "## Report\n" + _FINGERPRINT_START + "\nfp\n" + _FINGERPRINT_END + ) + tool_ctx.executor = mock_executor + + mock_gh = AsyncMock() + mock_gh.has_token = True + mock_gh.search_issues.return_value = { + "success": True, + "total_count": 1, + "items": [ + { + "number": 7, + "title": "fp", + "html_url": "https://github.com/owner/repo/issues/7", + "body": "Original body — no error_context here", + "state": "open", + } + ], + } + mock_gh.add_comment.return_value = {"success": True, "comment_id": 55, "url": "u"} + tool_ctx.github_client = mock_gh + + result = json.loads( + await report_bug("brand new error text", str(tmp_path), severity="blocking") + ) + + assert result["success"] is True + mock_gh.add_comment.assert_awaited_once() + assert result["github"]["duplicate"] is True + assert result["github"]["comment_added"] is True + + +@pytest.mark.anyio +async def test_report_bug_skips_comment_if_already_present(tool_ctx, tmp_path): + """If error_context is already in the issue body, no comment is posted.""" + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = True + tool_ctx.config.github.default_repo = "owner/repo" + + error_ctx = "exact error text already filed" + mock_executor = AsyncMock() + mock_executor.run.return_value = _skill_ok() + tool_ctx.executor = mock_executor + + mock_gh = AsyncMock() + mock_gh.has_token = True + mock_gh.search_issues.return_value = { + "success": True, + "total_count": 1, + "items": [ + { + "number": 3, + "title": "fp", + "html_url": "https://github.com/owner/repo/issues/3", + "body": f"body contains {error_ctx} already", + "state": "open", + } + ], + } + tool_ctx.github_client = mock_gh + + result = json.loads(await report_bug(error_ctx, str(tmp_path), severity="blocking")) + + mock_gh.add_comment.assert_not_awaited() + assert result["github"]["comment_added"] is False + + +@pytest.mark.anyio +async def test_report_bug_skips_github_if_no_token(tool_ctx, tmp_path): + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = True + + mock_executor = AsyncMock() + mock_executor.run.return_value = _skill_ok() + tool_ctx.executor = mock_executor + + mock_gh = AsyncMock() + mock_gh.has_token = False + tool_ctx.github_client = mock_gh + + result = json.loads(await report_bug("err", str(tmp_path), severity="blocking")) + + assert result["success"] is True + mock_gh.search_issues.assert_not_awaited() + assert result["github"]["skipped"] is True + assert result["github"]["reason"] == "no_token" + + +@pytest.mark.anyio +async def test_report_bug_skips_github_if_no_default_repo(tool_ctx, tmp_path): + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = True + tool_ctx.config.github.default_repo = None + + mock_executor = AsyncMock() + mock_executor.run.return_value = _skill_ok() + tool_ctx.executor = mock_executor + + mock_gh = AsyncMock() + mock_gh.has_token = True + tool_ctx.github_client = mock_gh + + result = json.loads(await report_bug("err", str(tmp_path), severity="blocking")) + + mock_gh.search_issues.assert_not_awaited() + assert result["github"]["skipped"] is True + + +@pytest.mark.anyio +async def test_report_bug_github_filing_disabled(tool_ctx, tmp_path): + """github_filing=false must skip all GitHub calls.""" + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = False + tool_ctx.config.github.default_repo = "owner/repo" + + mock_executor = AsyncMock() + mock_executor.run.return_value = _skill_ok() + tool_ctx.executor = mock_executor + + mock_gh = AsyncMock() + mock_gh.has_token = True + tool_ctx.github_client = mock_gh + + result = json.loads(await report_bug("err", str(tmp_path), severity="blocking")) + + mock_gh.search_issues.assert_not_awaited() + assert result["github"] == {} + + +@pytest.mark.anyio +async def test_report_bug_blocking_github_client_raises_does_not_propagate(tool_ctx, tmp_path): + """If the GitHub client raises unexpectedly, the error must be captured in the github dict.""" + tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") + tool_ctx.config.report_bug.github_filing = True + tool_ctx.config.github.default_repo = "owner/repo" + + mock_executor = AsyncMock() + mock_executor.run.return_value = _skill_ok( + "# Report\n" + _FINGERPRINT_START + "\nfp1\n" + _FINGERPRINT_END + ) + tool_ctx.executor = mock_executor + + mock_gh = MagicMock() + mock_gh.has_token = True + mock_gh.search_issues = AsyncMock(side_effect=RuntimeError("network failure")) + tool_ctx.github_client = mock_gh + + # Must not raise — exception is captured in github dict + result = json.loads(await report_bug("err", str(tmp_path), severity="blocking")) + assert result["success"] is True # session succeeded + assert result["github"].get("skipped") is True + assert "unexpected error" in result["github"].get("reason", "") + assert "network failure" in result["github"].get("reason", "") diff --git a/tests/server/test_tools_integrations.py b/tests/server/test_tools_integrations.py index 810d99b7b2..8cd893ab51 100644 --- a/tests/server/test_tools_integrations.py +++ b/tests/server/test_tools_integrations.py @@ -1,33 +1,17 @@ -"""Tests for the report_bug and fetch_github_issue MCP tool handlers.""" +"""Integration tests for issue lifecycle, headless tool diagnostics, and PR ops.""" from __future__ import annotations import json -from pathlib import Path -from unittest.mock import AsyncMock, MagicMock +from unittest.mock import AsyncMock -import anyio import pytest from autoskillit.core import SkillResult from autoskillit.core.types import RetryReason -from autoskillit.pipeline.gate import UNGATED_TOOLS -from autoskillit.server.helpers import _extract_block -from autoskillit.server.tools_github import ( - _FINGERPRINT_END, - _FINGERPRINT_START, - _parse_fingerprint, - fetch_github_issue, - get_issue_title, - report_bug, -) from autoskillit.server.tools_issue_lifecycle import ( - _ENRICH_RESULT_END, - _ENRICH_RESULT_START, _PREPARE_RESULT_END, _PREPARE_RESULT_START, - _parse_enrich_result, - _parse_prepare_result, claim_issue, enrich_issues, prepare_issue, @@ -36,741 +20,6 @@ from autoskillit.server.tools_pr_ops import bulk_close_issues, get_pr_reviews from tests.conftest import _make_result -# --------------------------------------------------------------------------- -# _parse_fingerprint unit tests -# --------------------------------------------------------------------------- - - -def test_parse_fingerprint_present(): - report = ( - "Some preamble\n" - f"{_FINGERPRINT_START}\n" - "KeyError in recipe/validator.py: missing ingredient ref\n" - f"{_FINGERPRINT_END}\n" - "Report written to /tmp/report.md" - ) - assert _parse_fingerprint(report) == "KeyError in recipe/validator.py: missing ingredient ref" - - -def test_parse_fingerprint_missing_returns_none(): - assert _parse_fingerprint("No fingerprint block here") is None - - -def test_parse_fingerprint_empty_block_returns_none(): - report = f"{_FINGERPRINT_START}\n{_FINGERPRINT_END}\n" - assert _parse_fingerprint(report) is None - - -def test_parse_fingerprint_first_nonempty_line(): - """Only the first non-empty line inside the block is returned.""" - report = ( - f"{_FINGERPRINT_START}\n" - "\n" - " TypeError in execution/headless.py: runner=None \n" - "extra line\n" - f"{_FINGERPRINT_END}\n" - ) - assert _parse_fingerprint(report) == "TypeError in execution/headless.py: runner=None" - - -# --------------------------------------------------------------------------- -# _extract_block unit tests -# --------------------------------------------------------------------------- - - -def test_extract_block_returns_lines_within_delimiters(): - text = "preamble\n---start---\nline1\nline2\n---end---\npostamble" - assert _extract_block(text, "---start---", "---end---") == ["line1", "line2"] - - -def test_extract_block_no_start_returns_empty(): - assert _extract_block("no delimiters here", "---start---", "---end---") == [] - - -def test_extract_block_no_end_returns_empty(): - # end delimiter absent — no complete block - text = "---start---\nline1\nline2" - assert _extract_block(text, "---start---", "---end---") == [] - - -def test_extract_block_empty_block_returns_empty_list(): - text = "---start---\n---end---" - assert _extract_block(text, "---start---", "---end---") == [] - - -def test_extract_block_preserves_whitespace_in_lines(): - text = "---start---\n indented\n---end---" - assert _extract_block(text, "---start---", "---end---") == [" indented"] - - -# --------------------------------------------------------------------------- -# _parse_prepare_result unit tests -# --------------------------------------------------------------------------- - - -def test_parse_prepare_result_valid_json(): - payload = '{"success": true, "issue_url": "https://github.com/x/y/issues/1"}' - text = f"{_PREPARE_RESULT_START}\n{payload}\n{_PREPARE_RESULT_END}" - result = _parse_prepare_result(text) - assert result == {"success": True, "issue_url": "https://github.com/x/y/issues/1"} - - -def test_parse_prepare_result_no_block(): - result = _parse_prepare_result("no block here") - assert result == {"success": False, "error": "no result block found"} - - -def test_parse_prepare_result_invalid_json(): - text = f"{_PREPARE_RESULT_START}\nnot-json\n{_PREPARE_RESULT_END}" - result = _parse_prepare_result(text) - assert result == {"success": False, "error": "result block contained invalid JSON"} - - -# --------------------------------------------------------------------------- -# _parse_enrich_result unit tests -# --------------------------------------------------------------------------- - - -def test_parse_enrich_result_valid_json(): - payload = '{"enriched": [42], "skipped_already_enriched": []}' - text = f"{_ENRICH_RESULT_START}\n{payload}\n{_ENRICH_RESULT_END}" - result = _parse_enrich_result(text) - assert result == {"enriched": [42], "skipped_already_enriched": []} - - -def test_parse_enrich_result_no_block(): - result = _parse_enrich_result("no block here") - assert result == {"success": False, "error": "no result block found"} - - -def test_parse_enrich_result_invalid_json(): - text = f"{_ENRICH_RESULT_START}\nnot-json\n{_ENRICH_RESULT_END}" - result = _parse_enrich_result(text) - assert result == {"success": False, "error": "result block contained invalid JSON"} - - -# --------------------------------------------------------------------------- -# report_bug gate tests -# --------------------------------------------------------------------------- - - -@pytest.mark.anyio -async def test_report_bug_gate_closed(tool_ctx): - tool_ctx.gate.disable() - result = json.loads(await report_bug("some error", "/tmp")) - assert result["success"] is False - assert "not enabled" in result["result"].lower() or "gate" in result["result"].lower() - - -@pytest.mark.anyio -async def test_report_bug_no_executor(tool_ctx): - tool_ctx.executor = None - result = json.loads(await report_bug("error ctx", "/tmp")) - assert result["success"] is False - assert "executor" in result["error"].lower() - - -# --------------------------------------------------------------------------- -# Helpers: build a mock SkillResult -# --------------------------------------------------------------------------- - - -def _skill_ok(report_text: str = "## Bug Report\ndetails") -> SkillResult: - return SkillResult( - success=True, - result=report_text, - session_id="sid", - subtype="success", - is_error=False, - exit_code=0, - needs_retry=False, - retry_reason=RetryReason.NONE, - stderr="", - ) - - -def _skill_fail() -> SkillResult: - return SkillResult( - success=False, - result="", - session_id="", - subtype="error", - is_error=True, - exit_code=1, - needs_retry=False, - retry_reason=RetryReason.NONE, - stderr="something went wrong", - ) - - -# --------------------------------------------------------------------------- -# Blocking mode -# --------------------------------------------------------------------------- - - -@pytest.mark.anyio -async def test_report_bug_blocking_success(tool_ctx, tmp_path): - """Blocking mode awaits the session and returns status=complete.""" - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = False - - mock_executor = AsyncMock() - mock_executor.run.return_value = _skill_ok("## Report\nroot cause found") - tool_ctx.executor = mock_executor - - result = json.loads(await report_bug("KeyError in foo", str(tmp_path), severity="blocking")) - - assert result["success"] is True - assert result["status"] == "complete" - assert "report" in result - assert "report_path" in result - mock_executor.run.assert_awaited_once() - - -@pytest.mark.anyio -async def test_report_bug_blocking_failure_propagated(tool_ctx, tmp_path): - """If the headless session fails, status=failed is returned.""" - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = False - - mock_executor = AsyncMock() - mock_executor.run.return_value = _skill_fail() - tool_ctx.executor = mock_executor - - result = json.loads(await report_bug("crash here", str(tmp_path), severity="blocking")) - - assert result["success"] is False - assert result["status"] == "failed" - - -@pytest.mark.anyio -async def test_report_bug_blocking_writes_report_file(tool_ctx, tmp_path): - """The report text must be written to the resolved report_path.""" - report_dir = tmp_path / "rpts" - tool_ctx.config.report_bug.report_dir = str(report_dir) - tool_ctx.config.report_bug.github_filing = False - - mock_executor = AsyncMock() - mock_executor.run.return_value = _skill_ok("# Bug Report\nfoo bar") - tool_ctx.executor = mock_executor - - result = json.loads(await report_bug("err", str(tmp_path), severity="blocking")) - - report_path = Path(result["report_path"]) - assert report_path.exists() - assert "Bug Report" in report_path.read_text() - - -# --------------------------------------------------------------------------- -# Non-blocking mode -# --------------------------------------------------------------------------- - - -@pytest.mark.anyio -async def test_report_bug_non_blocking_returns_immediately(tool_ctx, tmp_path): - """Non-blocking mode must return dispatched before the session completes.""" - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = False - - ready = anyio.Event() - - async def slow_run(*args, **kwargs): - await ready.wait() # blocks until test signals - return _skill_ok() - - mock_executor = MagicMock() - mock_executor.run = slow_run - tool_ctx.executor = mock_executor - - result = json.loads(await report_bug("error ctx", str(tmp_path), severity="non_blocking")) - - assert result["success"] is True - assert result["status"] == "dispatched" - assert "report_path" in result - - # Let the background task finish cleanly. - ready.set() - await anyio.sleep(0) - - -@pytest.mark.anyio -async def test_report_bug_non_blocking_default_severity(tool_ctx, tmp_path): - """The default severity is non_blocking.""" - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = False - - mock_executor = AsyncMock() - mock_executor.run.return_value = _skill_ok() - tool_ctx.executor = mock_executor - - result = json.loads(await report_bug("err", str(tmp_path))) - assert result["status"] == "dispatched" - - -# --------------------------------------------------------------------------- -# Non-blocking outcome tests (supervised background task) -# --------------------------------------------------------------------------- - - -@pytest.mark.anyio -async def test_report_bug_non_blocking_outcome_writes_report_file(tool_ctx, tmp_path): - """After the background task completes, report_path must exist with content.""" - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = False - - mock_executor = AsyncMock() - mock_executor.run.return_value = _skill_ok("# Bug Report\nroot cause: missing guard") - tool_ctx.executor = mock_executor - - result = json.loads( - await report_bug("KeyError in foo", str(tmp_path), severity="non_blocking") - ) - assert result["status"] == "dispatched" - - report_path = Path(result["report_path"]) - await tool_ctx.background.drain() - - assert report_path.exists(), "report_path must exist after background task completes" - assert "Bug Report" in report_path.read_text() - - -@pytest.mark.anyio -async def test_report_bug_non_blocking_writes_status_file_on_success(tool_ctx, tmp_path): - """A status.json file must be written with status='complete' after successful dispatch.""" - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = False - - mock_executor = AsyncMock() - mock_executor.run.return_value = _skill_ok("# Report\nfoo") - tool_ctx.executor = mock_executor - - result = json.loads(await report_bug("err", str(tmp_path), severity="non_blocking")) - report_path = Path(result["report_path"]) - - # Before task runs: pending status file should exist - status_path = report_path.with_suffix(".status.json") - assert status_path.exists(), "status file must be written synchronously on dispatch" - pending = json.loads(status_path.read_text()) - assert pending["status"] == "pending" - - # After task completes: status should update to complete - await tool_ctx.background.drain() - - data = json.loads(status_path.read_text()) - assert data["status"] == "complete" - assert "completed_at" in data - - -@pytest.mark.anyio -async def test_report_bug_non_blocking_writes_status_file_on_failure(tool_ctx, tmp_path): - """When the headless session fails, status.json must reflect the failure.""" - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = False - - mock_executor = AsyncMock() - mock_executor.run.return_value = _skill_fail() - tool_ctx.executor = mock_executor - - result = json.loads(await report_bug("crash here", str(tmp_path), severity="non_blocking")) - status_path = Path(result["report_path"]).with_suffix(".status.json") - - await tool_ctx.background.drain() - - data = json.loads(status_path.read_text()) - assert data["status"] == "failed" - assert "completed_at" in data - - -@pytest.mark.anyio -async def test_report_bug_non_blocking_executor_raises_is_observed(tool_ctx, tmp_path): - """If executor.run() raises, the exception must be logged — not silently dropped.""" - - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = False - - mock_executor = AsyncMock() - mock_executor.run.side_effect = RuntimeError("executor exploded") - tool_ctx.executor = mock_executor - - result = json.loads(await report_bug("error ctx", str(tmp_path), severity="non_blocking")) - assert result["status"] == "dispatched" - - await tool_ctx.background.drain() - - # The exception must be captured and logged — not silently dropped - status_path = Path(result["report_path"]).with_suffix(".status.json") - assert status_path.exists(), "status file must exist even when executor raises" - data = json.loads(status_path.read_text()) - assert data["status"] == "failed" - assert "executor exploded" in data.get("error", "") - - -@pytest.mark.anyio -async def test_report_bug_no_pending_tasks_after_completion(tool_ctx, tmp_path): - """After background task completes, no tasks remain in the supervisor's pending set.""" - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = False - - mock_executor = AsyncMock() - mock_executor.run.return_value = _skill_ok() - tool_ctx.executor = mock_executor - - await report_bug("err", str(tmp_path), severity="non_blocking") - - await tool_ctx.background.drain() - - assert tool_ctx.background.pending_count == 0 - - -# --------------------------------------------------------------------------- -# GitHub filing — blocking mode (easier to assert synchronously) -# --------------------------------------------------------------------------- - - -@pytest.mark.anyio -async def test_report_bug_creates_github_issue_on_no_duplicate(tool_ctx, tmp_path): - """When no matching issue is found, create_issue is called.""" - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = True - tool_ctx.config.github.default_repo = "owner/repo" - - report_with_fp = ( - f"{_FINGERPRINT_START}\n" - "KeyError in recipe/validator.py: missing ref\n" - f"{_FINGERPRINT_END}\n" - "## Bug Report\ndetails" - ) - mock_executor = AsyncMock() - mock_executor.run.return_value = _skill_ok(report_with_fp) - tool_ctx.executor = mock_executor - - mock_gh = AsyncMock() - mock_gh.has_token = True - mock_gh.search_issues.return_value = {"success": True, "total_count": 0, "items": []} - mock_gh.create_issue.return_value = { - "success": True, - "issue_number": 99, - "url": "https://github.com/owner/repo/issues/99", - } - tool_ctx.github_client = mock_gh - - result = json.loads(await report_bug("KeyError crash", str(tmp_path), severity="blocking")) - - assert result["success"] is True - mock_gh.search_issues.assert_awaited_once() - mock_gh.create_issue.assert_awaited_once() - assert result["github"]["duplicate"] is False - assert result["github"]["issue_url"] == "https://github.com/owner/repo/issues/99" - - -@pytest.mark.anyio -async def test_report_bug_comments_on_duplicate_issue(tool_ctx, tmp_path): - """When a matching issue exists and error_context is new, add_comment is called.""" - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = True - tool_ctx.config.github.default_repo = "owner/repo" - - mock_executor = AsyncMock() - mock_executor.run.return_value = _skill_ok( - "## Report\n" + _FINGERPRINT_START + "\nfp\n" + _FINGERPRINT_END - ) - tool_ctx.executor = mock_executor - - mock_gh = AsyncMock() - mock_gh.has_token = True - mock_gh.search_issues.return_value = { - "success": True, - "total_count": 1, - "items": [ - { - "number": 7, - "title": "fp", - "html_url": "https://github.com/owner/repo/issues/7", - "body": "Original body — no error_context here", - "state": "open", - } - ], - } - mock_gh.add_comment.return_value = {"success": True, "comment_id": 55, "url": "u"} - tool_ctx.github_client = mock_gh - - result = json.loads( - await report_bug("brand new error text", str(tmp_path), severity="blocking") - ) - - assert result["success"] is True - mock_gh.add_comment.assert_awaited_once() - assert result["github"]["duplicate"] is True - assert result["github"]["comment_added"] is True - - -@pytest.mark.anyio -async def test_report_bug_skips_comment_if_already_present(tool_ctx, tmp_path): - """If error_context is already in the issue body, no comment is posted.""" - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = True - tool_ctx.config.github.default_repo = "owner/repo" - - error_ctx = "exact error text already filed" - mock_executor = AsyncMock() - mock_executor.run.return_value = _skill_ok() - tool_ctx.executor = mock_executor - - mock_gh = AsyncMock() - mock_gh.has_token = True - mock_gh.search_issues.return_value = { - "success": True, - "total_count": 1, - "items": [ - { - "number": 3, - "title": "fp", - "html_url": "https://github.com/owner/repo/issues/3", - "body": f"body contains {error_ctx} already", - "state": "open", - } - ], - } - tool_ctx.github_client = mock_gh - - result = json.loads(await report_bug(error_ctx, str(tmp_path), severity="blocking")) - - mock_gh.add_comment.assert_not_awaited() - assert result["github"]["comment_added"] is False - - -@pytest.mark.anyio -async def test_report_bug_skips_github_if_no_token(tool_ctx, tmp_path): - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = True - - mock_executor = AsyncMock() - mock_executor.run.return_value = _skill_ok() - tool_ctx.executor = mock_executor - - mock_gh = AsyncMock() - mock_gh.has_token = False - tool_ctx.github_client = mock_gh - - result = json.loads(await report_bug("err", str(tmp_path), severity="blocking")) - - assert result["success"] is True - mock_gh.search_issues.assert_not_awaited() - assert result["github"]["skipped"] is True - assert result["github"]["reason"] == "no_token" - - -@pytest.mark.anyio -async def test_report_bug_skips_github_if_no_default_repo(tool_ctx, tmp_path): - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = True - tool_ctx.config.github.default_repo = None - - mock_executor = AsyncMock() - mock_executor.run.return_value = _skill_ok() - tool_ctx.executor = mock_executor - - mock_gh = AsyncMock() - mock_gh.has_token = True - tool_ctx.github_client = mock_gh - - result = json.loads(await report_bug("err", str(tmp_path), severity="blocking")) - - mock_gh.search_issues.assert_not_awaited() - assert result["github"]["skipped"] is True - - -@pytest.mark.anyio -async def test_report_bug_github_filing_disabled(tool_ctx, tmp_path): - """github_filing=false must skip all GitHub calls.""" - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = False - tool_ctx.config.github.default_repo = "owner/repo" - - mock_executor = AsyncMock() - mock_executor.run.return_value = _skill_ok() - tool_ctx.executor = mock_executor - - mock_gh = AsyncMock() - mock_gh.has_token = True - tool_ctx.github_client = mock_gh - - result = json.loads(await report_bug("err", str(tmp_path), severity="blocking")) - - mock_gh.search_issues.assert_not_awaited() - assert result["github"] == {} - - -@pytest.mark.anyio -async def test_report_bug_blocking_github_client_raises_does_not_propagate(tool_ctx, tmp_path): - """If the GitHub client raises unexpectedly, the error must be captured in the github dict.""" - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = True - tool_ctx.config.github.default_repo = "owner/repo" - - mock_executor = AsyncMock() - mock_executor.run.return_value = _skill_ok( - "# Report\n" + _FINGERPRINT_START + "\nfp1\n" + _FINGERPRINT_END - ) - tool_ctx.executor = mock_executor - - mock_gh = MagicMock() - mock_gh.has_token = True - mock_gh.search_issues = AsyncMock(side_effect=RuntimeError("network failure")) - tool_ctx.github_client = mock_gh - - # Must not raise — exception is captured in github dict - result = json.loads(await report_bug("err", str(tmp_path), severity="blocking")) - assert result["success"] is True # session succeeded - assert result["github"].get("skipped") is True - assert "unexpected error" in result["github"].get("reason", "") - assert "network failure" in result["github"].get("reason", "") - - -# --------------------------------------------------------------------------- -# Config defaults -# --------------------------------------------------------------------------- - - -def test_report_bug_config_defaults(): - from autoskillit.config import AutomationConfig - - cfg = AutomationConfig() - assert cfg.report_bug.timeout == 600 - assert cfg.report_bug.model is None - assert cfg.report_bug.report_dir is None - assert cfg.report_bug.github_filing is True - assert "autoreported" in cfg.report_bug.github_labels - assert "bug" in cfg.report_bug.github_labels - - -@pytest.mark.anyio -async def test_fetch_github_issue_no_client(tool_ctx): - tool_ctx.github_client = None - result = json.loads(await fetch_github_issue("owner/repo#1")) - assert result["success"] is False - assert "error" in result - - -@pytest.mark.anyio -async def test_fetch_github_issue_delegates_to_client(tool_ctx): - mock_client = AsyncMock() - mock_client.fetch_issue.return_value = { - "success": True, - "issue_number": 1, - "title": "T", - "url": "u", - "state": "open", - "labels": [], - "content": "# T", - } - tool_ctx.github_client = mock_client - result = json.loads(await fetch_github_issue("owner/repo#1")) - assert result["success"] is True - mock_client.fetch_issue.assert_called_once_with("owner/repo#1", include_comments=True) - - -@pytest.mark.anyio -async def test_fetch_github_issue_bare_number_with_default_repo(tool_ctx): - tool_ctx.config.github.default_repo = "owner/repo" - mock_client = AsyncMock() - mock_client.fetch_issue.return_value = { - "success": True, - "issue_number": 42, - "title": "T", - "url": "u", - "state": "open", - "labels": [], - "content": "# T", - } - tool_ctx.github_client = mock_client - result = json.loads(await fetch_github_issue("42")) - assert result["success"] is True - mock_client.fetch_issue.assert_called_once_with("owner/repo#42", include_comments=True) - - -@pytest.mark.anyio -async def test_fetch_github_issue_bare_number_no_default_repo(tool_ctx): - tool_ctx.config.github.default_repo = None - tool_ctx.github_client = AsyncMock() - result = json.loads(await fetch_github_issue("42")) - assert result["success"] is False - assert "default_repo" in result["error"] - - -@pytest.mark.anyio -async def test_fetch_github_issue_client_error_propagated(tool_ctx): - mock_client = AsyncMock() - mock_client.fetch_issue.return_value = {"success": False, "error": "Not Found"} - tool_ctx.github_client = mock_client - result = json.loads(await fetch_github_issue("owner/repo#404")) - assert result["success"] is False - - -def test_fetch_github_issue_in_gated_tools(): - from autoskillit.pipeline.gate import GATED_TOOLS - - assert "fetch_github_issue" in GATED_TOOLS - assert "fetch_github_issue" not in UNGATED_TOOLS - - -def test_github_config_defaults(): - from autoskillit.config import AutomationConfig - - config = AutomationConfig() - assert config.github.token is None - assert config.github.default_repo is None - - -# --------------------------------------------------------------------------- -# get_issue_title tool tests -# --------------------------------------------------------------------------- - - -class TestGetIssueTitleTool: - @pytest.mark.anyio - async def test_get_issue_title_success(self, tool_ctx): - """Delegates to github_client.fetch_title; returns JSON result.""" - mock_client = AsyncMock() - mock_client.fetch_title.return_value = { - "success": True, - "number": 42, - "title": "Fix merge conflict triage", - "slug": "fix-merge-conflict-triage", - } - tool_ctx.github_client = mock_client - result = json.loads(await get_issue_title("https://github.com/owner/repo/issues/42")) - assert result["success"] is True - assert result["number"] == 42 - assert result["title"] == "Fix merge conflict triage" - assert result["slug"] == "fix-merge-conflict-triage" - mock_client.fetch_title.assert_called_once_with("https://github.com/owner/repo/issues/42") - - @pytest.mark.anyio - async def test_get_issue_title_no_github_client(self, tool_ctx): - """Returns error JSON when github_client is None.""" - tool_ctx.github_client = None - result = json.loads(await get_issue_title("https://github.com/owner/repo/issues/1")) - assert result["success"] is False - assert "error" in result - - @pytest.mark.anyio - async def test_get_issue_title_client_error_propagated(self, tool_ctx): - """Propagates {success: False, error: ...} from fetch_title.""" - mock_client = AsyncMock() - mock_client.fetch_title.return_value = {"success": False, "error": "Not Found"} - tool_ctx.github_client = mock_client - result = json.loads(await get_issue_title("owner/repo#404")) - assert result["success"] is False - - def test_get_issue_title_is_gated(self): - """'get_issue_title' in GATED_TOOLS.""" - from autoskillit.pipeline.gate import GATED_TOOLS - - assert "get_issue_title" in GATED_TOOLS - assert "get_issue_title" not in UNGATED_TOOLS - - # --------------------------------------------------------------------------- # claim_issue / release_issue / prepare_issue / enrich_issues — gated tools # --------------------------------------------------------------------------- @@ -825,19 +74,16 @@ async def test_claim_issue_already_claimed(self, tool_ctx): # P5F4-T1 @pytest.mark.anyio async def test_claim_issue_binds_structlog_context(self, tool_ctx, monkeypatch): - """claim_issue must bind structlog context vars via bound_contextvars.""" - import contextlib - + """claim_issue must bind structlog context vars via bind_contextvars.""" import structlog captured = {} - @contextlib.contextmanager - def fake_bound_contextvars(**kwargs): + def fake_bind_contextvars(**kwargs): captured.update(kwargs) - yield - monkeypatch.setattr(structlog.contextvars, "bound_contextvars", fake_bound_contextvars) + monkeypatch.setattr(structlog.contextvars, "bind_contextvars", fake_bind_contextvars) + monkeypatch.setattr(structlog.contextvars, "clear_contextvars", lambda: None) tool_ctx.github_client = None # triggers early return after bind @@ -896,7 +142,7 @@ async def test_claim_issue_allow_reentry_true_still_claims_when_label_absent(sel assert result["success"] is True assert result["claimed"] is True assert result.get("reentry", False) is False - mock_client.add_labels.assert_called_once() + mock_client.add_labels.assert_called_once_with("owner", "repo", 42, ["in-progress"]) class TestReleaseIssueTool: @@ -933,19 +179,16 @@ async def test_release_issue_success(self, tool_ctx): # P5F4-T2 @pytest.mark.anyio async def test_release_issue_binds_structlog_context(self, tool_ctx, monkeypatch): - """release_issue must bind structlog context vars via bound_contextvars.""" - import contextlib - + """release_issue must bind structlog context vars via bind_contextvars.""" import structlog captured = {} - @contextlib.contextmanager - def fake_bound_contextvars(**kwargs): + def fake_bind_contextvars(**kwargs): captured.update(kwargs) - yield - monkeypatch.setattr(structlog.contextvars, "bound_contextvars", fake_bound_contextvars) + monkeypatch.setattr(structlog.contextvars, "bind_contextvars", fake_bind_contextvars) + monkeypatch.setattr(structlog.contextvars, "clear_contextvars", lambda: None) tool_ctx.github_client = None # triggers early return after bind @@ -1444,62 +687,6 @@ async def test_headless_tool_failure_paths_include_all_diagnostic_fields( assert response["session_id"] == skill_result_kwargs["session_id"] -class TestReportBugTool: - @pytest.mark.anyio - async def test_report_bug_failure_includes_session_id_and_stderr(self, tool_ctx, tmp_path): - """Blocking failure response must include session_id and stderr for diagnosis.""" - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = False - - mock_executor = AsyncMock() - mock_executor.run.return_value = SkillResult( - success=False, - result="", - session_id="fail-session-id", - subtype="missing_completion_marker", - is_error=True, - exit_code=1, - needs_retry=False, - retry_reason=RetryReason.NONE, - stderr="Claude crashed", - ) - tool_ctx.executor = mock_executor - - result = json.loads(await report_bug("some error", str(tmp_path), severity="blocking")) - - assert result["success"] is False - assert result["session_id"] == "fail-session-id" - assert result["stderr"] == "Claude crashed" - - @pytest.mark.anyio - async def test_report_bug_passes_expected_output_patterns_to_executor( - self, tool_ctx, tmp_path - ): - """output_pattern_resolver is consulted and patterns are passed to executor.run().""" - tool_ctx.config.report_bug.report_dir = str(tmp_path / "bug-reports") - tool_ctx.config.report_bug.github_filing = False - - mock_executor = AsyncMock() - mock_executor.run.return_value = SkillResult( - success=True, - result="## Report\nfindings", - session_id="sid", - subtype="success", - is_error=False, - exit_code=0, - needs_retry=False, - retry_reason=RetryReason.NONE, - stderr="", - ) - tool_ctx.executor = mock_executor - tool_ctx.output_pattern_resolver = lambda cmd: ["---bug-fingerprint---"] - - await report_bug("error ctx", str(tmp_path), severity="blocking") - - call_kwargs = mock_executor.run.call_args.kwargs - assert call_kwargs.get("expected_output_patterns") == ["---bug-fingerprint---"] - - class TestGetPrReviews: @pytest.mark.anyio async def test_returns_structured_reviews(self, tool_ctx): diff --git a/tests/server/test_tools_integrations_release.py b/tests/server/test_tools_integrations_release.py index e302bf79e9..a5b885c1fd 100644 --- a/tests/server/test_tools_integrations_release.py +++ b/tests/server/test_tools_integrations_release.py @@ -36,7 +36,7 @@ async def test_release_issue_non_default_branch_applies_staged(self, tool_ctx, m color="0075ca", description="Implementation staged and waiting for promotion to main", ) - mock_client.add_labels.assert_called_once() + mock_client.add_labels.assert_called_once_with("owner", "repo", 42, ["staged"]) @pytest.mark.anyio async def test_release_issue_default_branch_no_staged(self, tool_ctx, monkeypatch): @@ -52,7 +52,7 @@ async def test_release_issue_default_branch_no_staged(self, tool_ctx, monkeypatc ) assert result["success"] is True assert result.get("staged") is False - mock_client.remove_label.assert_called_once() + mock_client.remove_label.assert_called_once_with("owner", "repo", 42, "in-progress") mock_client.ensure_label.assert_not_called() mock_client.add_labels.assert_not_called() diff --git a/tests/server/test_tools_issue_lifecycle.py b/tests/server/test_tools_issue_lifecycle.py index d3d5cad354..4849c6e908 100644 --- a/tests/server/test_tools_issue_lifecycle.py +++ b/tests/server/test_tools_issue_lifecycle.py @@ -389,4 +389,4 @@ async def test_release_issue_stages_when_different_branch( ) assert result["success"] is True assert result["staged"] is True - assert result["staged_label"] is not None + assert result["staged_label"] == "staged" diff --git a/tests/server/test_tools_kitchen.py b/tests/server/test_tools_kitchen.py index 3b5921ec3b..7e83ce32ea 100644 --- a/tests/server/test_tools_kitchen.py +++ b/tests/server/test_tools_kitchen.py @@ -2,11 +2,15 @@ from __future__ import annotations +import asyncio +import dataclasses import json from unittest.mock import AsyncMock, MagicMock, patch import pytest +from autoskillit.hooks._fmt_primitives import _HOOK_CONFIG_PATH_COMPONENTS + def _make_mock_ctx(): """Return a minimal mock ToolContext with a gate.""" @@ -51,6 +55,26 @@ def test_close_kitchen_disables_gate(tmp_path, monkeypatch): mock_ctx.gate.disable.assert_called_once() +def test_hook_config_path_is_inside_temp_dir(tmp_path): + """_hook_config_path() must resolve to a path inside the project temp directory. + + This invariant ensures .hook_config.json receives automatic gitignore coverage + from temp/.gitignore ('*') and can never produce a gitignore gap regardless of + whatever entries are present in .gitignore or _AUTOSKILLIT_GITIGNORE_ENTRIES. + """ + from autoskillit.core.io import resolve_temp_dir + from autoskillit.server.helpers import _hook_config_path + + hook_path = _hook_config_path(tmp_path) + temp_dir = resolve_temp_dir(tmp_path, None) + + assert hook_path.is_relative_to(temp_dir), ( + f"_hook_config_path() returned {hook_path!r} which is NOT inside " + f"temp dir {temp_dir!r}. Session-bridge files must live in temp/ " + f"to receive automatic gitignore coverage via temp/.gitignore." + ) + + # T2c def test_close_kitchen_no_file_no_error(tmp_path, monkeypatch): """_close_kitchen_handler() doesn't raise when no gate file exists.""" @@ -64,7 +88,7 @@ def test_close_kitchen_no_file_no_error(tmp_path, monkeypatch): _close_kitchen_handler() # Should not raise # Gate file was never created — confirm it still does not exist - assert not (tmp_path / ".autoskillit" / "temp" / ".autoskillit_hook_config.json").exists() + assert not tmp_path.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS).exists() # T-CACHE-1 @@ -89,12 +113,15 @@ async def test_open_kitchen_primes_quota_cache(tmp_path, monkeypatch): # T-CACHE-2 @pytest.mark.anyio async def test_open_kitchen_writes_hook_config_json(tmp_path, monkeypatch): - """open_kitchen must write temp/.autoskillit_hook_config.json with user quota_guard values.""" + """open_kitchen must write .autoskillit/.hook_config.json with user quota_guard values.""" monkeypatch.chdir(tmp_path) mock_ctx = _make_mock_ctx() - mock_ctx.config.quota_guard.threshold = 85.0 + mock_ctx.config.quota_guard.short_window_threshold = 85.0 + mock_ctx.config.quota_guard.long_window_threshold = 98.0 + mock_ctx.config.quota_guard.long_window_patterns = ["weekly", "sonnet", "opus"] mock_ctx.config.quota_guard.cache_max_age = 300 mock_ctx.config.quota_guard.cache_path = "/custom/path.json" + mock_ctx.config.quota_guard.buffer_seconds = 60 # _write_hook_config uses 'from autoskillit.server import _get_ctx' at call time. # Patching autoskillit.server._get_ctx correctly intercepts that deferred import; @@ -111,12 +138,17 @@ async def test_open_kitchen_writes_hook_config_json(tmp_path, monkeypatch): "_get_ctx must be called in both _open_kitchen_handler and _write_hook_config; " "if call_count < 2 the patch did not cover _write_hook_config's deferred import" ) - hook_cfg = tmp_path / ".autoskillit" / "temp" / ".autoskillit_hook_config.json" + hook_cfg = tmp_path.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS) assert hook_cfg.exists(), "Hook config file must be written by open_kitchen" data = json.loads(hook_cfg.read_text()) - assert data["quota_guard"]["threshold"] == 85.0 assert data["quota_guard"]["cache_max_age"] == 300 assert data["quota_guard"]["cache_path"] == "/custom/path.json" + assert data["quota_guard"]["buffer_seconds"] == 60 + # threshold fields are pre-computed into should_block in the cache — not written to hook_config + assert "threshold" not in data["quota_guard"] + assert "short_window_threshold" not in data["quota_guard"] + assert "long_window_threshold" not in data["quota_guard"] + assert "long_window_patterns" not in data["quota_guard"] # Confirm kitchen_id rename: hook config must contain 'kitchen_id' (not 'pipeline_id') assert "kitchen_id" in data, ( "hook config must contain 'kitchen_id' after rename from 'pipeline_id'" @@ -129,12 +161,15 @@ async def test_open_kitchen_writes_hook_config_json(tmp_path, monkeypatch): # T-CACHE-3 @pytest.mark.anyio async def test_close_kitchen_removes_hook_config_json(tmp_path, monkeypatch): - """close_kitchen must remove temp/.autoskillit_hook_config.json to prevent stale config.""" + """close_kitchen must remove .autoskillit/.hook_config.json to prevent stale config.""" monkeypatch.chdir(tmp_path) mock_ctx = _make_mock_ctx() - mock_ctx.config.quota_guard.threshold = 90.0 + mock_ctx.config.quota_guard.short_window_threshold = 85.0 + mock_ctx.config.quota_guard.long_window_threshold = 98.0 + mock_ctx.config.quota_guard.long_window_patterns = ["weekly", "sonnet", "opus"] mock_ctx.config.quota_guard.cache_max_age = 300 mock_ctx.config.quota_guard.cache_path = "~/.claude/quota_cache.json" + mock_ctx.config.quota_guard.buffer_seconds = 60 with patch("autoskillit.server._get_ctx", return_value=mock_ctx): with patch("autoskillit.server.logger"): @@ -147,7 +182,7 @@ async def test_close_kitchen_removes_hook_config_json(tmp_path, monkeypatch): await _open_kitchen_handler() _close_kitchen_handler() - hook_cfg = tmp_path / ".autoskillit" / "temp" / ".autoskillit_hook_config.json" + hook_cfg = tmp_path.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS) assert not hook_cfg.exists(), "Hook config must be removed by close_kitchen" @@ -204,9 +239,12 @@ async def test_open_kitchen_does_not_write_gate_file(tmp_path, monkeypatch): """_open_kitchen_handler must never write a gate file.""" monkeypatch.chdir(tmp_path) mock_ctx = _make_mock_ctx() - mock_ctx.config.quota_guard.threshold = None - mock_ctx.config.quota_guard.cache_max_age = None - mock_ctx.config.quota_guard.cache_path = None + mock_ctx.config.quota_guard.short_window_threshold = 85.0 + mock_ctx.config.quota_guard.long_window_threshold = 98.0 + mock_ctx.config.quota_guard.long_window_patterns = ["weekly", "sonnet", "opus"] + mock_ctx.config.quota_guard.cache_max_age = 300 + mock_ctx.config.quota_guard.cache_path = "~/.claude/quota_cache.json" + mock_ctx.config.quota_guard.buffer_seconds = 60 with patch("autoskillit.server._get_ctx", return_value=mock_ctx): with patch("autoskillit.server.logger"): with patch("autoskillit.server.tools_kitchen._prime_quota_cache", new=AsyncMock()): @@ -232,9 +270,8 @@ def test_close_kitchen_does_not_produce_gate_file(tmp_path, monkeypatch): @pytest.mark.anyio async def test_open_kitchen_includes_categorized_tool_listing(tmp_path, monkeypatch): - """open_kitchen response contains static categorized tool groups from TOOL_CATEGORIES.""" - from autoskillit.core.types import TOOL_CATEGORIES - from autoskillit.server.tools_kitchen import open_kitchen + """open_kitchen response contains static categorized tool groups from _DISPLAY_CATEGORIES.""" + from autoskillit.server.tools_kitchen import _DISPLAY_CATEGORIES, open_kitchen monkeypatch.chdir(tmp_path) mock_ctx = _make_mock_ctx() @@ -244,16 +281,18 @@ async def test_open_kitchen_includes_categorized_tool_listing(tmp_path, monkeypa with patch("autoskillit.server.logger"): with patch("autoskillit.server.tools_kitchen._prime_quota_cache", new=AsyncMock()): with patch("autoskillit.server.tools_kitchen._write_hook_config"): - result = await open_kitchen(ctx=mock_ctx) + result_str = await open_kitchen(ctx=mock_ctx) + parsed = json.loads(result_str) + content = parsed["content"] seen: set[str] = set() - for category_name, tools in TOOL_CATEGORIES: - assert category_name in result, ( + for category_name, tools in _DISPLAY_CATEGORIES: + assert category_name in content, ( f"Category '{category_name}' missing from open_kitchen response" ) for tool_name in tools: if tool_name not in seen: - assert tool_name in result, ( + assert tool_name in content, ( f"Tool '{tool_name}' missing from open_kitchen response" ) seen.add(tool_name) @@ -297,6 +336,7 @@ async def test_open_kitchen_with_recipe_returns_combined_response(tmp_path, monk result_str = await open_kitchen(name="test-recipe", ctx=mock_ctx) result = json.loads(result_str) + assert result["success"] is True assert result["kitchen"] == "open" assert "version" in result assert "content" in result @@ -335,8 +375,8 @@ async def test_open_kitchen_with_recipe_not_found(tmp_path, monkeypatch): @pytest.mark.anyio -async def test_open_kitchen_without_recipe_returns_plain_text(tmp_path, monkeypatch): - """open_kitchen() without name returns plain text (not JSON).""" +async def test_open_kitchen_without_recipe_returns_json_envelope(tmp_path, monkeypatch): + """open_kitchen() without name returns JSON envelope with success=True.""" monkeypatch.chdir(tmp_path) mock_ctx = _make_mock_ctx() mock_ctx.enable_components = AsyncMock() @@ -350,8 +390,11 @@ async def test_open_kitchen_without_recipe_returns_plain_text(tmp_path, monkeypa result = await open_kitchen(ctx=mock_ctx) assert isinstance(result, str) - assert "Kitchen is open" in result - assert "content" not in result, "No-recipe open_kitchen should not contain recipe content key" + parsed = json.loads(result) + assert parsed["success"] is True + assert parsed["kitchen"] == "open" + assert "Kitchen is open" in parsed["content"] + assert parsed["ingredients_table"] is None # --------------------------------------------------------------------------- @@ -367,7 +410,10 @@ async def test_open_kitchen_denied_by_gate_when_headless(tmp_path, monkeypatch): result = json.loads(await open_kitchen()) assert result["success"] is False - assert result["subtype"] == "headless_error" + assert result["kitchen"] == "failed" + assert "user_visible_message" in result + assert len(result["user_visible_message"]) > 0 + assert result["stage"] == "headless_guard" @pytest.mark.anyio @@ -497,3 +543,614 @@ def test_close_kitchen_clears_active_recipe_packs(tmp_path, monkeypatch): _close_kitchen_handler() assert mock_ctx.active_recipe_packs is None + + +# T-REFRESH-1 +@pytest.mark.anyio +async def test_open_kitchen_starts_quota_refresh_task(tmp_path, monkeypatch): + """After _open_kitchen_handler(), ctx.quota_refresh_task is a running asyncio.Task.""" + monkeypatch.chdir(tmp_path) + mock_ctx = _make_mock_ctx() + + async def instant_loop(config): + await asyncio.sleep(0) + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + with patch("autoskillit.server.tools_kitchen._prime_quota_cache", AsyncMock()): + with patch("autoskillit.server.tools_kitchen._write_hook_config"): + with patch( + "autoskillit.server.tools_kitchen._quota_refresh_loop", instant_loop + ): + from autoskillit.server.tools_kitchen import _open_kitchen_handler + + await _open_kitchen_handler() + + assert mock_ctx.quota_refresh_task is not None + assert isinstance(mock_ctx.quota_refresh_task, asyncio.Task) + mock_ctx.quota_refresh_task.cancel() + + +# T-REFRESH-2 +def test_close_kitchen_cancels_quota_refresh_task(tmp_path, monkeypatch): + """_close_kitchen_handler cancels ctx.quota_refresh_task and sets it to None.""" + monkeypatch.chdir(tmp_path) + mock_ctx = _make_mock_ctx() + mock_task = MagicMock(spec=asyncio.Task) + mock_ctx.quota_refresh_task = mock_task + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + from autoskillit.server.tools_kitchen import _close_kitchen_handler + + _close_kitchen_handler() + + mock_task.cancel.assert_called_once() + assert mock_ctx.quota_refresh_task is None + + +# T-REFRESH-3 +def test_tool_context_has_quota_refresh_task_field(): + """ToolContext must have a quota_refresh_task field defaulting to None.""" + from autoskillit.pipeline.context import ToolContext + + fields = {f.name: f for f in dataclasses.fields(ToolContext)} + assert "quota_refresh_task" in fields + assert fields["quota_refresh_task"].default is None + + +# T-KITCHEN-1 +@pytest.mark.anyio +async def test_open_kitchen_warns_on_orphaned_hooks(tmp_path, monkeypatch): + """When settings.json contains a hook not in HOOK_REGISTRY, open_kitchen() + must include a drift warning in its response.""" + from autoskillit.hook_registry import HookDriftResult + + settings_dir = tmp_path / ".claude" + settings_dir.mkdir() + (settings_dir / "settings.json").write_text("{}") + + monkeypatch.setattr( + "autoskillit.hook_registry._claude_settings_path", + lambda scope: settings_dir / "settings.json", + ) + monkeypatch.setattr( + "autoskillit.hook_registry._count_hook_registry_drift", + lambda _: HookDriftResult(missing=0, orphaned=1), + ) + monkeypatch.setattr( + "autoskillit.hook_registry.find_broken_hook_scripts", + lambda _: [], + ) + + mock_ctx = _make_mock_ctx() + mock_ctx.enable_components = AsyncMock() + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + with patch("autoskillit.server.tools_kitchen._prime_quota_cache", new=AsyncMock()): + with patch("autoskillit.server.tools_kitchen._write_hook_config"): + from autoskillit.server.tools_kitchen import open_kitchen + + result = await open_kitchen(ctx=mock_ctx) + + parsed = json.loads(result) + content = parsed["content"] + assert ( + "orphan" in content.lower() or "drift" in content.lower() or "install" in content.lower() + ), "open_kitchen() must include a hook drift warning when orphaned > 0" + + +# T-KITCHEN-2 +@pytest.mark.anyio +async def test_open_kitchen_warns_on_missing_hook_scripts(tmp_path, monkeypatch): + """When hook scripts are absent from disk, open_kitchen() must warn.""" + from autoskillit.hook_registry import HookDriftResult + + settings_dir = tmp_path / ".claude" + settings_dir.mkdir() + (settings_dir / "settings.json").write_text("{}") + + monkeypatch.setattr( + "autoskillit.hook_registry._claude_settings_path", + lambda scope: settings_dir / "settings.json", + ) + monkeypatch.setattr( + "autoskillit.hook_registry.find_broken_hook_scripts", + lambda _: ["python3 /missing/status_health_guard.py"], + ) + monkeypatch.setattr( + "autoskillit.hook_registry._count_hook_registry_drift", + lambda _: HookDriftResult(missing=0, orphaned=0), + ) + + mock_ctx = _make_mock_ctx() + mock_ctx.enable_components = AsyncMock() + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + with patch("autoskillit.server.tools_kitchen._prime_quota_cache", new=AsyncMock()): + with patch("autoskillit.server.tools_kitchen._write_hook_config"): + from autoskillit.server.tools_kitchen import open_kitchen + + result = await open_kitchen(ctx=mock_ctx) + + parsed = json.loads(result) + content = parsed["content"] + assert "Hook scripts not found" in content, ( + "open_kitchen() must include the exact _build_hook_diagnostic_warning phrase" + ) + + +@pytest.mark.anyio +async def test_prime_quota_cache_catches_typeerror(monkeypatch): + """_prime_quota_cache must catch TypeError and not propagate — 'fails open' contract.""" + import autoskillit.execution as _exec_mod + from autoskillit.server.helpers import _prime_quota_cache + + async def raise_type_error(*a, **kw): + raise TypeError("float() argument must be a string or a real number, not 'NoneType'") + + monkeypatch.setattr(_exec_mod, "check_and_sleep_if_needed", raise_type_error) + + mock_ctx = MagicMock() + mock_ctx.config.quota_guard = MagicMock() + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.helpers.logger") as mock_logger: + # Must not raise — fails open + await _prime_quota_cache() + mock_logger.warning.assert_called_once_with("quota_prime_failed", exc_info=True) + + +# --------------------------------------------------------------------------- +# Envelope contract tests — Phase 3 (#711 Part B) +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +async def test_open_kitchen_no_name_returns_json_envelope_with_success_true(tmp_path, monkeypatch): + """No-recipe open_kitchen returns JSON envelope with success=True.""" + monkeypatch.chdir(tmp_path) + mock_ctx = _make_mock_ctx() + mock_ctx.enable_components = AsyncMock() + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + with patch("autoskillit.server.tools_kitchen._prime_quota_cache", new=AsyncMock()): + with patch("autoskillit.server.tools_kitchen._write_hook_config"): + from autoskillit.server.tools_kitchen import open_kitchen + + result = await open_kitchen(ctx=mock_ctx) + + parsed = json.loads(result) + assert parsed["success"] is True + assert parsed["kitchen"] == "open" + assert "Kitchen is open" in parsed["content"] + assert parsed["ingredients_table"] is None + + +@pytest.mark.anyio +async def test_open_kitchen_recipe_found_returns_envelope_with_content_and_ingredients_table( + tmp_path, monkeypatch +): + """Recipe loads successfully: success=True, kitchen=open, version present.""" + monkeypatch.chdir(tmp_path) + mock_ctx = _make_mock_ctx() + mock_ctx.enable_components = AsyncMock() + mock_ctx.recipes = MagicMock() + mock_ctx.recipes.load_and_validate.return_value = { + "content": "name: demo\nsteps:\n do:\n tool: run_cmd\n", + "valid": True, + "suggestions": [], + "diagram": None, + "ingredients_table": "--- INGREDIENTS TABLE ---\n task required\n--- END TABLE ---", + } + mock_ctx.recipes.find.return_value = None + mock_ctx.config.migration.suppressed = [] + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + with patch("autoskillit.server.tools_kitchen._prime_quota_cache", new=AsyncMock()): + with patch("autoskillit.server.tools_kitchen._write_hook_config"): + from autoskillit.server.tools_kitchen import open_kitchen + + result_str = await open_kitchen(name="demo", ctx=mock_ctx) + + parsed = json.loads(result_str) + assert parsed["success"] is True + assert parsed["kitchen"] == "open" + assert "version" in parsed + assert "--- INGREDIENTS TABLE ---" in result_str + + +@pytest.mark.anyio +async def test_open_kitchen_smoke_test_renders_resolved_base_branch(monkeypatch): + """T7: open_kitchen smoke-test renders the config-resolved base_branch value.""" + import autoskillit.recipe._api as api_mod + from autoskillit.core import pkg_root + from autoskillit.recipe.repository import DefaultRecipeRepository + + project_dir = pkg_root().parent.parent + monkeypatch.chdir(project_dir) + monkeypatch.setattr(api_mod, "_LOAD_CACHE", {}) + monkeypatch.setattr( + "autoskillit.server.tools_kitchen.resolve_ingredient_defaults", + lambda _: {"base_branch": "integration"}, + ) + + mock_ctx = _make_mock_ctx() + mock_ctx.enable_components = AsyncMock() + mock_ctx.quota_refresh_task = None + mock_ctx.recipes = DefaultRecipeRepository() + mock_ctx.config.migration.suppressed = [] + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + with patch("autoskillit.server.tools_kitchen._prime_quota_cache", new=AsyncMock()): + with patch("autoskillit.server.tools_kitchen._write_hook_config"): + from autoskillit.server.tools_kitchen import open_kitchen + + result_str = await open_kitchen(name="smoke-test", ctx=mock_ctx) + + parsed = json.loads(result_str) + assert parsed["success"] is True + ing_table = parsed.get("ingredients_table") or "" + assert ing_table, "ingredients_table must be present and non-empty" + assert "integration" in ing_table + # base_branch row must NOT show the YAML literal "main" + base_branch_rows = [line for line in ing_table.splitlines() if "base_branch" in line] + assert base_branch_rows, "base_branch row must appear in ingredients_table" + assert all("main" not in row for row in base_branch_rows) + + +@pytest.mark.anyio +async def test_open_kitchen_recipe_not_found_returns_failure_envelope(tmp_path, monkeypatch): + """Invalid recipe name returns failure envelope (via load_and_validate raising).""" + monkeypatch.chdir(tmp_path) + mock_ctx = _make_mock_ctx() + mock_ctx.enable_components = AsyncMock() + mock_ctx.recipes = MagicMock() + mock_ctx.recipes.load_and_validate.side_effect = ValueError("No recipe 'bad' found") + mock_ctx.config.migration.suppressed = [] + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + with patch("autoskillit.server.tools_kitchen._prime_quota_cache", new=AsyncMock()): + with patch("autoskillit.server.tools_kitchen._write_hook_config"): + from autoskillit.server.tools_kitchen import open_kitchen + + result_str = await open_kitchen(name="bad", ctx=mock_ctx) + + parsed = json.loads(result_str) + assert parsed["success"] is False + assert parsed["kitchen"] == "failed" + assert len(parsed["user_visible_message"]) > 0 + assert "ValueError" in parsed["error"] + + +@pytest.mark.anyio +async def test_open_kitchen_server_not_initialized_returns_failure_envelope(tmp_path, monkeypatch): + """tool_ctx.recipes is None → failure envelope with user_visible_message.""" + monkeypatch.chdir(tmp_path) + mock_ctx = _make_mock_ctx() + mock_ctx.enable_components = AsyncMock() + mock_ctx.recipes = None + mock_ctx.config.migration.suppressed = [] + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + with patch("autoskillit.server.tools_kitchen._prime_quota_cache", new=AsyncMock()): + with patch("autoskillit.server.tools_kitchen._write_hook_config"): + from autoskillit.server.tools_kitchen import open_kitchen + + result_str = await open_kitchen(name="demo", ctx=mock_ctx) + + parsed = json.loads(result_str) + assert parsed["success"] is False + assert parsed["kitchen"] == "failed" + assert "user_visible_message" in parsed + assert "not initialized" in parsed["user_visible_message"] + + +@pytest.mark.anyio +async def test_open_kitchen_headless_denied_returns_failure_envelope(tmp_path, monkeypatch): + """AUTOSKILLIT_HEADLESS=1: failure envelope with user_visible_message present.""" + monkeypatch.setenv("AUTOSKILLIT_HEADLESS", "1") + monkeypatch.chdir(tmp_path) + from autoskillit.server.tools_kitchen import open_kitchen + + result = json.loads(await open_kitchen()) + assert result["success"] is False + assert result["kitchen"] == "failed" + assert "user_visible_message" in result + assert len(result["user_visible_message"]) > 0 + assert result["stage"] == "headless_guard" + + +@pytest.mark.anyio +async def test_open_kitchen_prime_quota_cache_typeerror_returns_failure_envelope( + tmp_path, monkeypatch +): + """_prime_quota_cache raising TypeError → failure envelope with stage=prime_quota_cache.""" + monkeypatch.chdir(tmp_path) + mock_ctx = _make_mock_ctx() + mock_ctx.enable_components = AsyncMock() + + async def raise_type_error(): + raise TypeError("float() argument must be a string or a real number, not 'NoneType'") + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + with patch( + "autoskillit.server.tools_kitchen._prime_quota_cache", + new=raise_type_error, + ): + with patch("autoskillit.server.tools_kitchen._write_hook_config"): + from autoskillit.server.tools_kitchen import open_kitchen + + result_str = await open_kitchen(ctx=mock_ctx) + + parsed = json.loads(result_str) + assert parsed["success"] is False + assert parsed["kitchen"] == "failed" + assert parsed["stage"] == "prime_quota_cache" + assert "TypeError" in parsed["error"] + assert len(parsed["user_visible_message"]) > 0 + + +@pytest.mark.anyio +async def test_open_kitchen_prime_quota_cache_runtimeerror_returns_failure_envelope( + tmp_path, monkeypatch +): + """_prime_quota_cache raising RuntimeError → failure envelope.""" + monkeypatch.chdir(tmp_path) + mock_ctx = _make_mock_ctx() + mock_ctx.enable_components = AsyncMock() + + async def raise_runtime(): + raise RuntimeError("unexpected failure") + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + with patch( + "autoskillit.server.tools_kitchen._prime_quota_cache", + new=raise_runtime, + ): + with patch("autoskillit.server.tools_kitchen._write_hook_config"): + from autoskillit.server.tools_kitchen import open_kitchen + + result_str = await open_kitchen(ctx=mock_ctx) + + parsed = json.loads(result_str) + assert parsed["success"] is False + assert parsed["stage"] == "prime_quota_cache" + + +@pytest.mark.anyio +async def test_open_kitchen_create_background_task_raises_returns_failure_envelope( + tmp_path, monkeypatch +): + """create_background_task raising → failure envelope with stage=start_quota_refresh.""" + monkeypatch.chdir(tmp_path) + mock_ctx = _make_mock_ctx() + mock_ctx.enable_components = AsyncMock() + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + with patch("autoskillit.server.tools_kitchen._prime_quota_cache", new=AsyncMock()): + with patch("autoskillit.server.tools_kitchen._write_hook_config"): + with patch( + "autoskillit.server.tools_kitchen.create_background_task", + side_effect=RuntimeError("task creation failed"), + ): + from autoskillit.server.tools_kitchen import open_kitchen + + result_str = await open_kitchen(ctx=mock_ctx) + + parsed = json.loads(result_str) + assert parsed["success"] is False + assert parsed["stage"] == "start_quota_refresh" + + +@pytest.mark.anyio +async def test_open_kitchen_load_and_validate_raises_returns_failure_envelope( + tmp_path, monkeypatch +): + """load_and_validate raising → failure envelope with stage=load_and_validate.""" + monkeypatch.chdir(tmp_path) + mock_ctx = _make_mock_ctx() + mock_ctx.enable_components = AsyncMock() + mock_ctx.recipes = MagicMock() + mock_ctx.recipes.load_and_validate.side_effect = OSError("disk full") + mock_ctx.config.migration.suppressed = [] + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + with patch("autoskillit.server.tools_kitchen._prime_quota_cache", new=AsyncMock()): + with patch("autoskillit.server.tools_kitchen._write_hook_config"): + from autoskillit.server.tools_kitchen import open_kitchen + + result_str = await open_kitchen(name="demo", ctx=mock_ctx) + + parsed = json.loads(result_str) + assert parsed["success"] is False + assert parsed["stage"] == "load_and_validate" + + +@pytest.mark.anyio +async def test_open_kitchen_apply_triage_gate_raises_returns_failure_envelope( + tmp_path, monkeypatch +): + """_apply_triage_gate raising → failure envelope with stage=apply_triage_gate.""" + monkeypatch.chdir(tmp_path) + mock_ctx = _make_mock_ctx() + mock_ctx.enable_components = AsyncMock() + mock_ctx.recipes = MagicMock() + mock_ctx.recipes.load_and_validate.return_value = { + "content": "test", + "valid": True, + "suggestions": [], + } + mock_ctx.recipes.find.return_value = None + mock_ctx.config.migration.suppressed = [] + + async def raise_apply(*a, **kw): + raise RuntimeError("triage failed") + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + with patch("autoskillit.server.tools_kitchen._prime_quota_cache", new=AsyncMock()): + with patch("autoskillit.server.tools_kitchen._write_hook_config"): + with patch( + "autoskillit.server.tools_kitchen._apply_triage_gate", + new=raise_apply, + ): + from autoskillit.server.tools_kitchen import open_kitchen + + result_str = await open_kitchen(name="demo", ctx=mock_ctx) + + parsed = json.loads(result_str) + assert parsed["success"] is False + assert parsed["stage"] == "apply_triage_gate" + + +@pytest.mark.anyio +async def test_open_kitchen_enable_components_raises_returns_failure_envelope( + tmp_path, monkeypatch +): + """ctx.enable_components raising → failure envelope with stage=enable_components.""" + monkeypatch.chdir(tmp_path) + mock_ctx = _make_mock_ctx() + mock_ctx.enable_components = AsyncMock(side_effect=RuntimeError("enable failed")) + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + with patch("autoskillit.server.tools_kitchen._prime_quota_cache", new=AsyncMock()): + with patch("autoskillit.server.tools_kitchen._write_hook_config"): + from autoskillit.server.tools_kitchen import open_kitchen + + result_str = await open_kitchen(ctx=mock_ctx) + + parsed = json.loads(result_str) + assert parsed["success"] is False + assert parsed["stage"] == "enable_components" + + +@pytest.mark.anyio +async def test_open_kitchen_sous_chef_read_raises_returns_failure_envelope(tmp_path, monkeypatch): + """Path.read_text raising OSError → failure envelope with stage=read_sous_chef.""" + monkeypatch.chdir(tmp_path) + mock_ctx = _make_mock_ctx() + mock_ctx.enable_components = AsyncMock() + + import autoskillit.server.tools_kitchen as tk_mod + + _original_pkg_root = tk_mod.pkg_root + + def fake_pkg_root(): + root = tmp_path / "fake_pkg" + sc_path = root / "skills" / "sous-chef" + sc_path.mkdir(parents=True, exist_ok=True) + skill_md = sc_path / "SKILL.md" + skill_md.write_text("dummy") + skill_md.chmod(0o000) + return root + + with patch("autoskillit.server._get_ctx", return_value=mock_ctx): + with patch("autoskillit.server.logger"): + with patch("autoskillit.server.tools_kitchen._prime_quota_cache", new=AsyncMock()): + with patch("autoskillit.server.tools_kitchen._write_hook_config"): + with patch.object(tk_mod, "pkg_root", fake_pkg_root): + from autoskillit.server.tools_kitchen import open_kitchen + + result_str = await open_kitchen(ctx=mock_ctx) + + # Restore permissions for cleanup + for p in tmp_path.rglob("SKILL.md"): + p.chmod(0o644) + + parsed = json.loads(result_str) + assert parsed["success"] is False + assert parsed["stage"] == "read_sous_chef" + + +# Parametrized: every failure envelope has user_visible_message +_FAILURE_STAGES = [ + "headless_guard", + "prime_quota_cache", + "start_quota_refresh", + "enable_components", + "load_and_validate", + "apply_triage_gate", + "recipe_context", +] + + +@pytest.mark.parametrize("stage", _FAILURE_STAGES) +def test_every_failure_envelope_has_user_visible_message(stage): + """All failure envelopes have a non-empty user_visible_message string.""" + from autoskillit.server.tools_kitchen import _kitchen_failure_envelope + + envelope = json.loads(_kitchen_failure_envelope(RuntimeError("test"), stage=stage)) + assert isinstance(envelope["user_visible_message"], str) + assert len(envelope["user_visible_message"]) > 0 + assert envelope["success"] is False + assert envelope["kitchen"] == "failed" + + +@pytest.mark.parametrize( + "stage", + _FAILURE_STAGES + ["hook_diagnostic", "read_sous_chef", "redisable_subsets"], +) +def test_every_return_path_parses_as_json_and_has_boolean_success(stage): + """Every failure envelope parses as JSON with boolean success.""" + from autoskillit.server.tools_kitchen import _kitchen_failure_envelope + + envelope = json.loads(_kitchen_failure_envelope(RuntimeError("test"), stage=stage)) + assert isinstance(envelope["success"], bool) + + +@pytest.mark.anyio +async def test_disable_quota_guard_writes_disabled_flag(tmp_path, monkeypatch): + """disable_quota_guard() sets quota_guard.disabled=True in the hook config file.""" + monkeypatch.chdir(tmp_path) + hook_cfg_path = tmp_path.joinpath(*_HOOK_CONFIG_PATH_COMPONENTS) + hook_cfg_path.parent.mkdir(parents=True, exist_ok=True) + hook_cfg_path.write_text( + json.dumps({"quota_guard": {"cache_path": "/some/path.json", "cache_max_age": 300}}) + ) + + from autoskillit.server.tools_kitchen import disable_quota_guard + + result_str = await disable_quota_guard() + parsed = json.loads(result_str) + assert parsed["success"] is True + + payload = json.loads(hook_cfg_path.read_text()) + assert payload["quota_guard"]["disabled"] is True + + +@pytest.mark.anyio +async def test_disable_quota_guard_denies_headless(tmp_path, monkeypatch): + """disable_quota_guard() returns an error when called from a headless session.""" + monkeypatch.chdir(tmp_path) + monkeypatch.setenv("AUTOSKILLIT_HEADLESS", "1") + + from autoskillit.server.tools_kitchen import disable_quota_guard + + result_str = await disable_quota_guard() + parsed = json.loads(result_str) + assert parsed["success"] is False + + +@pytest.mark.anyio +async def test_disable_quota_guard_returns_error_when_kitchen_not_open(tmp_path, monkeypatch): + """disable_quota_guard() returns an error when the kitchen is not open.""" + monkeypatch.chdir(tmp_path) + + from autoskillit.server.tools_kitchen import disable_quota_guard + + result_str = await disable_quota_guard() + parsed = json.loads(result_str) + assert parsed["success"] is False diff --git a/tests/server/test_tools_list_recipes.py b/tests/server/test_tools_list_recipes.py new file mode 100644 index 0000000000..7b356b9e78 --- /dev/null +++ b/tests/server/test_tools_list_recipes.py @@ -0,0 +1,162 @@ +"""Tests for autoskillit server list_recipes tool.""" + +from __future__ import annotations + +import json +from pathlib import Path +from unittest.mock import patch + +import pytest + +from autoskillit.pipeline.gate import DefaultGateState +from autoskillit.server.tools_recipe import list_recipes + + +class TestListRecipeTools: + """Tests for kitchen-gated list_recipes tool.""" + + @pytest.fixture(autouse=True) + def _ensure_ctx(self, tool_ctx): + """Ensure server context is initialized (gate open by default).""" + + # SS1 + @pytest.mark.anyio + @patch("autoskillit.recipe._api.list_recipes") + async def test_list_returns_json_object(self, mock_list): + """list_recipes returns JSON object with scripts array.""" + from autoskillit.core.types import LoadResult, RecipeSource + from autoskillit.recipe.schema import RecipeInfo + + mock_list.return_value = LoadResult( + items=[ + RecipeInfo( + name="impl", + description="Implement", + summary="plan > impl", + path=Path("/x"), + source=RecipeSource.PROJECT, + ), + ], + errors=[], + ) + result = json.loads(await list_recipes()) + assert isinstance(result, dict) + assert len(result["recipes"]) == 1 + assert result["recipes"][0]["name"] == "impl" + assert result["recipes"][0]["description"] == "Implement" + assert result["recipes"][0]["summary"] == "plan > impl" + assert "errors" not in result + + # SS4 + @pytest.mark.anyio + @patch("autoskillit.recipe._api.list_recipes") + async def test_list_reports_errors_in_response(self, mock_list): + """list_recipes includes errors in JSON when recipes fail to parse.""" + from autoskillit.core.types import LoadReport, LoadResult + + mock_list.return_value = LoadResult( + items=[], + errors=[LoadReport(path=Path("/recipes/broken.yaml"), error="bad yaml")], + ) + result = json.loads(await list_recipes()) + assert "errors" in result + assert len(result["errors"]) == 1 + assert result["errors"][0]["file"] == "broken.yaml" + assert "bad yaml" in result["errors"][0]["error"] + + # SS5 + @pytest.mark.anyio + async def test_list_integration_discovers_project_recipe(self, tmp_path, monkeypatch): + """Server tool returns project recipes alongside bundled recipes.""" + monkeypatch.chdir(tmp_path) + recipes_dir = tmp_path / ".autoskillit" / "recipes" + recipes_dir.mkdir(parents=True) + (recipes_dir / "pipeline.yaml").write_text( + "name: test-pipe\ndescription: Test\nsummary: a > b\n" + "steps:\n done:\n action: stop\n message: Done\n" + ) + result = json.loads(await list_recipes()) + names = {r["name"] for r in result["recipes"]} + assert "test-pipe" in names + + # SS6 + @pytest.mark.anyio + async def test_list_integration_reports_errors(self, tmp_path, monkeypatch): + """Server tool reports parse errors to the caller from real files.""" + monkeypatch.chdir(tmp_path) + recipes_dir = tmp_path / ".autoskillit" / "recipes" + recipes_dir.mkdir(parents=True) + (recipes_dir / "broken.yaml").write_text("[unclosed bracket\n") + result = json.loads(await list_recipes()) + assert "errors" in result + assert len(result["errors"]) == 1 + + # SS8 + @pytest.mark.anyio + async def test_list_recipes_includes_builtins_with_empty_project_dir( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """list_recipes MCP returns bundled recipes when .autoskillit/recipes/ is absent.""" + monkeypatch.chdir(tmp_path) + # No .autoskillit/recipes/ created — simulates a fresh project with no local recipes + result = json.loads(await list_recipes()) + names = {r["name"] for r in result["recipes"]} + assert "implementation" in names + assert "remediation" in names + assert "smoke-test" not in names + + # SS10 + @pytest.mark.anyio + @patch("autoskillit.recipe._api.list_recipes") + async def test_list_recipes_response_includes_source_field(self, mock_list): + """list_recipes MCP response must include source field for each recipe entry.""" + from autoskillit.core.types import LoadResult, RecipeSource + from autoskillit.recipe.schema import RecipeInfo + + mock_list.return_value = LoadResult( + items=[ + RecipeInfo( + name="impl", + description="Implement", + source=RecipeSource.BUILTIN, + path=Path("/recipes/impl.yaml"), + ), + RecipeInfo( + name="my-recipe", + description="Custom", + source=RecipeSource.PROJECT, + path=Path("/project/my-recipe.yaml"), + ), + ], + errors=[], + ) + result = json.loads(await list_recipes()) + assert "source" in result["recipes"][0], ( + "MCP list_recipes response must include 'source' field" + ) + assert result["recipes"][0]["source"] == "builtin" + assert result["recipes"][1]["source"] == "project" + + +# --------------------------------------------------------------------------- +# P5F2: Accessor pattern tests (gated tools use _get_ctx_or_none after gate check) +# --------------------------------------------------------------------------- + + +# P5F2-T1 +@pytest.mark.anyio +async def test_list_recipes_no_recipes_returns_empty(tool_ctx): + """list_recipes returns empty-list JSON when recipes is not configured.""" + tool_ctx.recipes = None + result = json.loads(await list_recipes()) + assert result == [] + + +# P5F2-T1b +@pytest.mark.anyio +async def test_list_recipes_gate_closed_returns_gate_error(tool_ctx): + """list_recipes returns gate_error JSON when kitchen gate is closed.""" + tool_ctx.gate = DefaultGateState(enabled=False) + result = json.loads(await list_recipes()) + assert result.get("success") is False + assert result.get("subtype") == "gate_error" diff --git a/tests/server/test_tools_load_recipe.py b/tests/server/test_tools_load_recipe.py new file mode 100644 index 0000000000..95de6935fd --- /dev/null +++ b/tests/server/test_tools_load_recipe.py @@ -0,0 +1,834 @@ +"""Tests for autoskillit server load_recipe and migrate_recipe tools.""" + +from __future__ import annotations + +import json +from pathlib import Path +from unittest.mock import AsyncMock, patch + +import pytest + +from autoskillit.config import AutomationConfig +from autoskillit.core import SkillResult +from autoskillit.core.types import RetryReason +from autoskillit.pipeline.gate import GATED_TOOLS, UNGATED_TOOLS, DefaultGateState +from autoskillit.server.tools_recipe import ( + load_recipe, + migrate_recipe, +) + +# --------------------------------------------------------------------------- +# Minimal valid script YAML used across migration suggestion tests +# --------------------------------------------------------------------------- + +_MINIMAL_SCRIPT_YAML = """\ +name: test-script +description: Test +summary: test +ingredients: + task: + description: What to do + required: true +steps: + do-thing: + tool: run_skill + with: + skill_command: "/autoskillit:investigate ${{ inputs.task }}" + cwd: "." + on_success: done + on_failure: escalate + done: + action: stop + message: "Done." + escalate: + action: stop + message: "Failed." +kitchen_rules: + - "Follow routing rules" +""" + + +def _write_minimal_script(scripts_dir: Path, name: str = "test-script") -> Path: + """Write a minimal valid workflow script with no autoskillit_version field.""" + scripts_dir.mkdir(parents=True, exist_ok=True) + path = scripts_dir / f"{name}.yaml" + path.write_text(_MINIMAL_SCRIPT_YAML) + return path + + +# --------------------------------------------------------------------------- +# Minimal recipe YAML used for diagram tests +# --------------------------------------------------------------------------- + +_MINIMAL_RECIPE_FOR_DIAGRAM = """\ +name: my-recipe +description: Test recipe for diagram tests +summary: step1 -> done +ingredients: + task: + description: What to do + required: true +steps: + step1: + tool: run_skill + with: + skill_command: "/autoskillit:investigate ${{ inputs.task }}" + cwd: "." + on_success: done + on_failure: escalate + done: + action: stop + message: "Done." + escalate: + action: stop + message: "Failed." +kitchen_rules: + - "Use AutoSkillit tools only" +""" + + +class TestLoadRecipeTools: + """Tests for kitchen-gated load_recipe tool.""" + + @pytest.fixture(autouse=True) + def _ensure_ctx(self, tool_ctx): + """Ensure server context is initialized (gate open by default).""" + + # SS2 + @pytest.mark.anyio + async def test_load_returns_json_with_content(self, tmp_path, monkeypatch): + """load_recipe returns JSON with content and suggestions.""" + monkeypatch.chdir(tmp_path) + recipes_dir = tmp_path / ".autoskillit" / "recipes" + recipes_dir.mkdir(parents=True) + (recipes_dir / "test.yaml").write_text("name: test\ndescription: Test recipe\n") + result = json.loads(await load_recipe(name="test")) + assert "content" in result + assert "suggestions" in result + assert "name: test" in result["content"] + assert "description: Test recipe" in result["content"] + + # SS3 + @pytest.mark.anyio + async def test_load_unknown_returns_error(self, tmp_path, monkeypatch): + """load_recipe returns error JSON for unknown recipe name.""" + monkeypatch.chdir(tmp_path) + result = json.loads(await load_recipe(name="nonexistent")) + assert "error" in result + assert "nonexistent" in result["error"] + + # SS7 + @pytest.mark.anyio + async def test_load_returns_json_with_suggestions(self, tmp_path, monkeypatch): + """load_recipe response always has 'content' and 'suggestions' keys.""" + monkeypatch.chdir(tmp_path) + recipes_dir = tmp_path / ".autoskillit" / "recipes" + recipes_dir.mkdir(parents=True) + (recipes_dir / "test.yaml").write_text( + "name: test\ndescription: Test\nkitchen_rules:\n - test\n" + "steps:\n do:\n tool: test_check\n model: sonnet\n" + " on_success: done\n done:\n action: stop\n message: Done\n" + ) + result = json.loads(await load_recipe(name="test")) + assert "content" in result + assert "suggestions" in result + assert isinstance(result["suggestions"], list) + assert any(s["rule"] == "model-on-non-skill-step" for s in result["suggestions"]) + + # SS9 + @pytest.mark.anyio + async def test_load_recipe_mcp_returns_builtin_recipe( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """load_recipe MCP finds bundled recipes when no project .autoskillit/recipes/ dir.""" + monkeypatch.chdir(tmp_path) + result = json.loads(await load_recipe(name="implementation")) + assert "error" not in result, f"Unexpected error: {result.get('error')}" + assert "content" in result + assert len(result["content"]) > 0 + + @pytest.mark.anyio + async def test_load_recipe_parse_failure_is_logged_and_surfaced( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """load_recipe emits a warning log and surfaces a validation-error finding.""" + monkeypatch.chdir(tmp_path) + recipes_dir = tmp_path / ".autoskillit" / "recipes" + recipes_dir.mkdir(parents=True) + # Recipe must have 'steps' so the run_semantic_rules code path is reached + (recipes_dir / "test.yaml").write_text( + "name: test\ndescription: Test\nsteps:\n done:\n action: stop\n message: Done\n" + ) + + with ( + patch( + "autoskillit.recipe._api.run_semantic_rules", + side_effect=ValueError("injected crash"), + ), + patch("autoskillit.recipe._api._logger") as mock_logger, + ): + result = json.loads(await load_recipe(name="test")) + + assert "content" in result, "load_recipe must be non-blocking even on parse failure" + mock_logger.warning.assert_called_once() + assert any(s.get("rule") == "validation-error" for s in result["suggestions"]), ( + "Unexpected exception must appear as a validation-error finding in suggestions" + ) + findings = [s for s in result["suggestions"] if s.get("rule") == "validation-error"] + assert findings, "Expected at least one validation-error finding" + assert findings[0]["message"] == "Invalid recipe structure: injected crash" + + +class TestContractMigrationAdapterValidate: + """P7-2: ContractMigrationAdapter.validate uses _load_yaml, not yaml.safe_load.""" + + def test_valid_contract_returns_true(self, tmp_path: Path) -> None: + from autoskillit.migration.engine import ContractMigrationAdapter + + f = tmp_path / "contract.yaml" + f.write_text("skill_hashes:\n my-skill: abc123\n") + adapter = ContractMigrationAdapter() + ok, msg = adapter.validate(f) + assert ok is True + assert msg == "" + + def test_missing_skill_hashes_returns_false(self, tmp_path: Path) -> None: + from autoskillit.migration.engine import ContractMigrationAdapter + + f = tmp_path / "contract.yaml" + f.write_text("other_field: value\n") + adapter = ContractMigrationAdapter() + ok, msg = adapter.validate(f) + assert ok is False + assert "skill_hashes" in msg + + def test_invalid_yaml_returns_false(self, tmp_path: Path) -> None: + from autoskillit.migration.engine import ContractMigrationAdapter + + f = tmp_path / "contract.yaml" + f.write_bytes(b":\tbad: yaml: [unclosed\n") + adapter = ContractMigrationAdapter() + ok, msg = adapter.validate(f) + assert ok is False + assert msg != "" + + def test_missing_file_returns_false(self, tmp_path: Path) -> None: + from autoskillit.migration.engine import ContractMigrationAdapter + + adapter = ContractMigrationAdapter() + ok, msg = adapter.validate(tmp_path / "nonexistent.yaml") + assert ok is False + assert msg != "" + + +class TestLoadRecipeExceptionHandling: + """CC-1: Outer except in load_recipe must catch anticipated exceptions only.""" + + @pytest.fixture(autouse=True) + def _setup_ctx(self, tool_ctx): + """Initialize ToolContext so load_recipe can call _get_config().""" + + @pytest.mark.anyio + async def test_yaml_error_surfaces_as_suggestion( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """yaml.YAMLError is caught and returned as an error suggestion.""" + from autoskillit.core.io import YAMLError + + monkeypatch.chdir(tmp_path) + recipes_dir = tmp_path / ".autoskillit" / "recipes" + recipes_dir.mkdir(parents=True) + (recipes_dir / "test.yaml").write_text("name: test\n") + with patch("autoskillit.recipe._api.load_yaml", side_effect=YAMLError("bad yaml")): + result = json.loads(await load_recipe(name="test")) + assert "error" not in result + assert any( + s.get("rule") == "validation-error" and s.get("severity") == "error" + for s in result["suggestions"] + ) + + @pytest.mark.anyio + async def test_value_error_surfaces_as_suggestion( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """ValueError (malformed recipe structure) is caught and returned as error suggestion.""" + from autoskillit.core.types import RecipeSource + from autoskillit.recipe.schema import RecipeInfo + + monkeypatch.chdir(tmp_path) + recipes_dir = tmp_path / ".autoskillit" / "recipes" + recipes_dir.mkdir(parents=True) + recipe_path = recipes_dir / "test.yaml" + recipe_path.write_text( + "name: test\ndescription: Test\nsteps:\n done:\n action: stop\n message: Done\n" + ) + fake_match = RecipeInfo( + name="test", + description="Test", + source=RecipeSource.PROJECT, + path=recipe_path, + ) + with ( + patch("autoskillit.recipe.find_recipe_by_name", return_value=fake_match), + patch( + "autoskillit.recipe._api._parse_recipe", side_effect=ValueError("bad structure") + ), + ): + result = json.loads(await load_recipe(name="test")) + assert "error" not in result + assert any( + s.get("rule") == "validation-error" and s.get("severity") == "error" + for s in result["suggestions"] + ) + + @pytest.mark.anyio + async def test_file_not_found_surfaces_as_suggestion( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """FileNotFoundError is caught and returned as an error suggestion.""" + monkeypatch.chdir(tmp_path) + recipes_dir = tmp_path / ".autoskillit" / "recipes" + recipes_dir.mkdir(parents=True) + (recipes_dir / "test.yaml").write_text( + "name: test\ndescription: Test\nsteps:\n done:\n action: stop\n message: Done\n" + ) + with patch( + "autoskillit.recipe._api.load_recipe_card", + side_effect=FileNotFoundError("missing"), + ): + result = json.loads(await load_recipe(name="test")) + assert "error" not in result + assert any( + s.get("rule") == "validation-error" and s.get("severity") == "error" + for s in result["suggestions"] + ) + + @pytest.mark.anyio + async def test_unexpected_exception_returns_structured_error( + self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch + ) -> None: + """Unexpected exceptions are caught by the handler-level exception boundary.""" + monkeypatch.chdir(tmp_path) + recipes_dir = tmp_path / ".autoskillit" / "recipes" + recipes_dir.mkdir(parents=True) + (recipes_dir / "test.yaml").write_text( + "name: test\ndescription: Test\nsteps:\n done:\n action: stop\n message: Done\n" + ) + with patch( + "autoskillit.recipe._api.run_semantic_rules", + side_effect=AttributeError("programming error"), + ): + result = json.loads(await load_recipe(name="test")) + assert result["success"] is False + assert "error" in result + assert "programming error" in result["error"] + + +class TestMigrationSuppression: + """SUP1, SUP4: load_recipe respects migration.suppressed config.""" + + # SUP1 + @pytest.mark.anyio + async def test_outdated_version_not_in_suggestions_when_suppressed( + self, tmp_path, monkeypatch, tool_ctx + ): + """SUP1: outdated-recipe-version absent when recipe is suppressed; headless not called.""" + from autoskillit.config import MigrationConfig + + monkeypatch.chdir(tmp_path) + scripts_dir = tmp_path / ".autoskillit" / "recipes" + _write_minimal_script(scripts_dir, "test-script") + + tool_ctx.config = AutomationConfig(migration=MigrationConfig(suppressed=["test-script"])) + + mock_headless = AsyncMock( + return_value=SkillResult( + success=True, + result="ok", + session_id="", + subtype="success", + is_error=False, + exit_code=0, + needs_retry=False, + retry_reason=RetryReason.NONE, + stderr="", + ) + ) + with patch("autoskillit.execution.headless.run_headless_core", mock_headless): + result = json.loads(await load_recipe(name="test-script")) + + assert "suggestions" in result + rules = [s["rule"] for s in result["suggestions"]] + assert "outdated-recipe-version" not in rules + mock_headless.assert_not_called() + + # SUP4 + @pytest.mark.anyio + async def test_validate_always_includes_outdated_version_regardless_of_suppression( + self, tmp_path, tool_ctx + ): + """SUP4: validate_recipe includes outdated-script-version even when suppressed.""" + from autoskillit.config import MigrationConfig + from autoskillit.server.tools_recipe import validate_recipe + + script = tmp_path / "test-script.yaml" + script.write_text(_MINIMAL_SCRIPT_YAML) + + # Even with script suppressed in config, validate_recipe does not filter + tool_ctx.config = AutomationConfig(migration=MigrationConfig(suppressed=["test-script"])) + + result = json.loads(await validate_recipe(script_path=str(script))) + assert "findings" in result + rules = [s["rule"] for s in result["findings"]] + assert "outdated-recipe-version" in rules + + +class TestApplyTriageGate: + """T3: _apply_triage_gate caches triage result and skips on second call.""" + + @pytest.fixture(autouse=True) + def _close_kitchen(self, tool_ctx): + tool_ctx.gate = DefaultGateState(enabled=False) + + @pytest.mark.anyio + async def test_apply_triage_gate_second_call_skips_triage( + self, tmp_path, monkeypatch, tool_ctx + ): + """Second _apply_triage_gate call reads from cache; triage_staleness not re-invoked.""" + import copy + + from autoskillit.recipe.staleness_cache import read_staleness_cache + from autoskillit.server.helpers import _apply_triage_gate + + monkeypatch.chdir(tmp_path) + recipes_dir = tmp_path / ".autoskillit" / "recipes" + recipes_dir.mkdir(parents=True) + recipe_yaml = ( + "name: triage-test\ndescription: T\n" + "steps:\n done:\n action: stop\n message: Done\n" + ) + recipe_path = recipes_dir / "triage-test.yaml" + recipe_path.write_text(recipe_yaml) + + name = "triage-test" + result_template = { + "content": recipe_yaml, + "suggestions": [ + { + "rule": "stale-contract", + "reason": "hash_mismatch", + "skill": "investigate", + "stored_value": "sha256:old", + "current_value": "sha256:new", + "message": "investigate SKILL.md changed", + "severity": "info", + } + ], + "valid": True, + } + + # Get real recipe_info before mocking find + recipe_info = tool_ctx.recipes.find(name, Path.cwd()) + assert recipe_info is not None + + # Mock _ctx.recipes.find to verify it is NOT called when recipe_info is injected + mock_find = AsyncMock(return_value=recipe_info) + monkeypatch.setattr(tool_ctx.recipes, "find", mock_find) + + mock_triage = AsyncMock( + return_value=[{"meaningful": False, "summary": "ok", "skill": "investigate"}] + ) + with patch("autoskillit._llm_triage.triage_staleness", mock_triage): + # First call: triage_staleness invoked once + await _apply_triage_gate(copy.deepcopy(result_template), name, recipe_info=recipe_info) + + assert mock_triage.call_count == 1 + assert mock_find.call_count == 0, "find() must not be called when recipe_info is injected" + + cache_path = tmp_path / ".autoskillit" / "temp" / "recipe_staleness_cache.json" + cached = read_staleness_cache(cache_path, name) + assert cached is not None + assert cached.triage_result == "cosmetic" + + with patch("autoskillit._llm_triage.triage_staleness", mock_triage): + # Second call: must read from cache and skip triage_staleness entirely + await _apply_triage_gate(copy.deepcopy(result_template), name, recipe_info=recipe_info) + + assert mock_triage.call_count == 1, ( + "triage_staleness must not be called on second invocation" + ) + + +class TestLoadRecipeReadOnly: + """P4: load_recipe is strictly read-only — no migration, no contract card generation.""" + + @pytest.fixture(autouse=True) + def _ensure_ctx(self, tool_ctx): + """Ensure server context is initialized (gate open by default).""" + + @pytest.mark.anyio + async def test_load_recipe_does_not_call_migration_engine(self, tmp_path, monkeypatch): + """load_recipe must not trigger headless migration even when migrations are applicable.""" + monkeypatch.chdir(tmp_path) + with ( + patch("autoskillit.migration.loader.applicable_migrations", return_value=["v0.1.0"]), + patch("autoskillit.execution.headless.run_headless_core") as mock_headless, + patch("autoskillit.recipe.contracts.generate_recipe_card") as mock_gen, + ): + result = json.loads(await load_recipe(name="implementation")) + assert "error" not in result + mock_headless.assert_not_called() + mock_gen.assert_not_called() + + @pytest.mark.anyio + async def test_load_recipe_does_not_auto_generate_contract_card(self, tmp_path, monkeypatch): + """load_recipe must not call generate_recipe_card even when no card exists.""" + monkeypatch.chdir(tmp_path) + recipes_dir = tmp_path / ".autoskillit" / "recipes" + recipes_dir.mkdir(parents=True) + (recipes_dir / "test.yaml").write_text( + "name: test\ndescription: Test\nsteps:\n done:\n action: stop\n message: Done\n" + ) + with patch("autoskillit.recipe.contracts.generate_recipe_card") as mock_gen: + await load_recipe(name="test") + mock_gen.assert_not_called() + + +class TestMigrateRecipe: + """P4: migrate_recipe is a gated tool that runs migration engine and regenerates cards.""" + + @pytest.fixture(autouse=True) + def _open_kitchen(self, tool_ctx): + """migrate_recipe requires tool activation.""" + tool_ctx.gate = DefaultGateState(enabled=True) + + def _setup_migration_env( + self, + tmp_path, + monkeypatch, + tool_ctx, + *, + suppressed: list[str] | None = None, + ): + """Create directory structure, fake migration YAML, and config.""" + import autoskillit + import autoskillit.migration.loader as ml + from autoskillit.config import MigrationConfig + + monkeypatch.chdir(tmp_path) + recipes_dir = tmp_path / ".autoskillit" / "recipes" + recipes_dir.mkdir(parents=True) + recipe_path = recipes_dir / "test-script.yaml" + recipe_path.write_text(_MINIMAL_SCRIPT_YAML) + + installed_ver = autoskillit.__version__ + fake_mig_dir = tmp_path / "migrations" + fake_mig_dir.mkdir() + migration_yaml = ( + f"from_version: '0.0.0'\n" + f"to_version: '{installed_ver}'\n" + "description: Upgrade scripts\n" + "changes:\n" + " - id: add-summary-field\n" + " description: Scripts now require a summary field\n" + " instruction: Add summary field to your script\n" + ) + (fake_mig_dir / "0.0.0-migration.yaml").write_text(migration_yaml) + monkeypatch.setattr(ml, "_migrations_dir", lambda: fake_mig_dir) + + tool_ctx.config = AutomationConfig(migration=MigrationConfig(suppressed=suppressed or [])) + + temp_mig_dir = tmp_path / ".autoskillit" / "temp" / "migrations" + temp_mig_dir.mkdir(parents=True) + + migrated_content = _MINIMAL_SCRIPT_YAML + f"autoskillit_version: '{installed_ver}'\n" + return { + "recipe_path": recipe_path, + "temp_mig_dir": temp_mig_dir, + "migrated_content": migrated_content, + "installed_ver": installed_ver, + } + + def test_migrate_recipe_is_in_gated_tools(self): + """migrate_recipe is a gated tool.""" + assert "migrate_recipe" in GATED_TOOLS + + def test_migrate_recipe_not_in_ungated_tools(self): + """migrate_recipe is not an ungated tool.""" + assert "migrate_recipe" not in UNGATED_TOOLS + + @pytest.mark.anyio + async def test_migrate_recipe_requires_gate(self, tool_ctx): + """migrate_recipe returns gate_error when kitchen is closed.""" + tool_ctx.gate = DefaultGateState(enabled=False) + result = json.loads(await migrate_recipe(name="test")) + assert result["success"] is False + assert result["subtype"] == "gate_error" + + @pytest.mark.anyio + async def test_migrate_recipe_not_found(self, tmp_path, monkeypatch): + """migrate_recipe returns error for unknown recipe name.""" + monkeypatch.chdir(tmp_path) + result = json.loads(await migrate_recipe(name="nonexistent")) + assert "error" in result + assert "nonexistent" in result["error"] + + @pytest.mark.anyio + async def test_migrate_recipe_up_to_date(self, tmp_path, monkeypatch): # SRV-UPD-1 + """migrate_recipe returns up_to_date when no migrations applicable and contract fresh.""" + monkeypatch.chdir(tmp_path) + with ( + patch("autoskillit.migration.loader.applicable_migrations", return_value=[]), + patch("autoskillit.recipe.load_recipe_card", return_value={"skill_hashes": {}}), + patch("autoskillit.recipe.check_contract_staleness", return_value=[]), + ): + result = json.loads(await migrate_recipe(name="implementation")) + assert result.get("status") == "up_to_date" + + # LR1 + @pytest.mark.anyio + async def test_auto_migrates_outdated_recipe(self, tmp_path, monkeypatch, tool_ctx): + """LR1: When recipe version < installed, _run_headless_core is called once.""" + ctx = self._setup_migration_env(tmp_path, monkeypatch, tool_ctx) + (ctx["temp_mig_dir"] / "test-script.yaml").write_text(ctx["migrated_content"]) + + mock_headless = AsyncMock( + return_value=SkillResult( + success=True, + result="ok", + session_id="", + subtype="success", + is_error=False, + exit_code=0, + needs_retry=False, + retry_reason=RetryReason.NONE, + stderr="", + ) + ) + with ( + patch("autoskillit.execution.headless.run_headless_core", mock_headless), + patch("autoskillit.recipe.generate_recipe_card", return_value=None), + ): + result = json.loads(await migrate_recipe(name="test-script")) + + mock_headless.assert_awaited_once() + assert result.get("status") == "migrated" + assert "contracts_regenerated" in result + + # LR4 + @pytest.mark.anyio + async def test_clears_failure_record_after_successful_migration( + self, tmp_path, monkeypatch, tool_ctx + ): + """LR4: FailureStore.clear(name) is called when migration succeeds.""" + from autoskillit.migration.store import FailureStore, default_store_path + + ctx = self._setup_migration_env(tmp_path, monkeypatch, tool_ctx) + (ctx["temp_mig_dir"] / "test-script.yaml").write_text(ctx["migrated_content"]) + + store = FailureStore(default_store_path(tmp_path)) + store.record( + name="test-script", + file_path=ctx["recipe_path"], + file_type="recipe", + error="prior failure", + retries_attempted=1, + ) + assert store.has_failure("test-script") + + mock_headless = AsyncMock( + return_value=SkillResult( + success=True, + result="ok", + session_id="", + subtype="success", + is_error=False, + exit_code=0, + needs_retry=False, + retry_reason=RetryReason.NONE, + stderr="", + ) + ) + with ( + patch("autoskillit.execution.headless.run_headless_core", mock_headless), + patch("autoskillit.recipe.contracts.generate_recipe_card", return_value=None), + ): + await migrate_recipe(name="test-script") + + fresh_store = FailureStore(default_store_path(tmp_path)) + assert not fresh_store.has_failure("test-script") + + # LR5 + @pytest.mark.anyio + async def test_records_failure_when_migration_fails(self, tmp_path, monkeypatch, tool_ctx): + """LR5: When headless returns success=False, failure is recorded to failures.json.""" + from autoskillit.migration.store import FailureStore, default_store_path + + self._setup_migration_env(tmp_path, monkeypatch, tool_ctx) + + mock_headless = AsyncMock( + return_value=SkillResult( + success=False, + result="headless failed", + session_id="", + subtype="error", + is_error=True, + exit_code=1, + needs_retry=False, + retry_reason=RetryReason.NONE, + stderr="", + ) + ) + with patch("autoskillit.execution.headless.run_headless_core", mock_headless): + result = json.loads(await migrate_recipe(name="test-script")) + + assert "error" in result + store = FailureStore(default_store_path(tmp_path)) + assert store.has_failure("test-script") + + # LR7 + @pytest.mark.anyio + async def test_suppressed_recipe_not_migrated(self, tmp_path, monkeypatch, tool_ctx): + """LR7: When name in migration.suppressed, headless is never called.""" + self._setup_migration_env(tmp_path, monkeypatch, tool_ctx, suppressed=["test-script"]) + + mock_headless = AsyncMock( + return_value=SkillResult( + success=True, + result="ok", + session_id="", + subtype="success", + is_error=False, + exit_code=0, + needs_retry=False, + retry_reason=RetryReason.NONE, + stderr="", + ) + ) + with patch("autoskillit.execution.headless.run_headless_core", mock_headless): + result = json.loads(await migrate_recipe(name="test-script")) + + mock_headless.assert_not_called() + assert result.get("status") == "up_to_date" + + # LR8 + @pytest.mark.anyio + async def test_up_to_date_recipe_not_migrated(self, tmp_path, monkeypatch, tool_ctx): + """LR8: When applicable_migrations returns [], headless is never called.""" + import autoskillit + import autoskillit.migration.loader as ml + from autoskillit.config import MigrationConfig + + monkeypatch.chdir(tmp_path) + recipes_dir = tmp_path / ".autoskillit" / "recipes" + recipes_dir.mkdir(parents=True) + current_ver = autoskillit.__version__ + (recipes_dir / "test-script.yaml").write_text( + _MINIMAL_SCRIPT_YAML + f"autoskillit_version: '{current_ver}'\n" + ) + + empty_mig_dir = tmp_path / "migrations" + empty_mig_dir.mkdir() + monkeypatch.setattr(ml, "_migrations_dir", lambda: empty_mig_dir) + tool_ctx.config = AutomationConfig(migration=MigrationConfig(suppressed=[])) + + mock_headless = AsyncMock( + return_value=SkillResult( + success=True, + result="ok", + session_id="", + subtype="success", + is_error=False, + exit_code=0, + needs_retry=False, + retry_reason=RetryReason.NONE, + stderr="", + ) + ) + with ( + patch("autoskillit.execution.headless.run_headless_core", mock_headless), + patch("autoskillit.recipe.load_recipe_card", return_value={"skill_hashes": {}}), + patch("autoskillit.recipe.check_contract_staleness", return_value=[]), + ): + result = json.loads(await migrate_recipe(name="test-script")) + + mock_headless.assert_not_called() + assert result.get("status") == "up_to_date" + + # SRV-NEW-1 + @pytest.mark.anyio + async def test_migrate_recipe_regenerates_stale_contract( + self, tmp_path, monkeypatch, tool_ctx + ): + """migrate_recipe with version migration also regenerates stale contracts.""" + ctx = self._setup_migration_env(tmp_path, monkeypatch, tool_ctx) + (ctx["temp_mig_dir"] / "test-script.yaml").write_text(ctx["migrated_content"]) + + mock_headless = AsyncMock( + return_value=SkillResult( + success=True, + result="ok", + session_id="", + subtype="success", + is_error=False, + exit_code=0, + needs_retry=False, + retry_reason=RetryReason.NONE, + stderr="", + ) + ) + with ( + patch("autoskillit.execution.headless.run_headless_core", mock_headless), + patch("autoskillit.recipe.load_recipe_card", return_value=None), + patch("autoskillit.recipe.generate_recipe_card", return_value={}), + ): + result = json.loads(await migrate_recipe(name="test-script")) + + assert result.get("status") == "migrated" + assert result.get("contracts_regenerated") == ["test-script"] + + +class TestLoadRecipeDiagram: + """Tests for diagram field in load_recipe responses (DG-12 through DG-15).""" + + def _setup_project_recipe(self, tmp_path: Path, monkeypatch) -> Path: + monkeypatch.chdir(tmp_path) + recipes_dir = tmp_path / ".autoskillit" / "recipes" + recipes_dir.mkdir(parents=True) + recipe_path = recipes_dir / "my-recipe.yaml" + recipe_path.write_text(_MINIMAL_RECIPE_FOR_DIAGRAM) + return recipes_dir + + # DG-12 + @pytest.mark.anyio + async def test_load_recipe_response_has_diagram_key(self, tmp_path, monkeypatch, tool_ctx): + """DG-12: load_recipe response always contains a 'diagram' key.""" + self._setup_project_recipe(tmp_path, monkeypatch) + result = json.loads(await load_recipe(name="my-recipe")) + assert "diagram" in result + + # DG-13 + @pytest.mark.anyio + async def test_load_recipe_diagram_none_when_not_generated( + self, tmp_path, monkeypatch, tool_ctx + ): + """DG-13: diagram is None when no diagram file exists.""" + self._setup_project_recipe(tmp_path, monkeypatch) + result = json.loads(await load_recipe(name="my-recipe")) + assert result["diagram"] is None + + +# --------------------------------------------------------------------------- +# P5F2: Accessor pattern tests +# --------------------------------------------------------------------------- + + +# P5F2-T2 +@pytest.mark.anyio +async def test_load_recipe_no_ctx_returns_error(monkeypatch): + """load_recipe returns error JSON when server is uninitialized.""" + import autoskillit.server._state as _state_mod + + monkeypatch.setattr(_state_mod, "_ctx", None) + result = json.loads(await load_recipe(name="anything")) + assert "error" in result diff --git a/tests/server/test_tools_recipe.py b/tests/server/test_tools_recipe.py index 8fc33fc79e..4c9df342cb 100644 --- a/tests/server/test_tools_recipe.py +++ b/tests/server/test_tools_recipe.py @@ -1,24 +1,13 @@ -"""Tests for autoskillit server recipe tools.""" +"""Tests for autoskillit server validate_recipe tool and recipe docstring contracts.""" from __future__ import annotations import json import re -from pathlib import Path -from unittest.mock import AsyncMock, patch import pytest -from autoskillit.config import AutomationConfig -from autoskillit.core import SkillResult -from autoskillit.core.types import RetryReason -from autoskillit.pipeline.gate import GATED_TOOLS, UNGATED_TOOLS, DefaultGateState -from autoskillit.server.tools_recipe import ( - list_recipes, - load_recipe, - migrate_recipe, - validate_recipe, -) +from autoskillit.server.tools_recipe import validate_recipe def _extract_docstring_sections(desc: str) -> dict[str, str]: @@ -51,7 +40,6 @@ def _extract_docstring_sections(desc: str) -> dict[str, str]: for line in lines: stripped = line.strip() matched_header = None - for pattern in header_patterns: m = pattern.match(stripped) if m: @@ -74,7 +62,7 @@ def _extract_docstring_sections(desc: str) -> dict[str, str]: # --------------------------------------------------------------------------- -# Minimal valid script YAML used across migration suggestion tests +# Minimal valid script YAML used in migration suggestion tests # --------------------------------------------------------------------------- _MINIMAL_SCRIPT_YAML = """\ @@ -104,369 +92,6 @@ def _extract_docstring_sections(desc: str) -> dict[str, str]: """ -def _write_minimal_script(scripts_dir: Path, name: str = "test-script") -> Path: - """Write a minimal valid workflow script with no autoskillit_version field.""" - scripts_dir.mkdir(parents=True, exist_ok=True) - path = scripts_dir / f"{name}.yaml" - path.write_text(_MINIMAL_SCRIPT_YAML) - return path - - -class TestRecipeTools: - """Tests for kitchen-gated list_recipes and load_recipe tools.""" - - @pytest.fixture(autouse=True) - def _ensure_ctx(self, tool_ctx): - """Ensure server context is initialized (gate open by default).""" - - # SS1 - @pytest.mark.anyio - @patch("autoskillit.recipe._api.list_recipes") - async def test_list_returns_json_object(self, mock_list): - """list_recipes returns JSON object with scripts array.""" - from autoskillit.core.types import LoadResult, RecipeSource - from autoskillit.recipe.schema import RecipeInfo - - mock_list.return_value = LoadResult( - items=[ - RecipeInfo( - name="impl", - description="Implement", - summary="plan > impl", - path=Path("/x"), - source=RecipeSource.PROJECT, - ), - ], - errors=[], - ) - result = json.loads(await list_recipes()) - assert isinstance(result, dict) - assert len(result["recipes"]) == 1 - assert result["recipes"][0]["name"] == "impl" - assert result["recipes"][0]["description"] == "Implement" - assert result["recipes"][0]["summary"] == "plan > impl" - assert "errors" not in result - - # SS2 - @pytest.mark.anyio - async def test_load_returns_json_with_content(self, tmp_path, monkeypatch): - """load_recipe returns JSON with content and suggestions.""" - monkeypatch.chdir(tmp_path) - recipes_dir = tmp_path / ".autoskillit" / "recipes" - recipes_dir.mkdir(parents=True) - (recipes_dir / "test.yaml").write_text("name: test\ndescription: Test recipe\n") - result = json.loads(await load_recipe(name="test")) - assert "content" in result - assert "suggestions" in result - assert "name: test" in result["content"] - assert "description: Test recipe" in result["content"] - - # SS3 - @pytest.mark.anyio - async def test_load_unknown_returns_error(self, tmp_path, monkeypatch): - """load_recipe returns error JSON for unknown recipe name.""" - monkeypatch.chdir(tmp_path) - result = json.loads(await load_recipe(name="nonexistent")) - assert "error" in result - assert "nonexistent" in result["error"] - - # SS4 - @pytest.mark.anyio - @patch("autoskillit.recipe._api.list_recipes") - async def test_list_reports_errors_in_response(self, mock_list): - """list_recipes includes errors in JSON when recipes fail to parse.""" - from autoskillit.core.types import LoadReport, LoadResult - - mock_list.return_value = LoadResult( - items=[], - errors=[LoadReport(path=Path("/recipes/broken.yaml"), error="bad yaml")], - ) - result = json.loads(await list_recipes()) - assert "errors" in result - assert len(result["errors"]) == 1 - assert result["errors"][0]["file"] == "broken.yaml" - assert "bad yaml" in result["errors"][0]["error"] - - # SS5 - @pytest.mark.anyio - async def test_list_integration_discovers_project_recipe(self, tmp_path, monkeypatch): - """Server tool returns project recipes alongside bundled recipes.""" - monkeypatch.chdir(tmp_path) - recipes_dir = tmp_path / ".autoskillit" / "recipes" - recipes_dir.mkdir(parents=True) - (recipes_dir / "pipeline.yaml").write_text( - "name: test-pipe\ndescription: Test\nsummary: a > b\n" - "steps:\n done:\n action: stop\n message: Done\n" - ) - result = json.loads(await list_recipes()) - names = {r["name"] for r in result["recipes"]} - assert "test-pipe" in names - - # SS6 - @pytest.mark.anyio - async def test_list_integration_reports_errors(self, tmp_path, monkeypatch): - """Server tool reports parse errors to the caller from real files.""" - monkeypatch.chdir(tmp_path) - recipes_dir = tmp_path / ".autoskillit" / "recipes" - recipes_dir.mkdir(parents=True) - (recipes_dir / "broken.yaml").write_text("[unclosed bracket\n") - result = json.loads(await list_recipes()) - assert "errors" in result - assert len(result["errors"]) == 1 - - # SS7 - @pytest.mark.anyio - async def test_load_returns_json_with_suggestions(self, tmp_path, monkeypatch): - """load_recipe response always has 'content' and 'suggestions' keys.""" - monkeypatch.chdir(tmp_path) - recipes_dir = tmp_path / ".autoskillit" / "recipes" - recipes_dir.mkdir(parents=True) - (recipes_dir / "test.yaml").write_text( - "name: test\ndescription: Test\nkitchen_rules:\n - test\n" - "steps:\n do:\n tool: test_check\n model: sonnet\n" - " on_success: done\n done:\n action: stop\n message: Done\n" - ) - result = json.loads(await load_recipe(name="test")) - assert "content" in result - assert "suggestions" in result - assert isinstance(result["suggestions"], list) - assert any(s["rule"] == "model-on-non-skill-step" for s in result["suggestions"]) - - # SS8 - @pytest.mark.anyio - async def test_list_recipes_includes_builtins_with_empty_project_dir( - self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - """list_recipes MCP returns bundled recipes when .autoskillit/recipes/ is absent.""" - monkeypatch.chdir(tmp_path) - # No .autoskillit/recipes/ created — simulates a fresh project with no local recipes - result = json.loads(await list_recipes()) - names = {r["name"] for r in result["recipes"]} - assert "implementation" in names - assert "remediation" in names - assert "smoke-test" in names - - # SS9 - @pytest.mark.anyio - async def test_load_recipe_mcp_returns_builtin_recipe( - self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - """load_recipe MCP finds bundled recipes when no project .autoskillit/recipes/ dir.""" - monkeypatch.chdir(tmp_path) - result = json.loads(await load_recipe(name="implementation")) - assert "error" not in result, f"Unexpected error: {result.get('error')}" - assert "content" in result - assert len(result["content"]) > 0 - - # SS10 - @pytest.mark.anyio - @patch("autoskillit.recipe._api.list_recipes") - async def test_list_recipes_response_includes_source_field(self, mock_list): - """list_recipes MCP response must include source field for each recipe entry.""" - from autoskillit.core.types import LoadResult, RecipeSource - from autoskillit.recipe.schema import RecipeInfo - - mock_list.return_value = LoadResult( - items=[ - RecipeInfo( - name="impl", - description="Implement", - source=RecipeSource.BUILTIN, - path=Path("/recipes/impl.yaml"), - ), - RecipeInfo( - name="my-recipe", - description="Custom", - source=RecipeSource.PROJECT, - path=Path("/project/my-recipe.yaml"), - ), - ], - errors=[], - ) - result = json.loads(await list_recipes()) - assert "source" in result["recipes"][0], ( - "MCP list_recipes response must include 'source' field" - ) - assert result["recipes"][0]["source"] == "builtin" - assert result["recipes"][1]["source"] == "project" - - @pytest.mark.anyio - async def test_load_recipe_parse_failure_is_logged_and_surfaced( - self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - """load_recipe emits a warning log and surfaces a validation-error finding.""" - monkeypatch.chdir(tmp_path) - recipes_dir = tmp_path / ".autoskillit" / "recipes" - recipes_dir.mkdir(parents=True) - # Recipe must have 'steps' so the run_semantic_rules code path is reached - (recipes_dir / "test.yaml").write_text( - "name: test\ndescription: Test\nsteps:\n done:\n action: stop\n message: Done\n" - ) - - with ( - patch( - "autoskillit.recipe._api.run_semantic_rules", - side_effect=ValueError("injected crash"), - ), - patch("autoskillit.recipe._api._logger") as mock_logger, - ): - result = json.loads(await load_recipe(name="test")) - - assert "content" in result, "load_recipe must be non-blocking even on parse failure" - mock_logger.warning.assert_called_once() - assert any(s.get("rule") == "validation-error" for s in result["suggestions"]), ( - "Unexpected exception must appear as a validation-error finding in suggestions" - ) - findings = [s for s in result["suggestions"] if s.get("rule") == "validation-error"] - assert findings, "Expected at least one validation-error finding" - assert findings[0]["message"] == "Invalid recipe structure: injected crash" - - -class TestContractMigrationAdapterValidate: - """P7-2: ContractMigrationAdapter.validate uses _load_yaml, not yaml.safe_load.""" - - def test_valid_contract_returns_true(self, tmp_path: Path) -> None: - from autoskillit.migration.engine import ContractMigrationAdapter - - f = tmp_path / "contract.yaml" - f.write_text("skill_hashes:\n my-skill: abc123\n") - adapter = ContractMigrationAdapter() - ok, msg = adapter.validate(f) - assert ok is True - assert msg == "" - - def test_missing_skill_hashes_returns_false(self, tmp_path: Path) -> None: - from autoskillit.migration.engine import ContractMigrationAdapter - - f = tmp_path / "contract.yaml" - f.write_text("other_field: value\n") - adapter = ContractMigrationAdapter() - ok, msg = adapter.validate(f) - assert ok is False - assert "skill_hashes" in msg - - def test_invalid_yaml_returns_false(self, tmp_path: Path) -> None: - from autoskillit.migration.engine import ContractMigrationAdapter - - f = tmp_path / "contract.yaml" - f.write_bytes(b":\tbad: yaml: [unclosed\n") - adapter = ContractMigrationAdapter() - ok, msg = adapter.validate(f) - assert ok is False - assert msg != "" - - def test_missing_file_returns_false(self, tmp_path: Path) -> None: - from autoskillit.migration.engine import ContractMigrationAdapter - - adapter = ContractMigrationAdapter() - ok, msg = adapter.validate(tmp_path / "nonexistent.yaml") - assert ok is False - assert msg != "" - - -class TestLoadRecipeExceptionHandling: - """CC-1: Outer except in load_recipe must catch anticipated exceptions only.""" - - @pytest.fixture(autouse=True) - def _setup_ctx(self, tool_ctx): - """Initialize ToolContext so load_recipe can call _get_config().""" - - @pytest.mark.anyio - async def test_yaml_error_surfaces_as_suggestion( - self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - """yaml.YAMLError is caught and returned as an error suggestion.""" - from autoskillit.core.io import YAMLError - - monkeypatch.chdir(tmp_path) - recipes_dir = tmp_path / ".autoskillit" / "recipes" - recipes_dir.mkdir(parents=True) - (recipes_dir / "test.yaml").write_text("name: test\n") - with patch("autoskillit.recipe._api.load_yaml", side_effect=YAMLError("bad yaml")): - result = json.loads(await load_recipe(name="test")) - assert "error" not in result - assert any( - s.get("rule") == "validation-error" and s.get("severity") == "error" - for s in result["suggestions"] - ) - - @pytest.mark.anyio - async def test_value_error_surfaces_as_suggestion( - self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - """ValueError (malformed recipe structure) is caught and returned as error suggestion.""" - from autoskillit.core.types import RecipeSource - from autoskillit.recipe.schema import RecipeInfo - - monkeypatch.chdir(tmp_path) - recipes_dir = tmp_path / ".autoskillit" / "recipes" - recipes_dir.mkdir(parents=True) - recipe_path = recipes_dir / "test.yaml" - recipe_path.write_text( - "name: test\ndescription: Test\nsteps:\n done:\n action: stop\n message: Done\n" - ) - fake_match = RecipeInfo( - name="test", - description="Test", - source=RecipeSource.PROJECT, - path=recipe_path, - ) - with ( - patch("autoskillit.recipe.find_recipe_by_name", return_value=fake_match), - patch( - "autoskillit.recipe._api._parse_recipe", side_effect=ValueError("bad structure") - ), - ): - result = json.loads(await load_recipe(name="test")) - assert "error" not in result - assert any( - s.get("rule") == "validation-error" and s.get("severity") == "error" - for s in result["suggestions"] - ) - - @pytest.mark.anyio - async def test_file_not_found_surfaces_as_suggestion( - self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - """FileNotFoundError is caught and returned as an error suggestion.""" - monkeypatch.chdir(tmp_path) - recipes_dir = tmp_path / ".autoskillit" / "recipes" - recipes_dir.mkdir(parents=True) - (recipes_dir / "test.yaml").write_text( - "name: test\ndescription: Test\nsteps:\n done:\n action: stop\n message: Done\n" - ) - with patch( - "autoskillit.recipe._api.load_recipe_card", - side_effect=FileNotFoundError("missing"), - ): - result = json.loads(await load_recipe(name="test")) - assert "error" not in result - assert any( - s.get("rule") == "validation-error" and s.get("severity") == "error" - for s in result["suggestions"] - ) - - @pytest.mark.anyio - async def test_unexpected_exception_returns_structured_error( - self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch - ) -> None: - """Unexpected exceptions are caught by the exception boundary.""" - monkeypatch.chdir(tmp_path) - recipes_dir = tmp_path / ".autoskillit" / "recipes" - recipes_dir.mkdir(parents=True) - (recipes_dir / "test.yaml").write_text( - "name: test\ndescription: Test\nsteps:\n done:\n action: stop\n message: Done\n" - ) - with patch( - "autoskillit.recipe._api.run_semantic_rules", - side_effect=AttributeError("programming error"), - ): - result = json.loads(await load_recipe(name="test")) - assert result["success"] is False - assert result["subtype"] == "tool_exception" - assert "programming error" in result["error"] - - class TestValidateRecipeTool: """Tests for kitchen-gated validate_recipe tool.""" @@ -620,6 +245,26 @@ async def test_validate_recipe_includes_semantic_findings(self, tmp_path): assert result["valid"] is True # Warning does not block validity +class TestMigrationSuggestions: + """MSUG2: validate_recipe surfaces migration warnings.""" + + @pytest.fixture(autouse=True) + def _ensure_ctx(self, tool_ctx): + """Ensure server context is initialized (gate open by default).""" + + # MSUG2 + @pytest.mark.anyio + async def test_validate_always_includes_outdated_version(self, tmp_path): + """MSUG2: validate_recipe always includes outdated-script-version in semantic results.""" + script = tmp_path / "test-script.yaml" + script.write_text(_MINIMAL_SCRIPT_YAML) + + result = json.loads(await validate_recipe(script_path=str(script))) + assert "findings" in result + rules = [s["rule"] for s in result["findings"]] + assert "outdated-recipe-version" in rules + + class TestDocstringSemantics: """Section-aware semantic checks for tool descriptions. @@ -634,16 +279,12 @@ async def _get_tools(self) -> dict: from autoskillit.server import mcp - try: - mcp.enable(tags={"kitchen"}) - async with Client(mcp) as client: - tools = await client.list_tools() - finally: - mcp.disable(tags={"kitchen"}) + async with Client(mcp) as client: + tools = await client.list_tools() return {t.name: t for t in tools} @pytest.mark.anyio - async def test_load_recipe_action_protocol_routes_through_skill(self): + async def test_load_recipe_action_protocol_routes_through_skill(self, kitchen_enabled): """After loading section must route modifications through write-recipe.""" tools = await self._get_tools() desc = tools["load_recipe"].description or "" @@ -658,7 +299,9 @@ async def test_load_recipe_action_protocol_routes_through_skill(self): ) @pytest.mark.anyio - async def test_load_recipe_after_loading_does_not_instruct_direct_modification(self): + async def test_load_recipe_after_loading_does_not_instruct_direct_modification( + self, kitchen_enabled + ): """After loading section must not instruct direct file modification.""" tools = await self._get_tools() desc = tools["load_recipe"].description or "" @@ -676,17 +319,15 @@ async def test_load_recipe_after_loading_does_not_instruct_direct_modification(s assert not found, f"After loading section instructs direct modification: {found}" @pytest.mark.anyio - async def test_validate_recipe_has_failure_routing(self): + async def test_validate_recipe_has_failure_routing(self, kitchen_enabled): """validate_recipe must route validation failures to write-recipe.""" tools = await self._get_tools() desc = tools["validate_recipe"].description or "" - # Must reference the failure return case assert "false" in desc.lower(), ( "validate_recipe must document the failure case (e.g. {valid: false})" ) - # Failure routing must direct to write-recipe for remediation desc_lower = desc.lower() has_remediation_context = any( phrase in desc_lower for phrase in ["fix", "remediat", "correct the"] @@ -696,27 +337,24 @@ async def test_validate_recipe_has_failure_routing(self): ) @pytest.mark.anyio - async def test_validate_recipe_does_not_endorse_direct_editing(self): + async def test_validate_recipe_does_not_endorse_direct_editing(self, kitchen_enabled): """validate_recipe must not normalize direct recipe editing.""" tools = await self._get_tools() desc = tools["validate_recipe"].description or "" - # "or editing a recipe" without qualifying through write-recipe - # normalizes the model directly editing YAML files assert "or editing a recipe" not in desc, ( "validate_recipe normalizes direct editing with 'or editing a recipe'; " "should qualify as going through write-recipe" ) @pytest.mark.anyio - async def test_tool_description_sections_are_not_contradictory(self): + async def test_tool_description_sections_are_not_contradictory(self, kitchen_enabled): """After loading must not instruct what the prohibition section prohibits.""" tools = await self._get_tools() desc = tools["load_recipe"].description or "" sections = _extract_docstring_sections(desc) after_loading = sections.get("after loading", "") - # Accept either old or new section header prohibition = sections.get("during pipeline execution", "") or sections.get( "never use native", "" ) @@ -725,8 +363,6 @@ async def test_tool_description_sections_are_not_contradictory(self): "Missing prohibition section (NEVER use native / During pipeline execution)" ) - # If the prohibition section says Edit/Write are prohibited or "not used here", - # then "After loading" must not instruct behaviors requiring file writing if "not used here" in prohibition.lower() or "prohibited" in prohibition.lower(): write_implying_phrases = ["apply them", "save changes", "save as"] found = [p for p in write_implying_phrases if p.lower() in after_loading.lower()] @@ -736,7 +372,7 @@ async def test_tool_description_sections_are_not_contradictory(self): ) @pytest.mark.anyio - async def test_load_recipe_has_preview_format_spec(self): + async def test_load_recipe_has_preview_format_spec(self, kitchen_enabled): """load_recipe must specify presentation format for loaded recipes.""" tools = await self._get_tools() desc = tools["load_recipe"].description or "" @@ -749,20 +385,18 @@ async def test_load_recipe_has_preview_format_spec(self): ) @pytest.mark.anyio - async def test_recipe_tool_descriptions_are_coherent(self): + async def test_recipe_tool_descriptions_are_coherent(self, kitchen_enabled): """Recipe tools must form a coherent policy about recipe modification.""" tools = await self._get_tools() failures = [] - # load_recipe: modifications must route through write-recipe load_desc = tools["load_recipe"].description or "" load_sections = _extract_docstring_sections(load_desc) after_loading = load_sections.get("after loading", "") if "apply them" in after_loading.lower(): failures.append("load_recipe 'After loading' instructs direct editing ('apply them')") - # validate_recipe: failure must route through write-recipe validate_desc = tools["validate_recipe"].description or "" validate_lower = validate_desc.lower() has_failure_routing = ( @@ -773,7 +407,6 @@ async def test_recipe_tool_descriptions_are_coherent(self): if not has_failure_routing: failures.append("validate_recipe has no failure routing through write-recipe") - # validate_recipe: must not normalize direct editing if "or editing a recipe" in validate_desc: failures.append("validate_recipe normalizes direct editing ('or editing a recipe')") @@ -791,16 +424,12 @@ async def _get_tools(self) -> dict: from autoskillit.server import mcp - try: - mcp.enable(tags={"kitchen"}) - async with Client(mcp) as client: - tools = await client.list_tools() - finally: - mcp.disable(tags={"kitchen"}) + async with Client(mcp) as client: + tools = await client.list_tools() return {t.name: t for t in tools} @pytest.mark.anyio - async def test_description_documents_run_skill_failure(self): + async def test_description_documents_run_skill_failure(self, kitchen_enabled): """The routing rules must define failure for run_skill, not just test_check.""" tools = await self._get_tools() desc = tools["load_recipe"].description or "" @@ -808,585 +437,11 @@ async def test_description_documents_run_skill_failure(self): assert "success" in desc.lower() -class TestMigrationSuggestions: - """MSUG2: validate_recipe surfaces migration warnings.""" - - @pytest.fixture(autouse=True) - def _ensure_ctx(self, tool_ctx): - """Ensure server context is initialized (gate open by default).""" - - # MSUG2 - @pytest.mark.anyio - async def test_validate_always_includes_outdated_version(self, tmp_path): - """MSUG2: validate_recipe always includes outdated-script-version in semantic results.""" - script = tmp_path / "test-script.yaml" - script.write_text(_MINIMAL_SCRIPT_YAML) - - result = json.loads(await validate_recipe(script_path=str(script))) - assert "findings" in result - rules = [s["rule"] for s in result["findings"]] - assert "outdated-recipe-version" in rules - - -class TestMigrationSuppression: - """SUP1, SUP4: load_recipe respects migration.suppressed config.""" - - # SUP1 - @pytest.mark.anyio - async def test_outdated_version_not_in_suggestions_when_suppressed( - self, tmp_path, monkeypatch, tool_ctx - ): - """SUP1: outdated-recipe-version absent when recipe is suppressed; headless not called.""" - from autoskillit.config import MigrationConfig - - monkeypatch.chdir(tmp_path) - scripts_dir = tmp_path / ".autoskillit" / "recipes" - _write_minimal_script(scripts_dir, "test-script") - - tool_ctx.config = AutomationConfig(migration=MigrationConfig(suppressed=["test-script"])) - - mock_headless = AsyncMock( - return_value=SkillResult( - success=True, - result="ok", - session_id="", - subtype="success", - is_error=False, - exit_code=0, - needs_retry=False, - retry_reason=RetryReason.NONE, - stderr="", - ) - ) - with patch("autoskillit.execution.headless.run_headless_core", mock_headless): - result = json.loads(await load_recipe(name="test-script")) - - assert "suggestions" in result - rules = [s["rule"] for s in result["suggestions"]] - assert "outdated-recipe-version" not in rules - mock_headless.assert_not_called() - - # SUP4 - @pytest.mark.anyio - async def test_validate_always_includes_outdated_version_regardless_of_suppression( - self, tmp_path, tool_ctx - ): - """SUP4: validate_recipe includes outdated-script-version even when suppressed.""" - from autoskillit.config import MigrationConfig - - script = tmp_path / "test-script.yaml" - script.write_text(_MINIMAL_SCRIPT_YAML) - - # Even with script suppressed in config, validate_recipe does not filter - tool_ctx.config = AutomationConfig(migration=MigrationConfig(suppressed=["test-script"])) - - result = json.loads(await validate_recipe(script_path=str(script))) - assert "findings" in result - rules = [s["rule"] for s in result["findings"]] - assert "outdated-recipe-version" in rules - - -class TestApplyTriageGate: - """T3: _apply_triage_gate caches triage result and skips on second call.""" - - @pytest.fixture(autouse=True) - def _close_kitchen(self, tool_ctx): - tool_ctx.gate = DefaultGateState(enabled=False) - - @pytest.mark.anyio - async def test_apply_triage_gate_second_call_skips_triage( - self, tmp_path, monkeypatch, tool_ctx - ): - """Second _apply_triage_gate call reads from cache; triage_staleness not re-invoked.""" - import copy - - from autoskillit.recipe.staleness_cache import read_staleness_cache - from autoskillit.server.helpers import _apply_triage_gate - - monkeypatch.chdir(tmp_path) - recipes_dir = tmp_path / ".autoskillit" / "recipes" - recipes_dir.mkdir(parents=True) - recipe_yaml = ( - "name: triage-test\ndescription: T\n" - "steps:\n done:\n action: stop\n message: Done\n" - ) - recipe_path = recipes_dir / "triage-test.yaml" - recipe_path.write_text(recipe_yaml) - - name = "triage-test" - result_template = { - "content": recipe_yaml, - "suggestions": [ - { - "rule": "stale-contract", - "reason": "hash_mismatch", - "skill": "investigate", - "stored_value": "sha256:old", - "current_value": "sha256:new", - "message": "investigate SKILL.md changed", - "severity": "info", - } - ], - "valid": True, - } - - # Get real recipe_info before mocking find - recipe_info = tool_ctx.recipes.find(name, Path.cwd()) - assert recipe_info is not None - - # Mock _ctx.recipes.find to verify it is NOT called when recipe_info is injected - mock_find = AsyncMock(return_value=recipe_info) - monkeypatch.setattr(tool_ctx.recipes, "find", mock_find) - - mock_triage = AsyncMock( - return_value=[{"meaningful": False, "summary": "ok", "skill": "investigate"}] - ) - with patch("autoskillit._llm_triage.triage_staleness", mock_triage): - # First call: triage_staleness invoked once - await _apply_triage_gate(copy.deepcopy(result_template), name, recipe_info=recipe_info) - - assert mock_triage.call_count == 1 - assert mock_find.call_count == 0, "find() must not be called when recipe_info is injected" - - cache_path = tmp_path / ".autoskillit" / "temp" / "recipe_staleness_cache.json" - cached = read_staleness_cache(cache_path, name) - assert cached is not None - assert cached.triage_result == "cosmetic" - - with patch("autoskillit._llm_triage.triage_staleness", mock_triage): - # Second call: must read from cache and skip triage_staleness entirely - await _apply_triage_gate(copy.deepcopy(result_template), name, recipe_info=recipe_info) - - assert mock_triage.call_count == 1, ( - "triage_staleness must not be called on second invocation" - ) - - -class TestLoadRecipeReadOnly: - """P4: load_recipe is strictly read-only — no migration, no contract card generation.""" - - @pytest.fixture(autouse=True) - def _ensure_ctx(self, tool_ctx): - """Ensure server context is initialized (gate open by default).""" - - @pytest.mark.anyio - async def test_load_recipe_does_not_call_migration_engine(self, tmp_path, monkeypatch): - """load_recipe must not trigger headless migration even when migrations are applicable.""" - monkeypatch.chdir(tmp_path) - with ( - patch("autoskillit.migration.loader.applicable_migrations", return_value=["v0.1.0"]), - patch("autoskillit.execution.headless.run_headless_core") as mock_headless, - patch("autoskillit.recipe.contracts.generate_recipe_card") as mock_gen, - ): - result = json.loads(await load_recipe(name="implementation")) - assert "error" not in result - mock_headless.assert_not_called() - mock_gen.assert_not_called() - - @pytest.mark.anyio - async def test_load_recipe_does_not_auto_generate_contract_card(self, tmp_path, monkeypatch): - """load_recipe must not call generate_recipe_card even when no card exists.""" - monkeypatch.chdir(tmp_path) - recipes_dir = tmp_path / ".autoskillit" / "recipes" - recipes_dir.mkdir(parents=True) - (recipes_dir / "test.yaml").write_text( - "name: test\ndescription: Test\nsteps:\n done:\n action: stop\n message: Done\n" - ) - with patch("autoskillit.recipe.contracts.generate_recipe_card") as mock_gen: - await load_recipe(name="test") - mock_gen.assert_not_called() - - -class TestMigrateRecipe: - """P4: migrate_recipe is a gated tool that runs migration engine and regenerates cards.""" - - @pytest.fixture(autouse=True) - def _open_kitchen(self, tool_ctx): - """migrate_recipe requires tool activation.""" - tool_ctx.gate = DefaultGateState(enabled=True) - - def _setup_migration_env( - self, - tmp_path, - monkeypatch, - tool_ctx, - *, - suppressed: list[str] | None = None, - ): - """Create directory structure, fake migration YAML, and config.""" - import autoskillit - import autoskillit.migration.loader as ml - from autoskillit.config import MigrationConfig - - monkeypatch.chdir(tmp_path) - recipes_dir = tmp_path / ".autoskillit" / "recipes" - recipes_dir.mkdir(parents=True) - recipe_path = recipes_dir / "test-script.yaml" - recipe_path.write_text(_MINIMAL_SCRIPT_YAML) - - installed_ver = autoskillit.__version__ - fake_mig_dir = tmp_path / "migrations" - fake_mig_dir.mkdir() - migration_yaml = ( - f"from_version: '0.0.0'\n" - f"to_version: '{installed_ver}'\n" - "description: Upgrade scripts\n" - "changes:\n" - " - id: add-summary-field\n" - " description: Scripts now require a summary field\n" - " instruction: Add summary field to your script\n" - ) - (fake_mig_dir / "0.0.0-migration.yaml").write_text(migration_yaml) - monkeypatch.setattr(ml, "_migrations_dir", lambda: fake_mig_dir) - - tool_ctx.config = AutomationConfig(migration=MigrationConfig(suppressed=suppressed or [])) - - temp_mig_dir = tmp_path / ".autoskillit" / "temp" / "migrations" - temp_mig_dir.mkdir(parents=True) - - migrated_content = _MINIMAL_SCRIPT_YAML + f"autoskillit_version: '{installed_ver}'\n" - return { - "recipe_path": recipe_path, - "temp_mig_dir": temp_mig_dir, - "migrated_content": migrated_content, - "installed_ver": installed_ver, - } - - def test_migrate_recipe_is_in_gated_tools(self): - """migrate_recipe is a gated tool.""" - assert "migrate_recipe" in GATED_TOOLS - - def test_migrate_recipe_not_in_ungated_tools(self): - """migrate_recipe is not an ungated tool.""" - assert "migrate_recipe" not in UNGATED_TOOLS - - @pytest.mark.anyio - async def test_migrate_recipe_requires_gate(self, tool_ctx): - """migrate_recipe returns gate_error when kitchen is closed.""" - tool_ctx.gate = DefaultGateState(enabled=False) - result = json.loads(await migrate_recipe(name="test")) - assert result["success"] is False - assert result["subtype"] == "gate_error" - - @pytest.mark.anyio - async def test_migrate_recipe_not_found(self, tmp_path, monkeypatch): - """migrate_recipe returns error for unknown recipe name.""" - monkeypatch.chdir(tmp_path) - result = json.loads(await migrate_recipe(name="nonexistent")) - assert "error" in result - assert "nonexistent" in result["error"] - - @pytest.mark.anyio - async def test_migrate_recipe_up_to_date(self, tmp_path, monkeypatch): # SRV-UPD-1 - """migrate_recipe returns up_to_date when no migrations applicable and contract fresh.""" - monkeypatch.chdir(tmp_path) - with ( - patch("autoskillit.migration.loader.applicable_migrations", return_value=[]), - patch("autoskillit.recipe.load_recipe_card", return_value={"skill_hashes": {}}), - patch("autoskillit.recipe.check_contract_staleness", return_value=[]), - ): - result = json.loads(await migrate_recipe(name="implementation")) - assert result.get("status") == "up_to_date" - - # LR1 - @pytest.mark.anyio - async def test_auto_migrates_outdated_recipe(self, tmp_path, monkeypatch, tool_ctx): - """LR1: When recipe version < installed, _run_headless_core is called once.""" - ctx = self._setup_migration_env(tmp_path, monkeypatch, tool_ctx) - (ctx["temp_mig_dir"] / "test-script.yaml").write_text(ctx["migrated_content"]) - - mock_headless = AsyncMock( - return_value=SkillResult( - success=True, - result="ok", - session_id="", - subtype="success", - is_error=False, - exit_code=0, - needs_retry=False, - retry_reason=RetryReason.NONE, - stderr="", - ) - ) - with ( - patch("autoskillit.execution.headless.run_headless_core", mock_headless), - patch("autoskillit.recipe.generate_recipe_card", return_value=None), - ): - result = json.loads(await migrate_recipe(name="test-script")) - - mock_headless.assert_awaited_once() - assert result.get("status") == "migrated" - assert "contracts_regenerated" in result - - # LR4 - @pytest.mark.anyio - async def test_clears_failure_record_after_successful_migration( - self, tmp_path, monkeypatch, tool_ctx - ): - """LR4: FailureStore.clear(name) is called when migration succeeds.""" - from autoskillit.migration.store import FailureStore, default_store_path - - ctx = self._setup_migration_env(tmp_path, monkeypatch, tool_ctx) - (ctx["temp_mig_dir"] / "test-script.yaml").write_text(ctx["migrated_content"]) - - store = FailureStore(default_store_path(tmp_path)) - store.record( - name="test-script", - file_path=ctx["recipe_path"], - file_type="recipe", - error="prior failure", - retries_attempted=1, - ) - assert store.has_failure("test-script") - - mock_headless = AsyncMock( - return_value=SkillResult( - success=True, - result="ok", - session_id="", - subtype="success", - is_error=False, - exit_code=0, - needs_retry=False, - retry_reason=RetryReason.NONE, - stderr="", - ) - ) - with ( - patch("autoskillit.execution.headless.run_headless_core", mock_headless), - patch("autoskillit.recipe.contracts.generate_recipe_card", return_value=None), - ): - await migrate_recipe(name="test-script") - - fresh_store = FailureStore(default_store_path(tmp_path)) - assert not fresh_store.has_failure("test-script") - - # LR5 - @pytest.mark.anyio - async def test_records_failure_when_migration_fails(self, tmp_path, monkeypatch, tool_ctx): - """LR5: When headless returns success=False, failure is recorded to failures.json.""" - from autoskillit.migration.store import FailureStore, default_store_path - - self._setup_migration_env(tmp_path, monkeypatch, tool_ctx) - - mock_headless = AsyncMock( - return_value=SkillResult( - success=False, - result="headless failed", - session_id="", - subtype="error", - is_error=True, - exit_code=1, - needs_retry=False, - retry_reason=RetryReason.NONE, - stderr="", - ) - ) - with patch("autoskillit.execution.headless.run_headless_core", mock_headless): - result = json.loads(await migrate_recipe(name="test-script")) - - assert "error" in result - store = FailureStore(default_store_path(tmp_path)) - assert store.has_failure("test-script") - - # LR7 - @pytest.mark.anyio - async def test_suppressed_recipe_not_migrated(self, tmp_path, monkeypatch, tool_ctx): - """LR7: When name in migration.suppressed, headless is never called.""" - self._setup_migration_env(tmp_path, monkeypatch, tool_ctx, suppressed=["test-script"]) - - mock_headless = AsyncMock( - return_value=SkillResult( - success=True, - result="ok", - session_id="", - subtype="success", - is_error=False, - exit_code=0, - needs_retry=False, - retry_reason=RetryReason.NONE, - stderr="", - ) - ) - with patch("autoskillit.execution.headless.run_headless_core", mock_headless): - result = json.loads(await migrate_recipe(name="test-script")) - - mock_headless.assert_not_called() - assert result.get("status") == "up_to_date" - - # LR8 - @pytest.mark.anyio - async def test_up_to_date_recipe_not_migrated(self, tmp_path, monkeypatch, tool_ctx): - """LR8: When applicable_migrations returns [], headless is never called.""" - import autoskillit - import autoskillit.migration.loader as ml - from autoskillit.config import MigrationConfig - - monkeypatch.chdir(tmp_path) - recipes_dir = tmp_path / ".autoskillit" / "recipes" - recipes_dir.mkdir(parents=True) - current_ver = autoskillit.__version__ - (recipes_dir / "test-script.yaml").write_text( - _MINIMAL_SCRIPT_YAML + f"autoskillit_version: '{current_ver}'\n" - ) - - empty_mig_dir = tmp_path / "migrations" - empty_mig_dir.mkdir() - monkeypatch.setattr(ml, "_migrations_dir", lambda: empty_mig_dir) - tool_ctx.config = AutomationConfig(migration=MigrationConfig(suppressed=[])) - - mock_headless = AsyncMock( - return_value=SkillResult( - success=True, - result="ok", - session_id="", - subtype="success", - is_error=False, - exit_code=0, - needs_retry=False, - retry_reason=RetryReason.NONE, - stderr="", - ) - ) - with ( - patch("autoskillit.execution.headless.run_headless_core", mock_headless), - patch("autoskillit.recipe.load_recipe_card", return_value={"skill_hashes": {}}), - patch("autoskillit.recipe.check_contract_staleness", return_value=[]), - ): - result = json.loads(await migrate_recipe(name="test-script")) - - mock_headless.assert_not_called() - assert result.get("status") == "up_to_date" - - # SRV-NEW-1 - @pytest.mark.anyio - async def test_migrate_recipe_regenerates_stale_contract( - self, tmp_path, monkeypatch, tool_ctx - ): - """migrate_recipe with version migration also regenerates stale contracts.""" - ctx = self._setup_migration_env(tmp_path, monkeypatch, tool_ctx) - (ctx["temp_mig_dir"] / "test-script.yaml").write_text(ctx["migrated_content"]) - - mock_headless = AsyncMock( - return_value=SkillResult( - success=True, - result="ok", - session_id="", - subtype="success", - is_error=False, - exit_code=0, - needs_retry=False, - retry_reason=RetryReason.NONE, - stderr="", - ) - ) - with ( - patch("autoskillit.execution.headless.run_headless_core", mock_headless), - patch("autoskillit.recipe.load_recipe_card", return_value=None), - patch("autoskillit.recipe.generate_recipe_card", return_value={}), - ): - result = json.loads(await migrate_recipe(name="test-script")) - - assert result.get("status") == "migrated" - assert result.get("contracts_regenerated") == ["test-script"] - - -# --------------------------------------------------------------------------- -# Diagram field tests (DG-12 through DG-15) -# --------------------------------------------------------------------------- - -_MINIMAL_RECIPE_FOR_DIAGRAM = """\ -name: my-recipe -description: Test recipe for diagram tests -summary: step1 -> done -ingredients: - task: - description: What to do - required: true -steps: - step1: - tool: run_skill - with: - skill_command: "/autoskillit:investigate ${{ inputs.task }}" - cwd: "." - on_success: done - on_failure: escalate - done: - action: stop - message: "Done." - escalate: - action: stop - message: "Failed." -kitchen_rules: - - "Use AutoSkillit tools only" -""" - - -class TestLoadRecipeDiagram: - """Tests for diagram field in load_recipe responses (DG-12 through DG-15).""" - - def _setup_project_recipe(self, tmp_path: Path, monkeypatch) -> Path: - monkeypatch.chdir(tmp_path) - recipes_dir = tmp_path / ".autoskillit" / "recipes" - recipes_dir.mkdir(parents=True) - recipe_path = recipes_dir / "my-recipe.yaml" - recipe_path.write_text(_MINIMAL_RECIPE_FOR_DIAGRAM) - return recipes_dir - - # DG-12 - @pytest.mark.anyio - async def test_load_recipe_response_has_diagram_key(self, tmp_path, monkeypatch, tool_ctx): - """DG-12: load_recipe response always contains a 'diagram' key.""" - self._setup_project_recipe(tmp_path, monkeypatch) - result = json.loads(await load_recipe(name="my-recipe")) - assert "diagram" in result - - # DG-13 - @pytest.mark.anyio - async def test_load_recipe_diagram_none_when_not_generated( - self, tmp_path, monkeypatch, tool_ctx - ): - """DG-13: diagram is None when no diagram file exists.""" - self._setup_project_recipe(tmp_path, monkeypatch) - result = json.loads(await load_recipe(name="my-recipe")) - assert result["diagram"] is None - - # --------------------------------------------------------------------------- -# P5F2: Accessor pattern tests (gated tools use _get_ctx_or_none after gate check) +# P5F2: Accessor pattern tests # --------------------------------------------------------------------------- -# P5F2-T1 -@pytest.mark.anyio -async def test_list_recipes_no_recipes_returns_empty(tool_ctx): - """list_recipes returns empty-list JSON when recipes is not configured.""" - tool_ctx.recipes = None - result = json.loads(await list_recipes()) - assert result == [] - - -# P5F2-T1b -@pytest.mark.anyio -async def test_list_recipes_gate_closed_returns_gate_error(tool_ctx): - """list_recipes returns gate_error JSON when kitchen gate is closed.""" - tool_ctx.gate = DefaultGateState(enabled=False) - result = json.loads(await list_recipes()) - assert result.get("success") is False - assert result.get("subtype") == "gate_error" - - -# P5F2-T2 -@pytest.mark.anyio -async def test_load_recipe_no_ctx_returns_error(monkeypatch): - """load_recipe returns error JSON when server is uninitialized.""" - import autoskillit.server._state as _state_mod - - monkeypatch.setattr(_state_mod, "_ctx", None) - result = json.loads(await load_recipe(name="anything")) - assert "error" in result - - # P5F2-T3 @pytest.mark.anyio async def test_validate_recipe_no_recipes_returns_error(tool_ctx, tmp_path): diff --git a/tests/server/test_tools_run_cmd_unit.py b/tests/server/test_tools_run_cmd_unit.py new file mode 100644 index 0000000000..66fe01126a --- /dev/null +++ b/tests/server/test_tools_run_cmd_unit.py @@ -0,0 +1,157 @@ +"""Unit tests for run_cmd: observability, timing, and headless gate enforcement.""" + +from __future__ import annotations + +import json +from unittest.mock import AsyncMock + +import pytest +import structlog.contextvars +import structlog.testing + +from autoskillit.server.tools_execution import run_cmd +from tests.conftest import _make_result + + +class TestRunCmdObservability: + """run_cmd binds structlog contextvars and calls ctx.info/ctx.error.""" + + @pytest.fixture + def mock_ctx(self): + ctx = AsyncMock() + ctx.info = AsyncMock() + ctx.error = AsyncMock() + return ctx + + @pytest.mark.anyio + async def test_run_cmd_binds_tool_contextvar_and_calls_ctx_info(self, tool_ctx, mock_ctx): + """run_cmd binds tool='run_cmd' contextvar and calls ctx.info on success.""" + tool_ctx.runner.push(_make_result(0, "ok\n", "")) + with structlog.testing.capture_logs( + processors=[structlog.contextvars.merge_contextvars] + ) as logs: + await run_cmd(cmd="echo ok", cwd="/tmp", ctx=mock_ctx) + assert any(entry.get("tool") == "run_cmd" for entry in logs) + + @pytest.mark.anyio + async def test_run_cmd_returns_failure_result_on_nonzero_exit(self, tool_ctx, mock_ctx): + """run_cmd reports failure (success=false) when subprocess exits non-zero.""" + tool_ctx.runner.push(_make_result(1, "", "err")) + result = json.loads(await run_cmd(cmd="false", cwd="/tmp", ctx=mock_ctx)) + assert result["success"] is False + assert result["exit_code"] == 1 + + +class TestRunCmdTiming: + """run_cmd accumulates wall-clock timing when step_name is provided.""" + + @pytest.mark.anyio + async def test_run_cmd_step_name_records_timing(self, tool_ctx): + await run_cmd(cmd="echo hi", cwd="/tmp", step_name="clone") + report = tool_ctx.timing_log.get_report() + assert len(report) == 1 + assert report[0]["step_name"] == "clone" + assert report[0]["total_seconds"] >= 0.0 + assert report[0]["invocation_count"] == 1 + + @pytest.mark.anyio + async def test_run_cmd_empty_step_name_skips_timing(self, tool_ctx): + await run_cmd(cmd="echo hi", cwd="/tmp") + assert tool_ctx.timing_log.get_report() == [] + + +class TestRunCmdRecording: + """run_cmd threads SCENARIO_STEP_NAME into env kwarg for RecordingSubprocessRunner.""" + + @pytest.mark.anyio + async def test_run_cmd_with_step_name_passes_scenario_step_name_to_runner(self, tool_ctx): + """run_cmd with step_name passes SCENARIO_STEP_NAME in env kwarg to ctx.runner.""" + from autoskillit.execution.recording import SCENARIO_STEP_NAME_ENV + + tool_ctx.runner.push(_make_result(0, "ok", "")) + await run_cmd(cmd="echo hi", cwd="/tmp", step_name="setup") + call_kwargs = tool_ctx.runner.call_args_list[-1][3] + assert call_kwargs.get("env", {}).get(SCENARIO_STEP_NAME_ENV) == "setup" + + @pytest.mark.anyio + async def test_run_cmd_with_step_name_preserves_parent_env(self, tool_ctx, monkeypatch): + """run_cmd with step_name must not strip PATH/HOME from the child env.""" + from autoskillit.execution.recording import SCENARIO_STEP_NAME_ENV + + monkeypatch.setenv("PATH", "/usr/bin:/usr/local/bin") + monkeypatch.setenv("HOME", "/home/testuser") + tool_ctx.runner.push(_make_result(0, "ok", "")) + await run_cmd(cmd="echo hi", cwd="/tmp", step_name="setup") + call_kwargs = tool_ctx.runner.call_args_list[-1][3] + env = call_kwargs["env"] + assert env is not None + assert "PATH" in env, "run_cmd stripped PATH from child environment" + assert "HOME" in env, "run_cmd stripped HOME from child environment" + assert env[SCENARIO_STEP_NAME_ENV] == "setup" + + @pytest.mark.anyio + async def test_run_cmd_without_step_name_passes_no_env(self, tool_ctx): + """run_cmd without step_name passes env=None (no SCENARIO_STEP_NAME in env).""" + from autoskillit.execution.recording import SCENARIO_STEP_NAME_ENV + + tool_ctx.runner.push(_make_result(0, "", "")) + await run_cmd(cmd="echo hi", cwd="/tmp") + call_kwargs = tool_ctx.runner.call_args_list[-1][3] + env = call_kwargs.get("env") + assert env is None or SCENARIO_STEP_NAME_ENV not in env + + @pytest.mark.anyio + async def test_run_cmd_with_step_name_records_non_session_step(self, tool_ctx, monkeypatch): + """End-to-end: run_cmd step_name → RecordingSubprocessRunner.record_non_session_step().""" + from unittest.mock import Mock + + from autoskillit.execution.recording import RecordingSubprocessRunner + from tests.conftest import MockSubprocessRunner + from tests.conftest import _make_result as _mr + + mock_recorder = Mock() + inner = MockSubprocessRunner() + inner.push(_mr(0, "task output", "")) + recording_runner = RecordingSubprocessRunner(recorder=mock_recorder, inner=inner) + tool_ctx.runner = recording_runner + + await run_cmd(cmd="task install-worktree", cwd="/tmp", step_name="setup") + + mock_recorder.record_non_session_step.assert_called_once_with( + step_name="setup", + tool="run_cmd", + result_summary={"exit_code": 0, "stdout_head": "task output"}, + ) + + @pytest.mark.anyio + async def test_run_cmd_without_step_name_skips_recording(self, tool_ctx, monkeypatch): + """run_cmd without step_name does not call record_non_session_step.""" + from unittest.mock import Mock + + from autoskillit.execution.recording import RecordingSubprocessRunner + from tests.conftest import MockSubprocessRunner + from tests.conftest import _make_result as _mr + + mock_recorder = Mock() + inner = MockSubprocessRunner() + inner.push(_mr(0, "", "")) + recording_runner = RecordingSubprocessRunner(recorder=mock_recorder, inner=inner) + tool_ctx.runner = recording_runner + + await run_cmd(cmd="echo hi", cwd="/tmp") + + mock_recorder.record_non_session_step.assert_not_called() + + +class TestRunCmdHeadlessGate: + """run_cmd returns headless_error when AUTOSKILLIT_HEADLESS=1.""" + + @pytest.fixture(autouse=True) + def _set_headless_env(self, monkeypatch): + monkeypatch.setenv("AUTOSKILLIT_HEADLESS", "1") + + @pytest.mark.anyio + async def test_run_cmd_blocked_in_headless_session(self, tool_ctx): + """run_cmd returns headless_error when AUTOSKILLIT_HEADLESS=1.""" + result = json.loads(await run_cmd("echo hello", "/tmp")) + assert result["subtype"] == "headless_error" diff --git a/tests/server/test_tools_run_python.py b/tests/server/test_tools_run_python.py new file mode 100644 index 0000000000..a3bace81c1 --- /dev/null +++ b/tests/server/test_tools_run_python.py @@ -0,0 +1,52 @@ +"""Unit tests for run_python: observability and headless gate enforcement.""" + +from __future__ import annotations + +import json +from unittest.mock import AsyncMock + +import pytest +import structlog.contextvars +import structlog.testing + +from autoskillit.server.tools_execution import run_python + + +class TestRunPythonObservability: + """run_python binds structlog contextvars and calls ctx.info/ctx.error.""" + + @pytest.fixture + def mock_ctx(self): + ctx = AsyncMock() + ctx.info = AsyncMock() + ctx.error = AsyncMock() + return ctx + + @pytest.mark.anyio + async def test_run_python_binds_tool_contextvar_and_calls_ctx_info(self, tool_ctx, mock_ctx): + """run_python binds tool='run_python' contextvar and calls ctx.info on success.""" + with structlog.testing.capture_logs( + processors=[structlog.contextvars.merge_contextvars] + ) as logs: + await run_python(callable="json.dumps", args={"obj": 1}, ctx=mock_ctx) + assert any(entry.get("tool") == "run_python" for entry in logs) + + @pytest.mark.anyio + async def test_run_python_returns_failure_result_on_bad_module(self, tool_ctx, mock_ctx): + """run_python reports failure (success=false) when callable import fails.""" + result = json.loads(await run_python(callable="nonexistent.module.func", ctx=mock_ctx)) + assert result["success"] is False + + +class TestRunPythonHeadlessGate: + """run_python returns headless_error when AUTOSKILLIT_HEADLESS=1.""" + + @pytest.fixture(autouse=True) + def _set_headless_env(self, monkeypatch): + monkeypatch.setenv("AUTOSKILLIT_HEADLESS", "1") + + @pytest.mark.anyio + async def test_run_python_blocked_in_headless_session(self, tool_ctx): + """run_python returns headless_error when AUTOSKILLIT_HEADLESS=1.""" + result = json.loads(await run_python("os.getcwd")) + assert result["subtype"] == "headless_error" diff --git a/tests/server/test_tools_run_skill_retry.py b/tests/server/test_tools_run_skill_retry.py index 78f26e725c..bf1c9babac 100644 --- a/tests/server/test_tools_run_skill_retry.py +++ b/tests/server/test_tools_run_skill_retry.py @@ -11,6 +11,19 @@ from autoskillit.server.tools_execution import run_skill from tests.conftest import _make_result +# Deterministic UUID for tests that need to predict the per-invocation marker. +_DETERMINISTIC_HEX = "a1b2c3d4e5f6a7b890123456" +_DETERMINISTIC_MARKER = f"%%ORDER_UP::{_DETERMINISTIC_HEX[:8]}%%" + + +class _FixedUUID: + hex = _DETERMINISTIC_HEX + + +def _patch_uuid4(monkeypatch): + """Monkeypatch uuid4 to return a deterministic value for marker prediction.""" + monkeypatch.setattr("uuid.uuid4", lambda: _FixedUUID()) + class TestRunSkillRetryRemoved: """run_skill_retry must not exist as a separate MCP tool.""" @@ -27,8 +40,10 @@ def test_run_skill_retry_not_in_all(self): """run_skill_retry is not in tools_execution.__all__ (if defined).""" import autoskillit.server.tools_execution as module - all_exports = getattr(module, "__all__", []) - assert "run_skill_retry" not in all_exports + # tools_execution does not define __all__; verify via direct attribute check + assert not hasattr(module, "run_skill_retry"), ( + "run_skill_retry should not be a public attribute of tools_execution" + ) class TestRunSkillSessionOutcome: @@ -47,7 +62,7 @@ async def test_detects_max_turns_via_subtype(self, tool_ctx): } ) tool_ctx.runner.push(_make_result(1, stdout, "")) - result = json.loads(await run_skill("/retry-worktree plan.md", "/tmp")) + result = json.loads(await run_skill("/investigate plan.md", "/tmp")) assert result["needs_retry"] is True assert result["retry_reason"] == RetryReason.RESUME @@ -64,13 +79,15 @@ async def test_detects_context_limit(self, tool_ctx): } ) tool_ctx.runner.push(_make_result(1, stdout, "")) - result = json.loads(await run_skill("/retry-worktree plan.md", "/tmp")) + result = json.loads(await run_skill("/investigate plan.md", "/tmp")) assert result["needs_retry"] is True assert result["retry_reason"] == RetryReason.RESUME @pytest.mark.anyio - async def test_success_not_retriable(self, tool_ctx): + async def test_success_not_retriable(self, tool_ctx, monkeypatch): """Normal success -> needs_retry=False.""" + _patch_uuid4(monkeypatch) + marker = _DETERMINISTIC_MARKER assistant = json.dumps( { "type": "assistant", @@ -82,13 +99,13 @@ async def test_success_not_retriable(self, tool_ctx): "type": "result", "subtype": "success", "is_error": False, - "result": "Done. %%ORDER_UP%%", + "result": f"Done. {marker}", "session_id": "s1", } ) stdout = assistant + "\n" + result_record tool_ctx.runner.push(_make_result(0, stdout, "")) - result = json.loads(await run_skill("/retry-worktree plan.md", "/tmp")) + result = json.loads(await run_skill("/investigate plan.md", "/tmp")) assert result["needs_retry"] is False assert result["retry_reason"] == RetryReason.NONE @@ -105,14 +122,14 @@ async def test_execution_error_not_retriable(self, tool_ctx): } ) tool_ctx.runner.push(_make_result(1, stdout, "")) - result = json.loads(await run_skill("/retry-worktree plan.md", "/tmp")) + result = json.loads(await run_skill("/investigate plan.md", "/tmp")) assert result["needs_retry"] is False @pytest.mark.anyio async def test_unparseable_stdout_not_retriable(self, tool_ctx): """Non-JSON stdout -> needs_retry=False.""" tool_ctx.runner.push(_make_result(1, "crash dump", "segfault")) - result = json.loads(await run_skill("/retry-worktree plan.md", "/tmp")) + result = json.loads(await run_skill("/investigate plan.md", "/tmp")) assert result["needs_retry"] is False @@ -149,7 +166,7 @@ async def test_normal_success_result_passes_through(self, tool_ctx): } ) tool_ctx.runner.push(_make_result(0, stdout, "")) - result = json.loads(await run_skill("/retry-worktree plan.md", "/tmp")) + result = json.loads(await run_skill("/investigate plan.md", "/tmp")) assert result["result"] == "Done." @@ -187,14 +204,16 @@ class TestRunSkillFields: """run_skill includes needs_retry and retry_reason.""" @pytest.mark.anyio - async def test_includes_needs_retry_false(self, tool_ctx): + async def test_includes_needs_retry_false(self, tool_ctx, monkeypatch): """run_skill response includes needs_retry=False on normal success.""" + _patch_uuid4(monkeypatch) + marker = _DETERMINISTIC_MARKER stdout = json.dumps( { "type": "result", "subtype": "success", "is_error": False, - "result": "Done. %%ORDER_UP%%", + "result": f"Done. {marker}", "session_id": "s1", } ) diff --git a/tests/server/test_tools_status.py b/tests/server/test_tools_status.py index 37dd02de0f..beb6d95e25 100644 --- a/tests/server/test_tools_status.py +++ b/tests/server/test_tools_status.py @@ -2,14 +2,16 @@ from __future__ import annotations +import asyncio import json from datetime import UTC, datetime from pathlib import Path +from unittest.mock import MagicMock import anyio import pytest -from autoskillit.config import AutomationConfig, TokenUsageConfig +from autoskillit.config import AutomationConfig, ReadDbConfig, TokenUsageConfig from autoskillit.core.types import ChannelConfirmation from autoskillit.execution.github import DefaultGitHubFetcher from autoskillit.pipeline.audit import FailureRecord @@ -21,6 +23,7 @@ get_timing_summary, get_token_summary, kitchen_status, + read_db, write_telemetry_files, ) from tests.conftest import _make_result @@ -192,6 +195,22 @@ async def test_clear_true_resets_after_returning(self, tool_ctx): result2 = json.loads(await get_pipeline_report()) assert result2["total_failures"] == 0 + @pytest.mark.anyio + async def test_get_pipeline_report_awaits_startup_ready(self, tool_ctx, monkeypatch): + """get_pipeline_report must await _startup_ready before accessing audit data.""" + import autoskillit.server._state as _state_mod + + ready = asyncio.Event() + monkeypatch.setattr(_state_mod, "_startup_ready", ready) + + task = asyncio.create_task(get_pipeline_report()) + await asyncio.sleep(0.05) + assert not task.done(), "get_pipeline_report returned before _startup_ready was set" + + ready.set() + await asyncio.sleep(0.05) + assert task.done(), "get_pipeline_report did not unblock after _startup_ready was set" + class TestGetTokenSummary: """get_token_summary is a gated tool that returns accumulated token usage.""" @@ -522,13 +541,13 @@ async def test_returns_events_from_jsonl(self, tool_ctx, tmp_path, monkeypatch): { "ts": "2026-03-10T10:00:00+00:00", "event": "approved", - "threshold": 90.0, + "threshold": 85.0, "utilization": 50.0, }, { "ts": "2026-03-10T11:00:00+00:00", "event": "blocked", - "threshold": 90.0, + "threshold": 85.0, "utilization": 92.5, }, ] @@ -983,3 +1002,241 @@ async def test_get_timing_summary_order_id_filter_isolates_issue( step_names = [s["step_name"] for s in result["steps"]] assert "plan" in step_names assert "implement" not in step_names + + +# --------------------------------------------------------------------------- +# TestReadDb — moved from test_tools_workspace.py (tools_status owns read_db) +# --------------------------------------------------------------------------- + + +@pytest.mark.usefixtures("tool_ctx") +class TestReadDb: + """Integration tests for read_db tool with real SQLite databases.""" + + @pytest.fixture + def sample_db(self, tmp_path): + """Create a sample SQLite database for testing.""" + import sqlite3 + + db = tmp_path / "test.db" + conn = sqlite3.connect(str(db)) + conn.execute("CREATE TABLE users (id INTEGER, name TEXT, age INTEGER)") + conn.execute("INSERT INTO users VALUES (1, 'Alice', 30)") + conn.execute("INSERT INTO users VALUES (2, 'Bob', 25)") + conn.execute("INSERT INTO users VALUES (3, 'Charlie', 35)") + conn.commit() + conn.close() + return db + + @pytest.mark.anyio + async def test_simple_select(self, sample_db): + result = json.loads(await read_db(db_path=str(sample_db), query="SELECT * FROM users")) + assert result["row_count"] == 3 + assert result["column_names"] == ["id", "name", "age"] + assert len(result["rows"]) == 3 + assert result["truncated"] is False + + @pytest.mark.anyio + async def test_parameterized_query(self, sample_db): + result = json.loads( + await read_db( + db_path=str(sample_db), + query="SELECT name FROM users WHERE age > ?", + params="[28]", + ) + ) + assert result["row_count"] == 2 + names = [r["name"] for r in result["rows"]] + assert "Alice" in names + assert "Charlie" in names + + @pytest.mark.anyio + async def test_named_params(self, sample_db): + result = json.loads( + await read_db( + db_path=str(sample_db), + query="SELECT name FROM users WHERE age = :age", + params='{"age": 25}', + ) + ) + assert result["row_count"] == 1 + assert result["rows"][0]["name"] == "Bob" + + @pytest.mark.anyio + async def test_empty_result(self, sample_db): + result = json.loads( + await read_db( + db_path=str(sample_db), + query="SELECT * FROM users WHERE age > 100", + ) + ) + assert result["row_count"] == 0 + assert result["rows"] == [] + assert result["column_names"] == ["id", "name", "age"] + + @pytest.mark.anyio + async def test_rejects_insert(self, sample_db): + result = json.loads( + await read_db( + db_path=str(sample_db), + query="INSERT INTO users VALUES (4, 'Dave', 40)", + ) + ) + assert "error" in result + err_lower = result["error"].lower() + assert "forbidden" in err_lower or "select" in err_lower or "not authorized" in err_lower + + @pytest.mark.anyio + async def test_rejects_drop(self, sample_db): + result = json.loads( + await read_db( + db_path=str(sample_db), + query="DROP TABLE users", + ) + ) + assert "error" in result + + @pytest.mark.anyio + async def test_rejects_attach(self, sample_db): + result = json.loads( + await read_db( + db_path=str(sample_db), + query="ATTACH DATABASE ':memory:' AS other", + ) + ) + assert "error" in result + + @pytest.mark.anyio + async def test_nonexistent_db(self, tmp_path): + result = json.loads( + await read_db( + db_path=str(tmp_path / "nonexistent.db"), + query="SELECT 1", + ) + ) + assert "error" in result + assert "does not exist" in result["error"] or "not found" in result["error"].lower() + + @pytest.mark.anyio + async def test_not_a_file(self, tmp_path): + result = json.loads( + await read_db( + db_path=str(tmp_path), + query="SELECT 1", + ) + ) + assert "error" in result + + @pytest.mark.anyio + async def test_invalid_params_json(self, sample_db): + result = json.loads( + await read_db( + db_path=str(sample_db), + query="SELECT * FROM users", + params="not json", + ) + ) + assert "error" in result + assert "params" in result["error"].lower() + + @pytest.mark.anyio + async def test_gated_when_disabled(self, sample_db, tool_ctx): + tool_ctx.gate = DefaultGateState(enabled=False) + result = json.loads( + await read_db( + db_path=str(sample_db), + query="SELECT 1", + ) + ) + assert result["success"] is False + assert result["is_error"] is True + assert "not enabled" in result["result"].lower() + + @pytest.mark.anyio + async def test_max_rows_truncation(self, sample_db, tool_ctx): + tool_ctx.config = AutomationConfig(read_db=ReadDbConfig(max_rows=2)) + result = json.loads( + await read_db( + db_path=str(sample_db), + query="SELECT * FROM users", + ) + ) + assert result["row_count"] == 2 + assert result["truncated"] is True + + @pytest.mark.anyio + async def test_blob_base64_encoding(self, tmp_path): + import base64 + import sqlite3 + + db = tmp_path / "blob.db" + conn = sqlite3.connect(str(db)) + conn.execute("CREATE TABLE data (id INTEGER, content BLOB)") + conn.execute("INSERT INTO data VALUES (1, ?)", (b"\x00\x01\x02\xff",)) + conn.commit() + conn.close() + result = json.loads( + await read_db( + db_path=str(db), + query="SELECT * FROM data", + ) + ) + assert base64.b64decode(result["rows"][0]["content"]) == b"\x00\x01\x02\xff" + + @pytest.mark.anyio + async def test_query_timeout(self, sample_db, tool_ctx): + tool_ctx.config = AutomationConfig(read_db=ReadDbConfig(timeout=1)) + # Cross join 3 rows^18 = ~387 million rows — guaranteed to exceed 1s timeout + slow_query = "SELECT count(*) FROM " + ", ".join(f"users t{i}" for i in range(18)) + result = json.loads( + await read_db( + db_path=str(sample_db), + query=slow_query, + ) + ) + assert "error" in result + assert "timeout" in result["error"].lower() + + @pytest.mark.anyio + async def test_sql_error_returns_error(self, sample_db): + result = json.loads( + await read_db( + db_path=str(sample_db), + query="SELECT nonexistent_column FROM users", + ) + ) + assert "error" in result + + +@pytest.mark.anyio +async def test_tools_status_routes_through_db_reader(tool_ctx, tmp_path) -> None: + """read_db routes through ctx.db_reader.query().""" + import sqlite3 as _sqlite3 + + tool_ctx.db_reader = MagicMock() + tool_ctx.db_reader.query.return_value = {"rows": [], "count": 0} + + db_path = str(tmp_path / "test.db") + # Create an empty sqlite db so path-exists check passes + _sqlite3.connect(db_path).close() + await read_db(db_path, "SELECT 1") + tool_ctx.db_reader.query.assert_called_once() + call_kwargs = tool_ctx.db_reader.query.call_args + assert "SELECT 1" in str(call_kwargs) + + +# T3 — read_db error paths include success: False +# --------------------------------------------------------------------------- + + +@pytest.mark.anyio +async def test_read_db_all_error_paths_include_success_false(tool_ctx, monkeypatch): + """Every read_db error path must return success=False.""" + from autoskillit.server import _state + + monkeypatch.setattr(_state, "_ctx", tool_ctx) + + # Nonexistent db path — exercises the "does not exist" error branch + result = json.loads(await read_db(db_path="/nonexistent/path/db.sqlite", query="SELECT 1")) + assert result.get("success") is False + assert "error" in result diff --git a/tests/server/test_tools_workspace.py b/tests/server/test_tools_workspace.py index 3c60779ecf..510528e262 100644 --- a/tests/server/test_tools_workspace.py +++ b/tests/server/test_tools_workspace.py @@ -4,18 +4,15 @@ import json import os -from unittest.mock import MagicMock import pytest from autoskillit.config import ( AutomationConfig, - ReadDbConfig, ResetWorkspaceConfig, SafetyConfig, ) from autoskillit.core.types import AUTOSKILLIT_PRIVATE_ENV_VARS -from autoskillit.server.tools_status import read_db from autoskillit.server.tools_workspace import reset_test_dir, reset_workspace, test_check from autoskillit.workspace import CleanupResult from tests.conftest import _make_result @@ -388,224 +385,6 @@ def test_default_classify_fix_empty_prefixes(self): assert cfg.classify_fix.path_prefixes == [] -@pytest.mark.usefixtures("tool_ctx") -class TestReadDb: - """Integration tests for read_db tool with real SQLite databases.""" - - @pytest.fixture - def sample_db(self, tmp_path): - """Create a sample SQLite database for testing.""" - import sqlite3 - - db = tmp_path / "test.db" - conn = sqlite3.connect(str(db)) - conn.execute("CREATE TABLE users (id INTEGER, name TEXT, age INTEGER)") - conn.execute("INSERT INTO users VALUES (1, 'Alice', 30)") - conn.execute("INSERT INTO users VALUES (2, 'Bob', 25)") - conn.execute("INSERT INTO users VALUES (3, 'Charlie', 35)") - conn.commit() - conn.close() - return db - - @pytest.mark.anyio - async def test_simple_select(self, sample_db): - result = json.loads(await read_db(db_path=str(sample_db), query="SELECT * FROM users")) - assert result["row_count"] == 3 - assert result["column_names"] == ["id", "name", "age"] - assert len(result["rows"]) == 3 - assert result["truncated"] is False - - @pytest.mark.anyio - async def test_parameterized_query(self, sample_db): - result = json.loads( - await read_db( - db_path=str(sample_db), - query="SELECT name FROM users WHERE age > ?", - params="[28]", - ) - ) - assert result["row_count"] == 2 - names = [r["name"] for r in result["rows"]] - assert "Alice" in names - assert "Charlie" in names - - @pytest.mark.anyio - async def test_named_params(self, sample_db): - result = json.loads( - await read_db( - db_path=str(sample_db), - query="SELECT name FROM users WHERE age = :age", - params='{"age": 25}', - ) - ) - assert result["row_count"] == 1 - assert result["rows"][0]["name"] == "Bob" - - @pytest.mark.anyio - async def test_empty_result(self, sample_db): - result = json.loads( - await read_db( - db_path=str(sample_db), - query="SELECT * FROM users WHERE age > 100", - ) - ) - assert result["row_count"] == 0 - assert result["rows"] == [] - assert result["column_names"] == ["id", "name", "age"] - - @pytest.mark.anyio - async def test_rejects_insert(self, sample_db): - result = json.loads( - await read_db( - db_path=str(sample_db), - query="INSERT INTO users VALUES (4, 'Dave', 40)", - ) - ) - assert "error" in result - err_lower = result["error"].lower() - assert "forbidden" in err_lower or "select" in err_lower or "not authorized" in err_lower - - @pytest.mark.anyio - async def test_rejects_drop(self, sample_db): - result = json.loads( - await read_db( - db_path=str(sample_db), - query="DROP TABLE users", - ) - ) - assert "error" in result - - @pytest.mark.anyio - async def test_rejects_attach(self, sample_db): - result = json.loads( - await read_db( - db_path=str(sample_db), - query="ATTACH DATABASE ':memory:' AS other", - ) - ) - assert "error" in result - - @pytest.mark.anyio - async def test_nonexistent_db(self, tmp_path): - result = json.loads( - await read_db( - db_path=str(tmp_path / "nonexistent.db"), - query="SELECT 1", - ) - ) - assert "error" in result - assert "does not exist" in result["error"] or "not found" in result["error"].lower() - - @pytest.mark.anyio - async def test_not_a_file(self, tmp_path): - result = json.loads( - await read_db( - db_path=str(tmp_path), - query="SELECT 1", - ) - ) - assert "error" in result - - @pytest.mark.anyio - async def test_invalid_params_json(self, sample_db): - result = json.loads( - await read_db( - db_path=str(sample_db), - query="SELECT * FROM users", - params="not json", - ) - ) - assert "error" in result - assert "params" in result["error"].lower() - - @pytest.mark.anyio - async def test_gated_when_disabled(self, sample_db, tool_ctx): - from autoskillit.pipeline.gate import DefaultGateState - - tool_ctx.gate = DefaultGateState(enabled=False) - result = json.loads( - await read_db( - db_path=str(sample_db), - query="SELECT 1", - ) - ) - assert result["success"] is False - assert result["is_error"] is True - assert "not enabled" in result["result"].lower() - - @pytest.mark.anyio - async def test_max_rows_truncation(self, sample_db, tool_ctx): - tool_ctx.config = AutomationConfig(read_db=ReadDbConfig(max_rows=2)) - result = json.loads( - await read_db( - db_path=str(sample_db), - query="SELECT * FROM users", - ) - ) - assert result["row_count"] == 2 - assert result["truncated"] is True - - @pytest.mark.anyio - async def test_blob_base64_encoding(self, tmp_path): - import base64 - import sqlite3 - - db = tmp_path / "blob.db" - conn = sqlite3.connect(str(db)) - conn.execute("CREATE TABLE data (id INTEGER, content BLOB)") - conn.execute("INSERT INTO data VALUES (1, ?)", (b"\x00\x01\x02\xff",)) - conn.commit() - conn.close() - result = json.loads( - await read_db( - db_path=str(db), - query="SELECT * FROM data", - ) - ) - assert base64.b64decode(result["rows"][0]["content"]) == b"\x00\x01\x02\xff" - - @pytest.mark.anyio - async def test_query_timeout(self, sample_db, tool_ctx): - tool_ctx.config = AutomationConfig(read_db=ReadDbConfig(timeout=1)) - # Cross join 3 rows^18 = ~387 million rows — guaranteed to exceed 1s timeout - slow_query = "SELECT count(*) FROM " + ", ".join(f"users t{i}" for i in range(18)) - result = json.loads( - await read_db( - db_path=str(sample_db), - query=slow_query, - ) - ) - assert "error" in result - assert "timeout" in result["error"].lower() - - @pytest.mark.anyio - async def test_sql_error_returns_error(self, sample_db): - result = json.loads( - await read_db( - db_path=str(sample_db), - query="SELECT nonexistent_column FROM users", - ) - ) - assert "error" in result - - -@pytest.mark.anyio -async def test_tools_status_routes_through_db_reader(tool_ctx, tmp_path) -> None: - """read_db routes through ctx.db_reader.query().""" - import sqlite3 as _sqlite3 - - tool_ctx.db_reader = MagicMock() - tool_ctx.db_reader.query.return_value = {"rows": [], "count": 0} - - db_path = str(tmp_path / "test.db") - # Create an empty sqlite db so path-exists check passes - _sqlite3.connect(db_path).close() - await read_db(db_path, "SELECT 1") - tool_ctx.db_reader.query.assert_called_once() - call_kwargs = tool_ctx.db_reader.query.call_args - assert "SELECT 1" in str(call_kwargs) - - @pytest.mark.anyio async def test_reset_test_dir_returns_partial_failure_json(tool_ctx, tmp_path): """reset_test_dir returns structured JSON on partial failure.""" diff --git a/tests/server/test_track_response_size.py b/tests/server/test_track_response_size.py index ac162710d9..3e670e711f 100644 --- a/tests/server/test_track_response_size.py +++ b/tests/server/test_track_response_size.py @@ -92,3 +92,40 @@ async def bad_handler(): assert data["success"] is False assert "ValueError: something went wrong" in data["error"] assert data["subtype"] == "tool_exception" + + @pytest.mark.anyio + async def test_track_response_size_exception_envelope_includes_user_visible_message(self): + """Exception envelope includes non-empty user_visible_message with tool name.""" + from autoskillit.server.helpers import track_response_size + + @track_response_size("open_kitchen") + async def bad_handler(): + raise RuntimeError("boom") + + with patch("autoskillit.server.helpers._get_ctx_or_none", return_value=None): + result = await bad_handler() + + data = json.loads(result) + assert "user_visible_message" in data + assert isinstance(data["user_visible_message"], str) + assert len(data["user_visible_message"]) > 0 + assert "An internal error occurred in open_kitchen" in data["user_visible_message"] + + @pytest.mark.anyio + async def test_track_response_size_exception_envelope_preserves_existing_fields(self): + """Regression guard: success, error, exit_code, subtype keys still present.""" + from autoskillit.server.helpers import track_response_size + + @track_response_size("test_tool") + async def bad_handler(): + raise ValueError("fail") + + with patch("autoskillit.server.helpers._get_ctx_or_none", return_value=None): + result = await bad_handler() + + data = json.loads(result) + assert data["success"] is False + assert "ValueError: fail" in data["error"] + assert data["exit_code"] == -1 + assert data["subtype"] == "tool_exception" + assert "user_visible_message" in data diff --git a/tests/skills/test_arch_lens_context_path.py b/tests/skills/test_arch_lens_context_path.py new file mode 100644 index 0000000000..b636d8bd97 --- /dev/null +++ b/tests/skills/test_arch_lens_context_path.py @@ -0,0 +1,44 @@ +"""Tests that all arch-lens skills have an ## Arguments section and context_path handling.""" + +from pathlib import Path + +import pytest + +SKILLS_DIR = Path(__file__).parents[2] / "src/autoskillit/skills_extended" +ARCH_LENS_SLUGS = [ + "c4-container", + "concurrency", + "data-lineage", + "deployment", + "development", + "error-resilience", + "module-dependency", + "operational", + "process-flow", + "repository-access", + "scenarios", + "security", + "state-lifecycle", +] + + +@pytest.mark.parametrize("slug", ARCH_LENS_SLUGS) +def test_arch_lens_has_arguments_section(slug): + path = SKILLS_DIR / f"arch-lens-{slug}/SKILL.md" + assert path.exists(), f"arch-lens-{slug}/SKILL.md missing" + text = path.read_text() + assert "## Arguments" in text, f"arch-lens-{slug} missing ## Arguments section" + + +@pytest.mark.parametrize("slug", ARCH_LENS_SLUGS) +def test_arch_lens_documents_context_path_arg(slug): + path = SKILLS_DIR / f"arch-lens-{slug}/SKILL.md" + text = path.read_text() + assert "context_path" in text, f"arch-lens-{slug} must document context_path argument" + + +@pytest.mark.parametrize("slug", ARCH_LENS_SLUGS) +def test_arch_lens_has_step_0_for_context(slug): + path = SKILLS_DIR / f"arch-lens-{slug}/SKILL.md" + text = path.read_text() + assert "Step 0" in text, f"arch-lens-{slug} must have Step 0 for context reading" diff --git a/tests/skills/test_audit_arch_selfvalidation_contracts.py b/tests/skills/test_audit_arch_selfvalidation_contracts.py index ee27efc165..e7f3c05462 100644 --- a/tests/skills/test_audit_arch_selfvalidation_contracts.py +++ b/tests/skills/test_audit_arch_selfvalidation_contracts.py @@ -12,8 +12,8 @@ def test_selfvalidation_pass_section_exists(): ) -def test_selfvalidation_precedes_write_report(): - """T-AA-012: Self-Validation Pass appears before 'Write report'.""" +def test_selfvalidation_precedes_generate_report(): + """T-AA-012: Self-Validation Pass appears before 'Write report' step.""" text = SKILL_MD.read_text() selfval_idx = text.index("Self-Validation Pass") report_idx = text.index("**Write report**") diff --git a/tests/skills/test_conflict_resolution_guards.py b/tests/skills/test_conflict_resolution_guards.py index f0183d9921..8a8ab9ce51 100644 --- a/tests/skills/test_conflict_resolution_guards.py +++ b/tests/skills/test_conflict_resolution_guards.py @@ -329,12 +329,12 @@ def test_open_integration_pr_embeds_conflict_resolution_decisions(): ) -def test_open_pr_embeds_conflict_resolution_decisions(): - """open-pr SKILL.md must embed Conflict Resolution Decisions section.""" - skill_md_path = SKILLS_ROOT / "open-pr" / "SKILL.md" +def test_compose_pr_embeds_conflict_resolution_decisions(): + """compose-pr SKILL.md must embed Conflict Resolution Decisions section.""" + skill_md_path = SKILLS_ROOT / "compose-pr" / "SKILL.md" text = skill_md_path.read_text() assert "Conflict Resolution Decisions" in text, ( - "open-pr/SKILL.md must describe embedding a " + "compose-pr/SKILL.md must describe embedding a " "'Conflict Resolution Decisions' section per REQ-PIP-003" ) @@ -379,6 +379,54 @@ def test_resolve_merge_conflicts_remote_variable_is_defined(skill_md: str) -> No ) +def test_resolve_merge_conflicts_has_manifest_validation_step(skill_md: str) -> None: + """SKILL.md must document language-aware manifest validation after pre-commit (Step 5a).""" + assert "cargo metadata" in skill_md or "manifest validation" in skill_md.lower(), ( + "resolve-merge-conflicts SKILL.md must include language-aware manifest validation " + "(Step 5a) covering at minimum 'cargo metadata --no-deps' for Rust projects" + ) + assert "Step 5a" in skill_md, "Manifest validation must be documented as Step 5a in SKILL.md" + + +def test_resolve_merge_conflicts_has_duplicate_key_scan(skill_md: str) -> None: + """SKILL.md must document duplicate key scanning in TOML/JSON manifests (Step 5b).""" + assert "Step 5b" in skill_md, ( + "Duplicate key scanning must be documented as Step 5b in SKILL.md" + ) + assert "duplicate" in skill_md.lower(), ( + "SKILL.md must use the word 'duplicate' to describe the key scan" + ) + + +def test_resolve_merge_conflicts_manifest_failure_escalates(skill_md: str) -> None: + """SKILL.md must escalate (not auto-fix) when manifest validation fails.""" + step_5a_idx = skill_md.find("Step 5a") + step_5b_idx = skill_md.find("Step 5b", step_5a_idx) + step_5a_section = ( + skill_md[step_5a_idx:step_5b_idx] if step_5b_idx != -1 else skill_md[step_5a_idx:] + ) + assert "escalation_required" in step_5a_section, ( + "Step 5a must escalate (emit escalation_required=true) on manifest validation failure; " + "auto-fixing broken manifests is out of scope for this skill" + ) + + +def test_resolve_merge_conflicts_manifest_validation_covers_rust(skill_md: str) -> None: + """SKILL.md manifest validation must cover Rust (cargo metadata --no-deps).""" + assert "cargo metadata" in skill_md, ( + "resolve-merge-conflicts Step 5a must include 'cargo metadata --no-deps' " + "as the Rust manifest validation command — this is a fast parse-only check (<1s)" + ) + + +def test_resolve_merge_conflicts_manifest_validation_covers_python(skill_md: str) -> None: + """SKILL.md manifest validation must cover Python (tomllib or uv lock --check).""" + assert "tomllib" in skill_md or "uv lock --check" in skill_md, ( + "resolve-merge-conflicts Step 5a must include Python manifest validation " + "via tomllib.load() or 'uv lock --check'" + ) + + def test_resolve_merge_conflicts_no_hardcoded_origin(skill_md: str) -> None: """SKILL.md must not use literal 'origin' as remote in git fetch/rebase/show/log/rev-parse.""" bash_blocks = re.findall(r"```bash\s*\n(.*?)```", skill_md, re.DOTALL) diff --git a/tests/skills/test_investigate_contracts.py b/tests/skills/test_investigate_contracts.py new file mode 100644 index 0000000000..d66393a7fb --- /dev/null +++ b/tests/skills/test_investigate_contracts.py @@ -0,0 +1,209 @@ +"""Structural contracts for the investigate historical recurrence check step. + +Validates that investigate/SKILL.md carries the required instructions +for Step 3.5: Historical Recurrence Check — the JSONL log mining, git +history scan, and conditional analysis between Step 3 (Synthesize) and +Step 4 (Write Report). +""" + +import pytest + +from autoskillit.core.paths import pkg_root + + +@pytest.fixture(scope="module") +def skill_text() -> str: + skill_path = pkg_root() / "skills_extended" / "investigate" / "SKILL.md" + assert skill_path.exists(), f"SKILL.md not found at {skill_path}" + return skill_path.read_text() + + +@pytest.fixture(scope="module") +def step_35_section(skill_text: str) -> str: + """Extract only the Step 3.5 section text.""" + step_35_idx = skill_text.find("Step 3.5") + if step_35_idx == -1: + pytest.fail("Step 3.5 not found in investigate SKILL.md") + step_4_idx = skill_text.find("### Step 4", step_35_idx) + if step_4_idx != -1: + return skill_text[step_35_idx:step_4_idx] + return skill_text[step_35_idx:] + + +@pytest.fixture(scope="module") +def report_section(skill_text: str) -> str: + """Extract the Step 4: Write Report section text. + + Uses the next top-level ``## `` heading that is NOT inside a fenced + code block as the boundary. The report template contains ``## `` + headings inside a markdown code fence (```markdown ... ```) which must + be included — so we skip ``## `` occurrences between fence markers. + """ + step_4_idx = skill_text.find("### Step 4:") + if step_4_idx == -1: + pytest.fail("Step 4 not found in investigate SKILL.md") + in_fence = False + lines = skill_text[step_4_idx:].split("\n") + for i, line in enumerate(lines): + if i == 0: + continue + if line.startswith("```"): + in_fence = not in_fence + continue + if not in_fence and line.startswith("## ") and not line.startswith("### "): + end_idx = step_4_idx + sum(len(prev) + 1 for prev in lines[:i]) + return skill_text[step_4_idx:end_idx] + return skill_text[step_4_idx:] + + +def test_investigate_has_historical_recurrence_step(skill_text: str) -> None: + """investigate must contain a Step 3.5: Historical Recurrence Check section.""" + assert "Step 3.5" in skill_text, ( + "investigate SKILL.md must contain a 'Step 3.5: Historical Recurrence Check' " + "section inserted between Step 3 (Synthesize Findings) and Step 4 (Write Report)" + ) + + +def test_investigate_historical_step_positioned_after_step3(skill_text: str) -> None: + """Step 3.5 must appear after Step 3 and before Step 4.""" + step_3_idx = skill_text.find("### Step 3:") + step_35_idx = skill_text.find("Step 3.5") + step_4_idx = skill_text.find("### Step 4:") + assert step_3_idx != -1, "Step 3 heading ('### Step 3:') not found in investigate SKILL.md" + assert step_35_idx != -1, "Step 3.5 heading ('Step 3.5') not found in investigate SKILL.md" + assert step_4_idx != -1, "Step 4 heading ('### Step 4:') not found in investigate SKILL.md" + assert step_3_idx < step_35_idx < step_4_idx, ( + "Step 3.5 must be positioned after Step 3 and before Step 4 in investigate SKILL.md" + ) + + +def test_investigate_historical_step_mines_jsonl_logs(step_35_section: str) -> None: + """Step 3.5 must instruct mining ~/.claude/projects/ JSONL logs.""" + assert ".claude/projects/" in step_35_section, ( + "Step 3.5 must reference '.claude/projects/' as the source directory for " + "prior Claude Code conversation logs containing /investigate invocations" + ) + assert ".jsonl" in step_35_section or "JSONL" in step_35_section, ( + "Step 3.5 must reference '.jsonl' or 'JSONL' as the log file format to scan" + ) + + +def test_investigate_historical_step_searches_prior_invocations(step_35_section: str) -> None: + """Step 3.5 must search for prior /investigate or skill invocations.""" + has_skill_grep = "investigate" in step_35_section.lower() + has_grep_pattern = "grep" in step_35_section.lower() + assert has_skill_grep and has_grep_pattern, ( + "Step 3.5 must instruct grep-based scanning for prior /investigate invocations " + "in the JSONL logs" + ) + + +def test_investigate_historical_step_uses_git_log(step_35_section: str) -> None: + """Step 3.5 must use git log to find prior fix commits.""" + assert "git log" in step_35_section, ( + "Step 3.5 must use 'git log' to scan recent commit history for prior fix commits " + "that touched the affected components" + ) + + +def test_investigate_historical_step_checks_fix_keywords(step_35_section: str) -> None: + """Step 3.5 must scan for fix and revert commit keywords.""" + has_keywords = "fix" in step_35_section.lower() and "revert" in step_35_section.lower() + assert has_keywords, ( + "Step 3.5 must list 'fix' and 'revert' as commit message keywords to scan for " + "when detecting prior fixes (expected in git --grep pattern or keyword list)" + ) + + +def test_investigate_historical_step_scoped_to_recent_history(step_35_section: str) -> None: + """Step 3.5 must scope git scan to bounded recent history.""" + has_depth_limit = ( + "-100" in step_35_section + or "--since" in step_35_section + or "100 commit" in step_35_section.lower() + ) + assert has_depth_limit, ( + "Step 3.5 must scope the git log scan to a bounded recent history " + "(e.g., last 100 commits or --since ) — unbounded all-history " + "scanning is too expensive for a lightweight recurrence check" + ) + + +def test_investigate_historical_step_conditional_subagent(step_35_section: str) -> None: + """Step 3.5 must conditionally spawn a subagent only when history is found.""" + has_conditional = "if" in step_35_section.lower() and ( + "found" in step_35_section.lower() or "match" in step_35_section.lower() + ) + has_subagent = "subagent" in step_35_section.lower() or "Task" in step_35_section + assert has_conditional and has_subagent, ( + "Step 3.5 must conditionally spawn a subagent only when prior history is found — " + "first-occurrence bugs must have a zero-overhead fast path" + ) + + +def test_investigate_historical_step_no_history_fast_path(step_35_section: str) -> None: + """Step 3.5 must have a fast path when no history is found (no subagent calls).""" + assert "no prior" in step_35_section.lower() or "no history" in step_35_section.lower(), ( + "Step 3.5 must explicitly describe the no-history fast path ('No prior " + "investigations...' or equivalent) so the skill records a single-line result " + "without spawning an analysis subagent" + ) + + +def test_investigate_report_template_has_historical_context(report_section: str) -> None: + """Step 4 report template must include a ## Historical Context section.""" + assert "Historical Context" in report_section, ( + "Step 4 report template must include a '## Historical Context' section populated " + "by the Step 3.5 analysis" + ) + + +def test_investigate_historical_context_after_similar_patterns(report_section: str) -> None: + """Historical Context must appear after Similar Patterns in the report template.""" + similar_idx = report_section.find("Similar Patterns") + historical_idx = report_section.find("Historical Context") + assert similar_idx != -1, "'Similar Patterns' section not found in Step 4 report template" + assert historical_idx != -1, "'Historical Context' section not found in Step 4 report template" + assert similar_idx < historical_idx, ( + "'Historical Context' must be positioned after 'Similar Patterns' in the " + "report template ordering" + ) + + +def test_investigate_historical_step_flags_rectify(step_35_section: str) -> None: + """Step 3.5 must flag /autoskillit:rectify when patterns are recurring.""" + assert "rectify" in step_35_section.lower(), ( + "Step 3.5 must reference '/autoskillit:rectify' as the follow-up remediation " + "path when prior fixes are insufficient and the root cause is recurring" + ) + + +def test_investigate_synthesize_includes_historical_context(skill_text: str) -> None: + """Step 3 synthesis list must include Historical Context as a finding item.""" + step_3_idx = skill_text.find("### Step 3:") + step_35_idx = skill_text.find("Step 3.5") + assert step_3_idx != -1, "Step 3 heading ('### Step 3:') not found in investigate SKILL.md" + assert step_35_idx != -1, "Step 3.5 heading ('Step 3.5') not found in investigate SKILL.md" + step_3_text = skill_text[step_3_idx:step_35_idx] + assert "Historical Context" in step_3_text, ( + "Step 3 synthesis numbered list must include 'Historical Context' as a finding " + "item so the report template sections are aligned with the synthesized findings" + ) + + +def test_investigate_historical_step_excludes_subagent_dirs(step_35_section: str) -> None: + """Step 3.5 must exclude subagent log subdirectories from JSONL scanning.""" + assert "subagent" in step_35_section.lower(), ( + "Step 3.5 must explicitly exclude subagent log subdirectories (e.g., " + "'*/subagents/*') when scanning JSONL logs — otherwise the scan double-counts " + "results from every prior subagent conversation" + ) + + +def test_investigate_historical_step_reads_prior_diffs(step_35_section: str) -> None: + """Step 3.5 analysis subagent must read prior fix diffs via git show.""" + assert "git show" in step_35_section or "git log -p" in step_35_section, ( + "Step 3.5 Part C analysis subagent must read prior fix diffs via 'git show' " + "or 'git log -p' so it can compare the prior fix approach against the current " + "root cause" + ) diff --git a/tests/skills/test_open_pr_closing_issue.py b/tests/skills/test_open_pr_closing_issue.py deleted file mode 100644 index d127c7752a..0000000000 --- a/tests/skills/test_open_pr_closing_issue.py +++ /dev/null @@ -1,62 +0,0 @@ -"""Tests for open-pr skill SKILL.md content assertions.""" - -from pathlib import Path - -SKILL_PATH = ( - Path(__file__).parent.parent.parent - / "src" - / "autoskillit" - / "skills_extended" - / "open-pr" - / "SKILL.md" -) - - -def test_closing_issue_arg_documented(): - """SKILL.md must document closing_issue as the 5th positional argument.""" - content = SKILL_PATH.read_text() - assert "closing_issue" in content - - -def test_closes_n_footer_documented(): - """SKILL.md must document insertion of 'Closes #' in the PR body.""" - content = SKILL_PATH.read_text() - assert "Closes #" in content - - -def test_closing_issue_is_optional(): - """SKILL.md must describe closing_issue as optional.""" - content = SKILL_PATH.read_text() - # Both the argument signature and the optional description - assert "optional" in content.lower() or "[closing_issue]" in content - - -def test_step5_marker_check_present(): - """Step 5 must instruct the agent to check for ★ or ● in each mermaid block.""" - content = SKILL_PATH.read_text() - assert "validated_diagrams" in content - # Both marker characters must be mentioned in the check instruction - assert "★" in content - assert "●" in content - - -def test_step5_discard_path_documented(): - """Step 5 must explicitly state that diagrams with no markers are discarded.""" - content = SKILL_PATH.read_text() - assert "discard" in content.lower() - - -def test_step6_conditional_section_present(): - """Step 6 must gate the Architecture Impact section on validated_diagrams being non-empty.""" - content = SKILL_PATH.read_text() - # The conditional gate language must appear in Step 6 - assert "validated_diagrams is non-empty" in content or ( - "validated_diagrams" in content and "non-empty" in content - ) - assert "omit" in content.lower() - - -def test_step4_lens_count_constraint_preserved(): - """Step 4 must still instruct the subagent to return 1–3 lenses.""" - content = SKILL_PATH.read_text() - assert "1–3" in content or "1-3" in content diff --git a/tests/skills/test_open_research_pr_decomposition.py b/tests/skills/test_open_research_pr_decomposition.py new file mode 100644 index 0000000000..f8a4aeca0b --- /dev/null +++ b/tests/skills/test_open_research_pr_decomposition.py @@ -0,0 +1,88 @@ +"""Structural guards: decomposed research-PR skills must not invoke sub-skills +via the Skill tool (that's the root cause of the 100% failure rate).""" + +from __future__ import annotations + +import pytest + +from autoskillit.core.paths import pkg_root + +_SKILLS_ROOT = pkg_root() / "skills_extended" + + +def _read_skill(name: str) -> str: + path = _SKILLS_ROOT / name / "SKILL.md" + assert path.exists(), f"SKILL.md not found for {name!r}" + return path.read_text() + + +def test_prepare_research_pr_has_no_skill_tool_sub_invocations(): + """prepare-research-pr must never invoke sub-skills via the Skill tool.""" + content = _read_skill("prepare-research-pr") + # The skill should NOT instruct the model to use the Skill tool for lens skills. + # It uses Agent subagents for analysis, NOT Skill tool for exp-lens. + assert "Skill tool" not in content, ( + "prepare-research-pr must never reference the Skill tool — " + "this recreates the end_turn termination bug" + ) + + +def test_compose_research_pr_has_no_skill_tool_sub_invocations(): + """compose-research-pr must never invoke sub-skills via the Skill tool.""" + content = _read_skill("compose-research-pr") + assert "Skill tool" not in content, ( + "compose-research-pr must never reference the Skill tool — " + "this recreates the end_turn termination bug" + ) + + +def test_prepare_research_pr_skill_exists(): + """prepare-research-pr SKILL.md must exist after decomposition.""" + path = _SKILLS_ROOT / "prepare-research-pr" / "SKILL.md" + assert path.exists() + + +def test_compose_research_pr_skill_exists(): + """compose-research-pr SKILL.md must exist after decomposition.""" + path = _SKILLS_ROOT / "compose-research-pr" / "SKILL.md" + assert path.exists() + + +def test_open_research_pr_skill_retired(): + """open-research-pr must be removed — it has been retired.""" + path = _SKILLS_ROOT / "open-research-pr" / "SKILL.md" + assert not path.exists(), ( + "open-research-pr/SKILL.md still exists — remove it once new skills are in place" + ) + + +@pytest.mark.parametrize( + "slug", + [ + "fair-comparison", + "estimand-clarity", + "causal-assumptions", + "comparator-construction", + "pipeline-integrity", + "variance-stability", + "reproducibility-artifacts", + "measurement-validity", + "sensitivity-robustness", + "benchmark-representativeness", + "unit-interference", + "error-budget", + "severity-testing", + "randomization-blocking", + "validity-threats", + "iterative-learning", + "exploratory-confirmatory", + "governance-risk", + ], +) +def test_exp_lens_skill_has_arguments_section(slug: str): + """Every exp-lens SKILL.md must have an ## Arguments section.""" + content = _read_skill(f"exp-lens-{slug}") + assert "## Arguments" in content, ( + f"exp-lens-{slug}/SKILL.md is missing ## Arguments section — " + "run_experiment_lenses passes context_path and experiment_plan_path positionally" + ) diff --git a/tests/skills/test_plan_experiment_schema_contracts.py b/tests/skills/test_plan_experiment_schema_contracts.py new file mode 100644 index 0000000000..654e0005f8 --- /dev/null +++ b/tests/skills/test_plan_experiment_schema_contracts.py @@ -0,0 +1,99 @@ +"""Contract tests: plan-experiment YAML frontmatter schema and revision_guidance argument.""" + +from pathlib import Path + + +def _repo_root() -> Path: + return Path(__file__).parent.parent.parent + + +def _read_skill_md(skill_name: str) -> str: + for rel_dir in ("skills_extended", "skills"): + path = _repo_root() / "src/autoskillit" / rel_dir / skill_name / "SKILL.md" + if path.exists(): + return path.read_text() + raise FileNotFoundError(f"SKILL.md not found for skill: {skill_name}") + + +def test_plan_experiment_accepts_revision_guidance_arg(): + """plan-experiment/SKILL.md documents revision_guidance as second optional positional arg.""" + content = _read_skill_md("plan-experiment") + assert "[{revision_guidance}]" in content, ( + "plan-experiment/SKILL.md must document 'revision_guidance' as an optional second " + "positional arg in usage line '[{revision_guidance}]', with path-scanning semantics" + ) + + +def test_plan_experiment_documents_frontmatter_delimiters(): + """plan-experiment/SKILL.md must use the word 'frontmatter' to describe the output format.""" + content = _read_skill_md("plan-experiment") + assert "frontmatter" in content.lower(), ( + "plan-experiment/SKILL.md must reference 'frontmatter' to describe the YAML " + "block written before '# Experiment Plan:' — checking for '---' alone is " + "non-discriminating because the skill's own YAML metadata header already " + "contains '---' delimiters" + ) + + +def test_plan_experiment_documents_all_required_frontmatter_fields(): + """plan-experiment/SKILL.md must reference all required schema fields.""" + content = _read_skill_md("plan-experiment") + required_fields = [ + "experiment_type", + "hypothesis_h0", + "hypothesis_h1", + "metrics", + "statistical_plan", + "success_criteria", + "environment", + "baselines", + ] + for field in required_fields: + assert field in content, ( + f"plan-experiment/SKILL.md missing required frontmatter field: {field!r}" + ) + + +def test_plan_experiment_defines_all_validation_rules(): + """plan-experiment/SKILL.md must define all 8 validation rules V1–V8 as labeled entries.""" + content = _read_skill_md("plan-experiment") + for rule_id in ["V1", "V2", "V3", "V4", "V5", "V6", "V7", "V8"]: + assert f"{rule_id}:" in content, ( + f"plan-experiment/SKILL.md missing validation rule label {rule_id!r} " + f"(expected '{rule_id}:' definition format)" + ) + + +def test_plan_experiment_frontmatter_before_heading(): + """plan-experiment/SKILL.md must specify frontmatter goes before # Experiment Plan: heading.""" + content = _read_skill_md("plan-experiment") + assert "BEFORE the # Experiment Plan" in content, ( + "plan-experiment/SKILL.md must contain the explicit ordering instruction " + "'BEFORE the # Experiment Plan' to specify frontmatter precedes the heading" + ) + + +def test_research_recipe_passes_revision_guidance_to_plan_experiment(): + """research.yaml plan_experiment step must pass context.revision_guidance.""" + recipe_path = _repo_root() / "src/autoskillit/recipes/research.yaml" + content = recipe_path.read_text() + assert "revision_guidance" in content, ( + "research.yaml must pass context.revision_guidance in the plan_experiment step " + "skill_command so revision passes receive the feedback file path" + ) + + +def test_skill_contracts_plan_experiment_has_revision_guidance_input(): + """skill_contracts.yaml must register revision_guidance as optional (required: false) input.""" + import yaml + + contracts_path = _repo_root() / "src/autoskillit/recipe/skill_contracts.yaml" + raw = yaml.safe_load(contracts_path.read_text()) + pe = raw.get("skills", {}).get("plan-experiment", {}) + inputs = {inp["name"]: inp for inp in pe.get("inputs", [])} + assert "revision_guidance" in inputs, ( + "skill_contracts.yaml plan-experiment must declare 'revision_guidance' input" + ) + assert inputs["revision_guidance"].get("required") is False, ( + "skill_contracts.yaml plan-experiment 'revision_guidance' input must have required: false" + ) diff --git a/tests/skills/test_project_local_audit_skill_content.py b/tests/skills/test_project_local_audit_skill_content.py new file mode 100644 index 0000000000..bab9052074 --- /dev/null +++ b/tests/skills/test_project_local_audit_skill_content.py @@ -0,0 +1,248 @@ +"""Tests for project-local audit skill content. + +Verifies that .claude/skills/audit-arch, audit-cohesion, audit-tests, and validate-audit +have the required frontmatter, temp path placeholders, exception whitelists, and quality +mechanisms documented in issue #723. +""" + +import re +from pathlib import Path + +import pytest +import yaml + +REPO_ROOT = Path(__file__).resolve().parents[2] +SKILLS_DIR = REPO_ROOT / ".claude" / "skills" + + +def _read_skill(skill_name: str) -> str: + path = SKILLS_DIR / skill_name / "SKILL.md" + return path.read_text(encoding="utf-8") + + +def _parse_frontmatter(content: str) -> dict: + """Extract and parse YAML frontmatter from a markdown file.""" + if not content.startswith("---"): + return {} + try: + end = content.index("---", 3) + except ValueError as exc: + raise ValueError("Unclosed frontmatter delimiter in SKILL.md content") from exc + fm_text = content[3:end].strip() + return yaml.safe_load(fm_text) or {} + + +# --------------------------------------------------------------------------- +# Test 1: categories: [audit] in frontmatter +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("skill_name", ["audit-arch", "audit-cohesion", "audit-tests"]) +def test_project_local_audit_skills_have_audit_category(skill_name: str) -> None: + content = _read_skill(skill_name) + fm = _parse_frontmatter(content) + assert "categories" in fm, f"{skill_name}/SKILL.md frontmatter missing 'categories'" + assert isinstance(fm["categories"], list), f"{skill_name}/SKILL.md 'categories' must be a list" + assert "audit" in fm["categories"], ( + f"{skill_name}/SKILL.md 'categories' must contain 'audit', got: {fm['categories']}" + ) + + +# --------------------------------------------------------------------------- +# Test 2: {{AUTOSKILLIT_TEMP}} placeholder — no literal temp/audit- paths +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("skill_name", ["audit-arch", "audit-cohesion", "audit-tests"]) +def test_project_local_audit_skills_use_autoskillit_temp_placeholder(skill_name: str) -> None: + content = _read_skill(skill_name) + + # Strip fenced code blocks so we don't false-positive on examples + stripped = re.sub(r"```.*?```", "", content, flags=re.DOTALL) + + # Must not contain literal temp/audit- path + literal_pattern = f"temp/{skill_name}/" + assert literal_pattern not in stripped, ( + f"{skill_name}/SKILL.md still contains literal '{literal_pattern}' " + f"outside fenced blocks — replace with {{{{AUTOSKILLIT_TEMP}}}}/{skill_name}/" + ) + + # Must contain the placeholder form at least once + placeholder = "{{AUTOSKILLIT_TEMP}}" + assert placeholder in content, ( + f"{skill_name}/SKILL.md does not contain '{placeholder}' — " + f"add {{{{AUTOSKILLIT_TEMP}}}}/{skill_name}/ to the report path" + ) + + +# --------------------------------------------------------------------------- +# Test 3: P12 composition-boundary tiers +# --------------------------------------------------------------------------- + + +def test_audit_arch_p12_has_composition_boundary_tiers() -> None: + content = _read_skill("audit-arch") + assert "Intra-package Default*" in content, ( + "audit-arch/SKILL.md P12 missing 'Intra-package Default*' tier marker" + ) + assert "L3 CLI" in content, "audit-arch/SKILL.md P12 missing 'L3 CLI' tier marker" + assert "DI convenience default" in content, ( + "audit-arch/SKILL.md P12 missing 'DI convenience default' tier marker" + ) + + +# --------------------------------------------------------------------------- +# Test 4: General Exception IDs GE-1..GE-17 in audit-arch +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("ge_id", ["GE-1", "GE-2", "GE-7", "GE-9", "GE-13", "GE-16", "GE-17"]) +def test_audit_arch_general_exceptions_present(ge_id: str) -> None: + content = _read_skill("audit-arch") + assert re.search(r"\*\*" + re.escape(ge_id) + r"\*\*", content), ( + f"audit-arch/SKILL.md missing exception ID '{ge_id}' in Exception Whitelist" + ) + + +# --------------------------------------------------------------------------- +# Test 5: Project-Specific Exception IDs PS-1..PS-8 in audit-arch +# --------------------------------------------------------------------------- + + +# PS-3/5/6 are cohesion-specific; tested in test_audit_cohesion_general_exceptions_present +@pytest.mark.parametrize("ps_id", ["PS-1", "PS-2", "PS-4", "PS-7", "PS-8"]) +def test_audit_arch_project_specific_exceptions_present(ps_id: str) -> None: + content = _read_skill("audit-arch") + assert ps_id in content, f"audit-arch/SKILL.md missing project-specific exception '{ps_id}'" + + +# --------------------------------------------------------------------------- +# Test 6: Pre-Flight Verification Checklist heading + five row labels +# --------------------------------------------------------------------------- + + +def test_audit_arch_has_pre_flight_checklist() -> None: + content = _read_skill("audit-arch") + assert "Pre-Flight Verification Checklist" in content, ( + "audit-arch/SKILL.md missing heading 'Pre-Flight Verification Checklist'" + ) + for row_label in [ + "Missing export", + "Missing decorator", + "Enforcement gap", + "Code duplication", + "Misplaced file", + ]: + assert row_label in content, ( + f"audit-arch/SKILL.md Pre-Flight Checklist missing row label '{row_label}'" + ) + + +# --------------------------------------------------------------------------- +# Test 7: Self-Validation Pass + four sub-checks +# --------------------------------------------------------------------------- + + +def test_audit_arch_has_self_validation_pass() -> None: + content = _read_skill("audit-arch") + assert "Self-Validation Pass" in content, ( + "audit-arch/SKILL.md missing 'Self-Validation Pass' section" + ) + assert "HIGH/CRITICAL re-read" in content, ( + "audit-arch/SKILL.md Self-Validation Pass missing 'HIGH/CRITICAL re-read' sub-check" + ) + assert "Concrete-class check" in content, ( + "audit-arch/SKILL.md Self-Validation Pass missing 'Concrete-class check' sub-check" + ) + assert "Enforcement-search confirmation" in content, ( + "audit-arch/SKILL.md Self-Validation Pass missing 'Enforcement-search confirmation'" + ) + # Either CONFIRMED or REVISED must appear (internal validation note markers) + assert "CONFIRMED" in content or "REVISED" in content, ( + "audit-arch/SKILL.md Self-Validation Pass missing 'CONFIRMED' or 'REVISED' note marker" + ) + + +# --------------------------------------------------------------------------- +# Test 8: Principle Suggestion constraints +# --------------------------------------------------------------------------- + + +def test_audit_arch_principle_suggestion_constraints() -> None: + content = _read_skill("audit-arch") + assert "ONE dedicated subagent" in content, ( + "audit-arch/SKILL.md Principle Suggestion missing 'ONE dedicated subagent' constraint" + ) + assert "At most ONE" in content, ( + "audit-arch/SKILL.md Principle Suggestion missing 'at most ONE' constraint" + ) + assert "MUST NOT generate findings" in content, ( + "audit-arch/SKILL.md Principle Suggestion missing 'MUST NOT generate findings' constraint" + ) + assert "MUST NOT be enforced" in content, ( + "audit-arch/SKILL.md Principle Suggestion missing 'MUST NOT be enforced' constraint" + ) + assert "MUST NOT invent or enforce principles" in content, ( + "audit-arch/SKILL.md per-principle subagent instructions missing " + "'MUST NOT invent or enforce principles' phrase" + ) + + +# --------------------------------------------------------------------------- +# Test 9: Cohesion exception IDs + C10 file-verification rule +# --------------------------------------------------------------------------- + + +def test_audit_cohesion_general_exceptions_present() -> None: + content = _read_skill("audit-cohesion") + for ge_id in ["GE-10", "GE-11", "GE-12", "GE-13", "GE-15"]: + assert ge_id in content, f"audit-cohesion/SKILL.md missing exception ID '{ge_id}'" + for ps_id in ["PS-3", "PS-5", "PS-6"]: + assert ps_id in content, ( + f"audit-cohesion/SKILL.md missing project-specific exception '{ps_id}'" + ) + assert "read the actual file at the cited path" in content, ( + "audit-cohesion/SKILL.md missing C10 file-verification rule phrase " + "'read the actual file at the cited path'" + ) + + +# --------------------------------------------------------------------------- +# Test 10: validate-audit project-local override exists with required content +# --------------------------------------------------------------------------- + + +def test_validate_audit_project_local_override_exists() -> None: + path = SKILLS_DIR / "validate-audit" / "SKILL.md" + assert path.exists(), ".claude/skills/validate-audit/SKILL.md does not exist" + content = path.read_text(encoding="utf-8") + fm = _parse_frontmatter(content) + assert "categories" in fm, "validate-audit/SKILL.md frontmatter missing 'categories'" + assert "audit" in fm.get("categories", []), ( + "validate-audit/SKILL.md 'categories' must contain 'audit'" + ) + assert "Known Project Exceptions" in content, ( + "validate-audit/SKILL.md missing '## Known Project Exceptions' section" + ) + for ps_id in [f"PS-{i}" for i in range(1, 9)]: + assert ps_id in content, ( + f"validate-audit/SKILL.md Known Project Exceptions table missing '{ps_id}'" + ) + + +# --------------------------------------------------------------------------- +# Test 11: validate-audit uses {{AUTOSKILLIT_TEMP}} placeholder +# --------------------------------------------------------------------------- + + +def test_validate_audit_uses_autoskillit_temp_placeholder() -> None: + path = SKILLS_DIR / "validate-audit" / "SKILL.md" + assert path.exists(), ".claude/skills/validate-audit/SKILL.md does not exist" + content = path.read_text(encoding="utf-8") + stripped = re.sub(r"```.*?```", "", content, flags=re.DOTALL) + assert "temp/validate-audit/" not in stripped, ( + "validate-audit/SKILL.md contains literal 'temp/validate-audit/' outside fenced blocks" + ) + assert "{{AUTOSKILLIT_TEMP}}" in content, ( + "validate-audit/SKILL.md does not contain '{{AUTOSKILLIT_TEMP}}' placeholder" + ) diff --git a/tests/skills/test_resolve_claims_review_guards.py b/tests/skills/test_resolve_claims_review_guards.py new file mode 100644 index 0000000000..58cca4eded --- /dev/null +++ b/tests/skills/test_resolve_claims_review_guards.py @@ -0,0 +1,91 @@ +"""Behavioral guards for resolve-claims-review/SKILL.md. + +Tests enforce fix-strategy taxonomy, protocol deviation and invalid statistics +classification rules, and needs_rerun structured output contract. +""" + +from pathlib import Path + +SKILL_PATH = ( + Path(__file__).parent.parent.parent + / "src" + / "autoskillit" + / "skills_extended" + / "resolve-claims-review" + / "SKILL.md" +) +SKILL_TEXT = SKILL_PATH.read_text() if SKILL_PATH.exists() else "" + + +def test_skill_path_exists() -> None: + """SKILL.md must exist at the expected path.""" + assert SKILL_PATH.exists(), f"SKILL.md not found at {SKILL_PATH}" + + +def test_fix_strategies_defined() -> None: + """All five fix strategies must be defined.""" + for strategy in [ + "add_citation", + "qualify_claim", + "remove_claim", + "rerun_required", + "design_flaw", + ]: + assert strategy in SKILL_TEXT, f"SKILL.md must define fix strategy '{strategy}'" + + +def test_protocol_deviation_rule_present() -> None: + """SKILL.md must contain a protocol deviation classification rule mapping to rerun_required.""" + text = SKILL_TEXT.lower() + assert "protocol deviation" in text, ( + "SKILL.md must define a protocol deviation classification rule" + ) + pd_idx = text.find("protocol deviation") + context = SKILL_TEXT[pd_idx : pd_idx + 600] + assert "rerun_required" in context, ( + "Protocol deviation rule must map to rerun_required strategy" + ) + + +def test_invalid_statistics_rule_present() -> None: + """SKILL.md must contain an invalid statistics rule mapping to rerun_required.""" + text = SKILL_TEXT.lower() + assert "wrong unit of analysis" in text or "invalid statistic" in text, ( + "SKILL.md must define an invalid statistics classification rule" + ) + for needle in ["wrong unit of analysis", "invalid statistic"]: + idx = text.find(needle) + if idx != -1: + context = SKILL_TEXT[idx : idx + 600] + assert "rerun_required" in context, ( + "Invalid statistics rule must map to rerun_required strategy" + ) + break + + +def test_protocol_deviation_allows_justified_exception() -> None: + """Protocol deviation rule must allow justified exceptions (not blanket rerun).""" + text = SKILL_TEXT.lower() + pd_idx = text.find("protocol deviation") + assert pd_idx != -1 + context = text[pd_idx : pd_idx + 1000] + assert "justified" in context or "justification" in context or "rationale" in context, ( + "Protocol deviation rule must allow justified exceptions" + ) + + +def test_rerun_required_covers_protocol_deviations() -> None: + """Structured output description for rerun_required must cover protocol deviations.""" + text = SKILL_TEXT + so_idx = text.find("## Structured Output") + assert so_idx != -1, "SKILL.md must have Structured Output section" + so_section = text[so_idx:] + assert ( + "protocol deviation" in so_section.lower() or "execution diverged" in so_section.lower() + ), "rerun_required structured output description must reference protocol deviations" + + +def test_needs_rerun_structured_output_documented() -> None: + """SKILL.md must document needs_rerun emission format.""" + assert "needs_rerun" in SKILL_TEXT + assert "needs_rerun = " in SKILL_TEXT diff --git a/tests/skills/test_resolve_design_review_contracts.py b/tests/skills/test_resolve_design_review_contracts.py new file mode 100644 index 0000000000..51700d4bab --- /dev/null +++ b/tests/skills/test_resolve_design_review_contracts.py @@ -0,0 +1,119 @@ +"""Structural guards for resolve-design-review SKILL.md. + +Tests enforce the triage flow, ADDRESSABLE/STRUCTURAL/DISCUSS classification, +parallel subagents, conditional guidance emission, and structured output tokens. +""" + +from pathlib import Path + +SKILL_PATH = ( + Path(__file__).parent.parent.parent + / "src" + / "autoskillit" + / "skills_extended" + / "resolve-design-review" + / "SKILL.md" +) +SKILL_TEXT = SKILL_PATH.read_text() + + +def test_addressable_structural_discuss_classifications(): + """SKILL.md must define ADDRESSABLE, STRUCTURAL, and DISCUSS classifications.""" + assert "ADDRESSABLE" in SKILL_TEXT + assert "STRUCTURAL" in SKILL_TEXT + assert "DISCUSS" in SKILL_TEXT + + +def test_resolution_revised_when_any_addressable(): + """SKILL.md must state resolution=revised when any finding is ADDRESSABLE.""" + lower = SKILL_TEXT.lower() + assert "revised" in lower and "addressable" in lower + + +def test_resolution_failed_when_all_structural(): + """SKILL.md must state resolution=failed when all findings are STRUCTURAL.""" + lower = SKILL_TEXT.lower() + assert "failed" in lower and "structural" in lower + + +def test_revision_guidance_conditional_emission(): + """revision_guidance must be emitted ONLY when resolution=revised.""" + assert "revision_guidance" in SKILL_TEXT + lower = SKILL_TEXT.lower() + assert ( + "only when" in lower + or "emitted only" in lower + or "only emitted" in lower + or "only when resolution" in lower + ) + + +def test_parallel_subagents_for_classification(): + """SKILL.md must describe parallel subagents for feasibility validation.""" + lower = SKILL_TEXT.lower() + assert "parallel" in lower + assert "subagent" in lower or "sub-agent" in lower or "task tool" in lower + + +def test_analysis_before_guidance_in_workflow(): + """Analysis phase must be documented before guidance generation.""" + lower = SKILL_TEXT.lower() + analysis_idx = lower.find("analysis") + guidance_idx = lower.find("revision guidance") + assert analysis_idx != -1, "SKILL.md must describe an analysis phase" + assert guidance_idx != -1, "SKILL.md must describe revision guidance generation" + assert analysis_idx < guidance_idx, ( + "Analysis must appear before guidance generation in SKILL.md" + ) + + +def test_exit_zero_always(): + """SKILL.md must state that exit 0 applies to both outcomes.""" + lower = SKILL_TEXT.lower() + assert "exit 0" in lower + + +def test_structured_output_tokens_present(): + """SKILL.md must define resolution= structured output token.""" + assert "resolution = " in SKILL_TEXT + + +def test_temp_directory_is_resolve_design_review(): + """SKILL.md must use ``{{AUTOSKILLIT_TEMP}}/resolve-design-review/`` for output.""" + assert "{{AUTOSKILLIT_TEMP}}/resolve-design-review/" in SKILL_TEXT + + +# ── Diminishing-return detection ────────────────────────────────────────────── + + +def test_diminishing_return_detection_present(): + """SKILL.md must describe diminishing-return detection for finding themes.""" + lower = SKILL_TEXT.lower() + assert "diminishing" in lower or "goalposts" in lower or "theme comparison" in lower, ( + "resolve-design-review must detect diminishing returns — repeated findings " + "that are higher-abstraction restatements of previously addressed concerns." + ) + + +def test_goalposts_reclassified_as_structural(): + """Goalposts-moving findings must be reclassified as STRUCTURAL.""" + lower = SKILL_TEXT.lower() + has_goalposts_structural = "goalposts" in lower and "structural" in lower + has_diminishing_structural = "diminishing" in lower and "structural" in lower + has_reclassify = "reclassif" in lower + assert has_goalposts_structural or has_diminishing_structural or has_reclassify, ( + "Goalposts-moving findings must be reclassified as STRUCTURAL — " + "the fix-and-review cycle is not converging on that concern." + ) + + +def test_revision_guidance_context_input(): + """SKILL.md must accept prior revision_guidance as context for theme comparison.""" + lower = SKILL_TEXT.lower() + assert "prior" in lower or "previous" in lower, ( + "resolve-design-review must reference prior revision context " + "for diminishing-return detection." + ) + assert "[prior_revision_guidance_path]" in SKILL_TEXT or "optional" in lower, ( + "Prior revision_guidance must be an optional argument for backward compatibility." + ) diff --git a/tests/skills/test_resolve_failures_ci_aware.py b/tests/skills/test_resolve_failures_ci_aware.py new file mode 100644 index 0000000000..ce17e7aa91 --- /dev/null +++ b/tests/skills/test_resolve_failures_ci_aware.py @@ -0,0 +1,135 @@ +"""Contract guards for resolve-failures CI-awareness: verdict decision tree. + +Verifies that resolve-failures/SKILL.md contains the verdict decision tree +required by Part B of the parallel pipeline deadlock remediation. + +These are structural AST-style guards — they check the SKILL.md prose directly, +ensuring that the skill will emit the correct verdict tokens at runtime. + +Scenarios: + A: failure_subtype=flaky/timing_race + local tests green → verdict=flake_suspected + B: failure_subtype=deterministic + local tests green (CI red) → verdict=ci_only_failure + C: fix applied, local tests fail then pass → verdict=real_fix + fixes_applied>=1 +""" + +from __future__ import annotations + +import re + +import pytest + +from autoskillit.core import pkg_root + +_SKILL_MD = pkg_root() / "skills_extended" / "resolve-failures" / "SKILL.md" + + +@pytest.fixture(scope="module") +def skill_text() -> str: + assert _SKILL_MD.exists(), f"resolve-failures SKILL.md not found at {_SKILL_MD}" + return _SKILL_MD.read_text(encoding="utf-8") + + +# --------------------------------------------------------------------------- +# Step 2a: Read CI Context +# --------------------------------------------------------------------------- + + +def test_skill_reads_failure_subtype_from_diagnosis_path(skill_text: str) -> None: + """Skill must instruct reading failure_subtype from diagnosis_path input.""" + assert "failure_subtype" in skill_text, ( + "resolve-failures SKILL.md must reference 'failure_subtype' — " + "the skill must read CI failure classification from the diagnosis file" + ) + + +def test_skill_references_diagnosis_path_input(skill_text: str) -> None: + """Skill must reference diagnosis_path as an input to read CI context.""" + assert "diagnosis_path" in skill_text, ( + "resolve-failures SKILL.md must reference 'diagnosis_path' input — " + "the skill must consume the CI diagnosis from diagnose-ci" + ) + + +# --------------------------------------------------------------------------- +# Step 2c: Verdict Decision Tree +# --------------------------------------------------------------------------- + + +def test_skill_contains_verdict_decision_tree(skill_text: str) -> None: + """Skill must contain a verdict decision tree section.""" + assert "verdict" in skill_text.lower(), ( + "resolve-failures SKILL.md must contain a verdict decision tree" + ) + assert any( + phrase in skill_text + for phrase in ("Verdict Decision Tree", "verdict decision tree", "Verdict decision") + ), "resolve-failures SKILL.md must contain a 'Verdict Decision Tree' section" + + +def test_skill_maps_flaky_to_flake_suspected(skill_text: str) -> None: + """Scenario A: flaky/timing_race + local green → flake_suspected.""" + assert "flake_suspected" in skill_text, ( + "resolve-failures SKILL.md must include 'flake_suspected' verdict value " + "for the flaky/timing_race + local-green scenario" + ) + # The decision tree must map flaky or timing_race subtypes to flake_suspected + assert any(subtype in skill_text for subtype in ("flaky", "timing_race")), ( + "resolve-failures SKILL.md must reference 'flaky' or 'timing_race' subtypes " + "in the verdict decision tree" + ) + + +def test_skill_maps_deterministic_green_to_ci_only_failure(skill_text: str) -> None: + """Scenario B: deterministic + local tests green → ci_only_failure.""" + assert "ci_only_failure" in skill_text, ( + "resolve-failures SKILL.md must include 'ci_only_failure' verdict value " + "for the deterministic subtype + local-green scenario" + ) + assert "deterministic" in skill_text, ( + "resolve-failures SKILL.md must reference 'deterministic' subtype in the " + "verdict decision tree" + ) + + +def test_skill_maps_real_fix_correctly(skill_text: str) -> None: + """Scenario C: fix applied, local tests pass after fix → real_fix.""" + assert "real_fix" in skill_text, ( + "resolve-failures SKILL.md must include 'real_fix' verdict value " + "for the scenario where fixes are successfully applied" + ) + + +def test_skill_includes_already_green_verdict(skill_text: str) -> None: + """Skill must include 'already_green' verdict for the rebase re-entry path.""" + assert "already_green" in skill_text, ( + "resolve-failures SKILL.md must include 'already_green' verdict value " + "for the pre_resolve_rebase re-entry path" + ) + + +# --------------------------------------------------------------------------- +# Output tokens +# --------------------------------------------------------------------------- + + +def test_skill_emits_verdict_token(skill_text: str) -> None: + """Skill must emit 'verdict = {value}' in the output tokens block.""" + assert re.search(r"verdict\s*=\s*\{", skill_text), ( + "resolve-failures SKILL.md must emit 'verdict = {value}' in the " + "structured output tokens block" + ) + + +def test_skill_still_emits_fixes_applied_token(skill_text: str) -> None: + """Skill must still emit 'fixes_applied = {N}' alongside verdict.""" + assert re.search(r"fixes_applied\s*=\s*\{", skill_text), ( + "resolve-failures SKILL.md must still emit 'fixes_applied = {N}' " + "alongside the verdict token" + ) + + +def test_skill_verdict_covers_all_required_values(skill_text: str) -> None: + """All four verdict values must appear in the SKILL.md.""" + required = {"real_fix", "already_green", "flake_suspected", "ci_only_failure"} + missing = {v for v in required if v not in skill_text} + assert not missing, f"resolve-failures SKILL.md is missing these verdict values: {missing}" diff --git a/tests/skills/test_resolve_failures_guards.py b/tests/skills/test_resolve_failures_guards.py new file mode 100644 index 0000000000..5d17e7cfa0 --- /dev/null +++ b/tests/skills/test_resolve_failures_guards.py @@ -0,0 +1,110 @@ +"""Guards for resolve-failures SKILL.md: polling-cascade and output-bloat fixes.""" + +from __future__ import annotations + +import re + +from autoskillit.core.paths import pkg_root + +SKILL_MD = pkg_root() / "skills_extended" / "resolve-failures" / "SKILL.md" + + +def _skill_text() -> str: + return SKILL_MD.read_text() + + +def _extract_step(text: str, step_id: str) -> str: + """Extract the text of a named Step section up to the next Step heading. + + The lookahead ``(?=[:\\s\\n])`` ensures that ``step_id="Step 2"`` does NOT + match ``### Step 2a:`` (which sorts before ``### Step 2:`` in SKILL.md). + """ + pattern = rf"###\s+{re.escape(step_id)}(?=[:\s\n])[\s\S]*?(?=\n###\s+Step|\Z)" + m = re.search(pattern, text) + assert m is not None, f"Could not locate '{step_id}' section in resolve-failures/SKILL.md" + return m.group(0) + + +# --- Polling-cascade fix --- + + +def test_resolve_failures_step2_prohibits_bash_test_run() -> None: + """Step 2 must not instruct running tests via Bash (cd … && {test_command}). + + The Bash tool auto-backgrounds commands that exceed its timeout, forcing the + LLM into a polling cascade. test_check MCP blocks synchronously. + """ + text = _skill_text() + step2 = _extract_step(text, "Step 2") + assert "cd {worktree_path}" not in step2, ( + "resolve-failures Step 2 still instructs 'cd {worktree_path} && {test_command}' " + "via Bash. Replace with test_check MCP tool call to prevent polling cascade." + ) + + +def test_resolve_failures_step2_prescribes_test_check_mcp() -> None: + """Step 2 must prescribe using the test_check MCP tool, not a raw shell command.""" + text = _skill_text() + step2 = _extract_step(text, "Step 2") + assert "test_check" in step2, ( + "resolve-failures Step 2 must instruct use of the test_check MCP tool. " + "It currently runs tests via Bash, causing auto-backgrounding and polling." + ) + + +def test_resolve_failures_fix_loop_prohibits_bash_rerun() -> None: + """Step 3 fix loop must not re-run tests via Bash (cd … && {test_command}). + + Applies the same polling-cascade risk as Step 2. + """ + text = _skill_text() + step3 = _extract_step(text, "Step 3") + assert "cd {worktree_path}" not in step3, ( + "resolve-failures Step 3 fix loop still re-runs tests via " + "'cd {worktree_path} && {test_command}'. Replace with test_check MCP call." + ) + + +def test_resolve_failures_fix_loop_prescribes_test_check_mcp() -> None: + """Step 3 fix loop must use the test_check MCP tool for its re-run step.""" + text = _skill_text() + step3 = _extract_step(text, "Step 3") + assert "test_check" in step3, ( + "resolve-failures Step 3 fix loop must instruct use of the test_check MCP " + "tool for re-running tests. It currently uses a Bash command." + ) + + +# --- Output-bloat fix --- + + +def test_resolve_failures_fix_loop_instructs_output_summarization() -> None: + """Step 3 must instruct the LLM to retain only failure signal, discarding full stdout. + + Without this, 3–10K chars of pytest output accumulate per run (~17K tokens over + a session), inflating every subsequent API call's cache_read cost. + """ + text = _skill_text() + step3 = _extract_step(text, "Step 3") + # Must mention extracting/retaining only the key failure info + has_extract = bool( + re.search(r"extract|retain only|only.{0,40}(fail|count|name)", step3, re.IGNORECASE) + ) + assert has_extract, ( + "resolve-failures Step 3 must instruct the LLM to extract and retain only " + "the failure signal (counts, test names, error messages) from each test run, " + "discarding full pytest stdout to prevent context accumulation." + ) + + +def test_resolve_failures_fix_loop_instructs_stdout_discard() -> None: + """Step 3 must explicitly instruct discarding the full test output after extraction.""" + text = _skill_text() + step3 = _extract_step(text, "Step 3") + has_discard = bool( + re.search(r"discard.{0,60}(pytest|stdout|full output)", step3, re.IGNORECASE) + ) + assert has_discard, ( + "resolve-failures Step 3 must explicitly instruct discarding full pytest stdout " + "after extracting failure info. This prevents context bloat across fix iterations." + ) diff --git a/tests/skills/test_resolve_research_review_guards.py b/tests/skills/test_resolve_research_review_guards.py new file mode 100644 index 0000000000..1dd4b49576 --- /dev/null +++ b/tests/skills/test_resolve_research_review_guards.py @@ -0,0 +1,386 @@ +"""Behavioral guards for resolve-research-review/SKILL.md. + +Tests enforce research-dimension grouping, research REJECT vocabulary, +fix-strategy taxonomy, escalation protocol, ordered fix processing, +configurable validation, and all carry-over contracts from resolve-review. +""" + +from pathlib import Path + +SKILL_PATH = ( + Path(__file__).parent.parent.parent + / "src" + / "autoskillit" + / "skills_extended" + / "resolve-research-review" + / "SKILL.md" +) +SKILL_TEXT = SKILL_PATH.read_text() if SKILL_PATH.exists() else "" + + +def test_skill_path_exists() -> None: + """SKILL.md must exist at the expected path.""" + assert SKILL_PATH.exists(), f"SKILL.md not found at {SKILL_PATH}" + + +# --- Frontmatter --- + + +def test_has_research_category() -> None: + """Frontmatter must declare categories: [research].""" + text = SKILL_TEXT + assert any("research" in line for line in text.splitlines() if "categories:" in line), ( + "Frontmatter categories: field must include 'research'" + ) + + +# --- Dimension grouping (not file-path grouping) --- + + +def test_groups_by_dimension_not_path() -> None: + """SKILL.md must describe grouping by research dimension, not file path segment.""" + text = SKILL_TEXT + assert "dimension" in text.lower(), "SKILL.md must mention 'dimension' grouping" + # Must NOT use top-level path segment grouping language from resolve-review + assert "top-level path segment" not in text.lower(), ( + "resolve-research-review must NOT use top-level path segment grouping" + ) + + +def test_dimension_pattern_regex_present() -> None: + """DIMENSION_PATTERN regex must be documented to extract dimension from comment body.""" + text = SKILL_TEXT + assert "DIMENSION_PATTERN" in text or "dimension_pattern" in text.lower(), ( + "SKILL.md must define a DIMENSION_PATTERN for extracting dimension from comment body" + ) + + +def test_all_six_dimension_groups_present() -> None: + """All six dimension group keys must be defined.""" + text = SKILL_TEXT.lower() + for group in [ + "statistical", + "methodology", + "reproducibility", + "reporting", + "hygiene", + "unknown", + ]: + assert group in text, f"SKILL.md must define dimension group '{group}'" + + +# --- Research REJECT vocabulary --- + + +def test_research_reject_categories_present() -> None: + """REJECT must use research-specific category names.""" + text = SKILL_TEXT + for category in [ + "methodology_misunderstanding", + "false_positive_intentional", + "inconclusive_not_deficiency", + "out_of_scope", + "stale_comment", + ]: + assert category in text, f"SKILL.md must define REJECT category '{category}'" + + +def test_inconclusive_not_deficiency_reject_category() -> None: + """inconclusive_not_deficiency REJECT category must be explicitly present.""" + assert "inconclusive_not_deficiency" in SKILL_TEXT, ( + "SKILL.md must define the inconclusive_not_deficiency REJECT category — " + "inconclusive results are valid findings and must never be rejected as deficiencies" + ) + + +# --- Fix strategy taxonomy --- + + +def test_fix_strategies_defined() -> None: + """All five fix strategies must be defined.""" + text = SKILL_TEXT + for strategy in ["report_edit", "script_fix", "config_fix", "rerun_required", "design_flaw"]: + assert strategy in text, f"SKILL.md must define fix strategy '{strategy}'" + + +def test_report_edit_targets_research_md() -> None: + """report_edit strategy must target research/*.md files.""" + text = SKILL_TEXT + assert "report_edit" in text + report_edit_idx = text.find("report_edit") + context = text[report_edit_idx : report_edit_idx + 300] + assert "research/" in context or ".md" in context, ( + "report_edit strategy must reference research/*.md as the edit target" + ) + + +def test_script_fix_targets_scripts() -> None: + """script_fix strategy must target scripts/*.py or experiment code.""" + text = SKILL_TEXT + assert "script_fix" in text + script_fix_idx = text.find("script_fix") + context = text[script_fix_idx : script_fix_idx + 300] + assert "script" in context.lower() or ".py" in context, ( + "script_fix strategy must reference scripts/*.py or experiment code" + ) + + +# --- Escalation protocol --- + + +def test_escalation_protocol_documented() -> None: + """SKILL.md must describe the escalation protocol.""" + text = SKILL_TEXT.lower() + assert "escalat" in text, "SKILL.md must describe the escalation protocol" + + +def test_rerun_required_escalates_not_exits() -> None: + """rerun_required must escalate (not exit non-zero) and NOT add to addressed_thread_ids.""" + text = SKILL_TEXT + assert "rerun_required" in text + # Search from Step 4 (routing section) to find the ESCALATE block, not the taxonomy list + step4_idx = text.find("Step 4") + assert step4_idx != -1, "SKILL.md must have Step 4" + rr_idx = text.find("rerun_required", step4_idx) + assert rr_idx != -1, "Step 4 must mention rerun_required routing" + context = text[rr_idx : rr_idx + 500].lower() + assert "escalat" in context, "rerun_required must route to ESCALATE, not be applied as a fix" + assert "do not" in context or "not add" in context or "not resolve" in context, ( + "rerun_required must NOT add to addressed_thread_ids" + ) + + +def test_design_flaw_escalates_not_exits() -> None: + """design_flaw must escalate (not exit non-zero) and NOT add to addressed_thread_ids.""" + text = SKILL_TEXT + assert "design_flaw" in text + df_idx = text.find("design_flaw") + context = text[df_idx : df_idx + 500].lower() + assert "escalat" in context, "design_flaw must route to ESCALATE, not be applied as a fix" + + +def test_escalation_records_tracked() -> None: + """Escalation findings must be recorded in escalation_records.""" + assert "escalation_records" in SKILL_TEXT, ( + "SKILL.md must track escalation findings in escalation_records list" + ) + + +def test_escalation_does_not_cause_exit_nonzero() -> None: + """Escalation must not cause exit non-zero — only validation failure does.""" + text = SKILL_TEXT.lower() + escalat_idx = text.find("escalat") + assert "exit code remains 0" in text or ( + escalat_idx != -1 and "exit non-zero" not in text[escalat_idx : escalat_idx + 400] + ), "SKILL.md must state escalation does not cause exit non-zero" + + +def test_escalation_findings_get_inline_reply() -> None: + """Escalation findings must receive an inline reply (not just be recorded).""" + text = SKILL_TEXT + assert "ESCALATION" in text or "escalation" in text.lower() + # Reply template section must include escalation reply + reply_idx = text.lower().find("reply template") + if reply_idx == -1: + reply_idx = text.lower().find("reply") + assert reply_idx != -1 + context = text[reply_idx : reply_idx + 800] + assert "ESCALATION" in context or "escalat" in context.lower(), ( + "Reply templates must include escalation message templates" + ) + + +# --- Fix processing order --- + + +def test_fix_order_config_before_script_before_report() -> None: + """Fix processing order must be config → script → report.""" + text = SKILL_TEXT + config_idx = text.lower().find("config_fix") + script_idx = text.lower().find("script_fix", config_idx + 1) if config_idx != -1 else -1 + report_idx = text.lower().find("report_edit", script_idx + 1) if script_idx != -1 else -1 + assert config_idx != -1, "SKILL.md must mention config_fix" + assert script_idx != -1, "SKILL.md must mention script_fix after config_fix" + assert report_idx != -1, "SKILL.md must mention report_edit after script_fix" + assert config_idx < script_idx < report_idx, ( + "Fix order must be config_fix → script_fix → report_edit" + ) + + +# --- Configurable validation command --- + + +def test_validation_command_configurable() -> None: + """SKILL.md must describe reading validation_command from .autoskillit/config.yaml.""" + text = SKILL_TEXT + assert "validation_command" in text, "SKILL.md must define validation_command config key" + assert "config.yaml" in text or ".autoskillit/config" in text, ( + "SKILL.md must read validation_command from .autoskillit/config.yaml" + ) + + +def test_null_validation_command_skips_validation() -> None: + """null validation_command must skip the validation step.""" + text = SKILL_TEXT + assert "null" in text or "None" in text or "skip" in text.lower(), ( + "SKILL.md must state null validation_command skips validation" + ) + # validation_command context must mention skip + vc_idx = text.find("validation_command") + context = text[vc_idx : vc_idx + 500].lower() + assert "null" in context or "skip" in context, ( + "SKILL.md must state that null validation_command means skip" + ) + + +def test_configured_validation_uses_retry_logic() -> None: + """Configured validation_command must use retry logic (max 3 iterations).""" + text = SKILL_TEXT.lower() + assert "validation" in text and ("retry" in text or "iteration" in text or "iter" in text), ( + "SKILL.md must describe retry logic for the validation command" + ) + + +# --- Carry-over contracts from resolve-review --- + + +def test_pr_lookup_by_feature_branch() -> None: + """PR must be found by feature branch via gh pr list.""" + text = SKILL_TEXT + assert "gh pr list" in text or "gh pr" in text, "SKILL.md must look up PR by feature branch" + + +def test_graphql_thread_resolution() -> None: + """resolveReviewThread mutation must be used to close addressed threads.""" + assert "resolveReviewThread" in SKILL_TEXT + + +def test_addressed_thread_ids_accumulated() -> None: + """addressed_thread_ids must be accumulated for ACCEPT+fix findings only.""" + assert "addressed_thread_ids" in SKILL_TEXT + + +def test_reject_patterns_persisted() -> None: + """REJECT findings must be persisted to a JSON file.""" + text = SKILL_TEXT + assert "reject_patterns" in text or "reject patterns" in text.lower(), ( + "SKILL.md must persist reject patterns to JSON" + ) + reject_idx = text.find("reject_patterns") + assert reject_idx != -1 and ".json" in text[reject_idx : reject_idx + 50], ( + "SKILL.md must name the reject_patterns file with a .json extension" + ) + + +def test_max_three_fix_iterations() -> None: + """Skill must enforce max 3 fix-and-retry iterations.""" + text = SKILL_TEXT.lower() + assert "max 3" in text or "exceed 3" in text or "3 fix-and-retry" in text, ( + "SKILL.md must enforce a max of 3 fix iterations" + ) + + +def test_graceful_degradation_no_pr() -> None: + """Skill must exit 0 gracefully when gh is unavailable or no PR found.""" + text = SKILL_TEXT.lower() + assert "graceful" in text or ( + "exit 0" in text and ("unavailable" in text or "no pr" in text) + ), "SKILL.md must describe graceful degradation when gh is unavailable or no PR found" + + +def test_inline_replies_posted() -> None: + """Inline replies must be posted for every analyzed comment.""" + text = SKILL_TEXT.lower() + assert "reply" in text and ( + "for every" in text or "every analyzed" in text or "reply api" in text + ), "SKILL.md must describe posting inline replies for every analyzed comment" + + +def test_step7_report_includes_escalations() -> None: + """Step 7 report must include ESCALATIONS section.""" + text = SKILL_TEXT + report_idx = text.find("Step 7") + assert report_idx != -1, "SKILL.md must have a Step 7" + report_section = text[report_idx:] + assert ( + "Escalation" in report_section + or "ESCALATION" in report_section + or "escalat" in report_section.lower() + ), "Step 7 report must include escalation count" + + +def test_temp_dir_uses_resolve_research_review() -> None: + """Temp files must use ``{{AUTOSKILLIT_TEMP}}/resolve-research-review/`` directory.""" + assert "{{AUTOSKILLIT_TEMP}}/resolve-research-review/" in SKILL_TEXT, ( + "SKILL.md must use {{AUTOSKILLIT_TEMP}}/resolve-research-review/ for temp files" + ) + + +def test_dimension_groups_file_documented() -> None: + """Temp file layout must include dimension_groups_{pr}.json.""" + text = SKILL_TEXT + assert "dimension_groups_" in text or "dimension_groups" in text, ( + "SKILL.md must document dimension_groups_{pr}.json temp file" + ) + + +def test_needs_rerun_structured_output_documented() -> None: + text = SKILL_PATH.read_text() + assert "needs_rerun" in text + assert "needs_rerun = " in text # emit instruction format + + +# --- Protocol deviation and invalid statistics classification rules --- + + +def test_protocol_deviation_rule_present() -> None: + """SKILL.md must contain a protocol deviation classification rule mapping to rerun_required.""" + text = SKILL_TEXT.lower() + assert "protocol deviation" in text, ( + "SKILL.md must define a protocol deviation classification rule" + ) + # Find the protocol deviation section and verify it references rerun_required + pd_idx = text.find("protocol deviation") + context = SKILL_TEXT[pd_idx : pd_idx + 600] + assert "rerun_required" in context, ( + "Protocol deviation rule must map to rerun_required strategy" + ) + + +def test_invalid_statistics_rule_present() -> None: + """SKILL.md must contain an invalid statistics rule mapping to rerun_required.""" + text = SKILL_TEXT.lower() + assert "wrong unit of analysis" in text or "invalid statistic" in text, ( + "SKILL.md must define an invalid statistics classification rule" + ) + # Find the invalid statistics section and verify it references rerun_required + for needle in ["wrong unit of analysis", "invalid statistic"]: + idx = text.find(needle) + if idx != -1: + context = SKILL_TEXT[idx : idx + 600] + assert "rerun_required" in context, ( + "Invalid statistics rule must map to rerun_required strategy" + ) + break + + +def test_protocol_deviation_allows_justified_exception() -> None: + """Protocol deviation rule must allow justified exceptions (not blanket rerun).""" + text = SKILL_TEXT.lower() + pd_idx = text.find("protocol deviation") + assert pd_idx != -1 + context = text[pd_idx : pd_idx + 1000] + assert "justified" in context or "justification" in context or "rationale" in context, ( + "Protocol deviation rule must allow justified exceptions" + ) + + +def test_rerun_required_covers_protocol_deviations() -> None: + """Structured output description for rerun_required must cover protocol deviations.""" + text = SKILL_TEXT + so_idx = text.find("## Structured Output") + assert so_idx != -1, "SKILL.md must have Structured Output section" + so_section = text[so_idx:] + assert ( + "protocol deviation" in so_section.lower() or "execution diverged" in so_section.lower() + ), "rerun_required structured output description must reference protocol deviations" diff --git a/tests/skills/test_review_design_contracts.py b/tests/skills/test_review_design_contracts.py new file mode 100644 index 0000000000..406ef5173e --- /dev/null +++ b/tests/skills/test_review_design_contracts.py @@ -0,0 +1,554 @@ +"""Contract tests for review-design SKILL.md behavioral encoding.""" + +import re +from pathlib import Path + +import pytest + +SKILL_MD = Path(__file__).parents[2] / "src/autoskillit/skills_extended/review-design/SKILL.md" + + +@pytest.fixture(scope="module") +def skill_text() -> str: + return SKILL_MD.read_text() + + +# ── Triage classification ────────────────────────────────────────────────── + + +def test_triage_lists_all_five_experiment_types(skill_text): + """All five first-match triage classes must be named in the SKILL.md.""" + for name in [ + "benchmark", + "configuration_study", + "causal_inference", + "robustness_audit", + "exploratory", + ]: + assert name in skill_text, f"Missing triage type: {name!r}" + + +# ── Dimension weight matrix ──────────────────────────────────────────────── + + +def test_dimension_weight_tiers_defined(skill_text): + """H/M/L/S weight tiers must be defined in the SKILL.md.""" + for tier in ["H", "M", "L", "S"]: + assert f"weight={tier}" in skill_text or f"| {tier} " in skill_text, ( + f"Weight tier {tier!r} not found in weight matrix table or explicit weight= notation" + ) + + +def test_silent_tier_produces_no_output_contract(skill_text): + """SILENT (S) dimensions must be explicitly contracted to produce no output.""" + assert "SILENT" in skill_text, "SILENT tier label not found in SKILL.md" + assert "not spawned" in skill_text.lower(), ( + "Behavioral contract 'not spawned' not found — SILENT dimensions must be " + "explicitly documented as non-spawning" + ) + + +def test_universal_dimensions_always_run(skill_text): + """estimand_clarity and hypothesis_falsifiability must be listed as always-run L1.""" + assert "estimand_clarity" in skill_text + assert "hypothesis_falsifiability" in skill_text + # Both must be documented as always H-weight (not gated by triage like L4 dimensions) + assert "always H-weight" in skill_text, ( + "L1 dimensions must be explicitly documented as always H-weight regardless of triage" + ) + + +# ── Fail-fast gate ────────────────────────────────────────────────────────── + + +def test_l1_fail_fast_gate_present(skill_text): + """SKILL.md must encode the L1 fail-fast gate: halt on L1 critical.""" + text_lower = skill_text.lower() + assert "fail-fast" in text_lower or "fail fast" in text_lower, ( + "L1 fail-fast gate not found in SKILL.md" + ) + # Must assert that L2+ do NOT run when L1 is critical — use text_lower only + assert "do not proceed" in text_lower or "halt" in text_lower, ( + "Fail-fast gate must document that L2+ analysis does not run on L1 critical findings" + ) + + +# ── Red-team agent ────────────────────────────────────────────────────────── + + +def test_red_team_requires_decision_contract(skill_text): + """Red-team findings must always carry requires_decision: true (project-wide convention).""" + assert "requires_decision" in skill_text + # The contract must state true, not just mention the field + assert "requires_decision: true" in skill_text or '"requires_decision": true' in skill_text + + +def test_red_team_universal_challenges_present(skill_text): + """All five universal red-team challenges must be named.""" + for challenge in [ + "Goodhart", + "leakage", + "tuning", + "Survivorship", + "collision", + ]: + assert challenge.lower() in skill_text.lower(), ( + f"Red-team challenge {challenge!r} not found in SKILL.md" + ) + + +# ── Backward-compatible parsing ───────────────────────────────────────────── + + +def test_frontmatter_fallback_documented(skill_text): + """SKILL.md must document the two-level frontmatter parsing fallback.""" + assert "frontmatter" in skill_text.lower() + assert "LLM" in skill_text or "extraction" in skill_text.lower() + assert "source: frontmatter" in skill_text or "provenance" in skill_text.lower() + + +# ── Verdict logic ──────────────────────────────────────────────────────────── + + +def test_verdict_logic_all_three_outcomes(skill_text): + """Verdict logic must produce GO, REVISE, and STOP outcomes as explicit assignments.""" + for verdict in ["GO", "REVISE", "STOP"]: + assert f'verdict = "{verdict}"' in skill_text, ( + f"Verdict assignment 'verdict = \"{verdict}\"' not found in verdict logic code block" + ) + + +def test_verdict_stop_on_l1_critical(skill_text): + """STOP must be causally linked to STRUCTURAL L1 findings via the stop_triggers code block.""" + assert "stop_triggers" in skill_text, "stop_triggers code block not found" + # Verify causal linkage: stop_triggers must reference STRUCTURAL classification + step7_text = skill_text_between("### Step 7", "### Step 8", skill_text) + assert "STRUCTURAL" in step7_text, ( + "stop_triggers must be gated on STRUCTURAL classification, not raw dimension membership" + ) + # Both L1 dimensions must still be named as STOP-eligible dimensions + assert "estimand_clarity" in step7_text + assert "hypothesis_falsifiability" in step7_text + + +def test_verdict_proportional_warning_threshold(skill_text): + """REVISE threshold must use proportional formula, not a static count.""" + assert "WARNING_BUDGET_PER_DIM" in skill_text, ( + "Verdict logic must define WARNING_BUDGET_PER_DIM constant" + ) + assert "active_dimensions" in skill_text, ( + "Verdict logic must compute active_dimensions from spawned non-SILENT dimensions" + ) + assert "warning_threshold" in skill_text, ( + "Verdict logic must compute warning_threshold from active_dimensions" + " * WARNING_BUDGET_PER_DIM" + ) + # The old static threshold must be gone + assert "len(warning_findings) >= 3" not in skill_text, ( + "Static >= 3 threshold must be replaced with proportional formula" + ) + + +def test_evaluative_not_prescriptive_constraint(skill_text): + """Findings must describe WHAT is lacking, never HOW to fix it.""" + text_lower = skill_text.lower() + assert "what is lacking" in text_lower, ( + "SKILL.md must require findings to describe WHAT is lacking" + ) + assert "never prescribe how" in text_lower, "SKILL.md must prohibit prescriptive findings" + + +def test_findings_exclude_code_snippets_constraint(skill_text): + """Findings must never include code snippets or shell commands.""" + text_lower = skill_text.lower() + assert "findings must never include" in text_lower and "code snippets" in text_lower, ( + "SKILL.md must prohibit code snippets in findings" + ) + + +def test_design_scope_boundary_present(skill_text): + """Dimension subagents must be scoped to experimental design, not code review.""" + text_lower = skill_text.lower() + assert "experimental design" in text_lower or "design scope" in text_lower, ( + "SKILL.md must establish a design scope boundary for dimension subagents" + ) + assert re.search(r"do not evaluate[^.]*implementation code", text_lower, re.DOTALL), ( + "SKILL.md must exclude implementation code within the 'do not evaluate' scope block" + ) + + +def test_dashboard_yaml_includes_threshold_fields(skill_text): + """Machine-readable YAML summary must include active_dimensions and warning_threshold.""" + assert "active_dimensions:" in skill_text, ( + "Dashboard YAML summary must include active_dimensions field" + ) + assert "warning_threshold:" in skill_text, ( + "Dashboard YAML summary must include warning_threshold field" + ) + + +# ── Dashboard requirements ─────────────────────────────────────────────────── + + +def test_dashboard_cannot_assess_section(skill_text): + """evaluation_dashboard must include a 'Cannot Assess' section with ≥2 items.""" + # Assert the coupled phrase that ties the section to its minimum count requirement + assert "Cannot Assess" in skill_text + assert "Cannot Assess** section with at least 2" in skill_text, ( + "Cannot Assess section must be documented with its minimum count of 2 items" + ) + + +def test_dashboard_yaml_summary_block(skill_text): + """evaluation_dashboard must include a machine-readable YAML summary block.""" + assert "# --- review-design machine summary ---" in skill_text, ( + "Machine-readable YAML summary block header not found in SKILL.md" + ) + + +# ── Output token format ────────────────────────────────────────────────────── + + +def test_output_tokens_all_four_present(skill_text): + """All four output tokens must be named in the SKILL.md.""" + for token in ["verdict", "experiment_type", "evaluation_dashboard", "revision_guidance"]: + assert token in skill_text, f"Output token {token!r} not found" + + +def test_revision_guidance_only_on_revise(skill_text): + """revision_guidance must be documented as written only when verdict=REVISE.""" + assert "revision_guidance" in skill_text + assert "REVISE" in skill_text + # The file must couple revision_guidance to REVISE condition + lines_with_guidance = [line for line in skill_text.splitlines() if "revision_guidance" in line] + combined = "\n".join(lines_with_guidance) + assert "REVISE" in combined or "revise" in combined.lower(), ( + "revision_guidance must be tied to REVISE verdict in its description" + ) + + +# ── Section-scoped helpers ──────────────────────────────────────────────────── + + +def skill_text_between(start_heading: str, end_heading: str, text: str) -> str: + """Extract SKILL.md text between two headings (start inclusive, end exclusive).""" + pattern = re.escape(start_heading) + r".*?(?=" + re.escape(end_heading) + r")" + m = re.search(pattern, text, re.DOTALL) + assert m, f"Could not find section '{start_heading}' before '{end_heading}' in SKILL.md" + return m.group(0) + + +# ── L1 subagent context and severity calibration ────────────────────────────── + + +def test_l1_subagents_receive_experiment_type(skill_text: str) -> None: + """L1 subagents must list experiment_type as an explicit input. + + This is the structural contract that makes the false-STOP regression + immediately visible: any removal of experiment_type from Step 2 fails here. + The bug existed because no such assertion was present in the original suite. + """ + step2_text = skill_text_between("### Step 2", "### Step 3", skill_text) + assert "experiment_type" in step2_text, ( + "Step 2 L1 subagents must explicitly receive experiment_type as input. " + "Without it, severity thresholds default to causal_inference standards, " + "causing false STOP verdicts on benchmark and exploratory plans." + ) + + +def test_l1_severity_calibration_rubric_present(skill_text: str) -> None: + """Step 2 must contain a severity calibration rubric for L1 dimensions. + + The rubric is the mechanism that prevents false STOP verdicts: it tells + the L1 subagent what severity is appropriate per experiment type. + """ + step2_text = skill_text_between("### Step 2", "### Step 3", skill_text) + # Rubric must cover the anchoring experiment types + assert "causal_inference" in step2_text, ( + "Step 2 calibration rubric must specify causal_inference severity thresholds." + ) + assert "benchmark" in step2_text, ( + "Step 2 calibration rubric must specify benchmark severity thresholds." + ) + assert "exploratory" in step2_text, ( + "Step 2 calibration rubric must specify exploratory severity thresholds." + ) + # The rubric must distinguish critical from warning at minimum + step2_lower = step2_text.lower() + assert "critical" in step2_lower and "warning" in step2_lower, ( + "Step 2 must define what constitutes critical vs warning per experiment type." + ) + + +# ── All subagent steps must declare explicit inputs (Part B immunity) ───────── + + +@pytest.mark.parametrize( + "step_heading,next_heading", + [ + ("### Step 2", "### Step 3"), + ("### Step 3", "### Step 4"), + ("### Step 4", "### Step 5"), + ("### Step 5", "### Step 6"), + ], +) +def test_subagent_steps_declare_explicit_inputs( + step_heading: str, next_heading: str, skill_text: str +) -> None: + """Every subagent-spawning step must explicitly list its input variables. + + The false-STOP bug at Step 2 existed because there was no assertion + requiring explicit input declarations. This parameterized test enforces + the pattern for all subagent steps, making omission immediately visible. + + The established pattern (from Step 3 red-team) is: + 'Receives: ' + or an explicit 'Inputs:' / 'Each ... receives:' block. + """ + step_text = skill_text_between(step_heading, next_heading, skill_text) + # Must contain an explicit input declaration using the established pattern + assert any( + phrase in step_text.lower() + for phrase in ["receives:", "inputs:", "each subagent receives", "each ... receives"] + ), ( + f"{step_heading}: subagent-spawning steps must declare explicit inputs. " + "Use 'Receives:', 'Inputs:', or 'Each subagent receives:' to list context variables." + ) + + +@pytest.mark.parametrize( + "step_heading,next_heading", + [ + ("### Step 4", "### Step 5"), + ("### Step 5", "### Step 6"), + ], +) +def test_l3_l4_subagents_receive_experiment_type( + step_heading: str, next_heading: str, skill_text: str +) -> None: + """L3 and L4 subagents must receive experiment_type to calibrate severity. + + While L3/L4 findings route to REVISE (not STOP), type-agnostic severity + calibration is a structural gap. This test enforces experiment_type + propagation to all subagent steps. + """ + step_text = skill_text_between(step_heading, next_heading, skill_text) + assert "experiment_type" in step_text, ( + f"{step_heading}: L3/L4 subagents must receive experiment_type. " + "Type-agnostic severity calibration is a structural gap." + ) + + +# ── Red-team severity calibration ───────────────────────────────────────────── + + +def _parse_rt_rubric(skill_text: str) -> dict[str, str]: + """Parse the red-team severity calibration rubric into {experiment_type: severity}.""" + rt_cal_idx = skill_text.lower().find("red-team severity calibration") + assert rt_cal_idx != -1, "Red-team severity calibration rubric not found" + next_section_idx = skill_text.find("\n###", rt_cal_idx) + rt_section = ( + skill_text[rt_cal_idx:] + if next_section_idx == -1 + else skill_text[rt_cal_idx:next_section_idx] + ) + table_lines = [ln for ln in rt_section.splitlines() if "|" in ln and "---" not in ln] + assert len(table_lines) == 2, "Rubric must have exactly one header row and one data row" + headers = [c.strip().lower() for c in table_lines[0].split("|") if c.strip()] + values = [c.strip().lower() for c in table_lines[1].split("|") if c.strip()] + assert len(headers) == len(values), ( + f"Rubric table header/value count mismatch: {len(headers)} headers vs {len(values)} values" + ) + return dict(zip(headers, values)) + + +def test_red_team_severity_calibration_rubric_present(skill_text: str) -> None: + """Red-team dimension must have a severity calibration rubric by experiment type. + + Without this rubric, any critical red-team finding triggers STOP regardless + of experiment type, creating an unresolvable loop for benchmarks. + """ + rt_cal_idx = skill_text.lower().find("red-team severity calibration") + assert rt_cal_idx != -1, ( + "Red-team severity calibration rubric not found in SKILL.md. " + "Without it, any critical red-team finding triggers STOP regardless " + "of experiment type." + ) + next_section_idx = skill_text.find("\n###", rt_cal_idx) + rt_section = ( + skill_text[rt_cal_idx:] + if next_section_idx == -1 + else skill_text[rt_cal_idx:next_section_idx] + ) + for exp_type in ["causal_inference", "benchmark", "exploratory"]: + assert exp_type in rt_section, ( + f"Red-team calibration rubric must specify {exp_type} severity cap." + ) + + +def test_red_team_severity_cap_applied_before_verdict(skill_text: str) -> None: + """Severity cap must be applied BEFORE building stop_triggers in verdict logic. + + Without this ordering, red-team criticals bypass the cap and still trigger STOP. + """ + step7_text = skill_text_between("### Step 7", "### Step 8", skill_text) + cap_idx = step7_text.find("rt_cap") + stop_idx = step7_text.find('f.dimension == "red_team"') + assert cap_idx != -1, ( + "Step 7 verdict logic must reference rt_cap for red-team severity capping." + ) + assert stop_idx != -1, ( + "Step 7 verdict logic must reference red_team dimension in stop_triggers." + ) + assert cap_idx < stop_idx, ( + "rt_cap must be applied BEFORE the red_team stop_triggers line — " + "otherwise the cap has no effect on STOP eligibility." + ) + + +def test_benchmark_red_team_cannot_stop(skill_text: str) -> None: + """Benchmark experiment type must cap red-team severity at warning (no STOP).""" + rubric = _parse_rt_rubric(skill_text) + assert "benchmark" in rubric, "Benchmark column not found in red-team calibration rubric" + assert rubric["benchmark"] == "warning", ( + "Benchmark red-team severity must be capped at 'warning' — " + "STOP-eligible red-team findings are unreasonable for benchmarks." + ) + + +def test_causal_inference_red_team_can_stop(skill_text: str) -> None: + """causal_inference must retain critical as max red-team severity (STOP eligible).""" + rubric = _parse_rt_rubric(skill_text) + assert "causal_inference" in rubric, ( + "causal_inference column not found in red-team calibration rubric" + ) + assert rubric["causal_inference"] == "critical", ( + "causal_inference must retain critical as max red-team severity." + ) + + +# ── ADDRESSABLE/STRUCTURAL classification and priority tiers ────────────────── + + +def test_l1_gate_addressable_structural_classification_present(skill_text: str) -> None: + step2_text = skill_text_between("### Step 2", "### Step 3", skill_text) + assert "ADDRESSABLE" in step2_text, ( + "Step 2 fail-fast gate must classify L1 criticals as ADDRESSABLE or STRUCTURAL" + ) + assert "STRUCTURAL" in step2_text, ( + "Step 2 fail-fast gate must classify L1 criticals as ADDRESSABLE or STRUCTURAL" + ) + + +def test_addressable_findings_continue_l2_l4(skill_text: str) -> None: + step2_text = skill_text_between("### Step 2", "### Step 3", skill_text) + text_lower = step2_text.lower() + assert "addressable" in text_lower, ( + "Step 2 must reference ADDRESSABLE findings in the gate behavior" + ) + assert "continue" in text_lower, ( + "Step 2 must document that ADDRESSABLE L1 criticals continue to L2-L4 analysis" + ) + + +def test_structural_findings_halt_l2_l4(skill_text: str) -> None: + step2_text = skill_text_between("### Step 2", "### Step 3", skill_text) + assert "STRUCTURAL" in step2_text, ( + "Step 2 must document that STRUCTURAL L1 criticals halt L2-L4 analysis" + ) + text_lower = step2_text.lower() + assert ( + "halt" in text_lower or "do not proceed" in text_lower + ) and "structural" in text_lower, ( + "STRUCTURAL findings must still trigger halt at L1 fail-fast gate" + ) + + +def test_finding_priority_field_in_schema(skill_text: str) -> None: + assert '"priority"' in skill_text or "'priority'" in skill_text, ( + "Finding schema must include a 'priority' field" + ) + for tier in ["BLOCKING", "REQUIRED", "ADVISORY"]: + assert tier in skill_text, ( + f"Priority tier {tier!r} not found — finding schema must define " + "BLOCKING, REQUIRED, and ADVISORY tiers" + ) + assert '"fixability"' in skill_text or "'fixability'" in skill_text, ( + "Finding schema must include a 'fixability' field (ADDRESSABLE | STRUCTURAL | null)" + ) + + +def test_deduplication_instruction_present(skill_text: str) -> None: + text_lower = skill_text.lower() + assert ( + "deduplication" in text_lower or "deduplicate" in text_lower or "consolidat" in text_lower + ), "SKILL.md must contain a deduplication/consolidation instruction for repeated findings" + assert "sub-finding" in text_lower or "parent" in text_lower or "group" in text_lower, ( + "Deduplication instruction must describe grouping related findings under a parent" + ) + + +def test_verdict_pseudocode_uses_addressable_structural(skill_text: str) -> None: + step7_text = skill_text_between("### Step 7", "### Step 8", skill_text) + assert "STRUCTURAL" in step7_text, ( + "Step 7 verdict logic must reference STRUCTURAL classification in stop_triggers" + ) + assert "ADDRESSABLE" in step7_text, ( + "Step 7 verdict logic must reference ADDRESSABLE classification in verdict routing" + ) + + +def test_critical_constraints_updated_for_addressable(skill_text: str) -> None: + constraints_text = skill_text_between("## Critical Constraints", "## Workflow", skill_text) + assert "when any Level 1 finding is critical" not in constraints_text, ( + "Critical Constraints must not contain the unqualified " + "'any Level 1 finding is critical' halt — ADDRESSABLE findings should continue L2-L4" + ) + + +def test_dashboard_yaml_includes_priority_counts(skill_text: str) -> None: + assert "blocking_count:" in skill_text, ( + "Dashboard YAML summary must include blocking_count field" + ) + + +# ── agent_implementability dimension ───────────────────────────────────────── + + +def test_agent_implementability_subagent_checks(skill_text: str) -> None: + """All 7 agent_implementability sub-checks must be named in SKILL.md.""" + for check in [ + "step atomicity", + "file path resolvability", + "performance feasibility", + "verification criteria completeness", + "dependency ordering", + "absence of human-only actions", + "artifact continuity", + ]: + assert check.lower() in skill_text.lower(), ( + f"agent_implementability sub-check {check!r} not found in SKILL.md" + ) + + +def test_mechanizable_fixed_checklist_items(skill_text: str) -> None: + """Mechanizable check log must include two fixed checklist items.""" + assert "All implementation phases have runnable verification criteria" in skill_text + assert "All file paths in the implementation plan resolve to valid locations" in skill_text + + +def test_agent_implementability_not_stop_eligible(skill_text: str) -> None: + """agent_implementability must NOT appear in stop_triggers (L4 contract).""" + step7_text = skill_text_between("### Step 7", "### Step 8", skill_text) + assert "agent_implementability" not in step7_text, ( + "agent_implementability must not appear in Step 7 verdict logic — " + "L4 dimensions do not produce STOP-eligible findings" + ) + + +def test_agent_implementability_l4_step5_placement(skill_text: str) -> None: + """agent_implementability must be defined in Step 5 (L4), not elsewhere.""" + step5_text = skill_text_between("### Step 5", "### Step 6", skill_text) + assert "agent_implementability" in step5_text, ( + "agent_implementability must be placed in Step 5 (Level 4 dimensions)" + ) diff --git a/tests/skills/test_review_design_guards.py b/tests/skills/test_review_design_guards.py new file mode 100644 index 0000000000..5a1bffde11 --- /dev/null +++ b/tests/skills/test_review_design_guards.py @@ -0,0 +1,53 @@ +"""Guard tests for review-design SKILL.md — data_acquisition dimension.""" + +from pathlib import Path + +from autoskillit.recipe.experiment_type_registry import load_all_experiment_types + +SKILL_PATH = ( + Path(__file__).resolve().parent.parent.parent + / "src" + / "autoskillit" + / "skills_extended" + / "review-design" + / "SKILL.md" +) + + +def test_data_acquisition_dimension_exists() -> None: + text = SKILL_PATH.read_text() + assert "data_acquisition" in text + + +def test_data_acquisition_not_l_weight() -> None: + """data_acquisition must be M-weight minimum to influence verdict in at least one type.""" + types = load_all_experiment_types() + for name, spec in types.items(): + weight = spec.dimension_weights.get("data_acquisition") + if weight in ("M", "H"): + return + raise AssertionError("data_acquisition must have M or H weight in at least one bundled type") + + +def test_agent_implementability_dimension_exists() -> None: + text = SKILL_PATH.read_text() + assert "agent_implementability" in text + + +def test_agent_implementability_weight_row() -> None: + """agent_implementability must have H/H/M/M/L weights for the 5 bundled types.""" + types = load_all_experiment_types() + expected = { + "benchmark": "H", + "configuration_study": "H", + "causal_inference": "M", + "robustness_audit": "M", + "exploratory": "L", + } + for type_name, exp_weight in expected.items(): + spec = types.get(type_name) + assert spec is not None, f"Bundled type {type_name!r} not found" + actual = spec.dimension_weights.get("agent_implementability") + assert actual == exp_weight, ( + f"{type_name}.agent_implementability = {actual!r}, expected {exp_weight!r}" + ) diff --git a/tests/skills/test_review_pr_inline_comment_guards.py b/tests/skills/test_review_pr_inline_comment_guards.py index 82e8a8fbbb..6bde0a4061 100644 --- a/tests/skills/test_review_pr_inline_comment_guards.py +++ b/tests/skills/test_review_pr_inline_comment_guards.py @@ -106,10 +106,14 @@ def test_step6_uses_input_flag_not_field_for_comments(): SKILL.md and confirm this test fails. Then restore it. """ text = SKILL_TEXT - assert "--input -" in text, ( - "review-pr/SKILL.md Step 6 must prescribe '--input -' for the reviews POST. " - "Using '--field' for the comments array creates one array entry per flag " - "instead of a proper JSON array (Issue #206 root cause)." + step6_start = text.find("### Step 6") + step65_start = text.find("### Step 6.5") + assert step6_start != -1 + assert step65_start != -1 + step6_section = text[step6_start:step65_start] + assert "--input -" in step6_section, ( + "Step 6 must use '--input -' for the reviews POST payload. " + "This flag must appear within Step 6 specifically (not elsewhere in SKILL.md)." ) @@ -163,3 +167,125 @@ def test_step6_documents_event_mapping(): "review-pr/SKILL.md Step 6 must document the verdict-to-event mapping: " "approved → APPROVE, changes_requested → REQUEST_CHANGES." ) + + +# --- Section-scoped regression guards --- + + +def test_step6_builds_comments_from_jq_argjson(): + """Step 6 must contain the jq -n --argjson pattern for building COMMENTS_JSON.""" + text = SKILL_TEXT + step6_start = text.find("### Step 6") + step65_start = text.find("### Step 6.5") + assert step6_start != -1 + assert step65_start != -1 + step6_section = text[step6_start:step65_start] + assert "jq -n --argjson findings" in step6_section, ( + "Step 6 must contain 'jq -n --argjson findings' for building COMMENTS_JSON " + "from FILTERED_FINDINGS. Without this, inline comment construction is unguided." + ) + + +def test_step6_uses_filtered_findings_as_comment_source(): + """Step 6 must build COMMENTS_JSON from FILTERED_FINDINGS, not all findings.""" + text = SKILL_TEXT + step6_start = text.find("### Step 6") + step65_start = text.find("### Step 6.5") + assert step6_start != -1 + assert step65_start != -1 + step6_section = text[step6_start:step65_start] + assert "FILTERED_FINDINGS" in step6_section, ( + "Step 6 must reference FILTERED_FINDINGS as the source for inline comments. " + "Using all findings bypasses hunk-range validation from Step 4." + ) + + +def test_step65_positioned_between_step6_and_step7(): + """Step 6.5 (Post-Completion Confirmation) must exist between Step 6 and Step 7.""" + text = SKILL_TEXT + step6_idx = text.find("### Step 6:") + if step6_idx == -1: + step6_idx = text.find("### Step 6") + step65_idx = text.find("### Step 6.5") + step7_idx = text.find("### Step 7") + assert step6_idx != -1, "SKILL.md must contain Step 6" + assert step65_idx != -1, "SKILL.md must contain Step 6.5" + assert step7_idx != -1, "SKILL.md must contain Step 7" + assert step6_idx < step65_idx < step7_idx, ( + f"Step 6.5 must be positioned between Step 6 and Step 7. " + f"Found: Step 6 at {step6_idx}, Step 6.5 at {step65_idx}, Step 7 at {step7_idx}" + ) + + +def test_step65_contains_do_not_proceed_gate(): + """Step 6.5 must contain 'Do not proceed to Step 7' to prevent bypassing confirmation.""" + text = SKILL_TEXT + step65_start = text.find("### Step 6.5") + step7_start = text.find("### Step 7") + assert step65_start != -1 + assert step7_start != -1 + step65_section = text[step65_start:step7_start] + assert "do not proceed to step 7" in step65_section.lower(), ( + "Step 6.5 must contain 'Do not proceed to Step 7' as a hard gate. " + "Without this, a model that posted 0 inline comments can skip to verdict." + ) + + +def test_skill_prohibits_local_file_paths_in_review_body(): + """SKILL.md must explicitly prohibit referencing local file paths in review body.""" + text = SKILL_TEXT.lower() + assert any( + phrase in text + for phrase in [ + "never reference local file path", + "do not reference local file path", + "do not include local file path", + "never include local file path", + "must not reference local", + "must not include local", + ] + ), ( + "SKILL.md must explicitly prohibit referencing local file paths " + "(e.g., .autoskillit/temp/...) in the review body or inline comments. " + "GitHub readers cannot access local filesystem paths." + ) + + +def test_step8_ordering_enforcement(): + """Step 8 must contain ordering enforcement — it must execute after Steps 6 and 7.""" + text = SKILL_TEXT + step8_start = text.find("### Step 8") + assert step8_start != -1 + step8_section = text[step8_start:] + step8_lower = step8_section.lower() + assert any( + phrase in step8_lower + for phrase in [ + "after step", + "after steps 6 and 7", + "after posting", + "must execute after", + ] + ), ( + "Step 8 must contain explicit ordering enforcement stating it runs " + "after Steps 6 and 7. Writing the summary file before posting inline " + "comments anchors the model to treating the file as primary output." + ) + + +def test_mandatory_echo_positioned_between_step4_and_step5(): + """The mandatory 'I have N findings' echo must appear between Step 4 and Step 5.""" + text = SKILL_TEXT + step4_idx = text.find("### Step 4") + step5_idx = text.find("### Step 5") + assert step4_idx != -1 + assert step5_idx != -1 + between = text[step4_idx:step5_idx] + assert "my primary job is to post inline comments" in between.lower(), ( + "The mandatory echo ('My primary job is to post inline comments') must " + "appear between Step 4 and Step 5. This forces the model to acknowledge " + "its inline comment obligation before proceeding to verdict determination." + ) + assert "do not proceed to step 5" in between.lower(), ( + "The 'Do not proceed to Step 5' gate must appear between Step 4 and Step 5." + ) diff --git a/tests/skills/test_review_research_pr_guards.py b/tests/skills/test_review_research_pr_guards.py new file mode 100644 index 0000000000..b165e39ad5 --- /dev/null +++ b/tests/skills/test_review_research_pr_guards.py @@ -0,0 +1,125 @@ +"""Behavioral guards for review-research-pr/SKILL.md. + +Tests enforce research lens coverage, inconclusive-results contract, +verdict mechanics, and GitHub Reviews API posting requirements. +""" + +from pathlib import Path + +SKILL_PATH = ( + Path(__file__).parent.parent.parent + / "src" + / "autoskillit" + / "skills_extended" + / "review-research-pr" + / "SKILL.md" +) + + +def _text() -> str: + return SKILL_PATH.read_text() + + +def test_review_research_pr_has_research_category() -> None: + """Frontmatter must declare categories: [research].""" + text = _text() + assert "categories:" in text + # Verify 'research' appears on a categories line, not just anywhere in the file + assert any("research" in line for line in text.splitlines() if "categories:" in line), ( + "Frontmatter categories: field must include 'research'" + ) + + +def test_review_research_pr_has_all_seven_research_lenses() -> None: + """All 7 research audit dimension names must appear in SKILL.md.""" + text = _text() + research_lenses = [ + "methodology", + "reproducibility", + "report-quality", + "statistical-rigor", + "isolation", + "data-integrity", + "slop", + ] + for lens in research_lenses: + assert lens in text, f"review-research-pr/SKILL.md missing lens: {lens!r}" + + +def test_review_research_pr_does_not_include_deletion_regression() -> None: + """deletion_regression lens must not appear — it is a production-code concept.""" + assert "deletion_regression" not in _text(), ( + "review-research-pr must not include the deletion_regression audit dimension. " + "Research PRs do not have a base-branch deletion contract to enforce." + ) + + +def test_review_research_pr_treats_inconclusive_as_valid() -> None: + """SKILL.md must state inconclusive results are valid, not deficiencies.""" + lower = _text().lower() + assert "inconclusive" in lower, ( + "review-research-pr/SKILL.md must mention 'inconclusive' results" + ) + assert any( + kw in lower + for kw in ["not flag", "valid", "valid outcome", "not a deficiency", "do not flag"] + ), ( + "review-research-pr/SKILL.md must state that inconclusive results are valid " + "outcomes not to be flagged as deficiencies." + ) + + +def test_review_research_pr_finding_schema_includes_requires_decision() -> None: + """Subagent finding schema must include requires_decision field.""" + assert "requires_decision" in _text() + + +def test_review_research_pr_verdict_emits_on_final_line() -> None: + """Skill must instruct emitting verdict= on the final output line.""" + assert "verdict=" in _text(), ( + "review-research-pr/SKILL.md must instruct emitting 'verdict=' so the " + "recipe capture block can extract it." + ) + + +def test_review_research_pr_has_lnnn_markers_in_subagent_prompt() -> None: + """Subagent prompts must instruct use of [LNNN] markers for line numbers.""" + assert "[LNNN]" in _text(), ( + "review-research-pr/SKILL.md subagent prompts must instruct subagents to use " + "[LNNN] markers for line numbers — not compute them independently." + ) + + +def test_review_research_pr_uses_reviews_api() -> None: + """SKILL.md must prescribe the GitHub Reviews API for inline comment posting.""" + import re + + text = _text() + assert re.search(r"pulls/[^/\s]+/reviews", text), ( + "review-research-pr/SKILL.md must prescribe the GitHub Reviews API " + "(/repos/{owner}/{repo}/pulls/{n}/reviews) for inline comment posting." + ) + + +def test_data_scope_dimension_exists() -> None: + """data-scope must be listed as a review dimension.""" + assert "data-scope" in _text(), ( + "review-research-pr/SKILL.md must include 'data-scope' as an audit dimension" + ) + + +def test_eight_review_dimensions() -> None: + """All 8 research audit dimensions must appear in SKILL.md.""" + text = _text() + dimensions = [ + "methodology", + "reproducibility", + "report-quality", + "statistical-rigor", + "isolation", + "data-integrity", + "slop", + "data-scope", + ] + for dim in dimensions: + assert dim in text, f"review-research-pr/SKILL.md missing dimension: {dim!r}" diff --git a/tests/skills/test_skill_body_cleanliness.py b/tests/skills/test_skill_body_cleanliness.py new file mode 100644 index 0000000000..3f178c093b --- /dev/null +++ b/tests/skills/test_skill_body_cleanliness.py @@ -0,0 +1,27 @@ +"""Assert that no SKILL.md body references %%ORDER_UP%%.""" + +from pathlib import Path + +import pytest + +from autoskillit.core.paths import pkg_root + +_SKILLS_DIRS = [pkg_root() / "skills", pkg_root() / "skills_extended"] + + +def _all_skill_mds() -> list[Path]: + paths = [] + for d in _SKILLS_DIRS: + paths.extend(d.glob("*/SKILL.md")) + return sorted(paths) + + +@pytest.mark.parametrize("skill_md", _all_skill_mds(), ids=lambda p: p.parent.name) +def test_no_order_up_in_skill_body(skill_md: Path) -> None: + """No SKILL.md should reference %%ORDER_UP%% — completion is injected at prompt level.""" + text = skill_md.read_text() + assert "%%ORDER_UP%%" not in text, ( + f"{skill_md.parent.name}/SKILL.md contains %%ORDER_UP%% reference.\n" + "The completion directive is injected by _inject_completion_directive() " + "in commands.py. Remove it from the skill body." + ) diff --git a/tests/skills/test_skill_compliance.py b/tests/skills/test_skill_compliance.py index 41f004ccc2..b71cdcf3aa 100644 --- a/tests/skills/test_skill_compliance.py +++ b/tests/skills/test_skill_compliance.py @@ -18,7 +18,7 @@ import pytest from autoskillit.core.paths import pkg_root -from autoskillit.workspace.skills import SkillResolver +from autoskillit.workspace.skills import DefaultSkillResolver _SKILLS_DIRS = [pkg_root() / "skills", pkg_root() / "skills_extended"] @@ -65,6 +65,19 @@ re.compile(r"(?i)do\s+not\s+emit\s+(?:any\s+)?(?:prose|text|status)"), ] +# Skills whose narration suppression is handled globally by _inject_narration_suppression() +# in build_full_headless_cmd() (headless path) and sous-chef/SKILL.md (cook path). +# Per-loop inline anti-prose guards are intentionally absent — they are redundant. +_GLOBALLY_GUARDED_SKILLS: frozenset[str] = frozenset( + { + "process-issues", + "open-integration-pr", + "setup-project", + "collapse-issues", + "validate-audit", + } +) + def _all_skill_dirs() -> list[Path]: """Discover all skill directories that contain a SKILL.md from both skill directories.""" @@ -75,7 +88,7 @@ def _all_skill_dirs() -> list[Path]: def _skill_text(skill_name: str) -> str: - result = SkillResolver().resolve(skill_name) + result = DefaultSkillResolver().resolve(skill_name) assert result is not None, f"Skill not found: {skill_name}" return result.path.read_text() @@ -176,7 +189,7 @@ def _check_loop_boundary(skill_text: str) -> list[str]: return violations -@pytest.mark.parametrize("skill_name", ["open-pr", "open-integration-pr"]) +@pytest.mark.parametrize("skill_name", ["open-integration-pr"]) def test_no_prose_output_immediately_before_skill_invocation(skill_name: str) -> None: """Assert that no SKILL.md step instructs the model to output plain text immediately before a Skill tool call. @@ -196,7 +209,7 @@ def test_no_prose_output_immediately_before_skill_invocation(skill_name: str) -> ) -@pytest.mark.parametrize("skill_name", ["open-pr", "open-integration-pr"]) +@pytest.mark.parametrize("skill_name", ["open-integration-pr"]) def test_arch_lens_context_via_file_not_prose(skill_name: str) -> None: """Assert that PR context for arch-lens skills is passed via a temp file (Write tool), not as inline prose text output. @@ -206,7 +219,7 @@ def test_arch_lens_context_via_file_not_prose(skill_name: str) -> None: it as a conversational text block. """ text = _skill_text(skill_name) - assert f".autoskillit/temp/{skill_name}/pr_arch_lens_context_" in text, ( + assert f"{{{{AUTOSKILLIT_TEMP}}}}/{skill_name}/pr_arch_lens_context_" in text, ( f"{skill_name}/SKILL.md does not reference a skill-scoped pr_arch_lens_context file. " "PR context must be written to a skill-scoped temp file, not a shared path." ) @@ -222,12 +235,17 @@ def test_no_text_then_tool_in_any_step(skill_dir: Path) -> None: same step or consecutive sub-steps, or an unguarded loop with tool invocations. + Skills in _GLOBALLY_GUARDED_SKILLS are exempt from the loop-boundary + check — their narration suppression is injected at the prompt level + by build_full_headless_cmd() and sous-chef/SKILL.md. + This is a project-wide structural invariant, not specific to open-pr or arch-lens. """ text = (skill_dir / "SKILL.md").read_text() violations = _check_text_then_tool(text) - violations.extend(_check_loop_boundary(text)) + if skill_dir.name not in _GLOBALLY_GUARDED_SKILLS: + violations.extend(_check_loop_boundary(text)) assert not violations, ( f"{skill_dir.name}/SKILL.md contains text-then-tool anti-pattern:\n" + "\n".join(f" - {v}" for v in violations) diff --git a/tests/skills/test_skill_genericization.py b/tests/skills/test_skill_genericization.py index cc9e26a042..5e8e6c8d32 100644 --- a/tests/skills/test_skill_genericization.py +++ b/tests/skills/test_skill_genericization.py @@ -5,6 +5,7 @@ from pathlib import Path SKILLS_DIR = Path(__file__).parent.parent.parent / "src/autoskillit/skills" +SKILLS_EXTENDED_DIR = Path(__file__).parent.parent.parent / "src/autoskillit/skills_extended" def _skill_content(name: str) -> str: @@ -67,3 +68,25 @@ def test_code_index_examples_are_generic() -> None: f"These skills have AutoSkillit-specific code-index path examples: " f"{skills_with_violations}. Replace with generic placeholders (REQ-GEN-004)." ) + + +def test_scope_has_no_hardcoded_metrics_rs() -> None: + """scope/SKILL.md must not reference the hardcoded src/metrics.rs path.""" + content = (SKILLS_EXTENDED_DIR / "scope" / "SKILL.md").read_text() + assert "src/metrics.rs" not in content, ( + "scope/SKILL.md hardcodes 'src/metrics.rs'. " + "Use generic evaluation framework search (REQ-GEN-005)." + ) + assert "test_metrics_assess" not in content, ( + "scope/SKILL.md hardcodes 'test_metrics_assess'. " + "Use generic evaluation framework search (REQ-GEN-005)." + ) + + +def test_plan_experiment_has_no_hardcoded_metrics_rs() -> None: + """plan-experiment/SKILL.md must not reference the hardcoded src/metrics.rs path.""" + content = (SKILLS_EXTENDED_DIR / "plan-experiment" / "SKILL.md").read_text() + assert "src/metrics.rs" not in content, ( + "plan-experiment/SKILL.md hardcodes 'src/metrics.rs'. " + "Use generic evaluation framework language (REQ-GEN-005)." + ) diff --git a/tests/skills/test_skill_output_compliance.py b/tests/skills/test_skill_output_compliance.py index 6069508fea..4b07e1f56f 100644 --- a/tests/skills/test_skill_output_compliance.py +++ b/tests/skills/test_skill_output_compliance.py @@ -10,7 +10,7 @@ import yaml from autoskillit.core import pkg_root -from autoskillit.workspace.skills import SkillResolver +from autoskillit.workspace.skills import DefaultSkillResolver # Skills whose output files are intentionally fixed-name (no timestamp needed). # These are idempotent by design — the filename IS the identity. @@ -41,8 +41,11 @@ ) # Lines that contain output file path instructions (write/save directives). +# Matches both legacy literal ``.autoskillit/temp/`` and the placeholder +# ``{{AUTOSKILLIT_TEMP}}/`` form used by SKILL.md files post-substitution. OUTPUT_PATH_LINE = re.compile( - r"(?:write|save|output)\s+.*?(?:to|path|file)\s*[:=]?\s*`?(?:\.autoskillit/)?temp/", + r"(?:write|save|output)\s+.*?(?:to|path|file)\s*[:=]?\s*" + r"`?(?:\.autoskillit/temp/|\{\{AUTOSKILLIT_TEMP\}\}/)", re.IGNORECASE, ) @@ -72,7 +75,7 @@ def _get_file_producing_skills() -> list[str]: """Return skill names whose SKILL.md contains temp/ output path instructions.""" - resolver = SkillResolver() + resolver = DefaultSkillResolver() producing = [] for info in resolver.list_all(): if info.name not in FIXED_NAME_SKILLS: @@ -84,7 +87,7 @@ def _get_file_producing_skills() -> list[str]: def _get_skills_with_output_tokens() -> list[str]: """Return skill names whose SKILL.md contains structured output tokens.""" - resolver = SkillResolver() + resolver = DefaultSkillResolver() token_skills = [] # Simple check for key = value or key=value pattern in unlabeled code blocks token_pattern = re.compile( @@ -111,7 +114,7 @@ def _get_skills_with_output_tokens() -> list[str]: @pytest.mark.parametrize("skill_name", _get_file_producing_skills()) def test_skill_output_uses_hhmmss_timestamp(skill_name: str) -> None: """Every file-producing skill must use {YYYY-MM-DD_HHMMSS} in output paths.""" - resolver = SkillResolver() + resolver = DefaultSkillResolver() info = resolver.resolve(skill_name) assert info is not None content = info.path.read_text() @@ -120,7 +123,7 @@ def test_skill_output_uses_hhmmss_timestamp(skill_name: str) -> None: output_lines = [ line for line in content.splitlines() - if re.search(r"(?:\.autoskillit/)?temp/.*\{.*\}", line) + if re.search(r"(?:\.autoskillit/temp/|\{\{AUTOSKILLIT_TEMP\}\}/).*\{.*\}", line) and not line.strip().startswith("#") ] @@ -135,7 +138,7 @@ def test_skill_output_uses_hhmmss_timestamp(skill_name: str) -> None: @pytest.mark.parametrize("skill_name", _get_skills_with_output_tokens()) def test_structured_output_tokens_have_spaces(skill_name: str) -> None: """Structured output tokens must use 'key = value' format (spaces around =).""" - resolver = SkillResolver() + resolver = DefaultSkillResolver() info = resolver.resolve(skill_name) assert info is not None content = info.path.read_text() @@ -151,7 +154,7 @@ def test_structured_output_tokens_have_spaces(skill_name: str) -> None: @pytest.mark.parametrize("skill_name", _get_file_producing_skills()) def test_no_shared_scratch_files(skill_name: str) -> None: """Skills must not write to shared fixed-name scratch files.""" - resolver = SkillResolver() + resolver = DefaultSkillResolver() info = resolver.resolve(skill_name) assert info is not None content = info.path.read_text() @@ -166,7 +169,7 @@ def test_no_shared_scratch_files(skill_name: str) -> None: @pytest.mark.parametrize("skill_name", _get_file_producing_skills()) def test_no_namespace_prefix_in_output_paths(skill_name: str) -> None: """Output paths must not include the autoskillit: namespace prefix.""" - resolver = SkillResolver() + resolver = DefaultSkillResolver() info = resolver.resolve(skill_name) assert info is not None content = info.path.read_text() @@ -184,7 +187,7 @@ def test_no_namespace_prefix_in_output_paths(skill_name: str) -> None: @pytest.mark.parametrize("skill_name", _get_file_producing_skills()) def test_file_producing_skills_have_cwd_anchor(skill_name: str) -> None: """Every file-producing skill must anchor temp/ writes to the current working directory.""" - resolver = SkillResolver() + resolver = DefaultSkillResolver() info = resolver.resolve(skill_name) assert info is not None content = info.path.read_text() @@ -221,6 +224,23 @@ def test_output_path_tokens_synchronized() -> None: "analysis_file", "conflict_report_path", "recipe_path", + # Research recipe skills (added in #504) + "scope_report", + "experiment_plan", + "results_path", + "report_path", + # review-design skill outputs (added in #593) + "evaluation_dashboard", + "revision_guidance", + # prepare-research-pr output (decomposed research-PR flow) + "prep_path", + # plan-visualization outputs (groupF Part A) + "visualization_plan_path", + "report_plan_path", + # bundle-local-report output (groupG) + "html_path", + # stage-data skill output (resource feasibility report path) + "resource_report", } ) @@ -276,6 +296,19 @@ def test_resolve_failures_skill_switches_code_index_to_worktree(): "arch-lens-scenarios": ["diagram_path"], "arch-lens-state-lifecycle": ["diagram_path"], "arch-lens-deployment": ["diagram_path"], + "vis-lens-always-on": ["diagram_path"], + "vis-lens-antipattern": ["diagram_path"], + "vis-lens-caption-annot": ["diagram_path"], + "vis-lens-chart-select": ["diagram_path"], + "vis-lens-color-access": ["diagram_path"], + "vis-lens-domain-norms": ["diagram_path"], + "vis-lens-figure-table": ["diagram_path"], + "vis-lens-multi-compare": ["diagram_path"], + "vis-lens-reproducibility": ["diagram_path"], + "vis-lens-story-arc": ["diagram_path"], + "vis-lens-temporal": ["diagram_path"], + "vis-lens-uncertainty": ["diagram_path"], + "review-design": ["evaluation_dashboard", "revision_guidance"], } ABSOLUTE_PATH_KEYWORDS = ("absolute", "/abs", "$(pwd)", "$(cd") diff --git a/tests/skills/test_skill_placeholder_contracts.py b/tests/skills/test_skill_placeholder_contracts.py index 1edff8353b..f10603ccc4 100644 --- a/tests/skills/test_skill_placeholder_contracts.py +++ b/tests/skills/test_skill_placeholder_contracts.py @@ -67,6 +67,9 @@ ("review-pr", "owner"), ("review-pr", "repo"), ("review-pr", "pr_number"), + ("review-research-pr", "owner"), + ("review-research-pr", "repo"), + ("review-research-pr", "pr_number"), # ── GRAPHQL FIELD NAMES (false positives) ───────────────────────────────────── # These appear inside single-quoted GraphQL query strings as JSON field names, not # as bash template placeholders. The {identifier} regex matches them spuriously. @@ -78,9 +81,47 @@ ("review-pr", "verdict"), # computed verdict string ("review-pr", "summary_markdown"), # computed review summary ("review-pr", "escalation_user_mention"), # prose: "set escalation_user_mention=..." + ("review-research-pr", "verdict"), # computed verdict string + ("review-research-pr", "summary_markdown"), # computed review summary + ( + "review-research-pr", + "escalation_user_mention", + ), # prose: "set escalation_user_mention=..." ("resolve-review", "comment_id"), # per-comment REST database ID in the inline-reply loop ("resolve-review", "file"), # per-finding file path from review comments ("resolve-merge-conflicts", "file"), # per-iteration conflicted file path + # ── resolve-research-review: same pattern as resolve-review ────────────────── + ("resolve-research-review", "owner"), # GitHub API URL template (gh repo view) + ("resolve-research-review", "repo"), # GitHub API URL template (gh repo view) + ("resolve-research-review", "number"), # PR number from gh pr list output + ( + "resolve-research-review", + "comment_id", + ), # per-comment REST database ID in inline-reply loop + ("resolve-research-review", "file"), # per-finding file path from review comments + ("resolve-research-review", "databaseId"), # GraphQL field name (false positive) + ("resolve-research-review", "isResolved"), # GraphQL field name (false positive) + ("resolve-research-review", "description"), # per-commit description derived from finding + ( + "resolve-research-review", + "dimension", + ), # per-commit dimension label derived from finding + # ── audit-claims: mirrors review-research-pr pattern ───────────────────────── + ("audit-claims", "owner"), # GitHub API URL template (gh repo view) + ("audit-claims", "repo"), # GitHub API URL template (gh repo view) + ("audit-claims", "pr_number"), # PR number from argument + ("audit-claims", "verdict"), # computed verdict string + ("audit-claims", "summary_markdown"), # computed review summary + # ── resolve-claims-review: mirrors resolve-research-review pattern ──────────── + ("resolve-claims-review", "owner"), # GitHub API URL template (gh repo view) + ("resolve-claims-review", "repo"), # GitHub API URL template (gh repo view) + ("resolve-claims-review", "number"), # PR number from gh pr list output + ("resolve-claims-review", "comment_id"), # per-comment REST database ID + ("resolve-claims-review", "file"), # per-finding file path from review comments + ("resolve-claims-review", "databaseId"), # GraphQL field name (false positive) + ("resolve-claims-review", "isResolved"), # GraphQL field name (false positive) + ("resolve-claims-review", "description"), # per-commit description derived from finding + ("resolve-claims-review", "dimension"), # per-commit dimension label derived from finding # ── PER-ITERATION / LOOP VALUES ────────────────────────────────────────────── # Used inside per-issue/per-PR/per-file loops. The prose establishes the loop # structure and makes the substitution unambiguous. @@ -98,10 +139,12 @@ ("open-integration-pr", "timestamp"), # generated timestamp ("open-integration-pr", "new_pr_number"), # newly created integration PR number ("open-integration-pr", "new_pr_url"), # newly created integration PR URL - ("open-pr", "plan_path"), # iterating over plan_paths (singular loop var) - ("open-pr", "closing_issue"), # optional arg declared as [closing_issue] - ("open-pr", "task_title"), # derived from first heading of plan file - ("open-pr", "timestamp"), # generated timestamp for temp file + # ── prepare-pr: runtime-computed values ────────────────────────────────────── + # task_title: synthesized from plan headings (single or multi-plan subagent) + ("prepare-pr", "task_title"), + # ── compose-pr: runtime-computed values ────────────────────────────────────── + # task_title: extracted from prep file in Step 1 + ("compose-pr", "task_title"), ("pipeline-summary", "bug_count"), # runtime computed count from audit log ("pipeline-summary", "date"), # runtime computed date string ("prepare-issue", "body"), @@ -115,6 +158,11 @@ ("process-issues", "recipe"), # recipe name from manifest ("triage-issues", "number"), # per-issue iteration value ("triage-issues", "recipe"), # recipe name from manifest + # ── compose-research-pr: runtime-computed values ────────────────────────────── + # title: extracted from prep file by Agent subagent in Step 1 + # pr_body_path: path to PR body file written in Step 3, used in Step 5 + ("compose-research-pr", "title"), + ("compose-research-pr", "pr_body_path"), } ) diff --git a/tests/skills/test_tier1_no_temp_reference.py b/tests/skills/test_tier1_no_temp_reference.py new file mode 100644 index 0000000000..4bd1de4ae6 --- /dev/null +++ b/tests/skills/test_tier1_no_temp_reference.py @@ -0,0 +1,33 @@ +"""Tier 1 SKILL.md files must not reference temp at all. + +Tier 1 skills (open-kitchen, close-kitchen, sous-chef) bypass the ephemeral +copy pipeline and the placeholder substitution. Any temp reference in their +SKILL.md is unsubstituted at runtime, so neither the literal path nor the +``{{AUTOSKILLIT_TEMP}}`` placeholder is permitted. +""" + +from __future__ import annotations + +from pathlib import Path + +_LITERAL = ".autoskillit/temp" +_PLACEHOLDER = "{{AUTOSKILLIT_TEMP}}" + + +def _tier1_root() -> Path: + return Path(__file__).resolve().parents[2] / "src" / "autoskillit" / "skills" + + +def test_tier1_skill_md_has_no_temp_reference() -> None: + root = _tier1_root() + assert root.is_dir(), f"Tier 1 skills root not found: {root}" + + offenders: list[str] = [] + for skill_md in root.rglob("SKILL.md"): + text = skill_md.read_text(encoding="utf-8") + if _LITERAL in text or _PLACEHOLDER in text: + offenders.append(skill_md.relative_to(root).as_posix()) + assert not offenders, ( + "Tier 1 SKILL.md files must contain neither the literal " + f"{_LITERAL!r} nor {_PLACEHOLDER!r}: {offenders}" + ) diff --git a/tests/skills/test_tier2_3_no_literal_temp.py b/tests/skills/test_tier2_3_no_literal_temp.py new file mode 100644 index 0000000000..d34bb5bb25 --- /dev/null +++ b/tests/skills/test_tier2_3_no_literal_temp.py @@ -0,0 +1,39 @@ +"""Tier 2/3 SKILL.md files must use ``{{AUTOSKILLIT_TEMP}}``, never the literal.""" + +from __future__ import annotations + +from pathlib import Path + +_LITERAL = ".autoskillit/temp" +_PLACEHOLDER = "{{AUTOSKILLIT_TEMP}}" + + +def _tier23_root() -> Path: + return Path(__file__).resolve().parents[2] / "src" / "autoskillit" / "skills_extended" + + +def test_tier2_3_skill_md_has_no_literal_temp_path() -> None: + root = _tier23_root() + assert root.is_dir(), f"Tier 2/3 skills root not found: {root}" + + offenders: list[str] = [] + for skill_md in root.rglob("SKILL.md"): + if _LITERAL in skill_md.read_text(encoding="utf-8"): + offenders.append(skill_md.relative_to(root).as_posix()) + assert not offenders, ( + f"Tier 2/3 SKILL.md files contain literal {_LITERAL!r} (must use " + f"{_PLACEHOLDER!r} instead): {offenders}" + ) + + +def test_tier2_3_at_least_one_skill_uses_placeholder() -> None: + """Sanity check that the migration ran — at least 50 SKILL.md files contain the placeholder.""" + root = _tier23_root() + count = sum( + 1 + for skill_md in root.rglob("SKILL.md") + if _PLACEHOLDER in skill_md.read_text(encoding="utf-8") + ) + assert count >= 50, ( + f"Expected ≥50 Tier 2/3 SKILL.md files to use {_PLACEHOLDER!r}; found {count}" + ) diff --git a/tests/skills/test_troubleshoot_experiment_contracts.py b/tests/skills/test_troubleshoot_experiment_contracts.py new file mode 100644 index 0000000000..3ce9c38b43 --- /dev/null +++ b/tests/skills/test_troubleshoot_experiment_contracts.py @@ -0,0 +1,16 @@ +from autoskillit.core.paths import pkg_root +from autoskillit.workspace.skills import DefaultSkillResolver + + +def test_troubleshoot_experiment_skill_is_discoverable(): + """troubleshoot-experiment must be discoverable via SkillResolver.""" + resolver = DefaultSkillResolver() + skills = resolver.list_all() + skill_names = [s.name for s in skills] + assert "troubleshoot-experiment" in skill_names + + +def test_troubleshoot_experiment_skill_has_skill_md(): + """troubleshoot-experiment directory must contain SKILL.md.""" + skill_path = pkg_root() / "skills_extended" / "troubleshoot-experiment" / "SKILL.md" + assert skill_path.exists(), f"SKILL.md not found at {skill_path}" diff --git a/tests/skills/test_validate_audit_contracts.py b/tests/skills/test_validate_audit_contracts.py index ea0ad3cfb7..e13bda345e 100644 --- a/tests/skills/test_validate_audit_contracts.py +++ b/tests/skills/test_validate_audit_contracts.py @@ -5,12 +5,12 @@ import functools from autoskillit.core.types import SkillSource -from autoskillit.workspace.skills import SkillResolver +from autoskillit.workspace.skills import DefaultSkillResolver @functools.cache def _skill_text() -> str: - info = SkillResolver().resolve("validate-audit") + info = DefaultSkillResolver().resolve("validate-audit") assert info is not None, "validate-audit skill not found" return info.path.read_text() @@ -18,14 +18,14 @@ def _skill_text() -> str: class TestValidateAuditSkillExists: # T-VAL-006 def test_validate_audit_skill_exists(self) -> None: - info = SkillResolver().resolve("validate-audit") + info = DefaultSkillResolver().resolve("validate-audit") assert info is not None assert info.source == SkillSource.BUNDLED_EXTENDED assert info.path.exists() # T-VAL-007 def test_validate_audit_has_audit_category(self) -> None: - info = SkillResolver().resolve("validate-audit") + info = DefaultSkillResolver().resolve("validate-audit") assert info is not None assert "audit" in info.categories @@ -67,7 +67,7 @@ def test_interactive_headless_distinction(self) -> None: # T-VAL-014 def test_output_dir(self) -> None: - assert ".autoskillit/temp/validate-audit/" in _skill_text() + assert "{{AUTOSKILLIT_TEMP}}/validate-audit/" in _skill_text() # T-VAL-015 def test_history_research_agent(self) -> None: diff --git a/tests/skills/test_vis_lens_structural.py b/tests/skills/test_vis_lens_structural.py new file mode 100644 index 0000000000..9c658f3dac --- /dev/null +++ b/tests/skills/test_vis_lens_structural.py @@ -0,0 +1,110 @@ +"""Structural assertions for P0 vis-lens skills.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +import yaml + +SKILLS_DIR = Path(__file__).parents[2] / "src/autoskillit/skills_extended" + +VIS_LENS_SLUGS = [ + "chart-select", + "uncertainty", + "antipattern", + "domain-norms", + "always-on", + "multi-compare", + "temporal", + "color-access", + "figure-table", + "caption-annot", + "story-arc", + "reproducibility", +] + +COMPOSITE_SLUGS = {"always-on"} # emits yaml:spec-index instead of yaml:figure-spec + + +def _read(slug: str) -> str: + path = SKILLS_DIR / f"vis-lens-{slug}" / "SKILL.md" + assert path.exists(), f"vis-lens-{slug}/SKILL.md is missing" + return path.read_text() + + +def _frontmatter(text: str) -> dict: + """Parse YAML frontmatter between the first pair of '---' delimiters.""" + lines = text.splitlines() + if lines[0].strip() != "---": + return {} + end = next(i for i, ln in enumerate(lines[1:], 1) if ln.strip() == "---") + return yaml.safe_load("\n".join(lines[1:end])) + + +@pytest.mark.parametrize("slug", VIS_LENS_SLUGS) +def test_skill_md_exists(slug: str) -> None: + path = SKILLS_DIR / f"vis-lens-{slug}" / "SKILL.md" + assert path.exists(), f"vis-lens-{slug}/SKILL.md missing" + + +@pytest.mark.parametrize("slug", VIS_LENS_SLUGS) +def test_has_arguments_section(slug: str) -> None: + assert "## Arguments" in _read(slug), f"vis-lens-{slug} missing ## Arguments section" + + +@pytest.mark.parametrize("slug", VIS_LENS_SLUGS) +def test_documents_context_path(slug: str) -> None: + assert "context_path" in _read(slug), f"vis-lens-{slug} must document context_path" + + +@pytest.mark.parametrize("slug", VIS_LENS_SLUGS) +def test_documents_experiment_plan_path(slug: str) -> None: + assert "experiment_plan_path" in _read(slug), ( + f"vis-lens-{slug} must document experiment_plan_path" + ) + + +@pytest.mark.parametrize("slug", VIS_LENS_SLUGS) +def test_has_step_0(slug: str) -> None: + assert "Step 0" in _read(slug), f"vis-lens-{slug} must have Step 0 for argument parsing" + + +@pytest.mark.parametrize("slug", VIS_LENS_SLUGS) +def test_diagram_path_in_constraints(slug: str) -> None: + text = _read(slug) + assert "diagram_path" in text, f"vis-lens-{slug} must mention diagram_path in constraints" + + +@pytest.mark.parametrize("slug", VIS_LENS_SLUGS) +def test_figure_spec_or_spec_index_in_output(slug: str) -> None: + text = _read(slug) + if slug in COMPOSITE_SLUGS: + assert "yaml:spec-index" in text, ( + f"vis-lens-{slug} (composite) must contain yaml:spec-index in output template" + ) + else: + assert "yaml:figure-spec" in text, ( + f"vis-lens-{slug} must contain yaml:figure-spec in output template" + ) + + +@pytest.mark.parametrize("slug", VIS_LENS_SLUGS) +def test_vis_spec_prefix_in_output_path(slug: str) -> None: + assert "vis_spec_" in _read(slug), f"vis-lens-{slug} output path must use vis_spec_ prefix" + + +@pytest.mark.parametrize("slug", VIS_LENS_SLUGS) +def test_frontmatter_categories(slug: str) -> None: + fm = _frontmatter(_read(slug)) + assert fm.get("categories") == ["vis-lens"], ( + f"vis-lens-{slug} frontmatter must have categories: [vis-lens]" + ) + + +@pytest.mark.parametrize("slug", VIS_LENS_SLUGS) +def test_frontmatter_activate_deps(slug: str) -> None: + fm = _frontmatter(_read(slug)) + assert fm.get("activate_deps") == ["mermaid"], ( + f"vis-lens-{slug} frontmatter must have activate_deps: [mermaid]" + ) diff --git a/tests/skills_extended/__init__.py b/tests/skills_extended/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/skills_extended/test_bundle_local_report.py b/tests/skills_extended/test_bundle_local_report.py new file mode 100644 index 0000000000..33e11683a7 --- /dev/null +++ b/tests/skills_extended/test_bundle_local_report.py @@ -0,0 +1,167 @@ +"""Tests for the bundle-local-report skill renderer.""" + +import re +import subprocess +import sys +from pathlib import Path + +_REPO_ROOT = Path(__file__).resolve().parents[2] +SKILL_MD = _REPO_ROOT / "src/autoskillit/skills_extended/bundle-local-report/SKILL.md" +MERMAID_JS = _REPO_ROOT / "src/autoskillit/assets/mermaid/mermaid.min.js" +MERMAID_VERSION = _REPO_ROOT / "src/autoskillit/assets/mermaid/VERSION" + + +def _extract_renderer(tmp_path: Path) -> Path: + """Extract the embedded Python renderer from SKILL.md to a temp file.""" + text = SKILL_MD.read_text() + match = re.search( + r"```python\n# bundle-local-report renderer\n(.*?)```", + text, + re.DOTALL, + ) + assert match, ( + "SKILL.md must contain a fenced python block" + " starting with '# bundle-local-report renderer'" + ) + script = match.group(1) + out = tmp_path / "renderer.py" + out.write_text(script) + return out + + +def _run_renderer( + renderer: Path, + research_dir: Path, + report_path: Path, + diagram_paths: str, + viz_plan_path: Path, +) -> tuple[int, str, str]: + result = subprocess.run( + [ + sys.executable, + str(renderer), + str(research_dir), + str(report_path), + diagram_paths, + str(viz_plan_path), + ], + capture_output=True, + text=True, + ) + return result.returncode, result.stdout, result.stderr + + +def test_renders_minimal_report(tmp_path: Path) -> None: + """One-paragraph markdown + zero diagrams → HTML has mermaid init + paragraph.""" + research_dir = tmp_path / "research" + research_dir.mkdir() + report = research_dir / "README.md" + report.write_text("Hello world paragraph.\n") + viz_plan = research_dir / "visualization-plan.md" + viz_plan.write_text("") + # Copy mermaid assets so renderer can find them + (research_dir / "mermaid.min.js").write_text("/* stub */") + + renderer = _extract_renderer(tmp_path) + rc, stdout, stderr = _run_renderer(renderer, research_dir, report, "", viz_plan) + assert rc == 0, stderr + + html_path = research_dir / "report.html" + assert html_path.exists() + html = html_path.read_text() + assert "mermaid.initialize" in html + assert "Hello world paragraph" in html + + +def test_renders_with_mermaid_diagram(tmp_path: Path) -> None: + """markdown + one valid exp-lens diagram → HTML body has
    ."""
    +    research_dir = tmp_path / "research"
    +    research_dir.mkdir()
    +    report = research_dir / "README.md"
    +    report.write_text("# Report\n\nBody text.\n")
    +    viz_plan = research_dir / "visualization-plan.md"
    +    viz_plan.write_text("")
    +    (research_dir / "mermaid.min.js").write_text("/* stub */")
    +
    +    diag = tmp_path / "diag.md"
    +    diag.write_text(
    +        "```mermaid\ngraph LR\n  treatment --> outcome\n  hypothesis --> causal\n```\n"
    +    )
    +
    +    renderer = _extract_renderer(tmp_path)
    +    rc, stdout, stderr = _run_renderer(renderer, research_dir, report, str(diag), viz_plan)
    +    assert rc == 0, stderr
    +
    +    html = (research_dir / "report.html").read_text()
    +    assert '
    ' in html
    +    assert "treatment" in html
    +
    +
    +def test_skips_invalid_mermaid_diagram(tmp_path: Path) -> None:
    +    """Diagram with <2 validation keywords is silently skipped (no mermaid block in HTML)."""
    +    research_dir = tmp_path / "research"
    +    research_dir.mkdir()
    +    report = research_dir / "README.md"
    +    report.write_text("# Report\n")
    +    viz_plan = research_dir / "visualization-plan.md"
    +    viz_plan.write_text("")
    +    (research_dir / "mermaid.min.js").write_text("/* stub */")
    +
    +    diag = tmp_path / "diag_invalid.md"
    +    diag.write_text("```mermaid\ngraph LR\n  A --> B\n```\n")  # no validation keywords
    +
    +    renderer = _extract_renderer(tmp_path)
    +    rc, stdout, stderr = _run_renderer(renderer, research_dir, report, str(diag), viz_plan)
    +    assert rc == 0, stderr
    +
    +    html = (research_dir / "report.html").read_text()
    +    assert '
    ' not in html
    +
    +
    +def test_images_inserted_from_figure_spec(tmp_path: Path) -> None:
    +    """figure-spec YAML in viz plan → HTML has  with correct src/alt at section."""
    +    research_dir = tmp_path / "research"
    +    research_dir.mkdir()
    +    images_dir = research_dir / "images"
    +    images_dir.mkdir()
    +    (images_dir / "fig-1.png").write_bytes(b"\x89PNG")
    +
    +    report = research_dir / "README.md"
    +    report.write_text("# Report\n\n## Results\n\nSome text here.\n")
    +
    +    viz_plan = research_dir / "visualization-plan.md"
    +    viz_plan.write_text(
    +        "```yaml:figure-spec\n"
    +        "figure_id: fig-1\n"
    +        "figure_title: Main Results\n"
    +        "report_section: Results\n"
    +        "image_path: images/fig-1.png\n"
    +        "```\n"
    +    )
    +    (research_dir / "mermaid.min.js").write_text("/* stub */")
    +
    +    renderer = _extract_renderer(tmp_path)
    +    rc, stdout, stderr = _run_renderer(renderer, research_dir, report, "", viz_plan)
    +    assert rc == 0, stderr
    +
    +    html = (research_dir / "report.html").read_text()
    +    assert 'src="images/fig-1.png"' in html
    +    assert 'alt="Main Results"' in html
    +
    +
    +def test_html_includes_mermaid_version_comment(tmp_path: Path) -> None:
    +    """Rendered HTML contains a  version comment."""
    +    research_dir = tmp_path / "research"
    +    research_dir.mkdir()
    +    report = research_dir / "README.md"
    +    report.write_text("# Report\n")
    +    viz_plan = research_dir / "visualization-plan.md"
    +    viz_plan.write_text("")
    +    (research_dir / "mermaid.min.js").write_text("/* stub */")
    +
    +    renderer = _extract_renderer(tmp_path)
    +    rc, stdout, stderr = _run_renderer(renderer, research_dir, report, "", viz_plan)
    +    assert rc == 0, stderr
    +
    +    html = (research_dir / "report.html").read_text()
    +    assert "